Skip to content

Commit 69754e0

Browse files
author
Shira Ayal
authored
Merge pull request #84 from shira-ayal/documentation-updates
Documentation updates
2 parents dcd50e6 + 0cffce6 commit 69754e0

17 files changed

+423
-322
lines changed

README.md

Lines changed: 15 additions & 229 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,10 @@
1616

1717
## Features
1818

19-
- **Direct integration** - Mount an MCP server directly to your FastAPI app
20-
- **Zero configuration** required - just point it at your FastAPI app and it works
21-
- **Automatic discovery** of all FastAPI endpoints and conversion to MCP tools
22-
- **Preserving schemas** of your request models and response models
23-
- **Preserve documentation** of all your endpoints, just as it is in Swagger
24-
- **Flexible deployment** - Mount your MCP server to the same app, or deploy separately
19+
- **Zero configuration** - Just point it at your FastAPI app and it works, with automatic discovery of endpoints and conversion to MCP tools
20+
- **Schema & docs preservation** - Keep the same request/response models and preserve documentation of all your endpoints
21+
- **Flexible deployment** - Mount your MCP server to the same FastAPI application, or deploy separately
22+
- **Custom endpoint exposure** - Control which endpoints become MCP tools using operation IDs and tags
2523
- **ASGI transport** - Uses FastAPI's ASGI interface directly by default for efficient communication
2624

2725
## Installation
@@ -54,236 +52,24 @@ mcp = FastApiMCP(app)
5452
mcp.mount()
5553
```
5654

57-
That's it! Your auto-generated MCP server is now available at `https://app.base.url/mcp`.
55+
That's it! Your auto-generated MCP server is now available at `https://app.base.url/mcp`.
5856

59-
## Tool Naming
57+
> **Note on `base_url`**: While `base_url` is optional, it is highly recommended to provide it explicitly. The `base_url` tells the MCP server where to send API requests when tools are called. Without it, the library will attempt to determine the URL automatically, which may not work correctly in deployed environments where the internal and external URLs differ.
6058
61-
FastAPI-MCP uses the `operation_id` from your FastAPI routes as the MCP tool names. When you don't specify an `operation_id`, FastAPI auto-generates one, but these can be cryptic.
59+
## Documentation, Examples and Advanced Usage
6260

63-
Compare these two endpoint definitions:
61+
FastAPI-MCP provides comprehensive documentation in the `docs` folder:
62+
- [Best Practices](docs/00_BEST_PRACTICES.md) - Essential guidelines for converting APIs to MCP tools safely and effectively
63+
- [FAQ](docs/00_FAQ.md) - Frequently asked questions about usage, development and support
64+
- [Tool Naming](docs/01_tool_naming.md) - Best practices for naming your MCP tools using operation IDs
65+
- [Connecting to MCP Server](docs/02_connecting_to_the_mcp_server.md) - How to connect various MCP clients like Cursor and Claude Desktop
66+
- [Advanced Usage](docs/03_advanced_usage.md) - Advanced features like custom schemas, endpoint filtering, and separate deployment
6467

65-
```python
66-
# Auto-generated operation_id (something like "read_user_users__user_id__get")
67-
@app.get("/users/{user_id}")
68-
async def read_user(user_id: int):
69-
return {"user_id": user_id}
70-
71-
# Explicit operation_id (tool will be named "get_user_info")
72-
@app.get("/users/{user_id}", operation_id="get_user_info")
73-
async def read_user(user_id: int):
74-
return {"user_id": user_id}
75-
```
76-
77-
For clearer, more intuitive tool names, we recommend adding explicit `operation_id` parameters to your FastAPI route definitions.
78-
79-
To find out more, read FastAPI's official docs about [advanced config of path operations.](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/)
80-
81-
## Advanced Usage
82-
83-
FastAPI-MCP provides several ways to customize and control how your MCP server is created and configured. Here are some advanced usage patterns:
84-
85-
### Customizing Schema Description
86-
87-
```python
88-
from fastapi import FastAPI
89-
from fastapi_mcp import FastApiMCP
90-
91-
app = FastAPI()
92-
93-
mcp = FastApiMCP(
94-
app,
95-
name="My API MCP",
96-
describe_all_responses=True, # Include all possible response schemas in tool descriptions
97-
describe_full_response_schema=True # Include full JSON schema in tool descriptions
98-
)
99-
100-
mcp.mount()
101-
```
102-
103-
### Customizing Exposed Endpoints
104-
105-
You can control which FastAPI endpoints are exposed as MCP tools using Open API operation IDs or tags:
106-
107-
```python
108-
from fastapi import FastAPI
109-
from fastapi_mcp import FastApiMCP
110-
111-
app = FastAPI()
112-
113-
# Only include specific operations
114-
mcp = FastApiMCP(
115-
app,
116-
include_operations=["get_user", "create_user"]
117-
)
118-
119-
# Exclude specific operations
120-
mcp = FastApiMCP(
121-
app,
122-
exclude_operations=["delete_user"]
123-
)
124-
125-
# Only include operations with specific tags
126-
mcp = FastApiMCP(
127-
app,
128-
include_tags=["users", "public"]
129-
)
130-
131-
# Exclude operations with specific tags
132-
mcp = FastApiMCP(
133-
app,
134-
exclude_tags=["admin", "internal"]
135-
)
136-
137-
# Combine operation IDs and tags (include mode)
138-
mcp = FastApiMCP(
139-
app,
140-
include_operations=["user_login"],
141-
include_tags=["public"]
142-
)
143-
144-
mcp.mount()
145-
```
146-
147-
Notes on filtering:
148-
- You cannot use both `include_operations` and `exclude_operations` at the same time
149-
- You cannot use both `include_tags` and `exclude_tags` at the same time
150-
- You can combine operation filtering with tag filtering (e.g., use `include_operations` with `include_tags`)
151-
- When combining filters, a greedy approach will be taken. Endpoints matching either criteria will be included
152-
153-
### Deploying Separately from Original FastAPI App
154-
155-
You are not limited to serving the MCP on the same FastAPI app from which it was created.
156-
157-
You can create an MCP server from one FastAPI app, and mount it to a different app:
158-
159-
```python
160-
from fastapi import FastAPI
161-
from fastapi_mcp import FastApiMCP
162-
163-
# Your API app
164-
api_app = FastAPI()
165-
# ... define your API endpoints on api_app ...
166-
167-
# A separate app for the MCP server
168-
mcp_app = FastAPI()
169-
170-
# Create MCP server from the API app
171-
mcp = FastApiMCP(api_app)
172-
173-
# Mount the MCP server to the separate app
174-
mcp.mount(mcp_app)
175-
176-
# Now you can run both apps separately:
177-
# uvicorn main:api_app --host api-host --port 8001
178-
# uvicorn main:mcp_app --host mcp-host --port 8000
179-
```
180-
181-
### Adding Endpoints After MCP Server Creation
182-
183-
If you add endpoints to your FastAPI app after creating the MCP server, you'll need to refresh the server to include them:
184-
185-
```python
186-
from fastapi import FastAPI
187-
from fastapi_mcp import FastApiMCP
188-
189-
app = FastAPI()
190-
# ... define initial endpoints ...
191-
192-
# Create MCP server
193-
mcp = FastApiMCP(app)
194-
mcp.mount()
195-
196-
# Add new endpoints after MCP server creation
197-
@app.get("/new/endpoint/", operation_id="new_endpoint")
198-
async def new_endpoint():
199-
return {"message": "Hello, world!"}
200-
201-
# Refresh the MCP server to include the new endpoint
202-
mcp.setup_server()
203-
```
204-
205-
### Communication with the FastAPI App
206-
207-
FastAPI-MCP uses ASGI transport by default, which means it communicates directly with your FastAPI app without making HTTP requests. This is more efficient and doesn't require a base URL.
208-
209-
It's not even necessary that the FastAPI server will run. See the examples folder for more.
210-
211-
If you need to specify a custom base URL or use a different transport method, you can provide your own `httpx.AsyncClient`:
212-
213-
```python
214-
import httpx
215-
from fastapi import FastAPI
216-
from fastapi_mcp import FastApiMCP
217-
218-
app = FastAPI()
219-
220-
# Use a custom HTTP client with a specific base URL
221-
custom_client = httpx.AsyncClient(
222-
base_url="https://api.example.com",
223-
timeout=30.0
224-
)
225-
226-
mcp = FastApiMCP(
227-
app,
228-
http_client=custom_client
229-
)
230-
231-
mcp.mount()
232-
```
233-
234-
## Examples
235-
236-
See the [examples](examples) directory for complete examples.
237-
238-
## Connecting to the MCP Server using SSE
239-
240-
Once your FastAPI app with MCP integration is running, you can connect to it with any MCP client supporting SSE, such as Cursor:
241-
242-
1. Run your application.
243-
244-
2. In Cursor -> Settings -> MCP, use the URL of your MCP server endpoint (e.g., `http://localhost:8000/mcp`) as sse.
245-
246-
3. Cursor will discover all available tools and resources automatically.
247-
248-
## Connecting to the MCP Server using [mcp-proxy stdio](https://github.com/sparfenyuk/mcp-proxy?tab=readme-ov-file#1-stdio-to-sse)
249-
250-
If your MCP client does not support SSE, for example Claude Desktop:
251-
252-
1. Run your application.
253-
254-
2. Install [mcp-proxy](https://github.com/sparfenyuk/mcp-proxy?tab=readme-ov-file#installing-via-pypi), for example: `uv tool install mcp-proxy`.
255-
256-
3. Add in Claude Desktop MCP config file (`claude_desktop_config.json`):
257-
258-
On Windows:
259-
```json
260-
{
261-
"mcpServers": {
262-
"my-api-mcp-proxy": {
263-
"command": "mcp-proxy",
264-
"args": ["http://127.0.0.1:8000/mcp"]
265-
}
266-
}
267-
}
268-
```
269-
On MacOS:
270-
```json
271-
{
272-
"mcpServers": {
273-
"my-api-mcp-proxy": {
274-
"command": "/Full/Path/To/Your/Executable/mcp-proxy",
275-
"args": ["http://127.0.0.1:8000/mcp"]
276-
}
277-
}
278-
}
279-
```
280-
Find the path to mcp-proxy by running in Terminal: `which mcp-proxy`.
281-
282-
4. Claude Desktop will discover all available tools and resources automatically
68+
Check out the [examples directory](examples) for code samples demonstrating these features in action.
28369

28470
## Development and Contributing
28571

286-
Thank you for considering contributing to FastAPI-MCP! We encourage the community to post Issues and Pull Requests.
72+
Thank you for considering contributing to FastAPI-MCP! We encourage the community to post Issues and create Pull Requests.
28773

28874
Before you get started, please see our [Contribution Guide](CONTRIBUTING.md).
28975

README_zh-CN.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
<p align="center"><a href="https://github.com/tadata-org/fastapi_mcp"><img src="https://github.com/user-attachments/assets/1cba1bf2-2fa4-46c7-93ac-1e9bb1a95257" alt="fastapi-mcp-usage" height="400"/></a></p>
1616

17+
> 注意:最新版本请参阅 [README.md](README.md).
18+
1719
## 特点
1820

1921
- **直接集成** - 直接将 MCP 服务器挂载到您的 FastAPI 应用

docs/00_BEST_PRACTICES.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Best Practices for API to MCP Tool Conversion
2+
3+
This guide outlines best practices for converting standard APIs into Model Context Protocol (MCP) tools for use with AI agents. Proper tool design helps ensure LLMs can understand and safely use your APIs.
4+
5+
---
6+
7+
## Tool Selection
8+
9+
- **Be selective:**
10+
Avoid exposing every endpoint as a tool. LLM clients perform better with a limited number of well-defined tools, and providers often impose tool limits.
11+
12+
- **Prioritize safety:**
13+
Do **not** expose `PUT` or `DELETE` endpoints unless absolutely necessary. LLMs are non-deterministic and could unintentionally alter or damage systems or databases.
14+
15+
- **Focus on data retrieval:**
16+
Prefer `GET` endpoints that return data safely and predictably.
17+
18+
- **Emphasize meaningful workflows:**
19+
Expose endpoints that reflect clear, goal-oriented tasks. Tools with focused actions are easier for agents to understand and use effectively.
20+
21+
---
22+
23+
## Tool Naming
24+
25+
- **Use short, descriptive names:**
26+
Helps LLMs select and use the right tool. Know that some MCP clients restrict tool name length.
27+
28+
- **Follow naming constraints:**
29+
- Must start with a letter
30+
- Can include only letters, numbers, and underscores
31+
- Avoid hyphens (e.g., AWS Nova does **not** support them)
32+
- Use either `camelCase` or `snake_case` consistently across all tools
33+
34+
- **Ensure uniqueness:**
35+
Each tool name should be unique and clearly indicate its function.
36+
37+
---
38+
39+
## Documentation
40+
41+
- **Describe every tool meaningfully:**
42+
Provide a clear and concise summary of what each tool does.
43+
44+
- **Include usage examples and parameter descriptions:**
45+
These help LLMs understand how to use the tool correctly.
46+
47+
- **Standardize documentation across tools:**
48+
Keep formatting and structure consistent to maintain quality and readability.
49+
50+
---
51+
52+
By following these best practices, you can build safer, more intuitive MCP tools that enhance the capabilities of LLM agents.

docs/00_FAQ.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Frequently Asked Questions (FAQ)
2+
3+
## Usage
4+
### How do I configure HTTP request timeouts?
5+
By default, HTTP requests timeout after 5 seconds. If you have API endpoints that take longer to respond, you can configure a custom timeout by injecting your own httpx client.
6+
7+
For a working example, see [07_configure_http_timeout_example.py](examples/07_configure_http_timeout_example.py).
8+
9+
### Why are my tools not showing up in the MCP inspector?
10+
If you add endpoints after creating and mounting the MCP server, they won't be automatically registered as tools. You need to either:
11+
1. Move the MCP creation after all your endpoint definitions
12+
2. Call `mcp.setup_server()` after adding new endpoints to re-register all tools
13+
14+
For a working example, see [05_reregister_tools_example.py](examples/05_reregister_tools_example.py).
15+
16+
### Can I add custom tools other than FastAPI endpoints?
17+
Currently, FastApiMCP only supports tools that are derived from FastAPI endpoints. If you need to add custom tools that don't correspond to API endpoints, you can:
18+
1. Create a FastAPI endpoint that wraps your custom functionality
19+
2. Contribute to the project by implementing custom tool support
20+
21+
Follow the discussion in [issue #75](https://github.com/tadata-org/fastapi_mcp/issues/75) for updates on this feature request.
22+
If you have specific use cases for custom tools, please share them in the issue to help guide the implementation.
23+
24+
### How do I test my FastApiMCP server is working?
25+
To verify your FastApiMCP server is working properly, you can use the MCP Inspector tool. Here's how:
26+
27+
1. Start your FastAPI application
28+
2. Open a new terminal and run the MCP Inspector:
29+
```bash
30+
npx @modelcontextprotocol/inspector node build/index.js
31+
```
32+
3. Connect to your MCP server by entering the mount path URL (default: `http://127.0.0.1:8000/mcp`)
33+
4. Navigate to the `Tools` section and click `List Tools` to see all available endpoints
34+
5. Test an endpoint by:
35+
- Selecting a tool from the list
36+
- Filling in any required parameters
37+
- Clicking `Run Tool` to execute
38+
6. Check your server logs for additional debugging information if needed
39+
40+
This will help confirm that your MCP server is properly configured and your endpoints are accessible.
41+
42+
## Development
43+
44+
### Can I contribute to the project?
45+
Yes! Please read our [CONTRIBUTING.md](CONTRIBUTING.md) file for detailed guidelines on how to contribute to the project and where to start.
46+
47+
## Support
48+
49+
### Where can I get help?
50+
- Check the documentation
51+
- Open an issue on GitHub
52+
- Join our community chat [MCParty Slack community](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg)

0 commit comments

Comments
 (0)