Model Context Protocol | Build MCP Server | Integrate MCP server with AI Agents - Local and Remote | Sagar Kakkala´s World






Model Context Protocol


Before we discuss about MCP, let us discuss the use case of it, lets say you have chatbot or an AI Agent, imagine you giving a prompt like "Play best horror film in Netflix" or "Book a flight from Delhi to Hyderabad under 3000 rupees". Imagine your chatbot searching flights, comparing flight prices and booking tickets for you and making you avoid lot of trouble. 
    And this is possible when your AI Agent has MCP Tool attached to it. MCP can either be local or even remote which we will understand it better later in this demo
     lets say you are running an Airlines or any hotel, May be any business that you are running, You can design your own MCP tool and publish it to use. And third party can integrate your MCP tool and make efficient use of your MCP tool which can help in your business profits as well.

MCP Components

MCP stands for Model Context Protocol, Model can be any LLM that you specify or agent can use model of its own choice. Context is telling what your model is designed to do and Protocol are some rules that are meant to be followed.

To design and MCP server, You need to have Resources, Tools , Prompts

We will understand this better when we implement the project.

let us say, we are running a hotel booking app business like Airbnb, Booking.com... and resources are nothing but data that we have, it can be details of particular hotel in particular place and prices of hotel.

let us take sample data for example

The Data of Hotels can be resources

Hotels 

  1. Grand Palace Hotel – New York
    • Standard: $200
    • Deluxe: $350
    • Suite: $500

  2. Ocean View Resort – Miami
    • Standard: $180
    • Deluxe: $300
    • Suite: $450

  3. Mountain Lodge – Denver
    • Standard: $150
    • Deluxe: $250
    • Suite: $400

  4. City Central Inn – New York
    • Standard: $170
    • Deluxe: $280
    • Suite: $420

  5. Sunset Boulevard Hotel – Los Angeles
    • Standard: $190
    • Deluxe: $320
    • Suite: $480


Now based on above data, we can design few tools like , A tool that can help get hotel details, another tool that can get prices of hotel, and also tool to book Hotel.

Depending on business and use case, you can design your own tools using MCP

and now we can also use prompts, to make our MCP server aware that user can search the following way and to be ready for it, it is more like expected input for the MCP to work

like user may ask "Please help me find the best hotel in {city} within a ${budget} budget" and what action to be taken is actually what we pre-design in prompt

Build Local MCP Server

let us understand it more clear by building MCP server using MCP Python SDK 

Note: If you want to Build MCP server using different SDK, you can checkout official documentation - MCP SDK

Install Jupyter Notebook on your local using Anaconda if you dont have it installed already- Anaconda

We will be using Jupyter Notebook, throughout our project and we will be installing uv for this particular project

UV is actually written in RUST and modern package alternate for PIP, which is reliable and fast

Install UV --- UV Download 

For MacOS

curl -LsSf https://astral.sh/uv/install.sh | sh

For Windows

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Let us use terminal in Jupyter Notebook as we will need terminal throughout our demo

click on New > Terminal




Once Terminal is opened, copy our UV install command as given in above code snippet


since i had UV installed already, you might have different output log


Now let us go for our MCP Python SDK readme file , you will find MCP installation commands



let us modify commands a bit for our hotel booking app

you can either create a folder , navigate to it and run "uv init" command in it or you can use something like "uv init hotel-booking", for uv to create folder directly

We will be creating inside AI Agents folder that we created in our last session - AI Agents session

Now we will be running commands inside our Terminal 

Navigate to directory where you want to create MCP server


and now we follow commands given in readme with slight modifications required for our local MCP sever

uv init hotel-booking

this creates a hotel-booking folder and you can verify the files inside it via Jupyter Notebook and you will be able to observe python files created inside directory



Now let us get back into our terminal to make this project ready

Navigate to freshly created directory and install mcpcli

cd hotel-booking
uv add "mcp[cli]"



and now you will be able to see uv.lock file once the command is run and it has all dependencies required


and now you can use MCP server that is mentioned in readme file for test, let us build our own MCP sever
create a new file "server.py" or any name of your choice




and now copy paste contents below in server.py - this is our main file that serves as our MCP server which has details required

from mcp.server.fastmcp import FastMCP

# Initialize FastMCP app
mcp = FastMCP("Hotel Booking Server")

# -------------------- RESOURCES --------------------
HOTELS = [
    {"id": 1, "name": "Grand Palace Hotel", "city": "New York", "rating": 4.5},
    {"id": 2, "name": "Ocean View Resort", "city": "Miami", "rating": 4.7},
    {"id": 3, "name": "Mountain Lodge", "city": "Denver", "rating": 4.2},
    {"id": 4, "name": "City Central Inn", "city": "New York", "rating": 4.0},
    {"id": 5, "name": "Sunset Boulevard Hotel", "city": "Los Angeles", "rating": 4.3}
]

PRICES = {
    1: {"standard": 200, "deluxe": 350, "suite": 500},
    2: {"standard": 180, "deluxe": 300, "suite": 450},
    3: {"standard": 150, "deluxe": 250, "suite": 400},
    4: {"standard": 170, "deluxe": 280, "suite": 420},
    5: {"standard": 190, "deluxe": 320, "suite": 480}
}

@mcp.resource("data://hotel_details")
def hotel_details():
    """Return all hotel details"""
    return HOTELS

@mcp.resource("data://hotel_prices")
def hotel_prices():
    """Return all hotel price details"""
    return PRICES

# -------------------- TOOLS --------------------
@mcp.tool()
def get_hotels(city: str) -> dict:
    """Get hotels available in a city"""
    city_lower = city.lower()
    results = [h for h in HOTELS if h["city"].lower() == city_lower]
    if not results:
        return {"message": f"No hotels found in {city}"}
    return {"hotels": results}

@mcp.tool()
def get_prices(hotel_id: int) -> dict:
    """Get room types and prices for a hotel"""
    data = PRICES.get(hotel_id)
    if not data:
        return {"error": f"No price information for hotel_id {hotel_id}"}
    return {"hotel_id": hotel_id, "prices": data}

@mcp.tool()
def book_hotel(hotel_id: int, guest_name: str) -> dict:
    """Book a hotel room for a guest"""
    hotel = next((h for h in HOTELS if h["id"] == hotel_id), None)
    if not hotel:
        return {"error": "Hotel not found."}
    confirmation = f"CONF-{hotel_id}-{guest_name[:3].upper()}"
    return {
        "message": "Booking successful!",
        "hotel": hotel["name"],
        "guest": guest_name,
        "confirmation_id": confirmation
    }

# -------------------- PROMPTS --------------------
@mcp.prompt()
def find_best_hotel(budget: float, city: str, preferences: str = "standard") -> str:
    """Generate a prompt for finding the best hotel within budget"""
    return f"""Please help me find the best hotel in {city} within a ${budget} budget.

Preferences: {preferences}

Consider:
- Price (must be under ${budget})
- Hotel rating and reviews
- Room type and amenities
- Location convenience

Use the get_hotels and get_prices tools to find options and provide a recommendation with reasoning."""

@mcp.prompt()
def handle_booking_issue(hotel_name: str, issue: str) -> str:
    """Generate a prompt for handling hotel booking issues"""
    return f"""A guest's booking at {hotel_name} has an issue: {issue}.

Please help resolve this by:
1. Understanding the guest's situation
2. Offering alternative hotels or room options
3. Providing clear rebooking or refund steps
4. Ensuring the guest feels accommodated

Be empathetic and solution-focused in your response."""

# -------------------- RUN MCP --------------------
if __name__ == "__main__":
    print("🏨 Starting Hotel Booking MCP Tool...")
    mcp.run()




As from above file, you can verify that there are decorators namely @mcp.resources , @mcp.tools, @mcp.prompts which stands as important for our MCP server and make sure you save the file.

Now to test if our MCP server works fine, we can use MCP inspector and before we use MCP inspector, please do install nodejs and npm from terminal

For MacOS

brew install node
For Windows

choco install nodejs



Now to use MCP inspector, run the following command in terminal

uv run mcp dev server.py


Now this would open MCP inspector on your browser



click on connect



once connected, you can see Tools, Resources, Prompts and other configurations



click on List Resources



similarly you can verify Prompts and Tools




This shows that we have built our MCP server successfully


Integrate Local MCP tool with AI Agent

Now before we move further into this demo, understand how to configure AI Agents, How to use Handoff Agents, How to Integrate AI Agents with tools - AI Agents

Now here in this demo, i will be using same setup that we had for AI Agents configured, which mean open-ai API key is configured, Prerequisites required for AI Agent has been done already
 
and since we are doing local MCP setup with open-ai agents, you can refer to official documentation here - openai agents python mcp 

since ours is local MCP setup, we will be using stdio MCP servers referring to the documentation



Now since we are using uv for this project to run our MCP project, we will make modifications accordingly.

Also know exact path of your MCP server locally , here path i would refer is /Users/sagar/AI Agents/hotel-booking




and now let us implement our agent, if you have not configured AI Agent already, make sure you get OpenAI API key, save it an .env file as showed in previous project

and run following commands

from dotenv import load_dotenv
load_dotenv()

and install open-ai agents

pip install openai-agents


AI agent tool with local MCP


from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
import asyncio

current_dir = Path("/Users/sagar/AI Agents/hotel-booking")  # path to server.py

chat_history = []

async def chat_with_hotel_agent():
    # Start your local MCP server in stdio mode
    async with MCPServerStdio(
        name="Hotel MCP Server",
        params={
            "command": "uv", 
            "args": ["run", "python", "server.py"],  # command to start your MCP server
            "cwd": str(current_dir),
        },
    ) as server:

        # Define the AI agent using this MCP server
        hotel_agent = Agent(
            name="Hotel Booking Agent",
            instructions="You help users find hotels, check prices, and make bookings using the MCP Hotel tool.",
            mcp_servers=[server],
        )

        print("🏨 Enter the hotel query. Type 'exit' to quit or 'history' to see previous chats.\n")

        while True:
            user_input = input("You: ")

            if user_input.lower() in ["exit", "quit"]:
                print("Goodbye! πŸ‘‹")
                break

            elif user_input.lower() == "history":
                print("\n---- Chat History ----")
                for i, (u, b) in enumerate(chat_history):
                    print(f"{i+1}. You: {u}\n   Agent: {b}")
                print("----------------------\n")
                continue

            # Send the message to the hotel agent
            result = await Runner.run(hotel_agent, input=user_input)
            response = result.final_output

            # Save to chat history
            chat_history.append((user_input, response))

            print(f"Agent: {response}\n")

# In Jupyter, call with await
await chat_with_hotel_agent()




Now after running this AI Agent, it opens chatbot and logic behind code has been explained in AI Agents session and we will be concentrating on integrating MCP servers in this Demo

As since we have integrated MCP tool, it must be able to show us hotel data, hotel prices from our local itself

let us verify now

As you can see from Below screenshot, it was able to book hotel for me and it gave me confirmation ID as well



it pulled up data from resources we provided and used tool that we specified.

AI agent with Local MCP sever to use only particular tool

Lets say, in this particular project, we had three tools for AI Agent to use and consider MCP server with lot of tools and giving access to AI Agents to lot of tools can raise security concerns if customer decide to use it with wrong intentions

You may configure as many tools in MCP but you can also restrict tools used here with static filters or even block particular tools


let us improvise our code accordingly to use only get_hotels tool which means it cant book hotel or check prices of hotel

from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio, create_static_tool_filter
import asyncio

current_dir = Path("/Users/sagar/AI Agents/hotel-booking")

chat_history = []

async def chat_with_hotel_agent_filtered():
    # Start MCP server in stdio mode with tool filtering
    async with MCPServerStdio(
        name="Hotel MCP Server",
        params={
            "command": "uv",
            "args": ["run", "python", "server.py"],
            "cwd": str(current_dir),
        },
        tool_filter=create_static_tool_filter(allowed_tool_names=["get_hotels"])
    ) as server:

        hotel_agent = Agent(
            name="Hotel Finder Agent",
            instructions="You help users find hotels in a city using the MCP get_hotels tool.",
            mcp_servers=[server],
        )

        print("🏨 Enter the city to find hotels. Type 'exit' to quit.\n")

        while True:
            user_input = input("You: ")
            if user_input.lower() in ["exit", "quit"]:
                print("Goodbye! πŸ‘‹")
                break

            result = await Runner.run(hotel_agent, input=user_input)
            response = result.final_output

            chat_history.append((user_input, response))
            print(f"Agent: {response}\n")

await chat_with_hotel_agent_filtered()


Now let us verify if it can book hotels now for us.



As you can see from above screenshot, Our Agent was able to get hotel details but not able to book hotel ,it is by default we only allowed one tool that is to get hotels.


Integrate AI Agent with Remote Server

since this is local MCP server, we can also use MCP server configured by that particular business, you can check list of MCP servers available here in readme file  - Remote MCP Servers

and now since there is chrome dev MCP server, let us integrate that MCP tool 



you may choose to integrate any other MCP tool that you are interested in, here i will be using Chrome Dev Tools - Chrome Dev MCP 

When you scroll down to readme file, you will be able to find how to integrate Chrome MCP server



Now let us make modifications and use this MCP tool to check Airbnb available in particular location

from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
import asyncio

chat_history = []

cwd = Path("/Users/sagar/AI Agents/hotel-booking")  # folder where you want the server to run

async def chat_with_airbnb_agent():
    # Start Airbnb MCP server via npx
    async with MCPServerStdio(
        name="chrome MCP Server",
        params={
            "command": "npx",
            "args": ["-y", "chrome-devtools-mcp@latest"],
            "cwd": str(cwd),
        }
    ) as server:

        # Define the AI agent using this MCP server
        airbnb_agent = Agent(
            name="airbnb Agent",
            instructions="You help users search Airbnb listings, check prices, and make bookings using the chrome search tool.",
            mcp_servers=[server]
        )

        print("🏠 Ask me to search Airbnb in chrome listings. Type 'exit' to quit.\n")

        while True:
            user_input = input("You: ")
            if user_input.lower() in ["exit", "quit"]:
                print("Goodbye! πŸ‘‹")
                break

            result = await Runner.run(airbnb_agent, input=user_input)
            response = result.final_output

            chat_history.append((user_input, response))
            print(f"Agent: {response}\n")

# Run in Jupyter
await chat_with_airbnb_agent()



Now we have asked our AI Agent to use chrome tool and search for Airbnb, also make sure you chrome installed in your laptop for this AI Agent to use chrome,


I gave prompt to search for Airbnb in Bengaluru and it opened chrome tool to show me



You can experiment using chrome tool the way you want it to work, let us use same MCP tool for different purpose, you can use the following codes to use it accordingly

Youtube Agent that can help you search for paticular videos

from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
import asyncio

chat_history = []

cwd = Path("/Users/sagar/AI Agents/hotel-booking")  # folder where you want the server to run

async def chat_with_youtube_agent():
    async with MCPServerStdio(
        name="chrome MCP Server",
        params={
            "command": "npx",
            "args": ["-y", "chrome-devtools-mcp@latest"],
            "cwd": str(cwd),
        }
    ) as server:

        # Define the AI agent using this MCP server
        youtube_agent = Agent(
            name="youtube Agent",
            instructions="You help users play videos on youtube that they have asked you and you use chrome tool for it.",
            mcp_servers=[server]
        )

        print("What do you love to watch on Youtube today? . Type 'exit' to quit.\n")

        while True:
            user_input = input("You: ")
            if user_input.lower() in ["exit", "quit"]:
                print("Goodbye! πŸ‘‹")
                break

            result = await Runner.run(youtube_agent, input=user_input)
            response = result.final_output

            chat_history.append((user_input, response))
            print(f"Agent: {response}\n")

# Run in Jupyter
await chat_with_youtube_agent()

Netflix Agent that can help you find particular film in Netflix

from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
import asyncio

chat_history = []

cwd = Path("/Users/sagar/AI Agents/hotel-booking")  # folder where you want the server to run

async def chat_with_netflix_agent():
    async with MCPServerStdio(
        name="chrome MCP Server",
        params={
            "command": "npx",
            "args": ["-y", "chrome-devtools-mcp@latest"],
            "cwd": str(cwd),
        }
    ) as server:

        # Define the AI agent using this MCP server
        netflix_agent = Agent(
            name="netflix Agent",
            instructions="You help users search for videos on Netflix that they have asked you and you use chrome tool for it.",
            mcp_servers=[server]
        )

        print("What do you want me to search on Netflix today? . Type 'exit' to quit.\n")

        while True:
            user_input = input("You: ")
            if user_input.lower() in ["exit", "quit"]:
                print("Goodbye! πŸ‘‹")
                break

            result = await Runner.run(netflix_agent, input=user_input)
            response = result.final_output

            chat_history.append((user_input, response))
            print(f"Agent: {response}\n")

# Run in Jupyter
await chat_with_netflix_agent()

similarly you can design your own Spotify search agent and to have no limitation using this MCP tool to your agent

This concludes the blog

πŸ“šYou can now Follow me on LinkedIn for latest updates

πŸ“œYou can now Follow me on Instagram for behind the scenes

πŸ“Ή Subscribe my Youtube Channel to stay up to date with contents








Comments