
在当今的 AI 开发世界中,应用程序和 AI 模型之间的无缝集成至关重要。模型上下文协议 (MCP) 通过允许 AI 模型访问外部工具和数据源来弥合这一差距。FastAPI MCP 是一个强大的工具,只需最少的配置即可将您现有的 FastAPI 端点转换为与 MCP 兼容的工具。本文将指导您设置和使用 FastAPI MCP 来增强您的 AI 应用程序。
一、FastAPI MCP 简介
FastAPI MCP 是一个零配置工具,可自动将您的 FastAPI 端点公开为模型上下文协议 (MCP) 工具。FastAPI MCP 的美妙之处在于它的简单性——它采用您现有的 API 端点并使它们可供 AI 模型访问,而无需您重写代码或创建单独的实现。
使用 FastAPI MCP,您可以:
- 自动将 FastAPI 端点转换为 MCP 工具;
- 保留 API 架构和文档;
- 将 MCP 服务器与 API 一起部署,或作为单独的服务部署;
- 自定义哪些终端节点作为工具公开;
- 控制工具描述的生成方式
PS: 通过将 Apidog MCP 服务器集成到您的 IDE 中来提升您的 AI 开发工作流程。这使您的 AI 助手能够实时访问 API 规范,使其能够生成代码、优化文档和简化数据模型创建,同时确保与您的 API 设计保持一致。
Apidog MCP 服务器介绍:https://apidog.com/blog/apidog-mcp-server/
Apidog MCP 服务器安装:https://www.npmjs.com/package/apidog-mcp-server
二、FastAPI MCP 入门
2.1 安装
在开始使用之前,需要安装 FastAPI MCP 包。下面介绍两种安装方式:
a)使用 uv(建议使用以加快安装速度):
uv add fastapi-mcp
b)使用pip
pip install fastapi-mcp
三、 FastAPI MCP基本实现
实现 FastAPI MCP 的最简单方法是将其直接挂载到您现有的 FastAPI 应用程序中。下面是一个最小示例:
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
# Your existing FastAPI app
app = FastAPI()
# Define your API endpoints
@app.get("/users/{user_id}", operation_id="get_user_info")
async def read_user(user_id: int):
return {"user_id": user_id}
# Add MCP server to your FastAPI app
mcp = FastApiMCP(
app,
name="My API MCP",
description="MCP server for my API",
base_url="<http://localhost:8000>"
)
# Mount the MCP server to your app
mcp.mount()
# Run your app as usual
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
只需这几行代码,FastAPI 应用程序现在就配备了一个可在 http://localhost:8000/mcp 访问的 MCP 服务器。现在支持MCP的大模型(例如 Claude)就可以与API 端点进行交互了。
四、工具命名的最佳实践
当 AI 模型与工具交互时,清晰的命名至关重要。FastAPI MCP 使用 FastAPI 路由中的 operation\_id 作为 MCP 工具名称。如果你没有指定 operation\_id,FastAPI 会自动生成一个,这可能对用户不太友好。
下面介绍两个终端节点定义方式:
# Auto-generated operation_id (e.g., "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}
第二种方法会创建一个更直观的工具名称,AI 模型会发现它更容易正确使用。始终提供显式 operation\_id 值,以便更清晰地使用工具名称。
五、高级配置
5.1 自定义Schema
FastAPI MCP 提供了一些选项来控制如何将 API 模式描述给 AI 模型:
mcp = FastApiMCP(
app,
name="My API MCP",
base_url="<http://localhost:8000>",
describe_all_responses=True, # Include all possible response schemas
describe_full_response_schema=True # Include full JSON schemas in descriptions
)
describe\_all\_responses 选项在工具描述中包括所有可能的响应架构,而 describe\_full\_response\_schema 选项包括完整的 JSON 架构,而不是简化版本。
5.2 筛选终端节点
您可能不希望所有 API 端点都作为 MCP 工具公开。FastAPI MCP 提供了几种方法来过滤哪些端点成为工具:
# 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
mcp = FastApiMCP(
app,
include_operations=["user_login"],
include_tags=["public"]
)
这些筛选功能使您可以精细控制哪些终端节点作为工具公开,从而使您能够在为 AI 模型提供必要功能的同时维护安全性。
5.3 部署选项
a)单独部署
虽然将 MCP 服务器挂载到现有的 FastAPI 应用程序很简单,但出于安全或架构原因,可能希望单独部署它。具体设置方法如下:
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
# Your API app
api_app = FastAPI()
# Define your API endpoints on api_app
@api_app.get("/users/{user_id}", operation_id="get_user_info")
async def read_user(user_id: int):
return {"user_id": user_id}
# 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
这种方法允许在不同的主机或端口上运行 API 和 MCP 服务器,从而提供更高的灵活性。
b)创建后更新工具
如果你在创建 MCP 服务器后向 FastAPI 应用程序添加新的端点,则需要刷新服务器来包含它们:
# 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()
# 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()
setup\_server()方法使用任何新端点更新 MCP 服务器,确保您的工具与 API 保持同步。
5.4 将 AI 模型连接到 MCP 服务器
运行MCP 集成的 FastAPI 应用程序后,您可以通过各种方式将 AI 模型连接到它:
a)使用服务器发送的事件 (SSE)
许多 MCP 客户端(如 Cursor)都支持用于实时通信的服务器发送事件 (SSE):
-
在启用 FastAPI MCP 的情况下运行应用程序;
-
在 Cursor 中,转到 设置 > MCP;
-
使用 MCP 服务器的端点(例如 http://localhost:8000/mcp)作为 SSE URL;
-
Cursor 将自动发现所有可用的工具和资源;
b)对其他客户端使用 MCP-Proxy
对于不直接支持 SSE 的客户端,例如 Claude Desktop,可以使用 mcp-proxy:
- 安装 mcp-proxy:
uv tool install mcp-proxy
- 将代理配置添加到 Claude Desktop 的 MCP 配置文件中
对于 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>"]
}
}
}
六、实际应用和优势
FastAPI MCP 为将 API 与 AI 模型集成开辟了一个充满可能性的世界:
-
数据访问 :允许 AI 模型查询您的数据库或数据服务;
-
文档处理 :使模型能够添加、检索或分析系统中的文档;
-
业务逻辑 :让模型通过 API 执行复杂的业务流程;
-
用户交互 :促进 AI 驱动的用户与应用程序的交互;
使用 FastAPI MCP 的主要优势包括:
- 开发效率 :重用现有 API,而不是构建单独的集成;
- 一致性 :维护 API 逻辑的单一事实来源;
- 维护简单 :对 API 的更新会自动传播到您的 MCP 工具;
- 安全性 :控制哪些端点暴露给 AI 模型