FastAPI-MCP: Expose FastAPI Endpoints as MCP Tools
Automatically expose FastAPI endpoints as MCP (Model Context Protocol) tools for AI agents.
- Step 1
Check Python version
Ensure you have Python 3.10 or higher installed (Python 3.12 recommended).
python --version - Step 2
Install FastAPI-MCP
Install the fastapi-mcp library which automatically generates MCP tools from your FastAPI OpenAPI schema. Using uv is recommended, but pip works as well.
uv add fastapi-mcp # Or using pip: pip install fastapi-mcp - Step 3
Create a FastAPI application
Create a basic FastAPI app with endpoints. Add the FastApiMCP class to convert your endpoints to MCP tools and mount them.
from fastapi import FastAPI from fastapi_mcp import FastApiMCP import uvicorn app = FastAPI( title="My MCP API", description="An API exposed as MCP tools for AI agents" ) @app.get("/items/{item_id}") async def get_item(item_id: int): """Retrieve an item by its ID""" return {"item_id": item_id, "name": f"Item {item_id}"} @app.post("/items") async def create_item(name: str, value: float): """Create a new item""" return {"name": name, "value": value} # Create MCP server from FastAPI app mcp = FastApiMCP(app) # Mount MCP endpoints to the same app mcp.mount() if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) - Step 4
Run the application
Start your FastAPI application with the MCP server. The MCP server will be available at /mcp endpoint.
python app.py - Step 5
Verify the MCP server
Check that the MCP connection endpoint is available and the server is responding.
curl http://localhost:8000/mcp - Step 6
Configure advanced options
FastAPI-MCP supports various configuration options including filtering endpoints, custom descriptions, and response schema options.
from fastapi_mcp import FastApiMCP mcp = FastApiMCP( app, name="My Custom MCP Server", description="Custom description for AI agents", describe_all_responses=True, describe_full_response_schema=True, include_operations=["get_item", "create_item"], # Filter by operation ID exclude_operations=["internal_health_check"], # Exclude specific operations include_tags=["public"], # Filter by tags exclude_tags=["admin"], headers=["authorization", "x-custom-header"] # Forward specific headers ) - Step 7
Add authentication (optional)
Use FastAPI dependencies to add authentication. The dependencies parameter accepts Depends() calls that raise 401/403 for unauthorized requests.
from fastapi import Depends, HTTPException from fastapi.security import HTTPBearer from fastapi_mcp import FastApiMCP, AuthConfig security = HTTPBearer() async def verify_token(credentials: HTTPBearer = Depends(security)): if not credentials.credentials.startswith("Bearer "): raise HTTPException(status_code=401, detail="Invalid token") return credentials.credentials @app.get("/protected") async def protected(user_data: str = Depends(verify_token)): return {"message": "Access granted"} # Configure MCP with authentication mcp = FastApiMCP( app, auth_config=AuthConfig( dependencies=[Depends(verify_token)] ) ) mcp.mount() - Step 8
Deploy MCP server separately (optional)
You can mount the MCP server to a separate FastAPI app to run it on a different port or server. The original API is not exposed, only via MCP.
from fastapi import FastAPI from fastapi_mcp import FastApiMCP import uvicorn # Original FastAPI app original_app = FastAPI(title="Original API") # Create MCP server from original app mcp_server = FastApiMCP(original_app) # Mount to separate app mcp_app = FastAPI(title="MCP Server") mcp_server.mount_http(mcp_app) if __name__ == "__main__": uvicorn.run(mcp_app, host="0.0.0.0", port=8000) - Step 9
Integrate with MCP clients
Configure AI assistant clients to connect to your MCP server. For Claude Desktop or other MCP-compatible clients.
{ "mcpServers": { "my-fastapi-api": { "command": "npx", "args": ["-y", "mcp-remote", "--url", "http://localhost:8000/mcp"] } } }⚠ Heads up: This is for claude_desktop_config.json or similar MCP client configurations. - Step 10
Test with mcp-python client
Use the mcp-python library to programmatically connect and list available tools.
from mcp import ClientSession import asyncio async def main(): client_session = await ClientSession.connect("http://localhost:8000/mcp") tools = await client_session.list_tools() print(f"Available tools: {[tool.name for tool in tools]}") asyncio.run(main()) - Step 11
Use OAuth authentication (optional)
Configure OAuth 2.0 for MCP clients using AuthConfig. This enables OAuth flow for authenticated MCP tool calls.
from fastapi_mcp import FastApiMCP, AuthConfig mcp = FastApiMCP( app, auth_config=AuthConfig( issuer="https://your-oauth-provider.com", authorize_url="https://your-oauth-provider.com/oauth/authorize", default_scope="openid profile email", client_id="your-client-id", setup_proxies=True, setup_fake_dynamic_registration=True ) ) mcp.mount()
Feature requests
Sign in to suggest features or vote on existing ones.
No feature requests yet.
Discussion
Sign in to join the discussion.
No comments yet.