> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.developerdoc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 日志

<div id="enable-section-numbers" />

Model Context Protocol (MCP) 为服务器向客户端发送结构化日志消息提供了标准化方式。
客户端可以通过设置最低日志级别来控制日志详细程度；服务器发送的通知会包含严重性级别、
可选的 logger 名称以及任意可 JSON 序列化的数据。

## 用户交互模型

实现可以自由地通过任何适合自身需求的界面模式公开日志；
协议本身并不强制规定任何特定的用户交互模型。

## 能力

会发出日志消息通知的服务器 **MUST** 声明 `logging` 能力：

```json theme={null}
{
  "capabilities": {
    "logging": {}
  }
}
```

## 日志级别

协议遵循 [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1) 中指定的标准 syslog 严重性级别：

| 级别        | 描述       | 示例用例     |
| --------- | -------- | -------- |
| debug     | 详细调试信息   | 函数进入/退出点 |
| info      | 常规信息性消息  | 操作进度更新   |
| notice    | 正常但重要的事件 | 配置变更     |
| warning   | 警告状况     | 使用已弃用功能  |
| error     | 错误状况     | 操作失败     |
| critical  | 严重状况     | 系统组件失败   |
| alert     | 必须立即采取行动 | 检测到数据损坏  |
| emergency | 系统不可用    | 系统完全失败   |

## 协议消息

### 设置日志级别

为了配置最低日志级别，客户端 **MAY** 发送 `logging/setLevel` 请求：

**请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "logging/setLevel",
  "params": {
    "level": "info"
  }
}
```

### 日志消息通知

服务器使用 `notifications/message` 通知发送日志消息：

```json theme={null}
{
  "jsonrpc": "2.0",
  "method": "notifications/message",
  "params": {
    "level": "error",
    "logger": "database",
    "data": {
      "error": "Connection failed",
      "details": {
        "host": "localhost",
        "port": 5432
      }
    }
  }
}
```

## 消息流

```mermaid theme={null}
sequenceDiagram
    participant Client
    participant Server

    Note over Client,Server: Configure Logging
    Client->>Server: logging/setLevel (info)
    Server-->>Client: Empty Result

    Note over Client,Server: Server Activity
    Server--)Client: notifications/message (info)
    Server--)Client: notifications/message (warning)
    Server--)Client: notifications/message (error)

    Note over Client,Server: Level Change
    Client->>Server: logging/setLevel (error)
    Server-->>Client: Empty Result
    Note over Server: Only sends error level<br/>and above
```

## 错误处理

服务器 **SHOULD** 针对常见失败情况返回标准 JSON-RPC 错误：

* 无效日志级别：`-32602`（Invalid params）
* 配置错误：`-32603`（Internal error）

## 实现注意事项

1. 服务器 **SHOULD**:
   * 对日志消息进行速率限制
   * 在 data 字段中包含相关上下文
   * 使用一致的 logger 名称
   * 移除敏感信息

2. 客户端 **MAY**:
   * 在 UI 中展示日志消息
   * 实现日志筛选/搜索
   * 以可视方式显示严重性
   * 持久化日志消息

## 安全

1. 日志消息 **MUST NOT** 包含：
   * 凭据或密钥
   * 个人身份识别信息
   * 可能帮助攻击的内部系统细节

2. 实现 **SHOULD**:
   * 对消息进行速率限制
   * 验证所有数据字段
   * 控制日志访问
   * 监控敏感内容
