๐ MCP in Action: A Developerโs Perspective
Model Context Protocol (MCP) isnโt just a theoretical standardโdevelopers can implement it today using modern Python frameworks like FastAPI. In this guide, weโll walk through a practical MCP implementation, showing how to:
- Spin up a FastAPI-based MCP server
- Register and invoke tools
- Handle stateful sessions
- Enable LLMs to interact with real-world tools
Step 1: Project Structure
project-root/
โโโ main.py # FastAPI server
โโโ tools/
โ โโโ weather.py # Tool logic
โโโ sessions/ # In-memory or persisted session store
โโโ schemas.py # JSON-RPC schemas
โโโ config.py # Config and setup
Step 2: Define Your Tool (e.g., Weather API)
# tools/weather.py
def get_weather(city: str):
# Normally call external API
return {"forecast": "Sunny", "temperature": "27ยฐC"}
Step 3: Set Up FastAPI MCP Server
# main.py
from fastapi import FastAPI, Request
from tools.weather import get_weather
app = FastAPI()
@app.post("/mcp")
async def handle_request(request: Request):
data = await request.json()
method = data.get("method")
params = data.get("params", {})
if method == "weather.get":
result = get_weather(**params)
return {"jsonrpc": "2.0", "result": result, "id": data.get("id")}
return {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": data.get("id")}
Step 4: Session Management
# sessions/session_store.py
session_store = {}
def get_or_create_session(session_id):
if session_id not in session_store:
session_store[session_id] = {"tools_used": []}
return session_store[session_id]
๐ง Why This Matters
This is the core of MCP: models interact via a standard (JSON-RPC 2.0), access external tools, and maintain long-term memory across sessionsโenabling agentic behavior.
Diagram: MCP Session and Tool Execution Flow
Explanation:
- LLM sends JSON-RPC
weather.get
via client - MCP server routes it to the tool
- Response flows back with updated session state
Where to Go From Here
- Add OpenAI key to simulate an agent
- Register more tools (e.g.,
search
,calendar.add
) - Move session management to Redis or a DB
This forms the base for building full-fledged MCP-powered agentic systems.
Next Up: Beyond Chatbots: MCP and Agentic AI โ