Custom Routing with APIRouter

You are not limited to mounting the MCP server on the root of your FastAPI application. You can mount it to a specific APIRouter to better organize your application's routes and apply router-level configurations like prefixes and dependencies.

This is particularly useful for versioning your MCP endpoint or grouping it with other related API routes.

Mounting to an APIRouter

Here's how to mount the MCP server to an APIRouter with a prefix:

# examples/06_custom_mcp_router_example.py
from fastapi import FastAPI, APIRouter
from fastapi_mcp import FastApiMCP

app = FastAPI()

# ... your other app routes ...

# 1. Create an APIRouter with a prefix.
# All routes on this router will be prefixed with '/api/v1'.
api_v1_router = APIRouter(prefix="/api/v1")

# 2. Create the FastApiMCP instance from your main app.
# It will still scan all routes on the main `app` instance.
mcp = FastApiMCP(app)

# 3. Mount the MCP server to the APIRouter.
# The default mount path '/mcp' will be appended to the router's prefix.
mcp.mount_http(api_v1_router)

# 4. Include the router in your main application.
app.include_router(api_v1_router)

# The MCP server is now available at: http://localhost:8000/api/v1/mcp

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Key Points

  • The final URL for the MCP endpoint is a combination of the APIRouter's prefix and the mount_path provided to the mount_http() or mount_sse() method.
  • Any dependencies, tags, or other configurations applied to the APIRouter will also apply to the MCP endpoint.