> ## 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" />

<Warning>
  **已弃用**：日志特性自协议版本 `2026-07-28` 起已弃用
  ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577))。
  根据[特性生命周期政策](/community/feature-lifecycle)，它会在此修订版发布后至少十二个月内保留在规范中，然后才有资格被移除。
  新实现 **SHOULD NOT** 采用它；现有实现 **SHOULD** 迁移为在 stdio 传输中记录到 `stderr`，或使用 [OpenTelemetry](https://opentelemetry.io/) 进行结构化可观测性。
  参见[已弃用特性注册表](/specification/draft/deprecated)。
</Warning>

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

## 用户交互模型

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

## 能力

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

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

<a id="log-levels" />

## 日志级别

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

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

## 请求日志消息

### 每请求日志级别

要接收特定请求的日志消息，请在请求的 `_meta` 中包含 `io.modelcontextprotocol/logLevel`。对于未包含此字段的请求，服务器 **MUST NOT** 发出 `notifications/message`。

当该字段存在时，服务器 **MAY** 在该请求的响应流上、最终响应之前，发送达到或高于所请求级别的 `notifications/message` 通知。`notifications/message` 以请求为作用域：服务器 **MUST NOT** 将其投递到 [`subscriptions/listen`](/specification/draft/basic/patterns/subscriptions) 流，也 **MUST NOT** 投递到承载设置了日志级别的请求响应之外的任何其他流。

## 协议消息

### 日志消息通知

服务器使用 `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
      }
    }
  }
}
```

## 错误处理

如果请求 `_meta` 中携带的 `io.modelcontextprotocol/logLevel` 值不是可识别的[日志级别](#log-levels)，服务器 **SHOULD** 使用标准 JSON-RPC 错误拒绝该请求：

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

## 实现注意事项

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

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

## 安全

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

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