Decorator that converts a FastAPI endpoint into an MCP tool
Router that handles MCP protocol requests and exposes FastAPI endpoints as MCP tools
Authentication handler for API key-based authentication
Authentication handler for OAuth2-based authentication
FastAPI MCP is a powerful library that transforms your existing FastAPI endpoints into Model Context Protocol (MCP) tools with minimal code changes. This integration allows AI assistants to directly interact with your API endpoints, making your services accessible to AI models through a standardized protocol. The library supports authentication mechanisms, allowing you to secure your endpoints while still making them available as MCP tools. With FastAPI MCP, developers can quickly expose their existing APIs to AI assistants without having to rewrite their codebase or build separate interfaces.
Install the package using pip:
pip install fastapi-mcp
To convert your FastAPI endpoints into MCP tools, follow these steps:
from fastapi import FastAPI
from fastapi_mcp import MCPRouter, mcp_endpoint
app = FastAPI()
mcp_router = MCPRouter()
mcp_endpoint
decorator:@app.get("/hello/{name}")
@mcp_endpoint(
name="say_hello",
description="Say hello to someone",
parameters=["name"]
)
async def hello(name: str):
return {"message": f"Hello, {name}!"}
app.include_router(mcp_router)
uvicorn main:app --reload
FastAPI MCP supports various authentication methods:
from fastapi_mcp.auth import APIKeyAuth
# Create an API key auth handler
api_key_auth = APIKeyAuth(
api_keys=["your-secret-key"],
header_name="X-API-Key"
)
# Use it with your MCP router
mcp_router = MCPRouter(auth=api_key_auth)
from fastapi_mcp.auth import OAuth2Auth
# Create an OAuth2 auth handler
oauth2_auth = OAuth2Auth(
token_url="https://your-auth-server.com/token",
client_id="your-client-id",
client_secret="your-client-secret",
scopes=["read", "write"]
)
# Use it with your MCP router
mcp_router = MCPRouter(auth=oauth2_auth)
You can customize the MCP router with additional options:
mcp_router = MCPRouter(
title="My API",
description="My API description",
version="1.0.0",
auth=api_key_auth,
prefix="/mcp"
)
You can test your MCP server using the Model Context Protocol Inspector:
npm install -g @modelcontextprotocol/inspector
mcp-inspector http://localhost:8000/mcp
This will show you the available tools and allow you to test them interactively.
To use your MCP server with AI assistants, you'll need to provide the server URL to the assistant. The exact method depends on the assistant you're using, but typically involves adding your server to the assistant's configuration.