FastAPI-MCP

MIT License
3,209
  • Linux
  • Apple

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

Integrations

  • Automatically exposes FastAPI endpoints as Model Context Protocol (MCP) tools, preserving schemas and documentation

  • Preserves documentation of all endpoints just as it is in Swagger

特征

  • 直接集成- 将 MCP 服务器直接安装到您的 FastAPI 应用中
  • 无需任何配置- 只需将其指向您的 FastAPI 应用程序即可工作
  • 自动发现所有 FastAPI 端点并转换为 MCP 工具
  • 保留请求模型和响应模型的模式
  • 保存所有端点的文档,就像在 Swagger 中一样
  • 灵活部署- 将您的 MCP 服务器安装到同一应用程序,或单独部署

安装

我们建议使用uv ,一个快速的 Python 包安装程序:

uv add fastapi-mcp

或者,您可以使用 pip 安装:

pip install fastapi-mcp

基本用法

使用 FastAPI-MCP 最简单的方法是将 MCP 服务器直接添加到你的 FastAPI 应用程序中:

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

就这样!您自动生成的 MCP 服务器现在可以在https://app.base.url/mcp上使用。

关于base_url注意事项base_url虽然base_url是可选的,但强烈建议明确提供。base_url 指示 MCP 服务器在调用工具时将 API 请求发送到哪里。如果没有它,库将尝试自动确定 URL,这在内部和外部 URL 不同的部署环境中可能无法正常工作。

工具命名

FastAPI-MCP 使用 FastAPI 路由中的operation_id作为 MCP 工具名称。如果您未指定operation_id ,FastAPI 会自动生成一个,但这些值可能比较隐晦。

比较这两个端点定义:

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

为了获得更清晰、更直观的工具名称,我们建议在 FastAPI 路由定义中添加明确的operation_id参数。

要了解更多信息,请阅读 FastAPI 官方文档中有关路径操作的高级配置。

高级用法

FastAPI-MCP 提供了多种方法来自定义和控制 MCP 服务器的创建和配置方式。以下是一些高级使用模式:

自定义架构描述

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

自定义暴露的端点

您可以使用 Open API 操作 ID 或标签来控制哪些 FastAPI 端点作为 MCP 工具公开:

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

过滤注意事项:

  • 不能同时使用include_operationsexclude_operations
  • 不能同时使用include_tagsexclude_tags
  • 您可以将操作过滤与标签过滤结合起来(例如,将include_operationsinclude_tags一起使用)
  • 组合筛选器时,将采用贪婪方法。符合任一条件的端点将被纳入

与原始 FastAPI 应用分开部署

您不限于在创建 MCP 的同一 FastAPI 应用上为其提供服务。

你可以从一个 FastAPI 应用创建一个 MCP 服务器,然后将其挂载到另一个应用:

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

MCP 服务器创建后添加端点

如果在创建 MCP 服务器后将端点添加到 FastAPI 应用,则需要刷新服务器以包含它们:

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

示例

请参阅示例目录以获取完整的示例。

使用 SSE 连接到 MCP 服务器

一旦你的集成了 MCP 的 FastAPI 应用运行起来,你就可以使用任何支持 SSE 的 MCP 客户端(例如 Cursor)连接到它:

  1. 运行您的应用程序。
  2. 在 Cursor -> Settings -> MCP 中,使用您的 MCP 服务器端点的 URL(例如, http://localhost:8000/mcp )作为 sse。
  3. Cursor 将自动发现所有可用的工具和资源。

使用mcp-proxy stdio连接到 MCP 服务器

如果您的 MCP 客户端不支持 SSE,例如 Claude Desktop:

  1. 运行您的应用程序。
  2. 安装mcp-proxy ,例如: uv tool install mcp-proxy
  3. 添加 Claude Desktop MCP 配置文件( claude_desktop_config.json ):

在 Windows 上:

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

在 MacOS 上:

{ "mcpServers": { "my-api-mcp-proxy": { "command": "/Full/Path/To/Your/Executable/mcp-proxy", "args": ["http://127.0.0.1:8000/mcp"] } } }

通过在终端中运行: which mcp-proxy来找到 mcp-proxy 的路径。

  1. Claude Desktop 将自动发现所有可用的工具和资源

开发与贡献

感谢您考虑为 FastAPI-MCP 做出贡献!我们鼓励社区发布问题 (Issues) 和拉取请求 (Pull Request)。

在开始之前,请参阅我们的贡献指南

社区

加入MCParty Slack 社区与其他 MCP 爱好者联系、提出问题并分享您使用 FastAPI-MCP 的经验。

要求

  • Python 3.10+(推荐3.12)
  • 紫外线

执照

MIT 许可证。版权所有 (c) 2024 Tadata Inc.

-
security - not tested
A
license - permissive license
-
quality - not tested

一种零配置工具,可自动将 FastAPI 端点公开为模型上下文协议 (MCP) 工具,从而允许 Claude 等 LLM 系统无需额外编码即可与您的 API 交互。

  1. Installation
    1. Basic Usage
      1. Tool Naming
        1. Advanced Usage
          1. Customizing Schema Description
          2. Customizing Exposed Endpoints
          3. Deploying Separately from Original FastAPI App
          4. Adding Endpoints After MCP Server Creation
        2. Examples
          1. Connecting to the MCP Server using SSE
            1. Connecting to the MCP Server using mcp-proxy stdio
              1. Development and Contributing
                1. Community
                  1. Requirements
                    1. License
                      ID: otm6rcvu3e