MODEL CONTEXT PROTOCOL
1. Why APIs Matter?
- API (Application Programming Interface): a set of rules that lets one piece of software talk to another.
- Analogy: a waiter in a restaurant — you (the client) order, the waiter takes it to the kitchen (server), and brings back your food.
- Without an API: you’d have to scrape websites or write custom code for every integration — fragile and time‑consuming.
- With an API: you get a stable, documented interface (e.g., REST) that returns clean data (usually JSON).
Example: GET https://api.weather.com?city=London → {“temp”:22}.
Read more about Api in this article: https://medium.com/@vengiboopathi/application-programming-interface-4dfda97e7428
2. The Problem Before MCP (How AI Agents Used Tools)
Before MCP, integrating tools with AI agents was messy and non‑standard:
2.1 Hardcoded Integrations
- Developer manually wrote if/elif blocks for each tool inside the agent code.
- LLM was told about tools via a plain‑text system prompt.
- Adding a new tool meant editing code and prompt.
2.2 Plugin Architectures (e.g., LangChain)
- Tools registered via decorators or config files; framework collected them.
- Framework generated prompt and parsed LLM output.
- Still framework‑specific; tools couldn’t be shared across different agent frameworks.
2.3 LLM‑Native Function Calling (OpenAI, etc.)
- Developer provided a list of function definitions (name, description, parameters) to the LLM API.
- LLM could return a structured function_call object.
- Execution still required custom code to call actual functions; definitions were static.
Common issues: no dynamic discovery, no standard way to package/share tools, each integration required custom glue code.
3. What is MCP?
MCP (Model Context Protocol) is an open protocol that standardizes how AI applications (clients) discover and use tools, data, and resources from external servers.
- Purpose: Make tool‑augmented AI interoperable, scalable, and plug‑and‑play.
- Analogy: Like USB‑C for AI agents — any agent (client) can plug into any tool server that speaks MCP.
- Not a general‑purpose API: Designed specifically for AI agents (LLM‑based applications) to interact with tools.
4. MCP Components
Component Description Example
Client: The AI application (e.g., chatbot, agent framework) that wants to use tools. It connects to one or more servers. Claude Desktop, custom Python agent
Server: A program that wraps one or more tools (functions) and exposes them via the MCP protocol. Weather server, calculator server
Protocol: The set of rules for communication — uses JSON‑RPC 2.0 over transports like stdio (local) or HTTP/SSE (remote). Messages like tools/list, tools/call
5. How MCP Works — Step by Step
5.1 Tool Discovery
- Client sends a tools/list request to the server.
- Server responds with a list of tools, each containing:
name — unique identifier
description - what the tool does (for the LLM)
inputSchema - JSON Schema describing expected argumentsExample request:
json
{"jsonrpc":"2.0", "id":1, "method":"tools/list"}Example response:
json
{
"jsonrpc":"2.0", "id":1,
"result": {
"tools": [
{
"name": "get_weather",
"description": "Get current weather for a city",
"inputSchema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}}]}}5.2 Informing the LLM
- Client takes these tool descriptions and injects them into the LLM’s prompt (or uses native function‑calling APIs).
- The LLM now knows what tools exist and how to call them.
5.3 LLM Decides to Call a Tool
- The LLM outputs a structured response indicating which tool to use and with what arguments.
- This could be a native function_call (OpenAI) or a custom JSON format.
Example (OpenAI style):
json{
"function_call": {
"name": "get_weather",
"arguments": "{\"city\": \"London\"}"
}
}5.4 Client(Agent) Translates and Sends tools/call
- Client parses the LLM’s response, extracts the tool name and arguments.
- Sends a tools/call request to the appropriate MCP server.
json
{
"jsonrpc":"2.0", "id":2,
"method":"tools/call",
"params": {
"name": "get_weather",
"arguments": {"city": "London"}
}
}5.5 Server Executes the Tool
- Server receives the request, looks up the function mapped to the tool name.
- Calls that function with the provided arguments (e.g., queries a real weather API).
- The function returns a result (e.g., “The temperature is 22°C”).
5.6 Server Returns the Result
- Server wraps the result in a CallToolResult response (with content, possibly multiple types).
json
{
"jsonrpc":"2.0", "id":2,
"result": {
"content": [
{"type": "text", "text": "The temperature in London is 22°C."}
]}}5.7 Client Feeds Result Back to LLM
- Client receives the result and sends it back to the LLM (e.g., as a function response).
- LLM uses this information to generate the final answer to the user.
6. Example MCP Server in Python (Using Official SDK)
python
from mcp.server import Server, stdio_server
from mcp.types import TextContent, Tool, CallToolResult
app = Server("weather-server")
# Actual tool implementation
def get_weather(city: str) -> str:
# Replace with real API call
return f"The temperature in {city} is 22°C."
# Register tool discovery
@app.list_tools()
async def list_tools():
return [
Tool(
name="get_weather",
description="Get current weather for a city",
inputSchema={
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
)
]
# Register tool execution
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> CallToolResult:
if name == "get_weather":
city = arguments["city"]
result_text = get_weather(city)
return CallToolResult(
content=[TextContent(type="text", text=result_text)]
)
raise ValueError(f"Unknown tool: {name}")
if __name__ == "__main__":
stdio_server.run(app)- This server runs over stdio (standard input/output). A client can launch it as a subprocess and communicate via stdin/stdout.
7. How the Server Maps Tool Names to Functions
Inside the server, you maintain a mapping (e.g., a dictionary) between tool names and the actual Python functions.
python
TOOL_FUNCTIONS = {
"get_weather": get_weather,
"calculator": lambda a,b: a+b,
# …
}
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name in TOOL_FUNCTIONS:
result = TOOL_FUNCTIONS[name](**arguments)
return CallToolResult(…)
…- The call_tool handler receives the name and arguments, looks up the function, calls it, and returns the result wrapped in the MCP response format.
8. Transport Options
Transport Description Typical Use
stdio: Server runs as subprocess; client writes to its stdin, reads from stdout. Local tools, lightweight, easy to spawn.
HTTP + SSE : Server runs as HTTP server; client sends requests via HTTP, receives streaming responses via Server‑Sent Events. Remote services, web‑based agents.
Get Vengadesa Boopathi’s stories in your inbox
Join Medium for free to get updates from this writer.
The protocol messages (JSON‑RPC) are the same; only the transport layer changes.
9. Benefits of MCP
- Dynamic Discovery: Client can ask “what tools do you have?” at runtime — no hardcoding.
- Standardized Invocation: Every tool is called the same way (tools/call with arguments).
- Language Agnostic: Servers can be written in any language (Python, JS, Rust, etc.) as long as they speak JSON‑RPC over a supported transport.
- Interoperability: Any MCP‑compatible client can use any MCP server without modification.
FastMCP
1. What is FastMCP?
FastMCP is a high‑level Python framework built on top of the official MCP (Model Context Protocol) SDK. It is designed to simplify and accelerate the development of MCP servers by providing a declarative, decorator‑based API. With FastMCP, you can focus on writing your tool logic without worrying about the underlying JSON‑RPC message handling, request routing, or schema generation.
2. Why FastMCP? The Problem It Solves
The base MCP Server class (from the official SDK) requires you to manually implement:
- list_tools() — to return tool definitions.
- call_tool() — to route incoming calls to the correct function.
- JSON‑RPC request parsing and response formatting.
- Argument validation and error handling.
- Transport setup (stdio or SSE).
This is repetitive and error‑prone, especially for servers with many tools. FastMCP automates all of that:
- Automatic tool discovery — just decorate a function with @mcp.tool().
- Automatic schema generation — from Python type hints and docstrings.
- Automatic request routing — based on the tool name.
- Built‑in validation — arguments are checked against the schema.
- Easy transport configuration — mcp.run(transport=”stdio”) or “sse”.
3. Core Concepts
3.1 The FastMCP Class
The central object. You create one instance per server:
python
from fastmcp import FastMCP
mcp = FastMCP("My Server Name")3.2 Tools
A tool is a Python function that can be called by an AI agent. Decorate it with @mcp.tool():
python
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b- The function name becomes the tool name (add).
- The docstring becomes the tool description (sent to the LLM).
- Type hints are used to generate the JSON Schema for input validation.
- The return value is automatically converted to a TextContent result (or you can return richer structures).
3.3 Resources
A resource exposes static or dynamically generated data (like files, database records) to the client. Use @mcp.resource():
python
@mcp.resource("config://app")
def get_config() -> str:
"""Return the application configuration."""
return "debug=True\nport=8080"Resources are identified by a URI scheme (here config://). The client can fetch them.
3.4 Prompts
A prompt is a reusable template that the client can request to insert into the LLM’s context. Use @mcp.prompt():
python
@mcp.prompt()
def analyze_sentiment(text: str) -> str:
"""Create a prompt for sentiment analysis."""
return f"Analyze the sentiment of the following text: {text}"Prompts can be parameterised and are returned as plain text or a list of messages.
4. How FastMCP Works Under the Hood
When you decorate a function with @mcp.tool(), FastMCP:
1. Inspects the function — name, docstring, parameters, type hints, return annotation.
2. Builds a JSON Schema from the parameters (using the pydantic library internally).
3. Registers the tool in an internal registry, storing the schema and a reference to the function.
4. When the server receives a tools/list request, it iterates the registry and returns the list of tool definitions.
5. When a tools/call request arrives, it:
- Looks up the function by name.
- Validates the arguments against the schema.
- Calls the function with the arguments.
- Converts the return value into an MCP CallToolResult (by default wrapping it in TextContent).
- Handles any exceptions and returns an error response.
All of this happens without any boilerplate from you.
5. Example: A Complete FastMCP Server
python
from fastmcp import FastMCP
# Create the server
mcp = FastMCP("Demo Server")
# - Tools -
@mcp.tool()
def greet(name: str) -> str:
"""Greet a person by name."""
return f"Hello, {name}!"
@mcp.tool()
def add(a: float, b: float) -> float:
"""Add two numbers."""
return a + b
# - Resource -
@mcp.resource("info://version")
def get_version() -> str:
"""Return the server version."""
return "1.0.0"
# - Prompt -
@mcp.prompt()
def haiku(topic: str) -> str:
"""Create a haiku prompt."""
return f"Write a haiku about {topic}."
# Run the server (stdio by default)
if __name__ == "__main__":
mcp.run()Save this as server.py. You can then connect any MCP client (like Claude Desktop) to it.
6. Running FastMCP Servers
FastMCP supports two transports:
6.1 stdio (Standard Input/Output)
The server runs as a subprocess. This is the default and is ideal for local tools.
python
mcp.run() # or mcp.run(transport="stdio")The client (e.g., Claude Desktop) launches your script and communicates via stdin/stdout.
6.2 SSE (Server‑Sent Events) over HTTP
The server runs as an HTTP server, and the client connects via HTTP. Useful for remote or containerised servers.
python
mcp.run(transport="sse", host="0.0.0.0", port=8000)Then clients can connect to http://your-host:8000/sse.
7. Advanced Features
7.1 Context Injection
If your tool needs access to the request context (e.g., to get client information, or to use logging), you can add a parameter of type fastmcp.Context. FastMCP will automatically inject the context.
python
from fastmcp import FastMCP, Context
mcp = FastMCP("Context Demo")
@mcp.tool()
def long_task(ctx: Context, duration: int) -> str:
"""Simulate a long task with progress reporting."""
for i in range(duration):
ctx.report_progress(i, duration) # sends progress notifications
time.sleep(1)
return "Done"The context object provides methods for logging, progress reporting, and accessing request metadata.
7.2 Custom Result Types
By default, FastMCP wraps return values in TextContent. You can return an mcp.types.CallToolResult directly for full control, or return other content types like ImageContent or EmbeddedResource.
python
from mcp.types import ImageContent
@mcp.tool()
def plot() -> list[ImageContent]:
# generate an image…
return [ImageContent(type="image", data=base64_data, mimeType="image/png")]9. Integration with MCP Clients
Any client that speaks the MCP protocol can connect to a FastMCP server. Popular examples:
- Claude Desktop — you can configure it to launch your FastMCP server as a subprocess.
- Custom Python agents — using the mcp client SDK.
- VS Code extensions — that support MCP.
Claude Desktop, for instance, allows you to add an MCP server by specifying the command to run your script (e.g., python my_server.py). It will then automatically discover your tools and make them available to Claude.
10. Benefits of Using FastMCP
- Speed of development — go from idea to working tool in minutes.
- Readability — your code clearly shows what tools exist and what they do.
- Maintainability — adding or changing a tool is a one‑line change.
- Type safety — type hints reduce bugs and improve IDE support.
- Ecosystem compatibility — works with all MCP clients.
- Extensibility — easy to add resources, prompts, and custom behaviour when needed.




