๐Ÿ›  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

MCP 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 โ†’