MCP (Model Context Protocol) Explained
MCP, the Model Context Protocol, is an open standard that lets AI apps connect to tools and data in one common way, like a USB port for AI.
The Problem MCP Solves
In the last chapter you wrote tools for one app. Now imagine you want the same "check stock" tool inside a chat app, inside your code editor's AI assistant, and inside an agent. Without a standard, you would write the connection three times, once for each app.
MCP fixes this. You write your tool once as an MCP server. Any AI app that speaks MCP can then use it. Many chat apps, coding assistants and agent frameworks support MCP today.
| Without MCP | With MCP |
|---|---|
| Every app needs its own custom connection to every tool | One server works with every MCP-compatible app |
| Tool code is copied and changed for each app | Tool code lives in one place |
| Hard to share tools with others | Servers can be shared like packages |
The Three Parts
| Part | What it is | Example |
|---|---|---|
| Host | The AI app the person uses | A desktop chat app or a code editor |
| Client | The part inside the host that talks to one server | Created by the host for each server |
| Server | A small program that offers tools and data | Your "karachi-shop" price server |
The host shows the server's tools to the model. When the model wants a tool, the host sends the request to the server through the client, and passes the result back to the model. Under the hood, MCP uses JSON-RPC messages.
What a Server Can Offer
- Tools: functions the model can call, like
get_priceorcreate_invoice - Resources: data the app can read, like files, database rows or documents
- Prompts: ready-made prompt templates the user can pick
Servers connect in two main ways:
- stdio: the host starts the server as a program on your computer and talks through its input and output. Good for local tools.
- Streamable HTTP: the server runs on the web, and many users can connect. Good for shared or company tools.
Build an MCP Server in Python
Install the official Python SDK with pip install mcp. The code below uses version 2 of the SDK, where the server class is called MCPServer. (Older tutorials use version 1, where it was called FastMCP. The idea is the same.)
Example
# shop_server.py
from mcp.server.mcpserver import MCPServer
mcp = MCPServer("karachi-shop")
PRICES = {"notebook": 150, "pen": 40, "school bag": 2200}
@mcp.tool()
def get_price(item: str) -> str:
"""Return the price in rupees of an item sold in the shop."""
price = PRICES.get(item.lower())
if price is None:
return f"Sorry, we do not sell '{item}'."
return f"{item} costs Rs {price}"
if __name__ == "__main__":
mcp.run() # talks to the AI app over stdioThat is a complete server. The SDK reads the function name, the type hints (item: str) and the docstring, and builds the tool description and JSON Schema for you. Compare that with the schema you wrote by hand in Function Calling and Tools.
Test It with a Client
You can test a server without any AI app. The SDK's Client can connect to the server object directly, in memory. Save this next to shop_server.py:
Example
# test_client.py
import asyncio
from mcp.client import Client
from shop_server import mcp
async def main():
async with Client(mcp) as client: # connects in memory for testing
tools = await client.list_tools()
print([t.name for t in tools.tools])
result = await client.call_tool("get_price", {"item": "school bag"})
print(result.content[0].text)
asyncio.run(main())['get_price'] school bag costs Rs 2200
This is exactly what a host does: it lists the tools, shows them to the model, and calls one when the model asks.
Connect It to an AI App
Most desktop AI apps and code editors have a settings file or screen where you list MCP servers. The exact file name and place differ by app, but the entry usually looks like this:
Example
{
"mcpServers": {
"karachi-shop": {
"command": "python",
"args": ["/full/path/to/shop_server.py"]
}
}
}After a restart, the app starts your server, and you can ask the model "How much is a school bag?". It will call get_price and answer from the result.
MCP Safety
An MCP server is a program that runs with your permissions. Treat it like installing any software:
- Install servers only from sources you trust, and read what tools they offer
- Prefer read-only tools; be careful with servers that can delete files, send email or spend money
- Keep API keys for the server in environment variables, not in the config file you share
- Text that comes back from a server (web pages, emails, documents) can contain hidden instructions. This is prompt injection, covered in Hallucinations and Prompt Injection
MCP standardises how tools connect. It does not make a tool safe. Your server should still check its inputs and limit what it can do.
Exercise
Exercise
In MCP, what is a "server"?
