使用说明
⚡ FastMCP
用于构建MCP服务器、客户端和应用程序的现代Python框架
由...建造 哈桑·萨利姆 · @哈桑萨利姆恰如其分
什么是FastMCP?
FastMCP 是一个生产级Python框架 模型上下文协议 (MCP)——将LLM连接到工具、数据和现实世界服务的开放标准。
MCP允许Claude、GPT和其他AI代理调用您的代码。FastMCP处理所有协议复杂性,因此您可以专注于工具的实际功能。
在一个装饰器中将Python函数转换为LLM可调用工具:
from fastmcp import FastMCP
mcp = FastMCP("MyServer")
@mcp.tool
def search_docs(query: str, limit: int = 10) -> list[dict]:
"""Search the knowledge base and return matching documents."""
return db.search(query, limit=limit)
mcp.run()
FastMCP自动处理模式生成、输入验证、错误处理、传输协商和完全MCP协议合规性。
为什么选择FastMCP?
| 不带FastMCP | 带FastMCP |
|---|---|
| 手动编写JSON模式 | 根据类型提示自动模式 |
| 手动实现MCP协议 | 将工具声明为Python函数 |
| 搬运运输样板 | mcp.run() 通过stdio、HTTP、WebSocket工作 |
| 从头开始构建身份验证 | 内置OAuth 2.0 |
| 使用子进程进行测试 | 全进程测试客户端 |
| 手动将服务器连接在一起 | mcp.mount() 以及代理人组成 |
特性
| 功能 | 描述 | |
|---|---|---|
| 🛠️ | 自动模式生成 | Python函数签名的类型、文档和验证 |
| 🔌 | 通用客户端 | 连接到任何MCP服务器——stdio、SSE、WebSocket、HTTP |
| 📱 | 交互式应用程序 | 直接在LLM对话中呈现UI |
| 🔐 | 内置身份验证 | OAuth 2.0(GitHub、Google、Azure、AWS、Clerk、Discord)+API密钥 |
| 🧩 | 服务器组成 | 具有完全命名空间控制的装载和代理服务器 |
| ⚡ | 异步优先 | 基于asyncio构建——本机处理并发 |
| 🧪 | 过程测试 | 完整测试客户端——无子流程、无网络、无模拟 |
| 🔀 | OpenAPI集成 | 从其OpenAPI规范中将任何REST API包装为MCP服务器 |
| 📊 | 遥测 | 内置OpenTetry跟踪 |
| 📦 | 后台任务 | 分布式任务队列的Docket集成 |
| 🔁 | 实时重新加载 | fastmcp dev 监视更改并自动重新启动 |
建筑
FastMCP有三个支柱——可以任意组合使用:
🖥️ 服务器——将Python作为MCP工具公开
from fastmcp import FastMCP
mcp = FastMCP("Demo")
@mcp.tool
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
@mcp.resource("data://config")
def get_config() -> dict:
"""Return server configuration."""
return {"version": "2.0"}
@mcp.prompt
def summarise(text: str) -> str:
"""Generate a summarisation prompt."""
return f"Please summarise the following: {text}"
🔌 客户端--连接到任何MCP服务器
from fastmcp import Client
async with Client("http://localhost:8000/mcp") as client:
tools = await client.list_tools()
result = await client.call_tool("add", a=3, b=7)
print(result) # 10
📱 应用程序——LLM对话中的交互式UI
from prefab_ui.components import Column, Heading, Badge
@mcp.tool(app=True)
def dashboard(metric: str) -> Column:
"""Show a live metric dashboard."""
with Column(gap=4) as view:
Heading(f"Metric: {metric}")
Badge("Live")
return view
安装
# Recommended
uv pip install fastmcp
# With pip
pip install fastmcp
# With extras
pip install "fastmcp[openai]" # OpenAI client
pip install "fastmcp[anthropic]" # Anthropic client
pip install "fastmcp[gemini]" # Google Gemini
pip install "fastmcp[azure]" # Azure auth
pip install "fastmcp[tasks]" # Background tasks
pip install "fastmcp[apps]" # Interactive UIs
# Everything
pip install "fastmcp[anthropic,openai,gemini,azure,tasks,apps]"
快速入门
# server.py
from fastmcp import FastMCP
mcp = FastMCP("QuickStart")
@mcp.tool
def greet(name: str, formal: bool = False) -> str:
"""Greet someone by name."""
prefix = "Good day" if formal else "Hello"
return f"{prefix}, {name}! Built with FastMCP."
mcp.run()
# Run it
python server.py
# Or with the CLI
fastmcp run server.py
# Dev mode with live reload
fastmcp dev server.py
# HTTP transport
fastmcp run server.py --transport streamable-http --port 8000
# Connect from a client
from fastmcp import Client
import asyncio
async def main():
async with Client("python server.py") as client:
result = await client.call_tool("greet", name="World")
print(result)
asyncio.run(main())
添加到克劳德桌面
在 claude_desktop_config.json:
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["/path/to/server.py"]
}
}
}
认证
from fastmcp import FastMCP
from fastmcp.server.auth import GitHubOAuthProvider
mcp = FastMCP(
"Secure Server",
auth=GitHubOAuthProvider(client_id="...", client_secret="...")
)
支持: GitHub·谷歌·Azure·AWS·文员·Discord·AuthKit
服务器组成
main = FastMCP("Main")
search = FastMCP("Search")
data = FastMCP("Data")
@search.tool
def find(query: str) -> list[str]: ...
@data.tool
def fetch(id: str) -> dict: ...
# Mount with namespace prefixes
main.mount(search, prefix="search") # → search_find
main.mount(data, prefix="data") # → data_fetch
main.run()
将任何REST API包装为MCP
from fastmcp import FastMCP
import httpx
mcp = FastMCP.from_openapi(
openapi_url="https://api.example.com/openapi.json",
client=httpx.AsyncClient(base_url="https://api.example.com"),
)
mcp.run()
测试
import pytest
from fastmcp import FastMCP, Client
mcp = FastMCP("Test")
@mcp.tool
def multiply(x: int, y: int) -> int:
"""Multiply two numbers."""
return x * y
@pytest.mark.asyncio
async def test_multiply():
async with Client(mcp) as client:
result = await client.call_tool("multiply", x=6, y=7)
assert result[0].text == "42"
无子流程。没有网络,没有模仿。测试以毫秒为单位运行。
项目结构
fastmcp/
├── src/fastmcp/
│ ├── server/ # FastMCP server class + tools/resources/prompts/auth
│ │ ├── server.py # Main FastMCP class
│ │ ├── context.py # Request context (auth, progress, logging)
│ │ ├── auth/ # OAuth providers
│ │ ├── middleware/ # Server middleware
│ │ ├── providers/ # OpenAPI, aggregate, proxy
│ │ └── tasks/ # Background task support (Docket)
│ ├── client/ # Universal MCP client + transports
│ ├── tools/ # Tool declaration and schema generation
│ ├── resources/ # Resource declaration
│ ├── prompts/ # Prompt declaration
│ ├── apps/ # Interactive UI support
│ ├── cli/ # `fastmcp` CLI
│ └── settings.py # FASTMCP_* environment config
│
├── examples/
│ ├── apps/ # UI examples (greet, QR, contacts, dashboard)
│ └── auth/ # OAuth examples (GitHub, Azure, AWS, Discord)
│
├── tests/ # Full test suite
└── docs/ # Documentation source
真实世界用例
AI代理工具 --将内部API作为MCP工具公开,这样Claude或GPT就可以在没有自定义集成代码的情况下调用它们。
企业RAG --将搜索、数据库和文档API包装为MCP服务器,并将其连接到任何使用MCP的LLM。
工作流程自动化 --构建n8n风格的自动化,其中每个步骤都是可由AI代理调用的MCP工具。
开发人员工具 --公开用于人工智能辅助开发的git操作、代码分析和CI/CD管道。
数据管道 --让AI代理通过类型化的MCP工具协调数据提取、转换和加载。
贡献
看 贡献.md.快跑 pre-commit install 克隆后。
安全
发现漏洞?看 安全.md 私人披露指示。 GitHub的 报告漏洞 按钮也可在“安全”选项卡上使用。
社区
| 🐛 Bug报告 | 问题追踪器 |
| 💡 增强功能 | 问题追踪器 |
| 💬 讨论 | GitHub讨论 |
| 🤝 贡献 | 贡献.md |
| 📜 行为准则 | 代码_OF_CONDUCT.md |
许可证
麻省理工学院——见 许可证.
作者
哈桑·萨利姆 · @哈桑萨利姆恰如其分
