谁适合阅读:想要迅速构建AI工具、无需复杂配置就能部署LLM服务的开发者,特别是需要快速交付AI产品的团队和个人。
一、为什么选择FastMCP?
FastMCP是Model Context Protocol(MCP)的Python实现框架,只需5分钟即可从零搭建专业级AI服务!它具有以下核心优势:
- ⚡ 极速构建标准MCP服务端,最快只需10行代码
- 🔌 灵活支持多种传输协议(STDIO/HTTP/SSE)
- 🧩 模块化设计支持服务组合与代理,可扩展性极强
- 🛠️ 开箱即用的工具/资源/提示词管理系统
- 🔒 企业级OAuth2认证安全架构
二、⏱️ 开始前的准备工作(30秒完成)
✅ 验证安装成功:
1 2
| import fastmcp print(fastmcp.__version__)
|
三、⚡ 极速入门:3分钟搭建你的AI服务
1. 基础服务构建(60秒)
1 2 3 4 5 6 7 8 9 10
| from fastmcp import FastMCP from fastmcp.transport import run
app = FastMCP( name="天气助手", instructions="提供实时天气查询和预报功能", lifespan=None, tags={"weather", "ai"} )
|
2. 添加智能功能(90秒)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @app.tool("get_weather") def get_weather(location: str): """获取指定地点的实时天气""" return {"temperature": 25, "condition": "晴", "humidity": "65%"}
@app.resource("forecast_template") def forecast_template(): return """ 【天气预报】 地点:{location} 温度:{temperature}℃ 状况:{condition} """
|
3. 一键启动服务(30秒)
1 2
| if __name__ == "__main__": run(app, transport="stdio")
|
💡 关键提示:到这一步,你已经拥有了一个功能完整的MCP服务!尝试用任何支持MCP的客户端连接它。
四、🧩 核心组件详解 - 按需扩展你的服务
1 2 3 4 5
| @app.tool("complex_analysis") async def complex_analysis(data: dict): result = await async_process(data) return format_result(result)
|
调用方式:
- ✅ 同步工具:直接返回值,适合快速操作
- ⏱️ 异步工具:使用
async/await
,适合网络请求与IO操作
2. 灵活的资源系统(Resources)
1 2 3 4 5 6 7 8 9 10 11
| @app.resource("streaming_log") def streaming_log(): def generator(): with open("server.log") as f: while True: line = f.readline() if not line: break yield line return generator()
|
3. 智能提示词模板(Prompts)
1 2 3 4 5 6 7 8
| @app.prompt("zh", "system_prompt") def zh_system(): return "你是专业的天气助理,使用中文回答"
@app.prompt("en", "system_prompt") def en_system(): return "You are a weather assistant, answer in English"
|
五、🚀 生产级部署指南 - 从测试到上线
1. 传输协议选择策略
协议 |
适用场景 |
优势 |
配置示例 |
STDIO |
本地工具集成 |
零配置,低延迟 |
run(app) |
HTTP |
Web服务集成 |
支持流式传输 |
run(app, transport="http", port=8000) |
SSE |
旧版浏览器兼容 |
实时性好 |
run(app, transport="sse", host="0.0.0.0") |
💡 专业提示:HTTP模式下自带Swagger文档,访问/docs
快速测试你的API
2. 服务组合模式(v2.2+)
1 2 3 4 5 6
| from other_server import analytics_server app.import_server(analytics_server)
app.mount("/v2", analytics_server)
|
3. 代理服务构建(v2.0+)
1 2 3 4 5 6 7 8
| from mcp.client import MCPClient
proxy_app = FastMCP.from_client( name="云端服务代理", client=MCPClient("https://api.example.com/mcp"), prefix="/remote" )
|
六、⚙️ 高级配置手册 - 定制你的服务
1. 自定义序列化器(v2.2.7+)
1 2 3 4 5 6 7 8 9
| def yaml_serializer(data): import yaml return yaml.dump(data)
app = FastMCP( tool_serializer=yaml_serializer, )
|
2. 安全认证配置(v2.2.7+)
1 2 3 4 5 6 7 8 9 10
| from mcp.auth import OAuthAuthorizationServerProvider
app = FastMCP( auth_server_provider=MyAuthProvider(), auth={ "client_id": "my_client", "scopes": ["read", "write"] } )
|
3. 环境变量配置(推荐)
1 2 3 4 5
| # 一次配置,到处运行 - 支持容器化部署 FASTMCP_SERVER_HOST=0.0.0.0 FASTMCP_SERVER_PORT=8080 FASTMCP_SERVER_LOG_LEVEL=DEBUG FASTMCP_SERVER_ON_DUPLICATE_TOOLS=overwrite
|
七、📋 最佳实践清单 - 架构师推荐
- 模块化设计:将不同功能拆分为独立服务,通过组合模式集成 → 降低维护成本
- 版本控制:为资源和提示词添加版本标签 → 避免接口变更风险
- 性能优化:
- ⚡ 对计算密集型任务使用线程池 → 提高CPU利用率
- 🔄 对IO密集型任务使用异步工具 → 减少等待时间
- 监控告警:
1 2 3 4 5 6 7 8
| @app.middleware("request") async def log_requests(request): start_time = time.time() response = await request.send() duration = time.time() - start_time logger.info(f"{request.method} {request.url} {duration:.2f}s") return response
|
八、❓ 常见问题速查
Q1:如何调试服务端?
A:启动时添加--log-level=DEBUG
参数,或设置环境变量FASTMCP_SERVER_LOG_LEVEL=DEBUG
,立即看到详细日志
Q2:如何处理跨域问题?
A:使用HTTP传输时,一行代码解决跨域:
1 2
| from fastmcp.middleware import CORSMiddleware app.add_middleware(CORSMiddleware, allow_origins=["*"])
|