1 模型概述
1.1 能力评估
FastAPI-MCP是一个开源工具,能将现有FastAPI应用端点自动转换为符合模型上下文协议(MCP) 的工具。它的核心能力主要体现在:
-
自动接口转换:无需手动编写适配代码,可自动扫描发现FastAPI应用中的所有端点,并将其转换为MCP兼容工具
-
接口规模:根据现有FastAPI应用的端点数量决定,支持动态扩展,新增端点无需重启即可实时同步到AI工具库
-
任务完成能力:使AI模型能够直接调用你的API接口,实现数据检索、业务处理、系统集成等多样化任务
1.2 技术特点
FastAPI-MCP在技术实现上具有多项突出特点:
-
零配置设计:通过解析FastAPI自动生成的OpenAPI文档,实现零配置转换,完整保留接口的请求/响应模型和Swagger文档
-
原生ASGI集成:采用FastAPI原生ASGI接口进行内部通信,消除HTTP协议开销,相比通用OpenAPI转换器性能显著提升
-
安全继承机制:完整继承FastAPI的依赖注入系统和Depends()安全模型,无需重写授权逻辑
-
双模部署:支持挂载到现有服务或独立部署,适应不同架构需求
1.3 应用场景
FastAPI-MCP适用于多种AI与API融合的场景:
-
安全AI数据检索:将敏感内部端点(如客户记录、库存数据)安全暴露给内部AI助手,继承现有权限控制
-
快速工具原型开发:开发者可使用标准FastAPI端点定义新功能,并立即通过MCP服务器暴露,加速AI团队测试迭代
-
统一基础设施管理:在相同ASGI实例上部署MCP服务器与现有API,简化容器化、监控和扩展
2 安装与部署方式
2.1 基础安装
FastAPI-MCP支持多种安装方式,以下是推荐方法:
使用uv安装(推荐)
使用pip安装
2.2 系统配置指南
Windows系统配置
-
安装uv包管理器(如未安装):
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
-
创建并激活虚拟环境:
uv venv
.\.venv\Scripts\activate
-
安装FastAPI-MCP:
macOS系统配置
-
使用Homebrew安装uv:
-
创建虚拟环境并激活:
uv venv
source .venv/bin/activate
-
安装FastAPI-MCP:
Linux系统配置
-
安装uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
-
创建虚拟环境并激活:
uv venv
source .venv/bin/activate
-
安装FastAPI-MCP:
2.3 常见安装问题与解决方案
依赖冲突问题
uv pip compile requirements.txt -o requirements_lock.txt
uv sync
虚拟环境激活失败
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
权限错误
pip install --user fastapi-mcp
3 配套客户端
3.1 主流客户端介绍
FastAPI-MCP兼容所有支持MCP协议的客户端,以下为常用选择:
Claude Desktop(免费)
Cursor IDE(免费+付费版)
Continue VS Code扩展(免费)
3.2 客户端配置详解
Claude Desktop自动配置
fastmcp install claude-desktop server.py --with pandas --with requests
Claude Desktop手动配置
编辑Claude Desktop配置文件:
{
"mcpServers": {
"my-server": {
"command": "uv",
"args": [
"run",
"--with", "fastmcp",
"--with", "pandas",
"fastmcp",
"run",
"server.py"
],
"env": {
"API_KEY": "your-api-key"
}
}
}
}
Cursor IDE配置
fastmcp install cursor server.py --workspace .
或手动编辑~/.cursor/mcp.json:
{
"mcpServers": {
"my-server": {
"command": "uv",
"args": [
"run",
"--python", "3.11",
"--with", "fastmcp",
"--with", "pandas",
"fastmcp",
"run",
"server.py"
]
}
}
}
4 案例讲解:用户管理系统AI助手
4.1 案例背景
假设我们有一个现有的FastAPI用户管理系统,希望让AI助手能够安全地查询用户信息和创建新用户,同时保持现有的权限验证机制。
4.2 完整代码实现
from fastapi import FastAPI, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr
from typing import List, Optional
from fastapi_mcp import FastApiMCP
import uvicorn
app = FastAPI(title="用户管理系统", version="1.0.0")
class User(BaseModel):
id: int
name: str
email: EmailStr
department: str
is_active: bool = True
class UserCreate(BaseModel):
name: str
email: EmailStr
department: str
fake_users_db = [
User(id=1, name="张三", email="zhangsan@company.com", department="技术部"),
User(id=2, name="李四", email="lisi@company.com", department="市场部"),
User(id=3, name="王五", email="wangwu@company.com", department="人事部"),
]
async def get_current_user(token: str = Depends(lambda x: "admin")):
"""模拟权限验证"""
if token != "admin":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="无效的认证令牌"
)
return {"username": "admin"}
@app.get("/users/", response_model=List[User], operation_id="list_users")
async def list_users(
current_user: dict = Depends(get_current_user),
department: Optional[str] = None,
skip: int = 0,
limit: int = 100
):
"""获取用户列表"""
users = fake_users_db
if department:
users = [user for user in users if user.department == department]
return users[skip : skip + limit]
@app.get("/users/{user_id}", response_model=User, operation_id="get_user")
async def get_user(
user_id: int,
current_user: dict = Depends(get_current_user)
):
"""根据ID获取用户信息"""
for user in fake_users_db:
if user.id == user_id:
return user
raise HTTPException(status_code=404, detail="用户不存在")
@app.post("/users/", response_model=User, operation_id="create_user")
async def create_user(
user_data: UserCreate,
current_user: dict = Depends(get_current_user)
):
"""创建新用户"""
new_id = max(user.id for user in fake_users_db) + 1
new_user = User(
id=new_id,
name=user_data.name,
email=user_data.email,
department=user_data.department
)
fake_users_db.append(new_user)
return new_user
mcp = FastApiMCP(
app,
name="用户管理MCP",
description="用户管理系统的AI助手接口",
base_url="http://localhost:8000",
)
mcp.mount()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
4.3 配置和测试
-
启动服务:
-
配置Claude Desktop:
fastmcp install claude-desktop main.py --env API_KEY=your-secret-key
-
测试功能:启动Claude Desktop后,AI助手现在可以:
-
查询所有用户列表
-
按部门筛选用户
-
根据ID查找特定用户
-
创建新用户
安全特性:所有AI发起的请求都会经过原有的get_current_user权限验证,确保系统安全。
5 使用成本与商业价值
5.1 使用成本分析
直接成本
-
零软件成本:FastAPI-MCP是完全开源的工具,无需支付许可费用
-
开发成本节约:相比手动编写MCP适配代码,可减少约70%的开发时间
-
维护成本降低:自动同步API变更,无需维护独立的MCP实现
基础设施成本
5.2 商业价值评估
效率提升价值
业务创新价值
技术优势价值
5.3 投资回报分析
根据实际应用数据,使用FastAPI-MCP带来的核心收益:
-
开发时间节约:传统MCP集成需要2-3周,使用FastAPI-MCP仅需几小时
-
维护成本降低:自动同步机制消除单独维护MCP适配器的需要
-
业务价值加速:AI助手可立即利用现有业务API,快速产生价值
6 总结
FastAPI-MCP作为连接现有FastAPI生态与AI助手的重要桥梁,以其零配置、高性能、安全继承的特点,显著降低了AI集成门槛。无论是技术团队想要快速为现有系统添加AI能力,还是企业希望充分利用现有API开发生态,FastAPI-MCP都提供了极为高效的解决方案。
该工具特别适合已有FastAPI基础、希望快速切入AI应用场景的团队,能够在几乎不改变现有代码的基础上,赋予系统AI协作能力,是数字化转型过程中的重要技术加速器。