You can absolutely integrate MCP into an existing FastAPI backend. There are two primary ways to do this depending on how much control you want over which routes are exposed.
The most common tool for this is the fastapi-mcp library (or the similar fastmcp utility), which acts as a bridge to turn your REST endpoints into "tools" that AI agents can call.
Option 1: Using fastapi-mcp (Best for existing apps)
This library is designed to sit on top of your existing FastAPI app. It inspects your routes and automatically generates the MCP schema.
1. Install the package:
pip install fastapi-mcp uvicorn
2. Integration Code:
You only need to add a few lines to your main.py file.
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI(title="My Existing Backend")
# Your existing routes
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "name": "Sample Item"}
# Initialize MCP and "mount" it to your app
mcp = FastApiMCP(
app,
name="My Business Tools",
base_url="http://localhost:8000"
)
mcp.mount() # This creates a /mcp endpoint automatically
Option 2: Using FastMCP.from_fastapi (Official SDK style)
If you are using the official mcp Python SDK, it includes a FastMCP class that can wrap a FastAPI app directly.
from fastmcp import FastMCP
from my_app import app # Import your existing FastAPI instance
# Convert the entire FastAPI app to an MCP server
mcp = FastMCP.from_fastapi(app)
if __name__ == "__main__":
mcp.run()
Key Technical Details
-
Automatic Tool Mapping: By default, these libraries convert your
POST,PUT, andDELETErequests into Tools and yourGETrequests into Resources. - SSE Transport: FastAPI-based MCP servers typically use Server-Sent Events (SSE). This is ideal because it runs over standard HTTP, meaning you don't need a separate process or complex setup for your AI to talk to your backend.
-
Filtering Routes: You likely don't want to expose every internal endpoint. You can use the
include_operationsorexclude_operationsarguments to control exactly what the AI sees:
mcp = FastApiMCP(app, include_operations=["get_user_info", "process_order"])
How to use it in your AI Tool (Cursor, Claude, etc.)
Once your server is running (e.g., at http://localhost:8000), you connect your AI agent using the SSE URL:
-
Endpoint:
http://localhost:8000/mcp - Type: SSE
Top comments (0)