跳转至

MCP Lifecycle

目的:MCP 协议完整生命周期 关联docs/MCP_PROTOCOL.mdtopics/deep-dive-mcp-client.md


1. 完整生命周期

sequenceDiagram
    participant Client as Claude Code
    participant Server as MCP Server
    participant User

    Client->>Server: initialize (protocolVersion, capabilities)
    Server-->>Client: protocolVersion, capabilities, serverInfo
    Client->>Server: initialized (notification)
    Client->>Server: tools/list
    Server-->>Client: { tools: [...] }
    Client->>User: 显示工具
    User->>Client: Use add tool with 1+2
    Client->>Server: tools/call (name: "add", args: {a:1, b:2})
    Server-->>Client: { content: [{type: "text", text: "3"}] }
    Client->>User: 显示结果
    Client->>Server: notifications/message (log)
    Server-->>Client: (ack)
    Client->>Server: resources/list
    Server-->>Client: { resources: [...] }
    Note over Client,Server: 持续直到 disconnect
    Client->>Server: shutdown
    Server-->>Client: (close)

8 步


2. 4 种 Transport 启动

graph TD
    A[Connect to MCP server] --> B{Transport}
    B -->|stdio| C[subprocess]
    C -->|stdin/stdout| D[JSON-RPC]
    B -->|SSE| E[HTTP]
    E -->|GET /sse| F[event stream]
    B -->|Streamable HTTP| G[HTTP POST]
    G -->|stream response| H[event stream]
    B -->|WebSocket| I[WS]
    I -->|ws://| J[bidirectional]
    D --> K[Server]
    F --> K
    H --> K
    J --> K
    K -->|JSON-RPC 2.0| L[Tool calls]

4 transport


3. 5 步 OAuth 流

sequenceDiagram
    participant Client
    participant Server
    participant Browser
    participant IdP as OAuth Provider

    Client->>Server: tools/call
    Server-->>Client: -32042 + ElicitRequestURLParams (url)
    Client->>Browser: openExternal(url)
    Browser->>IdP: GET /authorize
    IdP->>Browser: 登录页
    Browser->>IdP: 用户登录
    IdP->>Browser: redirect with code
    Browser->>Client: callback (localhost:port)
    Client->>Server: 携带 code 重试 tools/call
    Server->>IdP: POST /token (code)
    IdP-->>Server: { access_token, refresh_token }
    Server-->>Client: tool result

5 步 elicitation


4. 4 步 Dynamic Client Registration

sequenceDiagram
    participant Client
    participant Server

    Client->>Server: POST /oauth/register<br/>{ redirect_uris, client_name }
    Server-->>Client: { client_id, client_secret }
    Note over Client: 存 client_id/secret
    Client->>Server: GET /.well-known/oauth-authorization-server
    Server-->>Client: { authorization_endpoint, token_endpoint }
    Client->>Server: 5 步 OAuth 流

DCR 4 步


5. Token 刷新流

sequenceDiagram
    participant Client
    participant Server

    Client->>Server: tools/call (with old token)
    Server-->>Client: 401 Unauthorized
    Client->>Client: pending401Handlers.has(serverId)?
    alt already refreshing
        Client->>Client: 等待 pending promise
    else not refreshing
        Client->>Server: refresh token
        Server-->>Client: { new access_token }
    end
    Client->>Server: tools/call (with new token)
    Server-->>Client: 成功

401 → refresh


6. 5 种错误处理

graph TD
    A[Tool call] --> B{result}
    B -->|success| C[content]
    B -->|parse error| D[-32700]
    B -->|invalid request| E[-32600]
    B -->|method not found| F[-32601]
    B -->|invalid params| G[-32602]
    B -->|internal error| H[-32603]
    B -->|auth| I[401 → refresh]
    B -->|rate limit| J[429 → backoff]
    B -->|elicitation| K[-32042 → handleElicitation]
    C --> L[render]
    D --> M[show error]
    E --> M
    F --> M
    G --> M
    H --> M
    I --> N[retry]
    J --> O[wait]
    K --> P[open browser]

10 种结果


7. Sampling 反向调用

sequenceDiagram
    participant Client
    participant Server
    participant LLM

    Server->>Client: createMessage (sampling/createMessage)
    Note over Client: 可以拒绝
    Client->>LLM: 调 LLM
    LLM-->>Client: response
    Client-->>Server: { role: assistant, content: ... }

Sampling(server 反向调 LLM)。


8. Resources 4 步

sequenceDiagram
    participant Client
    participant Server

    Client->>Server: resources/list
    Server-->>Client: { resources: [{ uri, name, mimeType }] }
    Client->>User: 显示资源
    User->>Client: 读 file://...
    Client->>Server: resources/read { uri: "file://..." }
    Server-->>Client: { contents: [{ uri, mimeType, text/blob }] }

Resources 4 步


9. Prompts 模板

sequenceDiagram
    participant Client
    participant Server
    participant User

    Client->>Server: prompts/list
    Server-->>Client: { prompts: [{ name, description, arguments }] }
    Client->>User: 显示 prompts
    User->>Client: Use "review" prompt with code=...
    Client->>Server: prompts/get { name: "review", arguments: { code: "..." } }
    Server-->>Client: { messages: [{ role: user, content: "..." }] }
    Client->>LLM: 发送 messages

Prompts 5 步


10. Reconnect 流

sequenceDiagram
    participant Client
    participant Server

    Note over Client,Server: 连接断开
    Client->>Client: 检测断开
    loop 重试 3 次
        Client->>Server: reconnectMcpServer
        Server-->>Client: 成功 / 失败
    end
    alt 失败
        Client->>User: ask to retry
        User->>Client: retry
    else 成功
        Client->>Server: tools/list
        Server-->>Client: 工具列表
    end

Reconnect


11. 完整 tool call 流

sequenceDiagram
    participant User
    participant Claude
    participant Tool as Bash tool
    participant BashP as bashPermissions
    participant Security as bashSecurity
    participant Classifier
    participant Bash as bash process

    User->>Claude: git status
    Claude->>Tool: tool_use (Bash, "git status")
    Tool->>BashP: bashToolHasPermission
    BashP->>BashP: 1. mode check
    BashP->>BashP: 2. exact match (allow)
    BashP->>BashP: 3. wildcard match (allow)
    BashP->>BashP: return allow
    Tool->>Bash: exec("git status")
    Bash-->>Tool: stdout
    Tool-->>Claude: tool_result (stdout)
    Claude-->>User: 输出

Bash 完整流


12. 4 种 progress 通知

sequenceDiagram
    participant Client
    participant Server
    participant User

    Client->>Server: tools/call (long operation)
    Server->>Server: start work
    loop progress
        Server->>Client: notifications/progress { progress, total }
        Client->>User: show progress bar
    end
    Server-->>Client: tool_result
    Client->>User: show result

Progress 4 步


13. Elicitation 完整流

sequenceDiagram
    participant Server
    participant Client
    participant User
    participant Browser

    Server->>Client: tools/call
    Server-->>Client: -32042<br/>{url: "https://server.com/auth?..."}
    Client->>User: 需要额外信息
    User->>Client: 同意
    Client->>Browser: openExternal("https://server.com/auth?...")
    Browser->>User: 显示登录页
    User->>Browser: 登录
    Browser->>User: 跳转 callback (localhost:port)
    User->>Client: callback 触发
    Client->>Server: tools/call (携带 result)
    Server-->>Client: tool_result

Elicitation 完整流


14. 5 状态 Server 生命周期

stateDiagram-v2
    [*] --> Disconnected
    Disconnected --> Connecting: connect()
    Connecting --> Handshaking: initialize
    Handshaking --> Ready: initialized
    Ready --> Ready: tools/call
    Ready --> Ready: resources/list
    Ready --> Reconnecting: 连接断开
    Reconnecting --> Ready: 重连成功
    Reconnecting --> Disconnected: 重连失败
    Ready --> Disconnected: shutdown
    Disconnected --> [*]

5 状态


15. 6 大能力声明

graph TD
    A[initialize] --> B[capabilities]
    B --> C[tools]
    B --> D[resources]
    B --> E[prompts]
    B --> F[logging]
    B --> G[sampling]
    B --> H[elicitation]
    C --> C1[listTools / callTool]
    D --> D1[listResources / readResource / subscribe]
    E --> E1[listPrompts / getPrompt]
    F --> F1[setLevel / log]
    G --> G1[createMessage]
    H --> H1[elicit / handle]

6 能力


16. 完整协议时间线

gantt
    title MCP 协议时间线
    dateFormat HH:mm
    axisFormat %H:%M
    section 启动
    initialize           :a1, 00:00, 1m
    initialized          :a2, after a1, 30s
    section 工具
    tools/list            :b1, 00:02, 30s
    tools/call (多次)      :b2, 00:03, 5m
    section 资源
    resources/list        :c1, 00:08, 30s
    resources/read        :c2, 00:09, 1m
    section 关闭
    shutdown              :d1, 00:11, 30s

时间线


17. 错误流(详细)

graph TD
    A[Tool call] --> B{status}
    B -->|2xx| C[success]
    B -->|401| D{refresh?}
    D -->|yes| E[refresh token]
    D -->|no| F[OAuth flow]
    E --> G[retry]
    F --> G
    B -->|429| H[backoff]
    H -->|wait| I[retry]
    I --> A
    B -->|500+| J[retry with backoff]
    J -->|max retry| K[fail]
    B -->|-32042| L[handleElicitation]
    L --> M[open browser]
    M -->|callback| N[retry]
    B -->|4xx other| O[fail]

错误流


18. 4 步 caching 模式

graph TD
    A[request 1] --> B[server cache]
    B -->|miss| C[compute]
    C --> D[return]
    D -->|store| B
    A -->|2| E[cache hit]
    E -->|fast| F[return]
    A -->|3| G[cache expired]
    G -->|evict| B
    A -->|4| H[cache invalidate]
    H -->|clear| B

4 步 caching


19. 5 阶段 server 启动

graph TD
    A[1. parse config] --> B[2. init logger]
    B --> C[3. setup transport]
    C --> D{transport}
    D -->|stdio| E[subprocess]
    D -->|sse| F[HTTP server]
    D -->|http| G[streamable]
    D -->|ws| H[ws server]
    E --> I[4. accept connection]
    F --> I
    G --> I
    H --> I
    I --> J[5. handle JSON-RPC]

5 阶段


20. 8 种 JSON-RPC 消息

graph LR
    A[JSON-RPC] --> B[Request]
    A --> C[Response Success]
    A --> D[Response Error]
    A --> E[Notification]
    B --> F[method + params + id]
    C --> G[result + id]
    D --> H[error: code/message + id]
    E --> I[method + params 无 id]

4 类型 / 8 形式


21. 完整 flow (高级)

sequenceDiagram
    participant U as User
    participant CC as Claude Code
    participant MCP as MCP Server
    participant API as Anthropic API
    participant Browser
    participant IdP

    U->>CC: claude --mcp-config
    CC->>MCP: initialize
    MCP-->>CC: serverInfo
    CC->>MCP: tools/list
    MCP-->>CC: 工具列表
    U->>CC: 任务
    CC->>API: prompt + tools
    API-->>CC: tool_use
    CC->>MCP: tools/call
    alt -32042
        MCP-->>CC: elicitation
        CC->>Browser: open url
        Browser->>IdP: auth
        IdP-->>CC: callback
        CC->>MCP: retry with creds
    else success
        MCP-->>CC: result
    end
    CC->>API: tool_result
    API-->>CC: response
    CC-->>U: 输出

高级完整流


22. 总结

MCP Lifecycle = 8 步启动 + 4 transport + OAuth + Elicitation

核心: - 22 个 mermaid 图 - 完整 sequence / state / flow - 错误处理 + reconnect - Sampling / Resources / Prompts

下一步: - 渲染 SVG - 加到 mkdocs