Automatic MCP server generator for FastAPI applications - converts FastAPI endpoints to MCP tools for LLM integration
npx @tessl/cli install tessl/pypi-fastapi-mcp@0.4.0Automatic MCP server generator for FastAPI applications that converts FastAPI endpoints to MCP (Model Context Protocol) tools for LLM integration. This library provides seamless integration between FastAPI applications and Large Language Models like Claude, enabling AI agents to interact with web APIs through the standardized MCP protocol.
uv add fastapi-mcp or pip install fastapi-mcpfrom fastapi_mcp import FastApiMCPFor authentication:
from fastapi_mcp import FastApiMCP, AuthConfigFor OAuth metadata customization:
from fastapi_mcp import FastApiMCP, AuthConfig, OAuthMetadataFor type annotations:
from fastapi_mcp.types import HTTPRequestInfofrom fastapi import FastAPI
from fastapi_mcp import FastApiMCP
# Create your FastAPI application
app = FastAPI(title="My API", description="Example API for MCP integration")
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"id": user_id, "name": f"User {user_id}"}
@app.post("/users")
async def create_user(user: dict):
return {"id": 123, "name": user["name"], "created": True}
# Create MCP server from your FastAPI app
mcp_server = FastApiMCP(fastapi=app)
# Mount the MCP server (HTTP transport recommended)
mcp_server.mount_http()
# Your FastAPI app now has MCP endpoints at /mcp
# AI agents can connect and use your API endpoints as MCP toolsFastAPI-MCP uses a two-layer architecture:
Core functionality for creating MCP servers from FastAPI applications, with extensive configuration options for customizing tool generation, filtering operations, and handling responses.
from typing import Dict, List, Any, Literal, Optional
from fastapi import FastAPI, APIRouter
from mcp.server.lowlevel.server import Server
import mcp.types as types
import httpx
class FastApiMCP:
def __init__(
self,
fastapi: FastAPI,
name: Optional[str] = None,
description: Optional[str] = None,
describe_all_responses: bool = False,
describe_full_response_schema: bool = False,
http_client: Optional[httpx.AsyncClient] = None,
include_operations: Optional[List[str]] = None,
exclude_operations: Optional[List[str]] = None,
include_tags: Optional[List[str]] = None,
exclude_tags: Optional[List[str]] = None,
auth_config: Optional[AuthConfig] = None,
headers: List[str] = ["authorization"]
): ...
def mount_http(
self,
router: Optional[FastAPI | APIRouter] = None,
mount_path: str = "/mcp"
) -> None: ...
def mount_sse(
self,
router: Optional[FastAPI | APIRouter] = None,
mount_path: str = "/sse"
) -> None: ...
def mount(
self,
router: Optional[FastAPI | APIRouter] = None,
mount_path: str = "/mcp",
transport: Literal["sse"] = "sse"
) -> None: ...
@property
def server(self) -> Server: ...
@property
def tools(self) -> List[types.Tool]: ...
@property
def operation_map(self) -> Dict[str, Dict[str, Any]]: ...
@property
def fastapi(self) -> FastAPI: ...
@property
def name(self) -> str: ...
@property
def description(self) -> str: ...Complete OAuth 2.0 authentication system designed for MCP compliance, supporting custom metadata, proxy setups, and dynamic client registration for secure AI-to-API communication.
class AuthConfig:
version: Literal["2025-03-26"] = "2025-03-26"
dependencies: Optional[Sequence[params.Depends]] = None
issuer: Optional[str] = None
oauth_metadata_url: Optional[StrHttpUrl] = None
authorize_url: Optional[StrHttpUrl] = None
audience: Optional[str] = None
default_scope: str = "openid profile email"
client_id: Optional[str] = None
client_secret: Optional[str] = None
custom_oauth_metadata: Optional[OAuthMetadataDict] = None
setup_proxies: bool = False
setup_fake_dynamic_registration: bool = True
metadata_path: str = "/.well-known/oauth-authorization-server"
class OAuthMetadata:
issuer: StrHttpUrl
authorization_endpoint: Optional[StrHttpUrl] = None
token_endpoint: StrHttpUrl
scopes_supported: List[str] = ["openid", "profile", "email"]
response_types_supported: List[str] = ["code"]
grant_types_supported: List[str] = ["authorization_code", "client_credentials"]
token_endpoint_auth_methods_supported: List[str] = ["none"]
code_challenge_methods_supported: List[str] = ["S256"]
registration_endpoint: Optional[StrHttpUrl] = Nonefrom typing import Dict, Any, Union, List, Annotated
from pydantic import HttpUrl
from pydantic.main import IncEx
class HTTPRequestInfo:
"""HTTP request information passed to MCP tools."""
method: str
path: str
headers: Dict[str, str]
cookies: Dict[str, str]
query_params: Dict[str, str]
body: Any
# Type aliases
StrHttpUrl = Annotated[Union[str, HttpUrl], HttpUrl]
OAuthMetadataDict = Annotated[Union[Dict[str, Any], OAuthMetadata], OAuthMetadata]class ClientRegistrationRequest:
"""OAuth 2.0 dynamic client registration request."""
redirect_uris: List[str]
client_name: Optional[str] = None
grant_types: Optional[List[str]] = ["authorization_code"]
token_endpoint_auth_method: Optional[str] = "none"
class ClientRegistrationResponse:
"""OAuth 2.0 dynamic client registration response."""
client_id: str
client_id_issued_at: int
client_secret: Optional[str] = None
client_secret_expires_at: int = 0
redirect_uris: List[str]
grant_types: List[str]
token_endpoint_auth_method: str
client_name: str