Vol.10 · MCP Advanced Topics

Logging、Progress Notifications 与 Walkthrough

进阶 MCP server 不只要回最终结果,也要让 client 知道它正在做什么、卡在哪里、有没有异常。

Messages

JSON-RPC 三种消息

类型是否有 id是否期待回应
Request
Response有同一个 id
Notification

Progress notifications

{
  "jsonrpc": "2.0",
  "method": "notifications/progress",
  "params": {
    "progressToken": "job-123",
    "progress": 50,
    "total": 100
  }
}

progressToken 必须对应 active request,进度通知结束后要停止,频率也要限制。

Logging

Logging notifications

Server 若发送结构化日志,需声明 logging capability。Client 可用 logging/setLevel 设置最低等级。

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "logging/setLevel",
  "params": { "level": "info" }
}
{
  "jsonrpc": "2.0",
  "method": "notifications/message",
  "params": {
    "level": "error",
    "logger": "database",
    "data": { "error": "Connection failed" }
  }
}

考点

练习:为「重建全文索引」tool 设计 progress 与 logging 行为。

本节小结:为一个「重建全文索引」tool 设计 progress 与 logging 行为:何时发 progress,哪些错误进入日志,哪些内容不能写进日志?