[ PROMPT_NODE_24720 ]
fastmcp-server
[ SKILL_DOCUMENTATION ]
# FastMCP 3.0 服务器开发
使用 FastMCP 3.0 构建生产就绪 MCP(模型上下文协议)服务器的完整参考——这是将 LLM 连接到工具和数据的快速、Pythonic 框架。
## 何时使用此技能
**在以下情况使用 FastMCP 服务器:**
- 在 Python 中创建新的 MCP 服务器
- 向 MCP 服务器添加工具、资源或提示词
- 实现身份验证(OAuth、OIDC、令牌验证)
- 设置用于日志记录、速率限制或授权的中间件
- 配置提供程序(本地、文件系统、技能、自定义)
- 构建具有遥测和存储功能的生产级 MCP 服务器
- 从 FastMCP 2.x 升级到 3.0
**涵盖的关键领域:**
- **工具与资源** (核心):装饰器、验证、返回类型、模板
- **上下文与依赖注入** (核心):MCP 上下文、依赖注入、后台任务
- **身份验证** (安全):OAuth、OIDC、令牌验证、代理模式
- **授权** (安全):基于范围和角色的访问控制
- **中间件** (高级):请求/响应管道、内置中间件
- **提供程序** (高级):本地、文件系统、技能和自定义提供程序
- **特性** (高级):分页、采样、存储、OpenTelemetry、版本控制
## 快速参考
### 核心模式
**创建带有工具的服务器:**
python
from fastmcp import FastMCP
mcp = FastMCP("MyServer")
@mcp.tool
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
**创建资源:**
python
@mcp.resource("data://config")
def get_config() -> dict:
"""Return server configuration"""
return {"version": "1.0", "debug": False}
**创建资源模板:**
python
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> dict:
"""Get a user's profile by ID"""
return fetch_user(user_id)
**创建提示词:**
python
@mcp.prompt
def review_code(code: str, language: str = "python") -> str:
"""Review code for best practices"""
return f"Review this {language} code:nn{code}"
**运行服务器:**
python
if __name__ == "__main__":
mcp.run()
# 或者使用传输选项:
# mcp.run(transport="sse", host="0.0.0.0", port=8000)
### 在工具中使用上下文
python
from fastmcp import FastMCP, Context
mcp = FastMCP("MyServer")
@mcp.tool
def process_data(uri: str, ctx: Context) -> str:
"""Process data with logging and progress"""
ctx.info(f"Processing {uri}")
ctx.report_progress(0, 100)
data = ctx.read_resource(u