mcp-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Patterns
MCP模式
Patterns for building, composing, and securing Model Context Protocol servers. Based on the 2025-11-25 specification — the latest stable release maintained by the Agentic AI Foundation (Linux Foundation), co-founded by Anthropic, Block, and OpenAI.
Scaffolding a new server? Use Anthropic'sskill (mcp-builder) for project setup and evaluation creation. This skill focuses on patterns, security, and advanced features after initial setup.claude install anthropics/skillsDeploying to Cloudflare? See theskill for Workers-specific deployment patterns.building-mcp-server-on-cloudflare
本文档介绍用于构建、组合和加固Model Context Protocol(MCP)服务器的模式。基于2025-11-25版本规范——由Anthropic、Block和OpenAI联合创立的Agentic AI Foundation(隶属于Linux基金会)维护的最新稳定版本。
搭建新服务器? 使用Anthropic的技能(mcp-builder)进行项目初始化和评估创建。本技能专注于初始设置完成后的模式、安全与高级功能。claude install anthropics/skills部署到Cloudflare? 请查看技能,了解Workers专属的部署模式。building-mcp-server-on-cloudflare
Decision Tree — Which Rule to Read
决策树——应阅读哪条规则
What are you building?
│
├── New MCP server
│ ├── Setup & primitives ──────► rules/server-setup.md
│ ├── Transport selection ─────► rules/server-transport.md
│ └── Scaffolding ─────────────► mcp-builder skill (anthropics/skills)
│
├── Authentication & authorization
│ └── OAuth 2.1 + OIDC ───────► rules/auth-oauth21.md
│
├── Advanced server features
│ ├── Tool composition ────────► rules/advanced-composition.md
│ ├── Resource caching ────────► rules/advanced-resources.md
│ ├── Elicitation (user input) ► rules/elicitation.md
│ ├── Sampling (agent loops) ──► rules/sampling-tools.md
│ └── Interactive UI ──────────► rules/apps-ui.md
│
├── Client-side consumption
│ └── Connecting to servers ───► rules/client-patterns.md
│
├── Security hardening
│ ├── Prompt injection defense ► rules/security-injection.md
│ └── Zero-trust & verification ► rules/security-hardening.md
│
├── Testing & debugging
│ └── Inspector + unit tests ──► rules/testing-debugging.md
│
├── Discovery & ecosystem
│ └── Registries & catalogs ──► rules/registry-discovery.md
│
└── Browser-native tools
└── WebMCP (W3C) ───────────► rules/webmcp-browser.md你正在构建什么?
│
├── 全新MCP服务器
│ ├── 初始化与基础组件 ──────► rules/server-setup.md
│ ├── 传输方式选择 ─────► rules/server-transport.md
│ └── 项目脚手架 ─────────────► mcp-builder技能(anthropics/skills)
│
├── 认证与授权
│ └── OAuth 2.1 + OIDC ───────► rules/auth-oauth21.md
│
├── 高级服务器功能
│ ├── 工具组合 ────────► rules/advanced-composition.md
│ ├── 资源缓存 ────────► rules/advanced-resources.md
│ ├── 信息获取(用户输入) ► rules/elicitation.md
│ ├── 采样(Agent循环) ──► rules/sampling-tools.md
│ └── 交互式UI ──────────► rules/apps-ui.md
│
├── 客户端消费
│ └── 服务器连接 ───► rules/client-patterns.md
│
├── 安全加固
│ ├── 提示注入防护 ► rules/security-injection.md
│ └── 零信任与验证 ► rules/security-hardening.md
│
├── 测试与调试
│ └── 检查器+单元测试 ──► rules/testing-debugging.md
│
├── 发现与生态
│ └── 注册中心与目录 ──► rules/registry-discovery.md
│
└── 浏览器原生工具
└── WebMCP(W3C) ───────────► rules/webmcp-browser.mdQuick Reference
快速参考
| Category | Rule | Impact | Key Pattern |
|---|---|---|---|
| Server | | HIGH | FastMCP lifespan, Tool/Resource/Prompt primitives |
| Server | | HIGH | stdio for CLI, Streamable HTTP for production |
| Auth | | HIGH | PKCE, RFC 8707 resource indicators, token validation |
| Advanced | | MEDIUM | Pipeline, parallel, and branching tool composition |
| Advanced | | MEDIUM | Resource caching with TTL, LRU eviction, lifecycle |
| Advanced | | MEDIUM | Server-initiated structured input from users |
| Advanced | | MEDIUM | Server-side agent loops with tool calling |
| Advanced | | MEDIUM | Interactive UI via MCP Apps + @mcp-ui/* SDK |
| Client | | MEDIUM | TypeScript/Python MCP client connection patterns |
| Security | | HIGH | Description sanitization, encoding normalization |
| Security | | HIGH | Zero-trust allowlist, hash verification, rug pull detection |
| Quality | | MEDIUM | MCP Inspector, unit tests, transport debugging |
| Ecosystem | | LOW | Official registry API, server metadata |
| Ecosystem | | LOW | W3C browser-native agent tools (complementary) |
Total: 14 rules across 6 categories
| 类别 | 规则文档 | 影响等级 | 核心模式 |
|---|---|---|---|
| 服务器 | | 高 | FastMCP生命周期、工具/资源/提示基础组件 |
| 服务器 | | 高 | CLI使用stdio,生产环境使用可流式HTTP |
| 认证 | | 高 | PKCE、RFC 8707资源标识、令牌验证 |
| 高级功能 | | 中 | 流水线、并行与分支式工具组合 |
| 高级功能 | | 中 | 带TTL的资源缓存、LRU淘汰、生命周期管理 |
| 高级功能 | | 中 | 服务器发起的结构化用户输入 |
| 高级功能 | | 中 | 带工具调用的服务器端Agent循环 |
| 高级功能 | | 中 | 基于MCP Apps + @mcp-ui/* SDK的交互式UI |
| 客户端 | | 中 | TypeScript/Python MCP客户端连接模式 |
| 安全 | | 高 | 描述内容清理、编码标准化 |
| 安全 | | 高 | 零信任白名单、哈希验证、恶意工具检测 |
| 质量 | | 中 | MCP检查器、单元测试、传输调试 |
| 生态 | | 低 | 官方注册中心API、服务器元数据 |
| 生态 | | 低 | W3C浏览器原生Agent工具(补充功能) |
总计:6个类别下的14条规则
Key Decisions
核心决策
| Decision | Recommendation |
|---|---|
| Transport | stdio for CLI/Desktop, Streamable HTTP for production (SSE deprecated) |
| Language | TypeScript for production (better SDK support, type safety) |
| Auth | OAuth 2.1 with PKCE (S256) + RFC 8707 resource indicators |
| Server lifecycle | Always use FastMCP lifespan for resource management |
| Error handling | Return errors as text content (Claude can interpret and retry) |
| Tool composition | Pipeline for sequential, |
| Resource caching | TTL + LRU eviction with memory cap |
| Tool trust model | Zero-trust: explicit allowlist + hash verification |
| User input | Elicitation for runtime input; never request PII via elicitation |
| Interactive UI | MCP Apps with @mcp-ui/* SDK; sandbox all iframes |
| Token handling | Never pass through client tokens to downstream services |
| 决策项 | 推荐方案 |
|---|---|
| 传输方式 | CLI/桌面应用使用stdio,生产环境使用可流式HTTP(SSE已废弃) |
| 开发语言 | 生产环境使用TypeScript(更好的SDK支持、类型安全) |
| 认证方式 | 带PKCE(S256)+ RFC 8707资源标识的OAuth 2.1 |
| 服务器生命周期 | 始终使用FastMCP生命周期进行资源管理 |
| 错误处理 | 以文本内容返回错误(Claude可解析并重试) |
| 工具组合 | 流水线用于顺序执行, |
| 资源缓存 | 带内存上限的TTL + LRU淘汰机制 |
| 工具信任模型 | 零信任:显式白名单 + 哈希验证 |
| 用户输入 | 使用信息获取功能处理运行时输入;绝不通过信息获取请求PII(个人可识别信息) |
| 交互式UI | 基于@mcp-ui/* SDK的MCP Apps;对所有iframe进行沙箱隔离 |
| 令牌处理 | 绝不将客户端令牌传递给下游服务 |
Spec & Governance
规范与治理
- Protocol: Model Context Protocol, spec version 2025-11-25
- Governance: Agentic AI Foundation (Linux Foundation, Dec 2025)
- Platinum members: AWS, Anthropic, Block, Bloomberg, Cloudflare, Google, Microsoft, OpenAI
- Adoption: 10,000+ servers; Claude, Cursor, Copilot, Gemini, ChatGPT, VS Code
- Spec URL: https://modelcontextprotocol.io/specification/2025-11-25
- 协议:Model Context Protocol,规范版本2025-11-25
- 治理:Agentic AI Foundation(Linux基金会,2025年12月)
- 白金会员:AWS、Anthropic、Block、Bloomberg、Cloudflare、Google、Microsoft、OpenAI
- 采用情况:10000+台服务器;Claude、Cursor、Copilot、Gemini、ChatGPT、VS Code均已支持
- 规范地址:https://modelcontextprotocol.io/specification/2025-11-25
Feature Maturity
功能成熟度
| Feature | Spec Version | Status |
|---|---|---|
| Tools, Resources, Prompts | 2024-11-05 | Stable |
| Streamable HTTP transport | 2025-03-26 | Stable (replaces SSE) |
| OAuth 2.1 + Elicitation (form) | 2025-06-18 | Stable |
| Sampling with tool calling | 2025-11-25 | Stable |
| Elicitation URL mode | 2025-11-25 | Stable |
| MCP Apps (UI extension) | 2026-01-26 | Extension (ext-apps) |
| WebMCP (browser-native) | 2026-02-14 | W3C Community Draft |
| 功能 | 规范版本 | 状态 |
|---|---|---|
| 工具、资源、提示 | 2024-11-05 | 稳定 |
| 可流式HTTP传输 | 2025-03-26 | 稳定(替代SSE) |
| OAuth 2.1 + 表单式信息获取 | 2025-06-18 | 稳定 |
| 带工具调用的采样 | 2025-11-25 | 稳定 |
| URL模式信息获取 | 2025-11-25 | 稳定 |
| MCP Apps(UI扩展) | 2026-01-26 | 扩展功能(ext-apps) |
| WebMCP(浏览器原生) | 2026-02-14 | W3C社区草案 |
Example
示例
python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-server")
@mcp.tool()
async def search(query: str) -> str:
"""Search documents. Returns matching results."""
results = await db.search(query)
return "\n".join(r.title for r in results[:10])python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-server")
@mcp.tool()
async def search(query: str) -> str:
"""搜索文档。返回匹配结果。"""
results = await db.search(query)
return "\n".join(r.title for r in results[:10])Common Mistakes
常见错误
- No lifecycle management (connection/resource leaks on shutdown)
- Missing input validation on tool arguments
- Returning secrets in tool output (API keys, credentials)
- Unbounded response sizes (Claude has context limits)
- Trusting tool descriptions without sanitization (injection risk)
- No hash verification on tool invocations (rug pull vulnerability)
- Storing auth tokens in session IDs (credential leak)
- Blocking synchronous code in async server (use )
asyncio.to_thread() - Using SSE transport instead of Streamable HTTP (deprecated since March 2025)
- Passing through client tokens to downstream services (confused deputy)
- 无生命周期管理(关闭时出现连接/资源泄漏)
- 工具参数缺少输入验证
- 工具输出中返回敏感信息(API密钥、凭证)
- 响应大小无限制(Claude存在上下文长度限制)
- 未清理工具描述内容即信任(存在注入风险)
- 工具调用未进行哈希验证(存在恶意工具替换漏洞)
- 将认证令牌存储在会话ID中(凭证泄漏风险)
- 异步服务器中使用阻塞式同步代码(应使用)
asyncio.to_thread() - 使用SSE传输而非可流式HTTP(2025年3月起已废弃)
- 将客户端令牌传递给下游服务(混淆代理问题)
Ecosystem
生态系统
| Resource | What For |
|---|---|
| Scaffold new MCP servers + create evals |
| Deploy MCP servers on Cloudflare Workers |
| Implement MCP Apps UI standard |
| MCP Registry | Discover servers: https://registry.modelcontextprotocol.io/ |
| MCP Inspector | Debug and test servers interactively |
| 资源 | 用途 |
|---|---|
| 搭建新MCP服务器 + 创建评估用例 |
| 在Cloudflare Workers上部署MCP服务器 |
| 实现MCP Apps UI标准 |
| MCP注册中心 | 发现服务器:https://registry.modelcontextprotocol.io/ |
| MCP检查器 | 交互式调试与测试服务器 |
Related Skills
相关技能
- — LLM function calling patterns
llm-integration - — General input sanitization and layered security
security-patterns - — REST/GraphQL API design patterns
api-design
- — LLM函数调用模式
llm-integration - — 通用输入清理与分层安全
security-patterns - — REST/GraphQL API设计模式
api-design