引言
在当前AI快速发展的时代,如何让AI模型更便捷地与后端服务交互成为了开发者面临的重要挑战。Model Context Protocol (MCP)作为一个新兴协议,为AI模型提供了调用外部工具的能力,而FastAPI-MCP则是一个革命性的工具,它能够自动将现有的FastAPI应用转换为MCP服务器,实现AI与API的无缝集成。本文将深入探讨FastAPI-MCP的核心功能、使用方法及应用场景。
什么是FastAPI-MCP?
FastAPI-MCP是一个零配置工具,能够自动将FastAPI应用的所有端点转换为符合Model Context Protocol(MCP)规范的工具。它的主要特点包括:
- 零配置:只需几行代码即可集成,无需额外开发工作
- 自动发现:自动识别并转换FastAPI应用中的所有端点
- 完整兼容:保留原有API的请求模型、响应模型和文档
- 灵活部署:可以直接挂载到FastAPI应用中,也可以单独部署
MCP协议允许AI模型(如Claude、GPT等)调用外部工具来完成复杂任务,而FastAPI-MCP则简化了这些工具的创建过程,让开发者能够快速将现有服务暴露给AI模型使用。
安装与基本使用
安装
推荐使用uv(一个快速的Python包安装工具)进行安装:
uv add fastapi-mcp
或者使用传统的pip安装:
pip install fastapi-mcp
基本使用
FastAPI-MCP的基本使用非常简单,只需几行代码即可完成:
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI()
# 创建MCP服务器
mcp = FastApiMCP(
app,
name="My API MCP",
description="My API description",
base_url="http://localhost:8000",
)
# 将MCP服务器挂载到FastAPI应用
mcp.mount()
完成上述配置后,一个自动生成的MCP服务器将在/mcp
路径上可用。值得注意的是,虽然base_url
参数是可选的,但强烈建议提供,因为它告诉MCP服务器在调用工具时要发送API请求的位置。
高级功能与配置
工具命名
FastAPI-MCP使用FastAPI路由的operation_id
作为MCP工具名称。如果没有指定operation_id
,FastAPI会自动生成一个,但这些自动生成的名称可能不够直观。
比较以下两种端点定义:
# 自动生成的operation_id(类似于"read_user_users__user_id__get")
@app.get("/users/{user_id}")
async def read_user(user_id: int):
return {"user_id": user_id}
# 显式指定operation_id(工具将被命名为"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
参数。
自定义架构描述
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, # 在工具描述中包含所有可能的响应架构
describe_full_response_schema=True # 在工具描述中包含完整的JSON架构
)
mcp.mount()
自定义暴露的端点
可以通过OpenAPI操作ID或标签控制哪些FastAPI端点作为MCP工具暴露:
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI()
# 仅包含特定操作
mcp = FastApiMCP(
app,
include_operations=["get_user", "create_user"]
)
# 排除特定操作
mcp = FastApiMCP(
app,
exclude_operations=["delete_user"]
)
# 仅包含具有特定标签的操作
mcp = FastApiMCP(
app,
include_tags=["users", "public"]
)
# 排除具有特定标签的操作
mcp = FastApiMCP(
app,
exclude_tags=["admin", "internal"]
)
# 组合操作ID和标签(包含模式)
mcp = FastApiMCP(
app,
include_operations=["user_login"],
include_tags=["public"]
)
mcp.mount()
关于过滤的注意事项:
- 不能同时使用
include_operations
和exclude_operations
- 不能同时使用
include_tags
和exclude_tags
- 可以组合操作过滤和标签过滤(例如,同时使用
include_operations
和include_tags
) - 组合过滤器时,将采用贪婪方法,匹配任一条件的端点将被包含
与原始FastAPI应用分离部署
不限于在创建MCP的同一FastAPI应用中提供服务,可以从一个FastAPI应用创建MCP服务器,并将其挂载到另一个应用:
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
# 你的API应用
api_app = FastAPI()
# ... 在api_app上定义API端点 ...
# 用于MCP服务器的单独应用
mcp_app = FastAPI()
# 从API应用创建MCP服务器
mcp = FastApiMCP(
api_app,
base_url="http://api-host:8001", # API应用将运行的URL
)
# 将MCP服务器挂载到单独的应用
mcp.mount(mcp_app)
# 现在可以分别运行两个应用:
# 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()
# ... 定义初始端点 ...
# 创建MCP服务器
mcp = FastApiMCP(app)
mcp.mount()
# 在MCP服务器创建后添加新端点
@app.get("/new/endpoint/", operation_id="new_endpoint")
async def new_endpoint():
return {"message": "Hello, world!"}
# 刷新MCP服务器以包含新端点
mcp.setup_server()
连接到MCP服务器
使用SSE连接
一旦集成了MCP的FastAPI应用运行起来,可以使用任何支持SSE的MCP客户端(如Cursor)连接到它:
- 运行应用
- 在Cursor -> Settings -> MCP中,使用MCP服务器端点URL(例如
http://localhost:8000/mcp
)作为sse - Cursor将自动发现所有可用的工具和资源
使用mcp-proxy stdio连接
如果MCP客户端不支持SSE(例如Claude Desktop):
- 运行应用
- 安装mcp-proxy,例如:
uv tool install mcp-proxy
- 在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的路径。
应用场景
FastAPI-MCP的发布为AI与后端服务的集成带来了广阔的应用前景,典型用例包括:
- 数据分析:AI代理可以通过API直接访问数据处理端点,实现实时分析
- 内容管理:AI工具可以调用CMS接口,高效完成内容创建与更新
- 电子商务:AI助手可以通过API查询库存、下单或获取产品信息
- 自动化工作流:企业可以通过API实现跨系统的复杂自动化任务
得益于其与Claude、Cursor等MCP客户端的兼容性,FastAPI-MCP已成为开发者快速构建AI驱动应用的首选工具。
实际案例:构建智能客服系统
下面是一个构建智能客服系统的简单示例,通过将客户支持API暴露为MCP工具,使AI助手能够回答问题、查找订单和创建支持工单:
from fastapi import FastAPI, Depends, HTTPException
from fastapi_mcp import FastApiMCP
from pydantic import BaseModel
from typing import List, Optional
import databases
import sqlalchemy
# 数据库设置(示例)
DATABASE_URL = "sqlite:///./test.db"
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
# 定义模型
class OrderBase(BaseModel):
customer_id: str
total_amount: float
status: str
class Order(OrderBase):
id: int
class TicketCreate(BaseModel):
customer_id: str
subject: str
description: str
class Ticket(TicketCreate):
id: int
status: str = "open"
# 创建FastAPI应用
app = FastAPI(title="Customer Support API")
# 端点定义
@app.get("/orders/{customer_id}", response_model=List[Order], operation_id="get_customer_orders")
async def get_customer_orders(customer_id: str):
query = "SELECT * FROM orders WHERE customer_id = :customer_id"
return await database.fetch_all(query=query, values={"customer_id": customer_id})
@app.get("/order/{order_id}", response_model=Order, operation_id="get_order_details")
async def get_order_details(order_id: int):
query = "SELECT * FROM orders WHERE id = :order_id"
order = await database.fetch_one(query=query, values={"order_id": order_id})
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return order
@app.post("/tickets/", response_model=Ticket, operation_id="create_support_ticket")
async def create_support_ticket(ticket: TicketCreate):
query = """
INSERT INTO tickets(customer_id, subject, description, status)
VALUES (:customer_id, :subject, :description, 'open')
RETURNING id, customer_id, subject, description, status
"""
return await database.fetch_one(
query=query,
values={
"customer_id": ticket.customer_id,
"subject": ticket.subject,
"description": ticket.description
}
)
@app.get("/faqs/{query}", operation_id="search_faq")
async def search_faq(query: str):
# 这里可以实现FAQ搜索逻辑
faqs = [
{"question": "如何重置密码?", "answer": "访问登录页面,点击'忘记密码'链接,然后按照说明操作。"},
{"question": "何时会收到退款?", "answer": "退款通常在退货被处理后的3-5个工作日内处理。"},
# 更多FAQs...
]
return {"results": [faq for faq in faqs if query.lower() in faq["question"].lower()]}
# 创建并挂载MCP服务器
mcp = FastApiMCP(
app,
name="Customer Support MCP",
description="Customer support API for AI assistants",
base_url="http://localhost:8000",
)
mcp.mount()
# 启动事件
@app.on_event("startup")
async def startup():
await database.connect()
# 关闭事件
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
有了这个设置,AI助手可以调用这些API端点来:
- 查找客户的订单历史
- 获取特定订单的详细信息
- 为客户创建支持工单
- 搜索常见问题解答
这极大地增强了AI助手的能力,使其不仅能够提供基于其训练数据的信息,还能与后端系统交互,获取实时数据并执行操作。
结论
FastAPI-MCP作为一个零配置工具,为AI模型与后端服务的集成提供了革命性的解决方案。它极大地简化了将现有FastAPI应用暴露为MCP工具的过程,使开发者能够快速构建AI驱动的应用,而无需大量的额外开发工作。
随着MCP协议的普及,FastAPI-MCP有望成为AI与API交互的标准工具,推动AI应用的快速落地。无论是构建智能客服系统、数据分析工具,还是自动化工作流,FastAPI-MCP都为开发者提供了强大而灵活的解决方案。