MCP Python SDK
模型上下文协议(MCP)的Python实现
> [!注意]
> 此自述文件记录了MCP Python SDK(当前稳定版本)的v1.x。
>
> 有关v1.x代码和文档,请参阅 v1.x 分支.
> 对于即将发布的v2文档(pre-alpha,正在开发中 main),请参阅 README.v2.md.
目录
- MCP Python SDK
- 概述
- 安装
- 将MCP添加到python项目中
- 运行独立的MCP开发工具
- 快速启动
- 什么是MCP?
- 核心概念
- 服务器
- 资源
- 工具
- 结构化输出
- 提示
- 图像
- 上下文
- 在函数中获取上下文
- 上下文属性和方法
- 补全
- 引出
- 采样
- 日志记录和通知
- 认证
- FastMCP属性
- 会话属性和方法
- 请求上下文属性
- 运行服务器
- 发展模式
- Claude桌面集成
- 直接执行
- 可流式HTTP传输
- 基于浏览器的客户端的CORS配置
- 安装到现有ASGI服务器
- 流式HTTP服务器
- 基本安装
- 基于主机的路由
- 具有路径配置的多个服务器
- 初始化时的路径配置
- SSE服务器
- 高级用法
- 低级服务器
- 结构化输出支持
- 分页(高级)
- 编写MCP客户端
- 客户端显示实用程序
- 客户端的OAuth身份验证
- 解析工具结果
- MCP图元
- 服务器功能
- 文档
- 贡献
- 许可证
概述
模型上下文协议允许应用程序以标准化的方式为LLM提供上下文,将提供上下文的关注点与实际的LLM交互分开。此Python SDK实现了完整的MCP规范,使其易于:
- 构建可以连接到任何MCP服务器的MCP客户端
- 创建公开资源、提示和工具的MCP服务器
- 使用标准传输方式,如stdio、SSE和流式HTTP
- 处理所有MCP协议消息和生命周期事件
安装
将MCP添加到python项目中
我们建议使用 紫外线 管理你的Python项目。
如果你还没有创建一个uv管理的项目,请创建一个:```bash
uv init mcp-server-demo
cd mcp-server-demo
然后将MCP添加到您的项目依赖关系中:```bash
uv add "mcp[cli]"
或者,对于使用pip作为依赖关系的项目:```bash
pip install "mcp[cli]"
### 运行独立的MCP开发工具
要使用uv运行mcp命令:```bash
uv run mcp
快速启动
让我们创建一个简单的MCP服务器,它公开了一个计算器工具和一些数据:```python
"""
FastMCP quickstart example.
Run from the repository root:
uv run examples/snippets/servers/fastmcp_quickstart.py
"""
from mcp.server.fastmcp import FastMCP
Create an MCP server
mcp = FastMCP("Demo", json_response=True)
Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
Add a prompt
@mcp.prompt()
def greet_user(name: str, style: str = "friendly") -> str:
"""Generate a greeting prompt"""
styles = {
"friendly": "Please write a warm, friendly greeting",
"formal": "Please write a formal, professional greeting",
"casual": "Please write a casual, relaxed greeting",
}
return f"{styles.get(style, styles['friendly'])} for someone named {name}."
Run with streamable HTTP transport
if name == "main":
mcp.run(transport="streamable-http")
_完整示例: 示例/代码片段/服务器/fastmcp_quickstart.py_
您可以在以下位置安装此服务器 克劳德代码 并立即与之互动。首先,运行服务器:```bash
uv run --with mcp examples/snippets/servers/fastmcp_quickstart.py
然后将其添加到Claude Code中:```bash
claude mcp add --transport http my-server http://localhost:8000/mcp
或者,您可以使用MCP检查器进行测试。如上所述启动服务器,然后在单独的终端中:```bash
npx -y @modelcontextprotocol/inspector
在检查器UI中,连接到 http://localhost:8000/mcp.
什么是MCP?
这 模型上下文协议(MCP) 允许您构建以安全、标准化的方式向LLM应用程序公开数据和功能的服务器。将其视为一个web API,但它是专门为LLM交互而设计的。MCP服务器可以:
- 通过以下方式公开数据 资源 (将这些类似于GET端点;它们用于将信息加载到LLM的上下文中)
- 通过以下方式提供功能 工具 (有点像POST端点;它们用于执行代码或产生副作用)
- 通过以下方式定义交互模式 提示 (LLM交互的可重用模板)
- 还有更多!
核心概念
服务器
FastMCP服务器是MCP协议的核心接口。它处理连接管理、协议合规性和消息路由:```python
"""Example showing lifespan support for startup/shutdown with strong typing."""
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
Mock database class for example
class Database:
"""Mock database class for example."""
@classmethod
async def connect(cls) -> "Database":
"""Connect to database."""
return cls()
async def disconnect(self) -> None:
"""Disconnect from database."""
pass
def query(self) -> str:
"""Execute a query."""
return "Query result"
@dataclass
class AppContext:
"""Application context with typed dependencies."""
db: Database
@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
"""Manage application lifecycle with type-safe context."""
Initialize on startup
db = await Database.connect()
try:
yield AppContext(db=db)
finally:
Cleanup on shutdown
await db.disconnect()
Pass lifespan to server
mcp = FastMCP("My App", lifespan=app_lifespan)
Access type-safe lifespan context in tools
@mcp.tool()
def query_db(ctx: Context[ServerSession, AppContext]) -> str:
"""Tool that uses initialized resources."""
db = ctx.request_context.lifespan_context.db
return db.query()
_完整示例: examples/snippets/servers/lifespan示例.py_
### 资源
资源是您向LLM公开数据的方式。它们类似于REST API中的GET端点-它们提供数据,但不应执行显著的计算或产生副作用:```python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP(name="Resource Example")
@mcp.resource("file://documents/{name}")
def read_document(name: str) -> str:
"""Read a document by name."""
# This would normally read from disk
return f"Content of {name}"
@mcp.resource("config://settings")
def get_settings() -> str:
"""Get application settings."""
return """{
"theme": "dark",
"language": "en",
"debug": false
}"""
完整示例: 示例/代码片段/服务器/basic_resource.py
工具
工具允许LLM通过您的服务器执行操作。与资源不同,工具被期望执行计算并具有副作用:```python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP(name="Tool Example")
@mcp.tool()
def sum(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
@mcp.tool()
def get_weather(city: str, unit: str = "celsius") -> str:
"""Get weather for a city."""
This would normally call a weather API
return f"Weather in {city}: 22degrees{unit[0].upper()}"
_完整示例: 示例/代码片段/服务器/basictool.py_
工具可以通过在 `Context` 类型注释。此上下文由FastMCP框架自动注入,并提供对MCP功能的访问:```python
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
mcp = FastMCP(name="Progress Example")
@mcp.tool()
async def long_running_task(task_name: str, ctx: Context[ServerSession, None], steps: int = 5) -> str:
"""Execute a task with progress updates."""
await ctx.info(f"Starting: {task_name}")
for i in range(steps):
progress = (i + 1) / steps
await ctx.report_progress(
progress=progress,
total=1.0,
message=f"Step {i + 1}/{steps}",
)
await ctx.debug(f"Completed step {i + 1}")
return f"Task '{task_name}' completed"
完整示例: 示例/代码片段/服务器/toolprogress.py
结构化输出
如果返回类型为,则默认情况下工具将返回结构化结果
注释是兼容的。否则,它们将返回非结构化的结果。
结构化输出支持以下返回类型:
- Pydantic模型(BaseModel子类)
- 类型图片
- 数据类和其他具有类型提示的类
dict[str, T](其中T是任何JSON可序列化类型)- 基本类型(str、int、float、bool、bytes、None)-包装在
{"result": value} - 泛型类型(列表、元组、联合、可选等)-包装在
{"result": value}
没有类型提示的类不能序列化为结构化输出。仅
具有正确注释属性的类将转换为Pydantic模型
用于模式生成和验证。
结构化结果会根据输出模式自动验证
根据注释生成。这确保了工具返回良好的类型,
客户可以轻松处理的验证数据。
注: 为了向后兼容,非结构化结果也是
返回。提供非结构化结果以实现向后兼容性
与以前版本的MCP规范兼容,并且与怪癖兼容
当前版本的SDK中包含以前版本的FastMCP。
注: 在工具函数的返回类型注释的情况下
使工具被归类为结构化 这是不可取的,
通过传递可以抑制分类 structured_output=False
到 @tool 装饰师。
高级:直接调用工具结果
用于完全控制工具响应,包括 _meta 字段(用于将数据传递给客户端应用程序,而不将其暴露给模型),您可以返回 CallToolResult 直接:```python
"""Example showing direct CallToolResult return for advanced control."""
from typing import Annotated
from pydantic import BaseModel
from mcp.server.fastmcp import FastMCP
from mcp.types import CallToolResult, TextContent
mcp = FastMCP("CallToolResult Example")
class ValidationModel(BaseModel):
"""Model for validating structured output."""
status: str
data: dict[str, int]
@mcp.tool()
def advanced_tool() -> CallToolResult:
"""Return CallToolResult directly for full control including _meta field."""
return CallToolResult(
content=[TextContent(type="text", text="Response visible to the model")],
_meta={"hidden": "data for client applications only"},
)
@mcp.tool()
def validated_tool() -> Annotated[CallToolResult, ValidationModel]:
"""Return CallToolResult with structured output validation."""
return CallToolResult(
content=[TextContent(type="text", text="Validated response")],
structuredContent={"status": "success", "data": {"result": 42}},
_meta={"internal": "metadata"},
)
@mcp.tool()
def empty_result_tool() -> CallToolResult:
"""For empty results, return CallToolResult with empty content."""
return CallToolResult(content=[])
_完整示例: 示例/代码片段/服务器/direct_call_tool_result.py_
**重要提示:** `CallToolResult` 必须始终返回(否 `Optional` 或 `Union`).对于空结果,请使用 `CallToolResult(content=[])`。对于可选的简单类型,请使用 `str | None` 没有 `CallToolResult`.```python
"""Example showing structured output with tools."""
from typing import TypedDict
from pydantic import BaseModel, Field
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Structured Output Example")
# Using Pydantic models for rich structured data
class WeatherData(BaseModel):
"""Weather information structure."""
temperature: float = Field(description="Temperature in Celsius")
humidity: float = Field(description="Humidity percentage")
condition: str
wind_speed: float
@mcp.tool()
def get_weather(city: str) -> WeatherData:
"""Get weather for a city - returns structured data."""
# Simulated weather data
return WeatherData(
temperature=22.5,
humidity=45.0,
condition="sunny",
wind_speed=5.2,
)
# Using TypedDict for simpler structures
class LocationInfo(TypedDict):
latitude: float
longitude: float
name: str
@mcp.tool()
def get_location(address: str) -> LocationInfo:
"""Get location coordinates"""
return LocationInfo(latitude=51.5074, longitude=-0.1278, name="London, UK")
# Using dict[str, Any] for flexible schemas
@mcp.tool()
def get_statistics(data_type: str) -> dict[str, float]:
"""Get various statistics"""
return {"mean": 42.5, "median": 40.0, "std_dev": 5.2}
# Ordinary classes with type hints work for structured output
class UserProfile:
name: str
age: int
email: str | None = None
def __init__(self, name: str, age: int, email: str | None = None):
self.name = name
self.age = age
self.email = email
@mcp.tool()
def get_user(user_id: str) -> UserProfile:
"""Get user profile - returns structured data"""
return UserProfile(name="Alice", age=30, email="alice@example.com")
# Classes WITHOUT type hints cannot be used for structured output
class UntypedConfig:
def __init__(self, setting1, setting2): # type: ignore[reportMissingParameterType]
self.setting1 = setting1
self.setting2 = setting2
@mcp.tool()
def get_config() -> UntypedConfig:
"""This returns unstructured output - no schema generated"""
return UntypedConfig("value1", "value2")
# Lists and other types are wrapped automatically
@mcp.tool()
def list_cities() -> list[str]:
"""Get a list of cities"""
return ["London", "Paris", "Tokyo"]
# Returns: {"result": ["London", "Paris", "Tokyo"]}
@mcp.tool()
def get_temperature(city: str) -> float:
"""Get temperature as a simple float"""
return 22.5
# Returns: {"result": 22.5}
完整示例: 示例/代码片段/服务器/结构化输出.py
提示
提示是可重用的模板,可帮助LLM与您的服务器有效交互:```python
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.prompts import base
mcp = FastMCP(name="Prompt Example")
@mcp.prompt(title="Code Review")
def review_code(code: str) -> str:
return f"Please review this code:\n\n{code}"
@mcp.prompt(title="Debug Assistant")
def debug_error(error: str) -> list[base.Message]:
return [
base.UserMessage("I'm seeing this error:"),
base.UserMessage(error),
base.AssistantMessage("I'll help debug that. What have you tried so far?"),
]
_完整示例: 示例/代码片段/服务器/basic_prompt.py_
### 图标
MCP服务器可以提供用于UI显示的图标。图标可以添加到服务器实现、工具、资源和提示中:```python
from mcp.server.fastmcp import FastMCP, Icon
# Create an icon from a file path or URL
icon = Icon(
src="icon.png",
mimeType="image/png",
sizes="64x64"
)
# Add icons to server
mcp = FastMCP(
"My Server",
website_url="https://example.com",
icons=[icon]
)
# Add icons to tools, resources, and prompts
@mcp.tool(icons=[icon])
def my_tool():
"""Tool with an icon."""
return "result"
@mcp.resource("demo://resource", icons=[icon])
def my_resource():
"""Resource with an icon."""
return "content"
完整示例: 示例/fastmcp/icons_demo.py
图像
FastMCP提供 Image 自动处理图像数据的类:```python
"""Example showing image handling with FastMCP."""
from PIL import Image as PILImage
from mcp.server.fastmcp import FastMCP, Image
mcp = FastMCP("Image Example")
@mcp.tool()
def create_thumbnail(image_path: str) -> Image:
"""Create a thumbnail from an image"""
img = PILImage.open(image_path)
img.thumbnail((100, 100))
return Image(data=img.tobytes(), format="png")
_完整示例: 示例/片段/服务器/images.py_
### 上下文
Context对象会自动注入到通过类型提示请求它的工具和资源函数中。它提供对MCP功能的访问,如日志记录、进度报告、资源读取、用户交互和请求元数据。
#### 在函数中获取上下文
要在工具或资源函数中使用上下文,请添加一个参数 `Context` 类型注释:```python
from mcp.server.fastmcp import Context, FastMCP
mcp = FastMCP(name="Context Example")
@mcp.tool()
async def my_tool(x: int, ctx: Context) -> str:
"""Tool that uses context capabilities."""
# The context parameter can have any name as long as it's type-annotated
return await process_with_context(x, ctx)
上下文属性和方法
Context对象提供以下功能:
ctx.request_id-当前请求的唯一IDctx.client_id-客户端ID(如果可用)ctx.fastmcp-访问FastMCP服务器实例(请参阅 FastMCP属性)ctx.session-访问基础会话以进行高级通信(请参阅 会话属性和方法)ctx.request_context-访问请求特定数据和生命周期资源(请参阅 请求上下文属性)await ctx.debug(message)-发送调试日志消息await ctx.info(message)-发送信息日志消息await ctx.warning(message)-发送警告日志消息await ctx.error(message)-发送错误日志消息await ctx.log(level, message, logger_name=None)-发送自定义级别的日志await ctx.report_progress(progress, total=None, message=None)-报告操作进度await ctx.read_resource(uri)-按URI读取资源await ctx.elicit(message, schema)-通过验证向用户请求其他信息```python
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
mcp = FastMCP(name="Progress Example")
@mcp.tool()
async def long_running_task(task_name: str, ctx: Context[ServerSession, None], steps: int = 5) -> str:
"""Execute a task with progress updates."""
await ctx.info(f"Starting: {task_name}")
for i in range(steps):
progress = (i + 1) / steps
await ctx.report_progress(
progress=progress,
total=1.0,
message=f"Step {i + 1}/{steps}",
)
await ctx.debug(f"Completed step {i + 1}")
return f"Task '{task_name}' completed"
_完整示例: 示例/代码片段/服务器/toolprogress.py_
### 补全
MCP支持为提示参数和资源模板参数提供完成建议。使用上下文参数,服务器可以根据之前解析的值提供补全:
客户端使用情况:```python
"""
cd to the `examples/snippets` directory and run:
uv run completion-client
"""
import asyncio
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.types import PromptReference, ResourceTemplateReference
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="uv", # Using uv to run the server
args=["run", "server", "completion", "stdio"], # Server with completion support
env={"UV_INDEX": os.environ.get("UV_INDEX", "")},
)
async def run():
"""Run the completion client example."""
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# List available resource templates
templates = await session.list_resource_templates()
print("Available resource templates:")
for template in templates.resourceTemplates:
print(f" - {template.uriTemplate}")
# List available prompts
prompts = await session.list_prompts()
print("\nAvailable prompts:")
for prompt in prompts.prompts:
print(f" - {prompt.name}")
# Complete resource template arguments
if templates.resourceTemplates:
template = templates.resourceTemplates[0]
print(f"\nCompleting arguments for resource template: {template.uriTemplate}")
# Complete without context
result = await session.complete(
ref=ResourceTemplateReference(type="ref/resource", uri=template.uriTemplate),
argument={"name": "owner", "value": "model"},
)
print(f"Completions for 'owner' starting with 'model': {result.completion.values}")
# Complete with context - repo suggestions based on owner
result = await session.complete(
ref=ResourceTemplateReference(type="ref/resource", uri=template.uriTemplate),
argument={"name": "repo", "value": ""},
context_arguments={"owner": "modelcontextprotocol"},
)
print(f"Completions for 'repo' with owner='modelcontextprotocol': {result.completion.values}")
# Complete prompt arguments
if prompts.prompts:
prompt_name = prompts.prompts[0].name
print(f"\nCompleting arguments for prompt: {prompt_name}")
result = await session.complete(
ref=PromptReference(type="ref/prompt", name=prompt_name),
argument={"name": "style", "value": ""},
)
print(f"Completions for 'style' argument: {result.completion.values}")
def main():
"""Entry point for the completion client."""
asyncio.run(run())
if __name__ == "__main__":
main()
完整示例: 示例/代码片段/客户端/completion_client.py
引出
向用户索取更多信息。此示例显示了工具调用期间的激励:```python
"""Elicitation examples demonstrating form and URL mode elicitation.
Form mode elicitation collects structured, non-sensitive data through a schema.
URL mode elicitation directs users to external URLs for sensitive operations
like OAuth flows, credential collection, or payment processing.
"""
import uuid
from pydantic import BaseModel, Field
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
from mcp.shared.exceptions import UrlElicitationRequiredError
from mcp.types import ElicitRequestURLParams
mcp = FastMCP(name="Elicitation Example")
class BookingPreferences(BaseModel):
"""Schema for collecting user preferences."""
checkAlternative: bool = Field(description="Would you like to check another date?")
alternativeDate: str = Field(
default="2024-12-26",
description="Alternative date (YYYY-MM-DD)",
)
@mcp.tool()
async def book_table(date: str, time: str, party_size: int, ctx: Context[ServerSession, None]) -> str:
"""Book a table with date availability check.
This demonstrates form mode elicitation for collecting non-sensitive user input.
"""
Check if date is available
if date == "2024-12-25":
Date unavailable - ask user for alternative
result = await ctx.elicit(
message=(f"No tables available for {party_size} on {date}. Would you like to try another date?"),
schema=BookingPreferences,
)
if result.action == "accept" and result.data:
if result.data.checkAlternative:
return f"[SUCCESS] Booked for {result.data.alternativeDate}"
return "[CANCELLED] No booking made"
return "[CANCELLED] Booking cancelled"
Date available
return f"[SUCCESS] Booked for {date} at {time}"
@mcp.tool()
async def secure_payment(amount: float, ctx: Context[ServerSession, None]) -> str:
"""Process a secure payment requiring URL confirmation.
This demonstrates URL mode elicitation using ctx.elicit_url() for
operations that require out-of-band user interaction.
"""
elicitation_id = str(uuid.uuid4())
result = await ctx.elicit_url(
message=f"Please confirm payment of ${amount:.2f}",
url=f"https://payments.example.com/confirm?amount={amount}&id={elicitation_id}",
elicitation_id=elicitation_id,
)
if result.action == "accept":
In a real app, the payment confirmation would happen out-of-band
and you'd verify the payment status from your backend
return f"Payment of ${amount:.2f} initiated - check your browser to complete"
elif result.action == "decline":
return "Payment declined by user"
return "Payment cancelled"
@mcp.tool()
async def connect_service(service_name: str, ctx: Context[ServerSession, None]) -> str:
"""Connect to a third-party service requiring OAuth authorization.
This demonstrates the "throw error" pattern using UrlElicitationRequiredError.
Use this pattern when the tool cannot proceed without user authorization.
"""
elicitation_id = str(uuid.uuid4())
Raise UrlElicitationRequiredError to signal that the client must complete
a URL elicitation before this request can be processed.
The MCP framework will convert this to a -32042 error response.
raise UrlElicitationRequiredError(
[
ElicitRequestURLParams(
mode="url",
message=f"Authorization required to connect to {service_name}",
url=f"https://{service_name}.example.com/oauth/authorize?elicit={elicitation_id}",
elicitationId=elicitation_id,
)
]
)
_完整示例: 示例/片段/服务器/启发.py_
引用模式支持所有字段类型的默认值。默认值会自动包含在发送给客户端的JSON模式中,允许它们预填充表单。
这 `elicit()` 方法返回一个 `ElicitationResult` 与:
- `action`:“接受”、“拒绝”或“取消”
- `data`:已验证的响应(仅在接受时)
- `validation_error`:任何验证错误消息
### 采样
工具可以通过采样(生成文本)与LLM交互:```python
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
from mcp.types import SamplingMessage, TextContent
mcp = FastMCP(name="Sampling Example")
@mcp.tool()
async def generate_poem(topic: str, ctx: Context[ServerSession, None]) -> str:
"""Generate a poem using LLM sampling."""
prompt = f"Write a short poem about {topic}"
result = await ctx.session.create_message(
messages=[
SamplingMessage(
role="user",
content=TextContent(type="text", text=prompt),
)
],
max_tokens=100,
)
# Since we're not passing tools param, result.content is single content
if result.content.type == "text":
return result.content.text
return str(result.content)
完整示例: 示例/片段/服务器/采样.py
日志记录和通知
工具可以通过上下文发送日志和通知:```python
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
mcp = FastMCP(name="Notifications Example")
@mcp.tool()
async def process_data(data: str, ctx: Context[ServerSession, None]) -> str:
"""Process data with logging."""
Different log levels
await ctx.debug(f"Debug: Processing '{data}'")
await ctx.info("Info: Starting processing")
await ctx.warning("Warning: This is experimental")
await ctx.error("Error: (This is just a demo)")
Notify about resource changes
await ctx.session.send_resource_list_changed()
return f"Processed: {data}"
_完整示例: 示例/片段/服务器/通知.py_
### 认证
想要公开访问受保护资源的工具的服务器可以使用身份验证。
`mcp.server.auth` 实现OAuth 2.1资源服务器功能,其中MCP服务器充当资源服务器(RS),验证由单独的授权服务器(as)颁发的令牌。以下是 MCP授权规范 并实现了用于AS发现的RFC 9728(受保护资源元数据)。
MCP服务器可以通过提供以下实现来使用身份验证 `TokenVerifier` 协议:```python
"""
Run from the repository root:
uv run examples/snippets/servers/oauth_server.py
"""
from pydantic import AnyHttpUrl
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.settings import AuthSettings
from mcp.server.fastmcp import FastMCP
class SimpleTokenVerifier(TokenVerifier):
"""Simple token verifier for demonstration."""
async def verify_token(self, token: str) -> AccessToken | None:
pass # This is where you would implement actual token validation
# Create FastMCP instance as a Resource Server
mcp = FastMCP(
"Weather Service",
json_response=True,
# Token verifier for authentication
token_verifier=SimpleTokenVerifier(),
# Auth settings for RFC 9728 Protected Resource Metadata
auth=AuthSettings(
issuer_url=AnyHttpUrl("https://auth.example.com"), # Authorization Server URL
resource_server_url=AnyHttpUrl("http://localhost:3001"), # This server's URL
required_scopes=["user"],
),
)
@mcp.tool()
async def get_weather(city: str = "London") -> dict[str, str]:
"""Get weather data for a city"""
return {
"city": city,
"temperature": "22",
"condition": "Partly cloudy",
"humidity": "65%",
}
if __name__ == "__main__":
mcp.run(transport="streamable-http")
完整示例: 示例/片段/服务器/oauth_server.py
有关单独的授权服务器和资源服务器实现的完整示例,请参阅 examples/servers/simple-auth/.
架构:
- 授权服务器(AS):处理OAuth流、用户身份验证和令牌颁发
- 资源服务器(RS):您的MCP服务器,用于验证令牌并提供受保护的资源
- 客户端:通过RFC 9728发现AS,获取令牌,并将其用于MCP服务器
看 令牌验证器 有关实现令牌验证的更多详细信息。
FastMCP属性
FastMCP服务器实例可通过以下方式访问 ctx.fastmcp 提供对服务器配置和元数据的访问:
ctx.fastmcp.name-初始化期间定义的服务器名称ctx.fastmcp.instructions-向客户端提供的服务器说明/描述ctx.fastmcp.website_url-服务器的可选网站URLctx.fastmcp.icons-UI显示的可选图标列表ctx.fastmcp.settings-完整的服务器配置对象包含:debug-调试模式标志log_level-当前日志记录级别host和port-服务器网络配置mount_path,sse_path,streamable_http_path-运输路径stateless_http-服务器是否在无状态模式下运行- 以及其他配置选项```python
@mcp.tool()
def server_info(ctx: Context) -> dict:
"""Get information about the current server."""
return {
"name": ctx.fastmcp.name,
"instructions": ctx.fastmcp.instructions,
"debug_mode": ctx.fastmcp.settings.debug,
"log_level": ctx.fastmcp.settings.log_level,
"host": ctx.fastmcp.settings.host,
"port": ctx.fastmcp.settings.port,
}
### 会话属性和方法
会话对象可通过以下方式访问 `ctx.session` 提供对客户端通信的高级控制:
- `ctx.session.client_params` -客户端初始化参数和声明的功能
- `await ctx.session.send_log_message(level, data, logger)` -发送具有完全控制权的日志消息
- `await ctx.session.create_message(messages, max_tokens)` -请求LLM采样/完成
- `await ctx.session.send_progress_notification(token, progress, total, message)` -直接进度更新
- `await ctx.session.send_resource_updated(uri)` -通知客户端特定资源已更改
- `await ctx.session.send_resource_list_changed()` -通知客户端资源列表已更改
- `await ctx.session.send_tool_list_changed()` -通知客户端工具列表已更改
- `await ctx.session.send_prompt_list_changed()` -通知客户端提示列表已更改```python
@mcp.tool()
async def notify_data_update(resource_uri: str, ctx: Context) -> str:
"""Update data and notify clients of the change."""
# Perform data update logic here
# Notify clients that this specific resource changed
await ctx.session.send_resource_updated(AnyUrl(resource_uri))
# If this affects the overall resource list, notify about that too
await ctx.session.send_resource_list_changed()
return f"Updated {resource_uri} and notified clients"
请求上下文属性
请求上下文可通过以下方式访问 ctx.request_context 包含特定于请求的信息和资源:
ctx.request_context.lifespan_context-对服务器启动期间初始化的资源的访问- 数据库连接、配置对象、共享服务
- 键入对服务器生命周期函数中定义的资源的安全访问
ctx.request_context.meta-向客户端请求元数据,包括:progressToken-进度通知令牌- 其他客户端提供的元数据
ctx.request_context.request-用于高级处理的原始MCP请求对象ctx.request_context.request_id-此请求的唯一标识符```python
Example with typed lifespan context
@dataclass
class AppContext:
db: Database
config: AppConfig
@mcp.tool()
def query_with_config(query: str, ctx: Context) -> str:
"""Execute a query using shared database and configuration."""
Access typed lifespan context
app_ctx: AppContext = ctx.request_context.lifespan_context
Use shared resources
connection = app_ctx.db
settings = app_ctx.config
Execute query with configuration
result = connection.execute(query, timeout=settings.query_timeout)
return str(result)
_完整寿命示例: examples/snippets/servers/lifespan示例.py_
## 运行服务器
### 发展模式
测试和调试服务器的最快方法是使用MCP检查器:```bash
uv run mcp dev server.py
# Add dependencies
uv run mcp dev server.py --with pandas --with numpy
# Mount local code
uv run mcp dev server.py --with-editable .
Claude桌面集成
服务器准备就绪后,将其安装在Claude Desktop中:```bash
uv run mcp install server.py
Custom name
uv run mcp install server.py --name "My Analytics Server"
Environment variables
uv run mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://...
uv run mcp install server.py -f .env
### 直接执行
对于自定义部署等高级场景:```python
"""Example showing direct execution of an MCP server.
This is the simplest way to run an MCP server directly.
cd to the `examples/snippets` directory and run:
uv run direct-execution-server
or
python servers/direct_execution.py
"""
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("My App")
@mcp.tool()
def hello(name: str = "World") -> str:
"""Say hello to someone."""
return f"Hello, {name}!"
def main():
"""Entry point for the direct execution server."""
mcp.run()
if __name__ == "__main__":
main()
完整示例: 示例/代码片段/服务器/directexecution.py
运行它:```bash
python servers/direct_execution.py
or
uv run mcp run servers/direct_execution.py
请注意 `uv run mcp run` 或 `uv run mcp dev` 仅支持使用FastMCP的服务器,不支持低级服务器变体。
### 可流式HTTP传输
> **备注**:流式HTTP传输是生产部署的推荐传输方式。使用 `stateless_http=True` 和 `json_response=True` 以获得最佳的可扩展性。```python
"""
Run from the repository root:
uv run examples/snippets/servers/streamable_config.py
"""
from mcp.server.fastmcp import FastMCP
# Stateless server with JSON responses (recommended)
mcp = FastMCP("StatelessServer", stateless_http=True, json_response=True)
# Other configuration options:
# Stateless server with SSE streaming responses
# mcp = FastMCP("StatelessServer", stateless_http=True)
# Stateful server with session persistence
# mcp = FastMCP("StatefulServer")
# Add a simple tool to demonstrate the server
@mcp.tool()
def greet(name: str = "World") -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
# Run server with streamable_http transport
if __name__ == "__main__":
mcp.run(transport="streamable-http")
完整示例: 示例/代码片段/服务器/streamable_configure.py
您可以在Starlette应用程序中安装多个FastMCP服务器:```python
"""
Run from the repository root:
uvicorn examples.snippets.servers.streamable_starlette_mount:app --reload
"""
import contextlib
from starlette.applications import Starlette
from starlette.routing import Mount
from mcp.server.fastmcp import FastMCP
Create the Echo server
echo_mcp = FastMCP(name="EchoServer", stateless_http=True, json_response=True)
@echo_mcp.tool()
def echo(message: str) -> str:
"""A simple echo tool"""
return f"Echo: {message}"
Create the Math server
math_mcp = FastMCP(name="MathServer", stateless_http=True, json_response=True)
@math_mcp.tool()
def add_two(n: int) -> int:
"""Tool to add two to the input"""
return n + 2
Create a combined lifespan to manage both session managers
@contextlib.asynccontextmanager
async def lifespan(app: Starlette):
async with contextlib.AsyncExitStack() as stack:
await stack.enter_async_context(echo_mcp.session_manager.run())
await stack.enter_async_context(math_mcp.session_manager.run())
yield
Create the Starlette app and mount the MCP servers
app = Starlette(
routes=[
Mount("/echo", echo_mcp.streamable_http_app()),
Mount("/math", math_mcp.streamable_http_app()),
],
lifespan=lifespan,
)
Note: Clients connect to http://localhost:8000/echo/mcp and http://localhost:8000/math/mcp
To mount at the root of each path (e.g., /echo instead of /echo/mcp):
echo_mcp.settings.streamable_http_path = "/"
math_mcp.settings.streamable_http_path = "/"
_完整示例: 示例/代码片段/服务器/streamable_starlette_mount.py_
对于具有Streamable HTTP实现的低级服务器,请参阅:
- 状态服务器: `examples/servers/simple-streamablehttp/`
- 无状态服务器: `examples/servers/simple-streamablehttp-stateless/`
流式HTTP传输支持:
- 有状态和无状态操作模式
- 活动商店的可恢复性
- JSON或SSE响应格式
- 多节点部署的可扩展性更好
#### 基于浏览器的客户端的CORS配置
如果你想让基于浏览器的MCP客户端访问你的服务器,你需要配置CORS标头。这 `Mcp-Session-Id` 标头必须公开,以便浏览器客户端访问:```python
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
# Create your Starlette app first
starlette_app = Starlette(routes=[...])
# Then wrap it with CORS middleware
starlette_app = CORSMiddleware(
starlette_app,
allow_origins=["*"], # Configure appropriately for production
allow_methods=["GET", "POST", "DELETE"], # MCP streamable HTTP methods
…(正文过长,页面只展示前面部分,完整内容见仓库)
