Skip to content

Commit 7b954d2

Browse files
committed
WIP
1 parent e1b4834 commit 7b954d2

File tree

11 files changed

+871
-172
lines changed

11 files changed

+871
-172
lines changed

README.md

Lines changed: 103 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
# FastAPI-MCP
22

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.
44

55
[![PyPI version](https://badge.fury.io/py/fastapi-mcp.svg)](https://pypi.org/project/fastapi-mcp/)
66
[![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-mcp.svg)](https://pypi.org/project/fastapi-mcp/)
77

88
## Features
99

10-
- **Automatic discovery** of all FastAPI endpoints in your application
10+
- **Direct integration** - Mount an MCP server directly to your FastAPI app
1111
- **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
1413
- **Type-safe conversion** from FastAPI endpoints to MCP tools
1514
- **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
1816

1917
## Installation
2018

@@ -28,163 +26,149 @@ For detailed installation instructions and alternative methods, see [INSTALL.md]
2826

2927
## Usage
3028

31-
### Generate an MCP server from a FastAPI app
29+
### Direct integration (Recommended)
3230

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:
3632

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
3936

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()
4339

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}
4545

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
4859
```
4960

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.
5162

52-
```bash
53-
fastapi-mcp run
54-
```
63+
### Legacy CLI Usage
5564

56-
### Install the server for Claude
65+
The CLI is still available for backward compatibility:
5766

5867
```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
5978
fastapi-mcp install
6079
```
6180

6281
## How It Works
6382

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
6592

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
7294

73-
## Example
95+
See the [examples](examples) directory for complete examples.
7496

75-
Original FastAPI code:
97+
### Simple direct integration example:
7698

7799
```python
78100
from fastapi import FastAPI
79-
from pydantic import BaseModel
80-
81-
app = FastAPI()
101+
from fastapi_mcp import add_mcp_server
82102

83-
class Item(BaseModel):
84-
name: str
85-
price: float
86-
is_offer: bool = None
103+
app = FastAPI(title="Simple API")
87104

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}!"}
92109

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")
98112

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()
152119

153120
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)
156123
```
157124

158-
## Integration with FastAPI
125+
## Connecting to the MCP Server
159126

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:
161128

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
165132

166-
If your API requires authentication, you can customize the generated server code to include the necessary headers or tokens.
133+
## Advanced Configuration
167134

168-
## Using with Claude
135+
FastAPI-MCP provides several options for advanced configuration:
169136

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+
```
171148

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:
176150

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")
178156

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+
```
180165

181166
## Requirements
182167

183168
- Python 3.10+
184169
- FastAPI 0.100.0+
185170
- Pydantic 2.0.0+
186-
- mcp 1.3.0+
187-
- requests 2.25.0+
171+
- MCP 1.3.0+
188172

189173
## Contributing
190174

examples/README.md

Lines changed: 46 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,66 @@
11
# FastAPI-MCP Examples
22

3-
This directory contains examples of using FastAPI-MCP to generate MCP servers from FastAPI applications.
3+
This directory contains examples of using FastAPI-MCP to integrate Model Context Protocol (MCP) servers with FastAPI applications.
44

5-
## Sample App
5+
## Examples
66

7-
The `sample_app.py` file contains a simple FastAPI application with CRUD operations for an "Item" resource.
7+
### `simple_integration.py`
88

9-
To run the FastAPI application:
9+
Demonstrates the direct integration approach, where an MCP server is mounted directly to a FastAPI application.
1010

11-
```bash
12-
python sample_app.py
13-
```
11+
Features:
12+
- FastAPI app with CRUD operations for items
13+
- MCP server mounted at `/mcp`
14+
- Automatic conversion of API endpoints to MCP tools
15+
- Custom MCP tool not based on an API endpoint
1416

15-
To generate an MCP server from the sample app:
17+
To run this example:
1618

1719
```bash
18-
cd .. # Go to the root directory
19-
python -m fastapi_mcp generate examples/sample_app.py
20+
# From the examples directory
21+
python run_example.py
22+
23+
# Or directly
24+
uvicorn simple_integration:app --reload
2025
```
2126

22-
This will create a `mcp_server` directory with the generated MCP server.
27+
Then visit:
28+
- API documentation: http://localhost:8000/docs
29+
- MCP server endpoint: http://localhost:8000/mcp
2330

24-
To preview the generated MCP server:
31+
### `sample_app.py`
2532

26-
```bash
27-
python -m fastapi_mcp preview
28-
```
33+
Original example app to demonstrate the legacy code generation approach.
2934

30-
To run the generated MCP server:
35+
To use with the CLI:
3136

3237
```bash
33-
python -m fastapi_mcp run
38+
# Generate MCP server
39+
fastapi-mcp generate sample_app.py
40+
41+
# Preview the generated server
42+
fastapi-mcp preview
43+
44+
# Run the sample app
45+
uvicorn sample_app:app --reload
46+
47+
# In another terminal, run the MCP server
48+
fastapi-mcp run
3449
```
3550

36-
## How It Works
51+
## Using with Claude
52+
53+
To connect Claude to your MCP server:
54+
55+
1. Run any of the examples above
56+
2. In Claude, use the URL of your MCP server (e.g., `http://localhost:8000/mcp`)
57+
3. Claude will discover the available tools and resources automatically
58+
59+
## What's Next?
3760

38-
1. FastAPI-MCP discovers all endpoints in the FastAPI application
39-
2. It converts the endpoints to MCP tools
40-
3. It generates a standalone MCP server
41-
4. It preserves documentation and type information
61+
These examples demonstrate the basic functionality of FastAPI-MCP. For more advanced use cases, you can:
4262

43-
The generated MCP server can be used with any MCP client, such as Claude.
63+
- Add authentication to your API endpoints
64+
- Customize the MCP server with additional capabilities
65+
- Add custom MCP tools that go beyond your API functionality
66+
- Deploy your integrated app to a production environment

examples/run_example.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/usr/bin/env python
2+
"""
3+
Run the FastAPI-MCP example.
4+
"""
5+
6+
import uvicorn
7+
8+
if __name__ == "__main__":
9+
print("Starting FastAPI-MCP example...")
10+
print("Visit http://localhost:8000/docs to see the API documentation")
11+
print("Your MCP server is available at http://localhost:8000/mcp")
12+
13+
uvicorn.run(
14+
"simple_integration:app",
15+
host="127.0.0.1",
16+
port=8000,
17+
reload=True,
18+
)

0 commit comments

Comments
 (0)