Skip to content

MCP 连接生命周期

Model Context Protocol 定义了客户端和服务器之间连接的完整生命周期,包括建立、初始化、运行和终止阶段。

生命周期概述

mermaid
stateDiagram-v2
    [*] --> Disconnected
    Disconnected --> Connecting: 建立传输连接
    Connecting --> Connected: 连接成功
    Connected --> Initializing: 发送 initialize
    Initializing --> Initialized: 收到 initialized
    Initialized --> Ready: 发送 notifications/initialized
    Ready --> Ready: 正常操作
    Ready --> Disconnected: 连接断开
    Connecting --> Disconnected: 连接失败
    Initializing --> Disconnected: 初始化失败

阶段详解

1. 连接建立 (Connecting)

传输层连接

根据配置的传输方式建立底层连接:

stdio 传输:

bash
# 启动服务器进程
python -m weather_server

HTTP/SSE 传输:

javascript
const eventSource = new EventSource('https://api.example.com/mcp');

WebSocket 传输:

javascript
const ws = new WebSocket('wss://api.example.com/mcp');

连接验证

  • 验证传输层连接状态
  • 检查网络可达性
  • 确认服务器响应

2. 协议初始化 (Initializing)

initialize 请求

客户端发送初始化请求:

json
{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "protocolVersion": "2025-06-18",
    "capabilities": {
      "roots": { "listChanged": true },
      "sampling": {}
    },
    "clientInfo": {
      "name": "ExampleClient",
      "version": "1.0.0"
    }
  },
  "id": 1
}

initialized 响应

服务器返回初始化响应:

json
{
  "jsonrpc": "2.0",
  "result": {
    "protocolVersion": "2025-06-18",
    "capabilities": {
      "tools": { "listChanged": true },
      "resources": { "subscribe": true },
      "prompts": { "listChanged": true }
    },
    "serverInfo": {
      "name": "WeatherServer",
      "version": "2.1.0"
    }
  },
  "id": 1
}

版本协商

  • 检查协议版本兼容性
  • 协商使用的具体版本
  • 验证能力声明

3. 初始化完成 (Ready)

notifications/initialized

客户端发送初始化完成通知:

json
{
  "jsonrpc": "2.0",
  "method": "notifications/initialized"
}

状态同步

  • 同步初始状态信息
  • 建立订阅关系
  • 准备接收请求

4. 正常运行 (Ready)

在此阶段,客户端和服务器可以进行正常的协议操作:

工具调用

json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "location": "San Francisco"
    }
  },
  "id": 2
}

资源访问

json
{
  "jsonrpc": "2.0",
  "method": "resources/read",
  "params": {
    "uri": "file:///weather_data.json"
  },
  "id": 3
}

状态通知

json
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": {
    "uri": "file:///weather_data.json"
  }
}

5. 连接终止 (Disconnected)

优雅关闭

  1. 完成待处理请求: 等待所有进行中的操作完成
  2. 清理资源: 释放占用的系统资源
  3. 保存状态: 持久化必要的状态信息
  4. 关闭连接: 断开传输层连接

异常终止

  • 网络中断: 检测并处理网络故障
  • 进程崩溃: 处理意外的进程终止
  • 超时: 处理长时间无响应的情况

错误处理

初始化错误

版本不兼容

json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "Unsupported protocol version",
    "data": {
      "requestedVersion": "2025-06-18",
      "supportedVersions": ["2024-11-05"]
    }
  },
  "id": 1
}

能力不支持

json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "Unsupported capability",
    "data": {
      "capability": "sampling",
      "reason": "Feature not implemented"
    }
  },
  "id": 1
}

运行时错误

连接中断

  • 自动重连机制
  • 状态恢复策略
  • 用户通知机制

超时处理

  • 请求超时检测
  • 连接保活机制
  • 故障转移策略

连接保活

ping/pong 机制

json
// 客户端发送 ping
{
  "jsonrpc": "2.0",
  "method": "ping",
  "id": 4
}

// 服务器响应 pong
{
  "jsonrpc": "2.0",
  "result": {},
  "id": 4
}

保活策略

  • 定期检测: 每 30 秒发送一次 ping
  • 超时检测: 5 秒内未收到 pong 视为超时
  • 重连机制: 连续 3 次超时后尝试重连

重连机制

自动重连

javascript
class MCPClient {
  async reconnect() {
    let attempts = 0;
    const maxAttempts = 5;
    const baseDelay = 1000; // 1 秒
    
    while (attempts < maxAttempts) {
      try {
        await this.connect();
        await this.initialize();
        return;
      } catch (error) {
        attempts++;
        const delay = baseDelay * Math.pow(2, attempts); // 指数退避
        await this.sleep(delay);
      }
    }
    
    throw new Error('Failed to reconnect after maximum attempts');
  }
}

状态恢复

  • 订阅恢复: 重新建立资源订阅
  • 缓存同步: 同步本地缓存状态
  • 操作重试: 重试失败的操作

最佳实践

客户端实现

  1. 健壮的错误处理: 处理各种异常情况
  2. 自动重连: 实现智能重连机制
  3. 状态管理: 维护连接和协议状态
  4. 超时控制: 设置合理的超时时间

服务器实现

  1. 优雅关闭: 支持优雅的服务关闭
  2. 资源清理: 及时释放系统资源
  3. 并发控制: 处理并发连接和请求
  4. 监控日志: 记录详细的操作日志

相关文档

🚀 探索模型上下文协议的无限可能 | 连接 AI 与世界的桥梁 | 让智能更智能