跳转至

MCP Protocol

重要性:⭐⭐⭐⭐ 目标读者:MCP server 作者 / Claude Code 集成者 / 工具开发者 关联topics/deep-dive-mcp-client.mdtopics/mcp-elicitation.mdtopics/deep-dive-mcp-auth.md


1. MCP 概述

MCP (Model Context Protocol) = LLM 工具协议标准 - Anthropic 主导 - 跨厂商(Claude / Cursor / 其他 IDE) - JSON-RPC 2.0 协议


2. 4 种 Transport

Transport 用途
stdio 本地 subprocess(最常见)
SSE Server-Sent Events(HTTP)
Streamable HTTP HTTP 流式(新)
WebSocket 双向 WS

4 种 —— 项目用 [mcp/client.ts] 全部支持。


3. JSON-RPC 2.0 消息

3.1 Request

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": {}
}

4 字段

3.2 Response (Success)

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": { "tools": [...] }
}

3 字段

3.3 Response (Error)

{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32601,
    "message": "Method not found"
  }
}

error 字段。

3.4 Notification(无 id)

{
  "jsonrpc": "2.0",
  "method": "notifications/progress",
  "params": { "progress": 50 }
}

无 id —— 不期待响应。


4. 4 大核心方法

4.1 initialize

// Request
{ "method": "initialize", "params": {
  "protocolVersion": "2024-11-05",
  "capabilities": {},
  "clientInfo": { "name": "claude-code", "version": "1.0.0" }
}}

// Response
{ "result": {
  "protocolVersion": "2024-11-05",
  "capabilities": { "tools": {}, "resources": {}, "prompts": {} },
  "serverInfo": { "name": "...", "version": "..." }
}}

握手

4.2 tools/list

// Request
{ "method": "tools/list" }

// Response
{ "result": {
  "tools": [
    { "name": "...", "description": "...", "inputSchema": {...} }
  ]
}}

列工具

4.3 tools/call

// Request
{ "method": "tools/call", "params": {
  "name": "add",
  "arguments": { "a": 1, "b": 2 }
}}

// Response
{ "result": {
  "content": [
    { "type": "text", "text": "3" }
  ]
}}

调工具

4.4 resources/list / resources/read

// List
{ "method": "resources/list" }
{ "result": { "resources": [...] } }

// Read
{ "method": "resources/read", "params": { "uri": "file://..." } }
{ "result": { "contents": [{ "text": "..." }] } }

资源


5. 3 种 Tool 响应内容

5.1 Text

{ "type": "text", "text": "Hello, world!" }

纯文本

5.2 Image

{ "type": "image", "data": "<base64>", "mimeType": "image/png" }

图片

5.3 Resource

{ "type": "resource", "resource": { "uri": "...", "text": "..." } }

资源引用


6. 6 种标准错误码

名称
-32700 Parse error
-32600 Invalid Request
-32601 Method not found
-32602 Invalid params
-32603 Internal error
-32042 Elicitation (MCP 扩展)

6 种


7. Elicitation(-32042)

详见 mcp-elicitation.md

场景:server 需要额外信息(auth / user data)。

流程: 1. server 工具调用返回 -32042 2. 错误中含 url 3. client 打开 URL 4. 用户完成 5. client 拿 result 6. retry 工具调用


8. 4 种 Notification

8.1 notifications/progress

{ "method": "notifications/progress", "params": {
  "progressToken": "...",
  "progress": 50,
  "total": 100
}}

进度

8.2 notifications/message

{ "method": "notifications/message", "params": {
  "level": "info",
  "data": "..."
}}

日志

8.3 notifications/resources/updated

{ "method": "notifications/resources/updated", "params": { "uri": "..." }}

资源更新

8.4 notifications/cancelled

{ "method": "notifications/cancelled", "params": { "requestId": 1 }}

取消


9. OAuth 鉴权流程

详见 deep-dive-mcp-auth.md

8 步: 1. Discovery 2. Dynamic Client Registration 3. PKCE code_verifier 4. Open browser 5. Wait for callback 6. Exchange code → token 7. Store token 8. Use token


10. 协议版本

"protocolVersion": "2024-11-05"

日期版本

10.1 兼容

  • 客户端应支持多个版本
  • 服务端应声明支持的版本

10.2 协商

// Client
{ "protocolVersion": "2024-11-05" }

// Server
{ "protocolVersion": "2024-11-05" }  // 或更早

协商


11. 完整示例

// Client → Server: initialize
{
  "jsonrpc": "2.0", "id": 1,
  "method": "initialize",
  "params": { "protocolVersion": "2024-11-05", "capabilities": {} }
}

// Server → Client
{
  "jsonrpc": "2.0", "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": { "tools": {} },
    "serverInfo": { "name": "my-mcp", "version": "1.0.0" }
  }
}

// Client → Server: tools/list
{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }

// Server → Client
{
  "jsonrpc": "2.0", "id": 2,
  "result": {
    "tools": [
      {
        "name": "add",
        "description": "Add two numbers",
        "inputSchema": { "type": "object", "properties": { "a": {"type":"number"}, "b": {"type":"number"} }, "required": ["a", "b"] }
      }
    ]
  }
}

// Client → Server: tools/call
{
  "jsonrpc": "2.0", "id": 3,
  "method": "tools/call",
  "params": { "name": "add", "arguments": { "a": 1, "b": 2 } }
}

// Server → Client
{
  "jsonrpc": "2.0", "id": 3,
  "result": { "content": [{ "type": "text", "text": "3" }] }
}

完整流程


12. 8 个最佳实践

  1. JSON Schema 严格 —— 客户端校验
  2. 错误信息有用 —— 客户端可显示
  3. 超时控制 —— 防止挂起
  4. 资源用完释放 —— 文件句柄 / 连接
  5. Logging —— 调试
  6. 版本声明 —— protocolVersion
  7. 能力声明 —— capabilities
  8. 优雅降级 —— 客户端缺失能力

8 条


13. 安全考虑

13.1 信任 server

MCP server 完全可信(在主进程跑)。

13.2 OAuth

所有 HTTP server 必须 OAuth 鉴权。

13.3 输入校验

server 端 必须 校验所有输入。

13.4 资源 URI

  • file://, https://
  • ⚠️ 任意 scheme(小心)

13.5 Tool 描述

不要在 description 中放敏感信息。


14. 相关资源


15. 总结

MCP = 标准协议 —— 让 LLM 与工具通信。

核心: - JSON-RPC 2.0 - 4 种 transport - 4 种核心方法 - 3 种响应内容 - 6 种标准错误 - 1 种扩展(-32042) - 4 种 notification - OAuth 鉴权

写 servertutorials/build-mcp-server.md