1
1
# FastAPI-MCP
2
2
3
- A magical, zero-configuration tool for generating Model Context Protocol (MCP) servers from FastAPI applications.
3
+ A zero-configuration tool for integrating Model Context Protocol (MCP) servers with FastAPI applications.
4
4
5
5
[ ![ PyPI version] ( https://badge.fury.io/py/fastapi-mcp.svg )] ( https://pypi.org/project/fastapi-mcp/ )
6
6
[ ![ Python Versions] ( https://img.shields.io/pypi/pyversions/fastapi-mcp.svg )] ( https://pypi.org/project/fastapi-mcp/ )
7
7
8
8
## Features
9
9
10
- - ** Automatic discovery ** of all FastAPI endpoints in your application
10
+ - ** Direct integration ** - Mount an MCP server directly to your FastAPI app
11
11
- ** Zero configuration** required - just point it at your FastAPI app and it works
12
- - ** CLI tool** for easy generation and execution of MCP servers
13
- - ** Stdio support** for MCP protocol communication
12
+ - ** Automatic discovery** of all FastAPI endpoints and conversion to MCP tools
14
13
- ** Type-safe conversion** from FastAPI endpoints to MCP tools
15
14
- ** Documentation preservation** from FastAPI to MCP
16
- - ** Claude integration** for easy installation and use with Claude desktop application
17
- - ** API Integration** - automatically makes HTTP requests to your FastAPI endpoints
15
+ - ** Custom tools** - Add custom MCP tools alongside your API endpoints
18
16
19
17
## Installation
20
18
@@ -28,163 +26,149 @@ For detailed installation instructions and alternative methods, see [INSTALL.md]
28
26
29
27
## Usage
30
28
31
- ### Generate an MCP server from a FastAPI app
29
+ ### Direct integration (Recommended)
32
30
33
- ``` bash
34
- # Point to a FastAPI application file or module
35
- fastapi-mcp generate app.py
31
+ The simplest way to use FastAPI-MCP is to add an MCP server directly to your FastAPI application:
36
32
37
- # Or specify the app variable if it's not named 'app'
38
- fastapi-mcp generate module.py:my_app
33
+ ``` python
34
+ from fastapi import FastAPI
35
+ from fastapi_mcp import add_mcp_server
39
36
40
- # Use a custom base URL for the API endpoints (default: http://localhost:8000)
41
- fastapi-mcp generate app.py --base-url https://api.example.com
42
- ```
37
+ # Create your FastAPI app
38
+ app = FastAPI()
43
39
44
- ### Preview the generated MCP server
40
+ # Define your endpoints...
41
+ @app.get (" /items/{item_id} " )
42
+ def read_item (item_id : int , q : str = None ):
43
+ """ Get details for a specific item"""
44
+ return {" item_id" : item_id, " q" : q}
45
45
46
- ``` bash
47
- fastapi-mcp preview
46
+ # Add an MCP server to your app
47
+ mcp_server = add_mcp_server(
48
+ app, # Your FastAPI app
49
+ mount_path = " /mcp" , # Where to mount the MCP server
50
+ name = " My API MCP" , # Name for the MCP server
51
+ base_url = " http://localhost:8000" # Base URL for API requests
52
+ )
53
+
54
+ # Optionally add custom MCP tools
55
+ @mcp_server.tool ()
56
+ async def get_item_count () -> int :
57
+ """ Get the total number of items in the database."""
58
+ return 42 # Your custom implementation
48
59
```
49
60
50
- ### Run the generated MCP server
61
+ Your FastAPI app will now have an MCP server mounted at the specified path, with all your API endpoints available as MCP tools.
51
62
52
- ``` bash
53
- fastapi-mcp run
54
- ```
63
+ ### Legacy CLI Usage
55
64
56
- ### Install the server for Claude
65
+ The CLI is still available for backward compatibility:
57
66
58
67
``` bash
68
+ # Generate an MCP server from a FastAPI app
69
+ fastapi-mcp generate app.py
70
+
71
+ # Preview the generated server
72
+ fastapi-mcp preview
73
+
74
+ # Run the generated server
75
+ fastapi-mcp run
76
+
77
+ # Install the server for Claude
59
78
fastapi-mcp install
60
79
```
61
80
62
81
## How It Works
63
82
64
- FastAPI-MCP automatically:
83
+ FastAPI-MCP:
84
+
85
+ 1 . Takes your FastAPI application
86
+ 2 . Creates an MCP server instance
87
+ 3 . Mounts the MCP server to your FastAPI app
88
+ 4 . Extracts endpoint information from your OpenAPI schema
89
+ 5 . Creates MCP tools that make HTTP requests to your API endpoints
90
+ 6 . Preserves documentation and type information
91
+ 7 . Registers the tools with the MCP server
65
92
66
- 1 . Discovers all FastAPI endpoints in your application
67
- 2 . Converts route handlers to MCP tools
68
- 3 . Maps request/response models to MCP schemas
69
- 4 . Preserves documentation and type information
70
- 5 . Generates a standalone MCP server that uses the official MCP Python SDK
71
- 6 . ** Makes actual HTTP requests** to the underlying FastAPI endpoints
93
+ ## Examples
72
94
73
- ## Example
95
+ See the [ examples ] ( examples ) directory for complete examples.
74
96
75
- Original FastAPI code :
97
+ ### Simple direct integration example :
76
98
77
99
``` python
78
100
from fastapi import FastAPI
79
- from pydantic import BaseModel
80
-
81
- app = FastAPI()
101
+ from fastapi_mcp import add_mcp_server
82
102
83
- class Item (BaseModel ):
84
- name: str
85
- price: float
86
- is_offer: bool = None
103
+ app = FastAPI(title = " Simple API" )
87
104
88
- @app.get (" /items/ {item_id }" )
89
- def read_item ( item_id : int , q : str = None ):
90
- """ Get details for a specific item """
91
- return {" item_id " : item_id, " q " : q }
105
+ @app.get (" /hello/ {name }" )
106
+ async def hello ( name : str ):
107
+ """ Say hello to someone """
108
+ return {" message " : f " Hello, { name } ! " }
92
109
93
- @app.put (" /items/{item_id} " )
94
- def update_item (item_id : int , item : Item):
95
- """ Update an item with new information"""
96
- return {" item_id" : item_id, " item" : item}
97
- ```
110
+ # Add MCP server
111
+ mcp_server = add_mcp_server(app, mount_path = " /mcp" )
98
112
99
- Generated MCP server:
100
-
101
- ``` python
102
- # Generated MCP server
103
- # Original FastAPI app: FastAPI
104
-
105
- from mcp.server import FastMCP
106
- import json
107
- import requests
108
- from typing import Dict, List, Optional, Union, Any
109
- try :
110
- from pydantic import BaseModel
111
- except ImportError :
112
- from pydantic.main import BaseModel
113
-
114
- class Item (BaseModel ):
115
- name: str
116
- price: float
117
- is_offer: Optional[bool ] = None
118
-
119
- # Original handler: __main__.read_item
120
- # Original handler: __main__.update_item
121
-
122
- mcp = FastMCP(" FastAPI" )
123
-
124
- @mcp.tool ()
125
- async def read_item (item_id : int , q : str = None ) -> Any:
126
- """ Get details for a specific item
127
-
128
- Original route: GET /items/{item_id}
129
- """
130
- # Original handler: __main__.read_item
131
- url = f ' http://localhost:8000/items/ { item_id} '
132
- params = {}
133
- if q is not None :
134
- params[' q' ] = q
135
- response = requests.get(url, params = params)
136
- response.raise_for_status()
137
- return response.json()
138
-
139
- @mcp.tool ()
140
- async def update_item (item_id : int , name : str , price : float , is_offer : bool = None ) -> Any:
141
- """ Update an item with new information
142
-
143
- Original route: PUT /items/{item_id}
144
- """
145
- # Original handler: __main__.update_item
146
- url = f ' http://localhost:8000/items/ { item_id} '
147
- item = Item(** {" name" : name, " price" : price, " is_offer" : is_offer})
148
- json_data = item.dict()
149
- response = requests.put(url, json = json_data)
150
- response.raise_for_status()
151
- return response.json()
113
+ # Optionally add custom tools
114
+ @mcp_server.tool ()
115
+ async def get_current_time ():
116
+ """ Get the current server time"""
117
+ from datetime import datetime
118
+ return datetime.now().isoformat()
152
119
153
120
if __name__ == " __main__" :
154
- # Run the MCP server
155
- mcp .run()
121
+ import uvicorn
122
+ uvicorn .run(app, host = " 127.0.0.1 " , port = 8000 )
156
123
```
157
124
158
- ## Integration with FastAPI
125
+ ## Connecting to the MCP Server
159
126
160
- The generated MCP server makes HTTP requests to your actual FastAPI server, which must be running separately. You can :
127
+ Once your FastAPI app with MCP integration is running, you can connect to it with any MCP client, such as Claude :
161
128
162
- 1 . Run your FastAPI application normally (e.g., with ` uvicorn app:app ` )
163
- 2 . Generate the MCP server with a base URL pointing to your running FastAPI server
164
- 3 . Run the MCP server separately to provide MCP tools for LLMs
129
+ 1 . Run your application
130
+ 2 . In Claude, use the URL of your MCP server endpoint (e.g., ` http://localhost:8000/mcp ` )
131
+ 3 . Claude will discover all available tools and resources automatically
165
132
166
- If your API requires authentication, you can customize the generated server code to include the necessary headers or tokens.
133
+ ## Advanced Configuration
167
134
168
- ## Using with Claude
135
+ FastAPI-MCP provides several options for advanced configuration:
169
136
170
- FastAPI-MCP makes it easy to use your API endpoints with Claude:
137
+ ``` python
138
+ mcp_server = add_mcp_server(
139
+ app,
140
+ mount_path = " /mcp" ,
141
+ name = " My Custom MCP Server" ,
142
+ description = " Custom description for the MCP server" ,
143
+ capabilities = {" streaming" : True }, # Set MCP capabilities
144
+ serve_tools = True , # Whether to serve API endpoints as MCP tools
145
+ base_url = " https://api.example.com" # Base URL for API requests
146
+ )
147
+ ```
171
148
172
- 1 . Generate an MCP server from your FastAPI app
173
- 2 . Install the server: ` fastapi-mcp install `
174
- 3 . Open Claude desktop app
175
- 4 . Your API endpoints will be available as tools to Claude
149
+ You can also create and mount an MCP server separately:
176
150
177
- ## Examples
151
+ ``` python
152
+ from fastapi_mcp import create_mcp_server, mount_mcp_server
153
+
154
+ # Create an MCP server
155
+ mcp_server = create_mcp_server(app, name = " My MCP Server" )
178
156
179
- For more examples, see the [ examples] ( examples ) directory.
157
+ # Add custom tools
158
+ @mcp_server.tool ()
159
+ async def custom_tool ():
160
+ return " Custom tool result"
161
+
162
+ # Mount the MCP server to the FastAPI app
163
+ mount_mcp_server(app, mcp_server, mount_path = " /mcp" )
164
+ ```
180
165
181
166
## Requirements
182
167
183
168
- Python 3.10+
184
169
- FastAPI 0.100.0+
185
170
- Pydantic 2.0.0+
186
- - mcp 1.3.0+
187
- - requests 2.25.0+
171
+ - MCP 1.3.0+
188
172
189
173
## Contributing
190
174
0 commit comments