协议版本: 2024-11-05
Model Context Protocol (MCP) 为客户端-服务器连接定义了一个严谨的生命周期,确保正确的功能协商和状态管理。
  1. 初始化: 能力协商与协议版本约定
  2. 操作: 正常协议通信
  3. 关闭: 优雅地终止连接

生命周期阶段

初始化

The initialization phase 必须 be the first interaction between client and server. During this phase, the client and server:
  • 建立协议版本兼容性
  • 交换和协商能力
  • 分享实现细节
The client 必须 initiate this phase by sending an initialize request containing:
  • 支持的协议版本
  • 客户端能力
  • 客户端实现信息
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "roots": {
        "listChanged": true
      },
      "sampling": {}
    },
    "clientInfo": {
      "name": "ExampleClient",
      "version": "1.0.0"
    }
  }
}
The server 必须 respond with its own capabilities and information:
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "logging": {},
      "prompts": {
        "listChanged": true
      },
      "resources": {
        "subscribe": true,
        "listChanged": true
      },
      "tools": {
        "listChanged": true
      }
    },
    "serverInfo": {
      "name": "ExampleServer",
      "version": "1.0.0"
    }
  }
}
After successful initialization, the client 必须 send an initialized notification to indicate it is ready to begin normal operations:
{
  "jsonrpc": "2.0",
  "method": "notifications/initialized"
}
  • 客户端不应在服务器响应initialize请求之前发送pings之外的请求。
  • 服务器在收到initialized通知前,不应发送除 ping日志记录之外的请求。

版本协商

initialize请求中,客户端必须发送其支持的协议版本。 这应当是客户端支持的最新版本。 如果服务器支持请求的协议版本,它必须以相同版本作出响应。否则,服务器必须以它支持的其他协议版本作出响应。这应当是服务器支持的最新版本。 如果客户端不支持服务器响应中的版本,它应当断开连接。

功能协商

客户端与服务器通过能力协商机制确定会话期间可用的可选协议功能。 主要功能包括:
类别能力描述
客户端roots提供文件系统根目录的能力
客户端采样支持LLM sampling 请求
客户端实验性的描述对非标准实验性功能的支持
服务器prompts提供 提示模版
服务器resources提供可读的 resources
服务器工具暴露可调用的工具
服务器日志发送结构化日志消息
服务器实验性的描述对非标准实验性功能的支持
能力对象可以描述如下子能力:
  • listChanged: 支持列表更改通知(适用于提示、资源和工具)
  • subscribe: 支持订阅单个项目的更改(仅限资源)

操作

在操作阶段,客户端与服务器根据协商的能力交换消息。 双方 应当:
  • 遵守协商的协议版本
  • 仅使用已成功协商的功能

关闭

在关闭阶段,一方(通常是客户端)会干净利落地终止协议连接。未定义特定的关闭消息——而是应使用底层传输机制来发出连接终止信号:

标准输入输出

对于stdio transport传输, 客户端 应当 通过以下方式启动关闭:
  1. 首先,关闭子进程(即服务器)的输入流
  2. 等待服务器退出,或在合理时间内若服务器未退出则发送SIGTERM
  3. 如果服务器在收到SIGTERM后合理时间内没有退出,则发送SIGKILL
The server 可以 initiate shutdown by closing its output stream to the client and exiting.

超文本传输协议

对于HTTP transports, 关机通过关闭相关的HTTP连接来表示。

错误处理

Implementations 应当准备好处理这些错误情况:
  • 协议版本不匹配
  • 失败协商所需功能
  • 初始化请求超时
  • 关闭超时
实现应当为所有请求实现适当的超时机制,以防止连接挂起和资源耗尽。 初始化错误示例:
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32602,
    "message": "Unsupported protocol version",
    "data": {
      "supported": ["2024-11-05"],
      "requested": "1.0.0"
    }
  }
}