25MCP 协议

L4P0五步章 · 技术章
Why · 为什么要学
没 MCP 前:每个 agent 产品自己重新实现"怎么调外部工具"——Cursor 一套、Claude Code 一套、ChatGPT 一套。开发者要为每个 host 重写一遍 GitHub 集成、Notion 集成。MCP 出现后:写一次 MCP server,所有 host 都能用——97M+ 月下载,1 万+ 活跃 server。MCP 是 agent 生态的 USB-C 接口,不懂这一节你做不出能"插拔到任意 host"的工具。
1 ·核心要点

Model Context Protocol,Anthropic 2024-11 开源,2025-11 捐赠给 Linux Foundation 的 Agentic AI Foundation 共同治理。

三角架构:

┌─────────────────────────────────────┐
│  Host (Claude Desktop / Cursor /    │
│        ChatGPT / Claude Code)       │
│   ┌─────────────────────────────┐   │
│   │  Client (host 内嵌的 MCP    │   │
│   │          client 模块)       │   │
│   └─────────────────────────────┘   │
└─────────────────────────────────────┘
              ↓  stdio / SSE / HTTP
┌─────────────────────────────────────┐
│  Server (外部进程,你写的)          │
│   - 暴露 tools / resources / prompts│
│   - 用 MCP SDK 起一个 process       │
└─────────────────────────────────────┘

Host = 用户面对的 agent 产品;Client = host 内的 MCP 协议实现;Server = 你写的外部能力提供者。一个 host 可以连多个 server(GitHub server + Notion server + Slack server 同时挂)。

三种原语 + 控制者(MCP 设计最关键的点):

原语 控制者 何时触发 举例
Toolsmodel-controlled模型自己决定调read_file、query_db、send_message
Resourcesapplication-controlledhost / 用户决定注入文档、配置、参考材料、CHANGELOG
Promptsuser-controlled用户从菜单选/summarize、/translate、/explain

放在哪个原语取决于"谁该控这个能力的触发"——这是 MCP server 设计最高频出错的点。同一个能力,放 tool vs resource vs prompt 对用户体验完全不同。

传输方式:

· stdio:本地 process,Claude Desktop 默认。低延迟、自动管生命周期。适合本地工具(file ops、shell)。

· SSE / Streamable HTTP:远程 HTTP,适合 cloud service。需要自己管 auth、reconnect。

server 生命周期:initialize(协商版本+能力)→ list_tools/list_resources/list_prompts → 模型/用户触发 → call_tool/read_resource/get_prompt → shutdown。

2 ·最小代码示例
# Python SDK 起一个最小 MCP server
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("demo-server")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b

@mcp.resource("config://app")
def app_config() -> str:
    """Application configuration."""
    return "debug=true\nlog_level=info"

@mcp.prompt()
def summarize_code(language: str) -> str:
    """Generate a code summary prompt for given language."""
    return f"Summarize this {language} code in 3 bullets:\n"

if __name__ == "__main__":
    mcp.run()  # 默认 stdio

# host 端(Claude Desktop)config 注册:
# {
#   "mcpServers": {
#     "demo": {
#       "command": "python",
#       "args": ["/path/to/server.py"]
#     }
#   }
# }

跑起来后:Claude Desktop 里 add 会作为 tool(模型自动调用);app_config 作为 resource(用户/host 可主动注入);summarize_code 作为 slash command(用户菜单可选)。

3 ·工程权衡

何时写 MCP server

  1. 能力要跨多个 host 复用——一个 GitHub server 给 Claude Desktop / Cursor / Continue 都能用
  2. 能力涉及外部资源——DB、API、本地文件系统、SaaS 服务
  3. 能力会随时间演化——MCP server 可以独立升级,host 不动
  4. 要被第三方扩展——开源 MCP server 让社区贡献