|
| 1 | +--- |
| 2 | +title: Cancellation |
| 3 | +type: docs |
| 4 | +weight: 5 |
| 5 | +--- |
| 6 | + |
| 7 | +MCP supports request cancellation through a dedicated notification message. This allows either party to signal that they are no longer interested in the result of an in-flight request. |
| 8 | + |
| 9 | +## Cancellation Protocol |
| 10 | + |
| 11 | +When a party wants to cancel a request, they send a `cancelled` notification containing the ID of the request they wish to cancel: |
| 12 | + |
| 13 | +For example, initiating a request: |
| 14 | + |
| 15 | +```json |
| 16 | +{ |
| 17 | + "jsonrpc": "2.0", |
| 18 | + "id": "abc123", |
| 19 | + "method": "resources/read", |
| 20 | + "params": { |
| 21 | + "uri": "example://large-file" |
| 22 | + } |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +… then some time later, cancelling that request: |
| 27 | + |
| 28 | +```json |
| 29 | +{ |
| 30 | + "jsonrpc": "2.0", |
| 31 | + "method": "cancelled", |
| 32 | + "params": { |
| 33 | + "requestId": "abc123", |
| 34 | + "reason": "User interrupted operation" |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +## Handling Cancellation |
| 40 | + |
| 41 | +Upon receiving a cancellation notification, the receiver SHOULD: |
| 42 | + |
| 43 | +1. Stop any processing related to the cancelled request |
| 44 | +2. Free any resources associated with that request |
| 45 | +3. Not send a response for the cancelled request (even if already computed) |
| 46 | + |
| 47 | +However, due to race conditions and message latency: |
| 48 | + |
| 49 | +- The notification may arrive after processing is complete |
| 50 | +- A response may already be in transit when cancellation is received |
| 51 | +- Multiple cancellation notifications for the same request ID may be received |
| 52 | + |
| 53 | +## Special Cases |
| 54 | + |
| 55 | +### Initialize Request |
| 56 | + |
| 57 | +The client MUST NOT attempt to cancel its `initialize` request. Cancelling initialization leaves the protocol in an undefined state. |
| 58 | + |
| 59 | +### Long-Running Operations |
| 60 | + |
| 61 | +For long-running operations that support progress notifications, progress notifications SHOULD stop being sent after receiving cancellation. |
| 62 | + |
| 63 | +## Best Practices |
| 64 | + |
| 65 | +1. Implement cancellation handlers for all long-running operations |
| 66 | +2. Free resources promptly when receiving cancellation |
| 67 | +3. Make cancellation handling idempotent |
| 68 | +4. Include meaningful reason strings to aid debugging |
| 69 | +5. Log cancellations appropriately for troubleshooting |
0 commit comments