Cover image

一种用于自动将FastAPI端点作为模型上下文协议(MCP)工具的零配置工具。

3 years

Works with Finder

19

Github Watches

174

Github Forks

2k

Github Stars

fastapi-to-mcp

FastAPI-MCP

A zero-configuration tool for automatically exposing FastAPI endpoints as Model Context Protocol (MCP) tools.

PyPI version Python Versions FastAPI CI codecov

fastapi-mcp-usage

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

Installation

We recommend using uv, a fast Python package installer:

uv add fastapi-mcp

Alternatively, you can install with pip:

pip install fastapi-mcp

Basic Usage

The simplest way to use FastAPI-MCP is to add an MCP server directly to your FastAPI application:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
    app,

    # Optional parameters
    name="My API MCP",
    description="My API description",
    base_url="http://localhost:8000",
)

# Mount the MCP server directly to your FastAPI app
mcp.mount()

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

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.

Tool Naming

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.

Compare these two endpoint definitions:

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

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

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
    app,
    name="My API MCP",
    base_url="http://localhost:8000",
    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:

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:

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,
    base_url="http://api-host:8001",  # The URL where the API app will be running
)

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

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

Examples

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

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

  1. Run your application.

  2. Install mcp-proxy, for example: uv tool install mcp-proxy.

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

On Windows:

{
  "mcpServers": {
    "my-api-mcp-proxy": {
        "command": "mcp-proxy",
        "args": ["http://127.0.0.1:8000/mcp"]
    }
  }
}

On MacOS:

{
  "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.

  1. Claude Desktop will discover all available tools and resources automatically

Development and Contributing

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

Before you get started, please see our Contribution Guide.

Community

Join MCParty Slack community to connect with other MCP enthusiasts, ask questions, and share your experiences with FastAPI-MCP.

Requirements

  • Python 3.10+ (Recommended 3.12)
  • uv

License

MIT License. Copyright (c) 2024 Tadata Inc.

相关推荐

  • https://zenepic.net
  • Embark on a thrilling diplomatic quest across a galaxy on the brink of war. Navigate complex politics and alien cultures to forge peace and avert catastrophe in this immersive interstellar adventure.

  • Benedikt Ess
  • FindetundanalysiertOnlineProdukteeinschlielichAmazonnachVolumenBewertungenundPreis

  • https://thrive-vibes-hub.com
  • I specialize in identifying 'Novel Foods' in ingredient lists.

  • pontusab
  • 光标与风浪冲浪社区,查找规则和MCP

  • av
  • 毫不费力地使用一个命令运行LLM后端,API,前端和服务。

  • GeyserMC
  • 与Minecraft客户端/服务器通信的库。

  • 1Panel-dev
  • 🔥1Panel提供了直观的Web接口和MCP服务器,用于在Linux服务器上管理网站,文件,容器,数据库和LLMS。

  • awslabs
  • AWS MCP服务器 - 将AWS最佳实践直接带入您的开发工作流程的专门MCP服务器

  • WangRongsheng
  • 🧑‍🚀 llm 资料总结(数据处理、模型训练、模型部署、 o1 模型、mcp 、小语言模型、视觉语言模型)|摘要世界上最好的LLM资源。

  • appcypher
  • 很棒的MCP服务器 - 模型上下文协议服务器的策划列表

  • GLips
  • MCP服务器向像光标这样的AI编码代理提供FIGMA布局信息

  • Byaidu
  • PDF科学纸翻译带有保留格式的pdf -基于ai完整保留排版的pdf文档全文双语翻译

  • n8n-io
  • 具有本机AI功能的公平代码工作流程自动化平台。将视觉构建与自定义代码,自宿主或云相结合,400+集成。

  • activepieces
  • AI代理和MCPS&AI工作流程自动化•(AI代理280+ MCP服务器)•AI Automation / MCPS的AI Automation / AI Agent•AI Workfrows&AI代理•AI代理的MCPS

    Reviews

    3 (1)
    Avatar
    user_YVTsPNVK
    2025-04-17

    As a dedicated user of the fastapi_mcp application, I am genuinely impressed with tadata-org's work. This tool seamlessly integrates with FastAPI, enhancing my web development experience exponentially. The documentation is clear, and the community support is commendable. A must-have for anyone working with FastAPI!