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

# 取消

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

模型上下文协议 (MCP) 支持通过通知消息可选地取消进行中的请求。任何一方都可以发送取消通知，表明之前发出的请求应该被终止。

## 取消流程

当一方想要取消一个进行中的请求时，它会发送一个 `notifications/cancelled` 通知，包含：

* 要取消的请求的 ID
* 一个可选的原因字符串，可以记录或显示

```json theme={null}
{
  "jsonrpc": "2.0",
  "method": "notifications/cancelled",
  "params": {
    "requestId": "123",
    "reason": "User requested cancellation"
  }
}
```

## 行为要求

1. 取消通知 **MUST** 仅引用以下请求：
   * 之前在同一方向发出的
   * 被认为仍在进行中的
2. 客户端 **MUST NOT** 取消 `initialize` 请求
3. 对于 [任务增强请求](./tasks)，**MUST** 使用 `tasks/cancel` 请求而不是 `notifications/cancelled` 通知。任务有自己专用的取消机制，会返回最终任务状态。
4. 取消通知的接收者 **SHOULD**：
   * 停止处理被取消的请求
   * 释放相关资源
   * 不要为被取消的请求发送响应
5. 如果以下情况，接收者 **MAY** 忽略取消通知：
   * 引用的请求未知
   * 处理已经完成
   * 请求无法被取消
6. 取消通知的发送者 **SHOULD** 忽略随后到达的对该请求的任何响应

## 时序考虑

由于网络延迟，取消通知可能在请求处理完成后到达，甚至可能在响应已经发送之后到达。

双方 **MUST** 优雅地处理这些竞争条件：

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

   Client->>Server: Request (ID: 123)
   Note over Server: Processing starts
   Client--)Server: notifications/cancelled (ID: 123)
   alt
      Note over Server: Processing may have<br/>completed before<br/>cancellation arrives
   else If not completed
      Note over Server: Stop processing
   end
```

## 实现说明

* 双方 **SHOULD** 记录取消原因以便调试
* 应用程序 UI **SHOULD** 在请求取消时予以指示

## 错误处理

无效的取消通知 **SHOULD** 被忽略：

* 未知的请求 ID
* 已完成的请求
* 格式错误的通知

这保持了通知的“即发即弃”特性，同时允许异步通信中的竞争条件。
