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.00
# FastAPI-MCP
1
2
Automatic 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.
3
4
## Package Information
5
6
- **Package Name**: fastapi-mcp
7
- **Language**: Python 3.10+
8
- **Installation**: `uv add fastapi-mcp` or `pip install fastapi-mcp`
9
- **Repository**: https://github.com/tadata-org/fastapi_mcp
10
- **License**: MIT
11
12
## Core Imports
13
14
```python
15
from fastapi_mcp import FastApiMCP
16
```
17
18
For authentication:
19
20
```python
21
from fastapi_mcp import FastApiMCP, AuthConfig
22
```
23
24
For OAuth metadata customization:
25
26
```python
27
from fastapi_mcp import FastApiMCP, AuthConfig, OAuthMetadata
28
```
29
30
For type annotations:
31
32
```python
33
from fastapi_mcp.types import HTTPRequestInfo
34
```
35
36
## Basic Usage
37
38
```python
39
from fastapi import FastAPI
40
from fastapi_mcp import FastApiMCP
41
42
# Create your FastAPI application
43
app = FastAPI(title="My API", description="Example API for MCP integration")
44
45
@app.get("/users/{user_id}")
46
async def get_user(user_id: int):
47
return {"id": user_id, "name": f"User {user_id}"}
48
49
@app.post("/users")
50
async def create_user(user: dict):
51
return {"id": 123, "name": user["name"], "created": True}
52
53
# Create MCP server from your FastAPI app
54
mcp_server = FastApiMCP(fastapi=app)
55
56
# Mount the MCP server (HTTP transport recommended)
57
mcp_server.mount_http()
58
59
# Your FastAPI app now has MCP endpoints at /mcp
60
# AI agents can connect and use your API endpoints as MCP tools
61
```
62
63
## Architecture
64
65
FastAPI-MCP uses a two-layer architecture:
66
67
- **OpenAPI Analysis**: Automatically analyzes your FastAPI application's OpenAPI schema to discover all API endpoints, request/response schemas, and documentation
68
- **MCP Conversion**: Converts each API endpoint into an MCP tool with proper type definitions, parameter validation, and response handling
69
- **Transport Layer**: Provides both HTTP and SSE (Server-Sent Events) transport options for MCP client communication
70
- **Authentication Integration**: Seamlessly integrates with FastAPI's dependency injection system for authentication and authorization
71
- **ASGI Transport**: Uses direct ASGI communication for efficient API calls without HTTP overhead
72
73
## Capabilities
74
75
### MCP Server Creation
76
77
Core functionality for creating MCP servers from FastAPI applications, with extensive configuration options for customizing tool generation, filtering operations, and handling responses.
78
79
```python { .api }
80
from typing import Dict, List, Any, Literal, Optional
81
from fastapi import FastAPI, APIRouter
82
from mcp.server.lowlevel.server import Server
83
import mcp.types as types
84
import httpx
85
86
class FastApiMCP:
87
def __init__(
88
self,
89
fastapi: FastAPI,
90
name: Optional[str] = None,
91
description: Optional[str] = None,
92
describe_all_responses: bool = False,
93
describe_full_response_schema: bool = False,
94
http_client: Optional[httpx.AsyncClient] = None,
95
include_operations: Optional[List[str]] = None,
96
exclude_operations: Optional[List[str]] = None,
97
include_tags: Optional[List[str]] = None,
98
exclude_tags: Optional[List[str]] = None,
99
auth_config: Optional[AuthConfig] = None,
100
headers: List[str] = ["authorization"]
101
): ...
102
103
def mount_http(
104
self,
105
router: Optional[FastAPI | APIRouter] = None,
106
mount_path: str = "/mcp"
107
) -> None: ...
108
109
def mount_sse(
110
self,
111
router: Optional[FastAPI | APIRouter] = None,
112
mount_path: str = "/sse"
113
) -> None: ...
114
115
def mount(
116
self,
117
router: Optional[FastAPI | APIRouter] = None,
118
mount_path: str = "/mcp",
119
transport: Literal["sse"] = "sse"
120
) -> None: ...
121
122
@property
123
def server(self) -> Server: ...
124
125
@property
126
def tools(self) -> List[types.Tool]: ...
127
128
@property
129
def operation_map(self) -> Dict[str, Dict[str, Any]]: ...
130
131
@property
132
def fastapi(self) -> FastAPI: ...
133
134
@property
135
def name(self) -> str: ...
136
137
@property
138
def description(self) -> str: ...
139
```
140
141
[MCP Server](./mcp-server.md)
142
143
### OAuth Authentication
144
145
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.
146
147
```python { .api }
148
class AuthConfig:
149
version: Literal["2025-03-26"] = "2025-03-26"
150
dependencies: Optional[Sequence[params.Depends]] = None
151
issuer: Optional[str] = None
152
oauth_metadata_url: Optional[StrHttpUrl] = None
153
authorize_url: Optional[StrHttpUrl] = None
154
audience: Optional[str] = None
155
default_scope: str = "openid profile email"
156
client_id: Optional[str] = None
157
client_secret: Optional[str] = None
158
custom_oauth_metadata: Optional[OAuthMetadataDict] = None
159
setup_proxies: bool = False
160
setup_fake_dynamic_registration: bool = True
161
metadata_path: str = "/.well-known/oauth-authorization-server"
162
163
class OAuthMetadata:
164
issuer: StrHttpUrl
165
authorization_endpoint: Optional[StrHttpUrl] = None
166
token_endpoint: StrHttpUrl
167
scopes_supported: List[str] = ["openid", "profile", "email"]
168
response_types_supported: List[str] = ["code"]
169
grant_types_supported: List[str] = ["authorization_code", "client_credentials"]
170
token_endpoint_auth_methods_supported: List[str] = ["none"]
171
code_challenge_methods_supported: List[str] = ["S256"]
172
registration_endpoint: Optional[StrHttpUrl] = None
173
```
174
175
[Authentication](./authentication.md)
176
177
## Types
178
179
### Core Types
180
181
```python { .api }
182
from typing import Dict, Any, Union, List, Annotated
183
from pydantic import HttpUrl
184
from pydantic.main import IncEx
185
186
class HTTPRequestInfo:
187
"""HTTP request information passed to MCP tools."""
188
method: str
189
path: str
190
headers: Dict[str, str]
191
cookies: Dict[str, str]
192
query_params: Dict[str, str]
193
body: Any
194
195
# Type aliases
196
StrHttpUrl = Annotated[Union[str, HttpUrl], HttpUrl]
197
OAuthMetadataDict = Annotated[Union[Dict[str, Any], OAuthMetadata], OAuthMetadata]
198
```
199
200
### Client Registration Types
201
202
```python { .api }
203
class ClientRegistrationRequest:
204
"""OAuth 2.0 dynamic client registration request."""
205
redirect_uris: List[str]
206
client_name: Optional[str] = None
207
grant_types: Optional[List[str]] = ["authorization_code"]
208
token_endpoint_auth_method: Optional[str] = "none"
209
210
class ClientRegistrationResponse:
211
"""OAuth 2.0 dynamic client registration response."""
212
client_id: str
213
client_id_issued_at: int
214
client_secret: Optional[str] = None
215
client_secret_expires_at: int = 0
216
redirect_uris: List[str]
217
grant_types: List[str]
218
token_endpoint_auth_method: str
219
client_name: str
220
```