mcp-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP 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's
mcp-builder
skill (
claude install anthropics/skills
) for project setup and evaluation creation. This skill focuses on patterns, security, and advanced features after initial setup.
Deploying to Cloudflare? See the
building-mcp-server-on-cloudflare
skill for Workers-specific deployment patterns.
本文档介绍用于构建、组合和加固Model Context Protocol(MCP)服务器的模式。基于2025-11-25版本规范——由Anthropic、Block和OpenAI联合创立的Agentic AI Foundation(隶属于Linux基金会)维护的最新稳定版本。
搭建新服务器? 使用Anthropic的
mcp-builder
技能(
claude install anthropics/skills
)进行项目初始化和评估创建。本技能专注于初始设置完成后的模式、安全与高级功能
部署到Cloudflare? 请查看
building-mcp-server-on-cloudflare
技能,了解Workers专属的部署模式。

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.md

Quick Reference

快速参考

CategoryRuleImpactKey Pattern
Server
server-setup.md
HIGHFastMCP lifespan, Tool/Resource/Prompt primitives
Server
server-transport.md
HIGHstdio for CLI, Streamable HTTP for production
Auth
auth-oauth21.md
HIGHPKCE, RFC 8707 resource indicators, token validation
Advanced
advanced-composition.md
MEDIUMPipeline, parallel, and branching tool composition
Advanced
advanced-resources.md
MEDIUMResource caching with TTL, LRU eviction, lifecycle
Advanced
elicitation.md
MEDIUMServer-initiated structured input from users
Advanced
sampling-tools.md
MEDIUMServer-side agent loops with tool calling
Advanced
apps-ui.md
MEDIUMInteractive UI via MCP Apps + @mcp-ui/* SDK
Client
client-patterns.md
MEDIUMTypeScript/Python MCP client connection patterns
Security
security-injection.md
HIGHDescription sanitization, encoding normalization
Security
security-hardening.md
HIGHZero-trust allowlist, hash verification, rug pull detection
Quality
testing-debugging.md
MEDIUMMCP Inspector, unit tests, transport debugging
Ecosystem
registry-discovery.md
LOWOfficial registry API, server metadata
Ecosystem
webmcp-browser.md
LOWW3C browser-native agent tools (complementary)
Total: 14 rules across 6 categories
类别规则文档影响等级核心模式
服务器
server-setup.md
FastMCP生命周期、工具/资源/提示基础组件
服务器
server-transport.md
CLI使用stdio,生产环境使用可流式HTTP
认证
auth-oauth21.md
PKCE、RFC 8707资源标识、令牌验证
高级功能
advanced-composition.md
流水线、并行与分支式工具组合
高级功能
advanced-resources.md
带TTL的资源缓存、LRU淘汰、生命周期管理
高级功能
elicitation.md
服务器发起的结构化用户输入
高级功能
sampling-tools.md
带工具调用的服务器端Agent循环
高级功能
apps-ui.md
基于MCP Apps + @mcp-ui/* SDK的交互式UI
客户端
client-patterns.md
TypeScript/Python MCP客户端连接模式
安全
security-injection.md
描述内容清理、编码标准化
安全
security-hardening.md
零信任白名单、哈希验证、恶意工具检测
质量
testing-debugging.md
MCP检查器、单元测试、传输调试
生态
registry-discovery.md
官方注册中心API、服务器元数据
生态
webmcp-browser.md
W3C浏览器原生Agent工具(补充功能)
总计:6个类别下的14条规则

Key Decisions

核心决策

DecisionRecommendation
Transportstdio for CLI/Desktop, Streamable HTTP for production (SSE deprecated)
LanguageTypeScript for production (better SDK support, type safety)
AuthOAuth 2.1 with PKCE (S256) + RFC 8707 resource indicators
Server lifecycleAlways use FastMCP lifespan for resource management
Error handlingReturn errors as text content (Claude can interpret and retry)
Tool compositionPipeline for sequential,
asyncio.gather
for parallel
Resource cachingTTL + LRU eviction with memory cap
Tool trust modelZero-trust: explicit allowlist + hash verification
User inputElicitation for runtime input; never request PII via elicitation
Interactive UIMCP Apps with @mcp-ui/* SDK; sandbox all iframes
Token handlingNever pass through client tokens to downstream services
决策项推荐方案
传输方式CLI/桌面应用使用stdio,生产环境使用可流式HTTP(SSE已废弃)
开发语言生产环境使用TypeScript(更好的SDK支持、类型安全)
认证方式带PKCE(S256)+ RFC 8707资源标识的OAuth 2.1
服务器生命周期始终使用FastMCP生命周期进行资源管理
错误处理以文本内容返回错误(Claude可解析并重试)
工具组合流水线用于顺序执行,
asyncio.gather
用于并行执行
资源缓存带内存上限的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

功能成熟度

FeatureSpec VersionStatus
Tools, Resources, Prompts2024-11-05Stable
Streamable HTTP transport2025-03-26Stable (replaces SSE)
OAuth 2.1 + Elicitation (form)2025-06-18Stable
Sampling with tool calling2025-11-25Stable
Elicitation URL mode2025-11-25Stable
MCP Apps (UI extension)2026-01-26Extension (ext-apps)
WebMCP (browser-native)2026-02-14W3C 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-14W3C社区草案

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

常见错误

  1. No lifecycle management (connection/resource leaks on shutdown)
  2. Missing input validation on tool arguments
  3. Returning secrets in tool output (API keys, credentials)
  4. Unbounded response sizes (Claude has context limits)
  5. Trusting tool descriptions without sanitization (injection risk)
  6. No hash verification on tool invocations (rug pull vulnerability)
  7. Storing auth tokens in session IDs (credential leak)
  8. Blocking synchronous code in async server (use
    asyncio.to_thread()
    )
  9. Using SSE transport instead of Streamable HTTP (deprecated since March 2025)
  10. Passing through client tokens to downstream services (confused deputy)
  1. 无生命周期管理(关闭时出现连接/资源泄漏)
  2. 工具参数缺少输入验证
  3. 工具输出中返回敏感信息(API密钥、凭证)
  4. 响应大小无限制(Claude存在上下文长度限制)
  5. 未清理工具描述内容即信任(存在注入风险)
  6. 工具调用未进行哈希验证(存在恶意工具替换漏洞)
  7. 将认证令牌存储在会话ID中(凭证泄漏风险)
  8. 异步服务器中使用阻塞式同步代码(应使用
    asyncio.to_thread()
  9. 使用SSE传输而非可流式HTTP(2025年3月起已废弃)
  10. 将客户端令牌传递给下游服务(混淆代理问题)

Ecosystem

生态系统

ResourceWhat For
mcp-builder
skill (anthropics/skills)
Scaffold new MCP servers + create evals
building-mcp-server-on-cloudflare
skill
Deploy MCP servers on Cloudflare Workers
@mcp-ui/*
packages (npm)
Implement MCP Apps UI standard
MCP RegistryDiscover servers: https://registry.modelcontextprotocol.io/
MCP InspectorDebug and test servers interactively
资源用途
mcp-builder
技能(anthropics/skills)
搭建新MCP服务器 + 创建评估用例
building-mcp-server-on-cloudflare
技能
在Cloudflare Workers上部署MCP服务器
@mcp-ui/*
包(npm)
实现MCP Apps UI标准
MCP注册中心发现服务器:https://registry.modelcontextprotocol.io/
MCP检查器交互式调试与测试服务器

Related Skills

相关技能

  • llm-integration
    — LLM function calling patterns
  • security-patterns
    — General input sanitization and layered security
  • api-design
    — REST/GraphQL API design patterns
  • llm-integration
    — LLM函数调用模式
  • security-patterns
    — 通用输入清理与分层安全
  • api-design
    — REST/GraphQL API设计模式