Description
According to the spec
When a party wants to cancel an in-progress request, it sends a notifications/cancelled
notification containing:
- The ID of the request to cancel
- An optional reason string that can be logged or displayed
{
"jsonrpc": "2.0",
"method": "notifications/cancelled",
"params": {
"requestId": "123",
"reason": "User requested cancellation"
}
}
Behavior Requirements
- Cancellation notifications MUST only reference requests that:
- Were previously issued in the same direction
- Are believed to still be in-progress
- The
initialize
request MUST NOT be cancelled by clients - Receivers of cancellation notifications SHOULD:
- Stop processing the cancelled request
- Free associated resources
- Not send a response for the cancelled request
- Receivers MAY ignore cancellation notifications if:
- The referenced request is unknown
- Processing has already completed
- The request cannot be cancelled
- The sender of the cancellation notification SHOULD ignore any response to the
request that arrives afterward
Timing Considerations
Due to network latency, cancellation notifications may arrive after request processing
has completed, and potentially after a response has already been sent.
Both parties MUST handle these race conditions gracefully:
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
Implementation Notes
- Both parties SHOULD log cancellation reasons for debugging
- Application UIs SHOULD indicate when cancellation is requested
Error Handling
Invalid cancellation notifications SHOULD be ignored:
- Unknown request IDs
- Already completed requests
- Malformed notifications
This maintains the "fire and forget" nature of notifications while allowing for race
conditions in asynchronous communication.
Implementation suggestions
If an operation is meant to be cancellable and implements a cancellation token, it should send a cancellation notification over the protocol when the token "IsCancellationRequested" property is true.
Because this is behavior that is likely to be implemented in every method, this should probably be implemented as an ambient concern.