Skip to content

Documentation updates #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 15 additions & 229 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@

## Features

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

## Installation
Expand Down Expand Up @@ -55,236 +53,24 @@ mcp = FastApiMCP(app)
mcp.mount()
```

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

## Tool Naming
> **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.

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.
## Documentation, Examples and Advanced Usage

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

```python
# Auto-generated operation_id (something like "read_user_users__user_id__get")
@app.get("/users/{user_id}")
async def read_user(user_id: int):
return {"user_id": user_id}

# Explicit operation_id (tool will be named "get_user_info")
@app.get("/users/{user_id}", operation_id="get_user_info")
async def read_user(user_id: int):
return {"user_id": user_id}
```

For clearer, more intuitive tool names, we recommend adding explicit `operation_id` parameters to your FastAPI route definitions.

To find out more, read FastAPI's official docs about [advanced config of path operations.](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/)

## Advanced Usage

FastAPI-MCP provides several ways to customize and control how your MCP server is created and configured. Here are some advanced usage patterns:

### Customizing Schema Description

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
app,
name="My API MCP",
describe_all_responses=True, # Include all possible response schemas in tool descriptions
describe_full_response_schema=True # Include full JSON schema in tool descriptions
)

mcp.mount()
```

### Customizing Exposed Endpoints

You can control which FastAPI endpoints are exposed as MCP tools using Open API operation IDs or tags:

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# Only include specific operations
mcp = FastApiMCP(
app,
include_operations=["get_user", "create_user"]
)

# Exclude specific operations
mcp = FastApiMCP(
app,
exclude_operations=["delete_user"]
)

# Only include operations with specific tags
mcp = FastApiMCP(
app,
include_tags=["users", "public"]
)

# Exclude operations with specific tags
mcp = FastApiMCP(
app,
exclude_tags=["admin", "internal"]
)

# Combine operation IDs and tags (include mode)
mcp = FastApiMCP(
app,
include_operations=["user_login"],
include_tags=["public"]
)

mcp.mount()
```

Notes on filtering:
- You cannot use both `include_operations` and `exclude_operations` at the same time
- You cannot use both `include_tags` and `exclude_tags` at the same time
- You can combine operation filtering with tag filtering (e.g., use `include_operations` with `include_tags`)
- When combining filters, a greedy approach will be taken. Endpoints matching either criteria will be included

### Deploying Separately from Original FastAPI App

You are not limited to serving the MCP on the same FastAPI app from which it was created.

You can create an MCP server from one FastAPI app, and mount it to a different app:

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

# Your API app
api_app = FastAPI()
# ... define your API endpoints on api_app ...

# A separate app for the MCP server
mcp_app = FastAPI()

# Create MCP server from the API app
mcp = FastApiMCP(api_app)

# Mount the MCP server to the separate app
mcp.mount(mcp_app)

# Now you can run both apps separately:
# uvicorn main:api_app --host api-host --port 8001
# uvicorn main:mcp_app --host mcp-host --port 8000
```

### Adding Endpoints After MCP Server Creation

If you add endpoints to your FastAPI app after creating the MCP server, you'll need to refresh the server to include them:

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
# ... define initial endpoints ...

# Create MCP server
mcp = FastApiMCP(app)
mcp.mount()

# Add new endpoints after MCP server creation
@app.get("/new/endpoint/", operation_id="new_endpoint")
async def new_endpoint():
return {"message": "Hello, world!"}

# Refresh the MCP server to include the new endpoint
mcp.setup_server()
```

### Communication with the FastAPI App

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.

It's not even necessary that the FastAPI server will run. See the examples folder for more.

If you need to specify a custom base URL or use a different transport method, you can provide your own `httpx.AsyncClient`:

```python
import httpx
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# Use a custom HTTP client with a specific base URL
custom_client = httpx.AsyncClient(
base_url="https://api.example.com",
timeout=30.0
)

mcp = FastApiMCP(
app,
http_client=custom_client
)

mcp.mount()
```

## Examples

See the [examples](examples) directory for complete examples.

## Connecting to the MCP Server using SSE

Once your FastAPI app with MCP integration is running, you can connect to it with any MCP client supporting SSE, such as Cursor:

1. Run your application.

2. In Cursor -> Settings -> MCP, use the URL of your MCP server endpoint (e.g., `http://localhost:8000/mcp`) as sse.

3. Cursor will discover all available tools and resources automatically.

## Connecting to the MCP Server using [mcp-proxy stdio](https://github.com/sparfenyuk/mcp-proxy?tab=readme-ov-file#1-stdio-to-sse)

If your MCP client does not support SSE, for example Claude Desktop:

1. Run your application.

2. Install [mcp-proxy](https://github.com/sparfenyuk/mcp-proxy?tab=readme-ov-file#installing-via-pypi), for example: `uv tool install mcp-proxy`.

3. Add in Claude Desktop MCP config file (`claude_desktop_config.json`):

On Windows:
```json
{
"mcpServers": {
"my-api-mcp-proxy": {
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8000/mcp"]
}
}
}
```
On MacOS:
```json
{
"mcpServers": {
"my-api-mcp-proxy": {
"command": "/Full/Path/To/Your/Executable/mcp-proxy",
"args": ["http://127.0.0.1:8000/mcp"]
}
}
}
```
Find the path to mcp-proxy by running in Terminal: `which mcp-proxy`.

4. Claude Desktop will discover all available tools and resources automatically
Check out the [examples directory](examples) for code samples demonstrating these features in action.

## Development and Contributing

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

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

Expand Down
2 changes: 2 additions & 0 deletions README_zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

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

> 注意:最新版本请参阅 [README.md](README.md).

## 特点

- **直接集成** - 直接将 MCP 服务器挂载到您的 FastAPI 应用
Expand Down
52 changes: 52 additions & 0 deletions docs/00_BEST_PRACTICES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Best Practices for API to MCP Tool Conversion

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.

---

## Tool Selection

- **Be selective:**
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.

- **Prioritize safety:**
Do **not** expose `PUT` or `DELETE` endpoints unless absolutely necessary. LLMs are non-deterministic and could unintentionally alter or damage systems or databases.

- **Focus on data retrieval:**
Prefer `GET` endpoints that return data safely and predictably.

- **Emphasize meaningful workflows:**
Expose endpoints that reflect clear, goal-oriented tasks. Tools with focused actions are easier for agents to understand and use effectively.

---

## Tool Naming

- **Use short, descriptive names:**
Helps LLMs select and use the right tool. Know that some MCP clients restrict tool name length.

- **Follow naming constraints:**
- Must start with a letter
- Can include only letters, numbers, and underscores
- Avoid hyphens (e.g., AWS Nova does **not** support them)
- Use either `camelCase` or `snake_case` consistently across all tools

- **Ensure uniqueness:**
Each tool name should be unique and clearly indicate its function.

---

## Documentation

- **Describe every tool meaningfully:**
Provide a clear and concise summary of what each tool does.

- **Include usage examples and parameter descriptions:**
These help LLMs understand how to use the tool correctly.

- **Standardize documentation across tools:**
Keep formatting and structure consistent to maintain quality and readability.

---

By following these best practices, you can build safer, more intuitive MCP tools that enhance the capabilities of LLM agents.
52 changes: 52 additions & 0 deletions docs/00_FAQ.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Frequently Asked Questions (FAQ)

## Usage
### How do I configure HTTP request timeouts?
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.

For a working example, see [07_configure_http_timeout_example.py](examples/07_configure_http_timeout_example.py).

### Why are my tools not showing up in the MCP inspector?
If you add endpoints after creating and mounting the MCP server, they won't be automatically registered as tools. You need to either:
1. Move the MCP creation after all your endpoint definitions
2. Call `mcp.setup_server()` after adding new endpoints to re-register all tools

For a working example, see [05_reregister_tools_example.py](examples/05_reregister_tools_example.py).

### Can I add custom tools other than FastAPI endpoints?
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:
1. Create a FastAPI endpoint that wraps your custom functionality
2. Contribute to the project by implementing custom tool support

Follow the discussion in [issue #75](https://github.com/tadata-org/fastapi_mcp/issues/75) for updates on this feature request.
If you have specific use cases for custom tools, please share them in the issue to help guide the implementation.

### How do I test my FastApiMCP server is working?
To verify your FastApiMCP server is working properly, you can use the MCP Inspector tool. Here's how:

1. Start your FastAPI application
2. Open a new terminal and run the MCP Inspector:
```bash
npx @modelcontextprotocol/inspector node build/index.js
```
3. Connect to your MCP server by entering the mount path URL (default: `http://127.0.0.1:8000/mcp`)
4. Navigate to the `Tools` section and click `List Tools` to see all available endpoints
5. Test an endpoint by:
- Selecting a tool from the list
- Filling in any required parameters
- Clicking `Run Tool` to execute
6. Check your server logs for additional debugging information if needed

This will help confirm that your MCP server is properly configured and your endpoints are accessible.

## Development

### Can I contribute to the project?
Yes! Please read our [CONTRIBUTING.md](CONTRIBUTING.md) file for detailed guidelines on how to contribute to the project and where to start.

## Support

### Where can I get help?
- Check the documentation
- Open an issue on GitHub
- Join our community chat [MCParty Slack community](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg)
Loading