跳转至

第二章:协议规范

JSON-RPC 2.0 基础

MCP 基于 JSON-RPC 2.0 协议,理解其基础是掌握 MCP 的关键。

请求结构

{
  "jsonrpc": "2.0",
  "id": "request-123",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {
      "name": "my-client",
      "version": "1.0.0"
    }
  }
}

响应结构

成功响应:

{
  "jsonrpc": "2.0",
  "id": "request-123",
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {}
    },
    "serverInfo": {
      "name": "my-server",
      "version": "1.0.0"
    }
  }
}

错误响应:

{
  "jsonrpc": "2.0",
  "id": "request-123",
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": {"detail": "Missing required field"}
  }
}

错误码

错误码 含义
-32700 Parse error(解析错误)
-32600 Invalid Request(无效请求)
-32601 Method not found(方法未找到)
-32602 Invalid params(无效参数)
-32603 Internal error(内部错误)

MCP 协议版本

当前最新版本:2024-11-05

版本协商

# 客户端初始化
{
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {...},
    "clientInfo": {...}
  }
}

# 服务器响应
{
  "result": {
    "protocolVersion": "2024-11-05",  # 服务器支持的版本
    "capabilities": {...},
    "serverInfo": {...}
  }
}

生命周期

连接建立流程

Client                                    Server
  │                                         │
  │──── initialize ────────────────────────>│
  │<─── initialize result ──────────────────│
  │                                         │
  │──── notifications/initialized ─────────>│
  │                                         │
  │         连接就绪,可以正常通信            │
  │                                         │
  │──── tools/list ────────────────────────>│
  │<─── tools/list result ──────────────────│
  │                                         │
  │──── tools/call ────────────────────────>│
  │<─── tools/call result ──────────────────│
  │                                         │

初始化参数

interface InitializeRequest {
  protocolVersion: string;
  capabilities: ClientCapabilities;
  clientInfo: Implementation;
}

interface InitializeResult {
  protocolVersion: string;
  capabilities: ServerCapabilities;
  serverInfo: Implementation;
  instructions?: string;  // 服务器使用说明
}

能力协商

客户端能力

{
  "capabilities": {
    "roots": {
      "listChanged": true  // 支持根目录变更通知
    },
    "sampling": {}  // 支持采样(让服务器调用 LLM)
  }
}

服务器能力

{
  "capabilities": {
    "resources": {
      "subscribe": true,    // 支持资源订阅
      "listChanged": true   // 支持资源列表变更通知
    },
    "tools": {},
    "prompts": {},
    "logging": {}
  }
}

核心方法

Resources(资源)

列出资源

// 请求
{
  "method": "resources/list",
  "params": {
    "cursor": "optional-pagination-token"
  }
}

// 响应
{
  "result": {
    "resources": [
      {
        "uri": "file:///project/README.md",
        "name": "README.md",
        "description": "项目说明文档",
        "mimeType": "text/markdown"
      }
    ],
    "nextCursor": "next-page-token"
  }
}

读取资源

// 请求
{
  "method": "resources/read",
  "params": {
    "uri": "file:///project/README.md"
  }
}

// 响应
{
  "result": {
    "contents": [
      {
        "uri": "file:///project/README.md",
        "mimeType": "text/markdown",
        "text": "# 项目说明\n..."
      }
    ]
  }
}

资源模板

{
  "method": "resources/templates/list",
  "result": {
    "resourceTemplates": [
      {
        "uriTemplate": "file:///project/{path}",
        "name": "项目文件",
        "description": "访问项目中的任意文件",
        "mimeType": "text/plain"
      }
    ]
  }
}

Tools(工具)

列出工具

{
  "method": "tools/list",
  "result": {
    "tools": [
      {
        "name": "execute_command",
        "description": "执行 shell 命令",
        "inputSchema": {
          "type": "object",
          "properties": {
            "command": {
              "type": "string",
              "description": "要执行的命令"
            },
            "timeout": {
              "type": "number",
              "description": "超时时间(毫秒)"
            }
          },
          "required": ["command"]
        }
      }
    ]
  }
}

调用工具

// 请求
{
  "method": "tools/call",
  "params": {
    "name": "execute_command",
    "arguments": {
      "command": "ls -la",
      "timeout": 5000
    }
  }
}

// 响应
{
  "result": {
    "content": [
      {
        "type": "text",
        "text": "total 32\ndrwxr-xr-x 4 user user 4096 ..."
      }
    ],
    "isError": false
  }
}

Prompts(提示词)

列出提示词

{
  "method": "prompts/list",
  "result": {
    "prompts": [
      {
        "name": "code_review",
        "description": "代码审查提示词",
        "arguments": [
          {
            "name": "language",
            "description": "编程语言",
            "required": true
          },
          {
            "name": "style",
            "description": "审查风格",
            "required": false
          }
        ]
      }
    ]
  }
}

获取提示词

// 请求
{
  "method": "prompts/get",
  "params": {
    "name": "code_review",
    "arguments": {
      "language": "Python",
      "style": "strict"
    }
  }
}

// 响应
{
  "result": {
    "description": "Python 代码严格审查",
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "请对以下 Python 代码进行严格审查..."
        }
      }
    ]
  }
}

通知机制

单向通知

通知没有 id,也不期望响应:

{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": {
    "uri": "file:///project/README.md"
  }
}

常用通知

通知 说明
notifications/initialized 初始化完成
notifications/resources/updated 资源更新
notifications/resources/list_changed 资源列表变更
notifications/tools/list_changed 工具列表变更
notifications/prompts/list_changed 提示词列表变更
notifications/message 日志消息

日志级别

{
  "method": "logging/setLevel",
  "params": {
    "level": "info"
  }
}

支持的级别: - debug:调试信息 - info:一般信息 - notice:提醒信息 - warning:警告 - error:错误 - critical:严重错误 - alert:需要立即处理 - emergency:系统不可用

传输层

stdio 传输

最常用的传输方式,通过标准输入输出通信:

import sys
import json

def read_message():
    """从标准输入读取消息"""
    line = sys.stdin.readline()
    return json.loads(line)

def write_message(message):
    """向标准输出写入消息"""
    print(json.dumps(message), flush=True)

HTTP + SSE 传输

适用于远程服务器:

Client                          Server
  │                               │
  │── POST /mcp ─────────────────>│  发送请求
  │<── 200 OK + SSE stream ───────│  SSE 响应
  │                               │
  │<── event: message ────────────│  接收通知
  │<── data: {...} ───────────────│
  │                               │

完整示例

初始化流程

import json
import sys

# 1. 接收初始化请求
request = json.loads(sys.stdin.readline())
# {"method": "initialize", "params": {...}}

# 2. 返回初始化响应
response = {
    "jsonrpc": "2.0",
    "id": request["id"],
    "result": {
        "protocolVersion": "2024-11-05",
        "capabilities": {
            "tools": {},
            "resources": {}
        },
        "serverInfo": {
            "name": "my-server",
            "version": "1.0.0"
        }
    }
}
print(json.dumps(response), flush=True)

# 3. 接收初始化完成通知
notification = json.loads(sys.stdin.readline())
# {"method": "notifications/initialized"}

# 4. 开始正常通信...

小结

MCP 协议规范的核心要点:

  • 基于 JSON-RPC 2.0
  • 明确的生命周期管理
  • 灵活的能力协商
  • 支持资源和工具的标准化访问
  • 多种传输方式可选

下一章我们将学习如何开发 MCP 服务器。