jlowin/fastmcpView GitHub Homepage for Latest Official Releases
快速、Pythonic 的方式構建 MCP 伺服器和客戶端的開源框架
Apache-2.0Pythonfastmcpjlowin 15.8k Last Updated: August 06, 2025
FastMCP - 快速構建 MCP 伺服器和客戶端的 Python 框架
項目概述
FastMCP 是一個用於構建 Model Context Protocol (MCP) 伺服器和客戶端的高級 Python 框架,旨在讓開發者能夠快速、簡潔地創建工具、暴露資源、定義提示並連接組件。該項目由 GitHub 用戶 jlowin 開發維護,已經成為 MCP 生態系統中的重要組成部分。
為什麼選擇 FastMCP?
雖然 MCP 協議功能強大,但實現它需要大量樣板代碼 - 伺服器設置、協議處理程序、內容類型、錯誤管理等。FastMCP 處理所有複雜的協議細節和伺服器管理,讓您專注於構建優秀的工具。
FastMCP 的設計目標:
- 🚀 快速:高級接口意味著更少的代碼和更快的開發
- 🍀 簡單:用最少的樣板代碼構建 MCP 伺服器
- 🐍 Pythonic:對 Python 開發者感覺自然
- 🔍 完整:提供 MCP 核心規範的完整實現,支持伺服器和客戶端
核心功能特性
基礎功能
- 使用直觀裝飾器創建伺服器,樣板代碼最少
- 代理現有伺服器來修改配置或傳輸方式
- 將伺服器組合成複雜應用
- 從 OpenAPI 規範或 FastAPI 對象生成伺服器
- 以編程方式與 MCP 伺服器交互
- 使用任何傳輸協議連接到任何 MCP 伺服器
- 無需手動干預即可測試伺服器
- 利用核心 MCP 功能,如 LLM 採樣
版本演進
FastMCP 1.0 使構建 MCP 伺服器變得如此簡單,以至於它現在已經成為官方 Model Context Protocol Python SDK 的一部分!
FastMCP 2.0 在此基礎上引入了多種新功能:
- 代理和組合 MCP 伺服器等高級功能
- 從 OpenAPI 規範或 FastAPI 對象自動生成伺服器
- 引入客戶端功能,如 LLM 採樣
安裝方法
推薦使用 uv 安裝 FastMCP:
uv pip install fastmcp
開發安裝:
git clone https://github.com/jlowin/fastmcp.git
cd fastmcp
uv sync
快速入門示例
基本伺服器示例
# server.py
from fastmcp import FastMCP
mcp = FastMCP("Demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
if __name__ == "__main__":
mcp.run()
安裝到 Claude Desktop:
fastmcp install server.py
核心概念詳解
1. FastMCP 實例
代表 MCP 應用的中心對象,處理連接、協議細節和路由:
from fastmcp import FastMCP
mcp = FastMCP("My App")
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
2. 工具 (Tools)
允許 LLM 通過執行 Python 函數來執行操作,適用於計算、外部 API 調用或副作用:
import httpx
from pydantic import BaseModel
class UserInfo(BaseModel):
user_id: int
notify: bool = False
@mcp.tool()
async def send_notification(user: UserInfo, message: str) -> dict:
"""Sends a notification to a user if requested."""
if user.notify:
print(f"Notifying user {user.user_id}: {message}")
return {"status": "sent", "user_id": user.user_id}
return {"status": "skipped", "user_id": user.user_id}
@mcp.tool()
def get_stock_price(ticker: str) -> float:
"""Gets the current price for a stock ticker."""
prices = {"AAPL": 180.50, "GOOG": 140.20}
return prices.get(ticker.upper(), 0.0)
3. 資源 (Resources)
向 LLM 暴露數據,主要提供信息而不進行重大計算或副作用:
@mcp.resource("config://app-version")
def get_app_version() -> str:
"""Returns the application version."""
return "v2.1.0"
@mcp.resource("db://users/{user_id}/email")
async def get_user_email(user_id: str) -> str:
"""Retrieves the email address for a given user ID."""
emails = {"123": "alice@example.com", "456": "bob@example.com"}
return emails.get(user_id, "not_found@example.com")
4. 提示 (Prompts)
定義可重用的模板或交互模式:
from fastmcp.prompts.base import UserMessage, AssistantMessage
@mcp.prompt()
def ask_review(code_snippet: str) -> str:
"""Generates a standard code review request."""
return f"Please review the following code snippet for potential bugs and style issues:\n```python\n{code_snippet}\n```"
@mcp.prompt()
def debug_session_start(error_message: str) -> list[Message]:
"""Initiates a debugging help session."""
return [
UserMessage(f"I encountered an error:\n{error_message}"),
AssistantMessage("Okay, I can help with that. Can you provide the full traceback and tell me what you were trying to do?")
]
高級功能
1. 代理伺服器
創建充當中間媒介的 FastMCP 伺服器,代理對另一個 MCP 端點的請求:
import asyncio
from fastmcp import FastMCP, Client
from fastmcp.client.transports import PythonStdioTransport
proxy_client = Client(
transport=PythonStdioTransport('path/to/original_stdio_server.py'),
)
proxy = FastMCP.from_client(proxy_client, name="Stdio-to-SSE Proxy")
if __name__ == "__main__":
proxy.run(transport='sse')
2. 伺服器組合
通過創建模塊化 FastMCP 伺服器並將它們"掛載"到父伺服器上來構建大型 MCP 應用:
from fastmcp import FastMCP
weather_mcp = FastMCP("Weather Service")
@weather_mcp.tool()
def get_forecast(city: str):
return f"Sunny in {city}"
news_mcp = FastMCP("News Service")
@news_mcp.tool()
def fetch_headlines():
return ["Big news!", "Other news"]
mcp = FastMCP("Composite")
mcp.mount("weather", weather_mcp)
mcp.mount("news", news_mcp)
3. 從 API 生成伺服器
從現有 Web API 自動生成 FastMCP 伺服器:
from fastapi import FastAPI
from fastmcp import FastMCP
fastapi_app = FastAPI(title="My Existing API")
@fastapi_app.get("/status")
def get_status():
return {"status": "running"}
mcp_server = FastMCP.from_fastapi(fastapi_app)
4. 客戶端功能
與任何 MCP 伺服器進行交互:
from fastmcp import Client
async with Client("path/to/server") as client:
result = await client.call_tool("weather", {"location": "San Francisco"})
print(result)
res = await client.read_resource("db://users/123/profile")
print(res)
運行伺服器
開發模式
fastmcp dev your_server_file.py
生產安裝
fastmcp install your_server_file.py
直接運行
if __name__ == "__main__":
mcp.run()
示例項目
項目包含多個示例文件:
simple_echo.py
: 基本工具、資源和提示complex_inputs.py
: 使用 Pydantic 模型作為工具輸入mount_example.py
: 掛載多個 FastMCP 伺服器sampling.py
: 在 MCP 伺服器中使用 LLM 完成screenshot.py
: 返回 Image 對象的工具text_me.py
: 與外部 API 交互的工具memory.py
: 帶數據庫交互的複雜示例
貢獻指南
FastMCP 歡迎社區貢獻:
環境要求
- Python 3.10+
- uv 包管理器
開發設置
git clone https://github.com/jlowin/fastmcp.git && cd fastmcp
uv venv && uv sync
測試
uv run pytest -vv
代碼質量
使用 ruff
和 pre-commit
:
pre-commit install
pre-commit run --all-files
項目意義
FastMCP 填補了 MCP 協議實現和實際應用開發之間的空白,讓開發者能夠:
- 快速原型化和部署 MCP 伺服器
- 輕鬆集成現有 API 和數據源
- 構建模塊化、可擴展的 AI 應用架構
- 專注於業務邏輯而不是協議實現細節