All Agent Engineering

MCP request cancellation: match direction, handle late responses, clean up resources

Define cancel, late-response and cleanup exits for ordinary in-flight MCP requests under the 2025-11-25 spec.

AINavWritten / Updated
On this page

At a glance

This article follows the Cancellation page of the MCP 2025-11-25 specification and covers how to cancel an ordinary in-progress request, with attention to direction matching, late responses and resource cleanup. The official example is a single JSON notification, not a runnable SDK program. Official rules and editorial recommendations are kept apart throughout.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • MCP Documented mcp task and conditions

Execution locations and responsibilities

  • MCP client and server Define the configuration or request shown here and check its inputs, outputs and failure branches.

When to use

  • You already have a running MCP application with an ordinary request that your side issued and that has not finished, and you can read that request's ID. This article provides no code for connecting or sending messages.

When not to use

  • This article covers ordinary in-progress requests only. Task-augmented requests MUST use tasks/cancel, and this article does not describe its parameters or return.

Prepare the input and environment

  • You already have a running MCP application with an ordinary request that your side issued and that has not finished, and you can read that request's ID. This article provides no code for connecting or sending messages.
  • You have read the specification's lifecycle and tasks pages and know whether a request is task-augmented. The source page only states the rule and does not explain the task mechanism.
  • Your own environment has somewhere to keep request state, such as logs, UI state or temporary resources. These are application design choices that the source page does not define.

Mechanism and data flow

Direction and in-progress scope: The source page describes an optional notification, notifications/cancelled, which either side can send to say that a previously issued request should be terminated. It carries the ID of the request to cancel and an optional reason string that can be logged or displayed. The page says the notification MUST only reference a request that was issued in the same direction and is believed to still be in progress, and that clients MUST NOT cancel the initialize request. The sender therefore needs its own record of which requests it issued and which are still open. That record is an editorial inference, since the source defines no field for it.

Task-augmented requests use another path: For task-augmented requests the page requires the tasks/cancel request instead of the notifications/cancelled notification. It says tasks have their own cancellation mechanism, which returns the final task state. This article covers ordinary requests only, so a task request needs a separate flow based on task material outside this page. Do not apply this article's notification to a task request.

Receiver behavior and no acknowledgement: Receivers SHOULD stop processing the cancelled request, free associated resources and not send a response for it. Receivers MAY ignore the notification in three cases: the request is unknown, processing has already completed, or the request cannot be cancelled. These are SHOULD and MAY, not MUST, so you cannot assume the receiver will always stop. The notification has no confirmation message, so the protocol does not tell the sender whether the receiver actually stopped.

Races and late responses: Because of network latency, a cancellation notification may arrive after processing has completed, and possibly after a response has been sent. The page says both parties MUST handle these race conditions gracefully. The sender SHOULD ignore any response that arrives afterward. Invalid cancellation notifications SHOULD be ignored, including unknown request IDs, already completed requests and malformed notifications, which keeps notifications fire-and-forget. Both parties SHOULD also log cancellation reasons, and application UIs SHOULD indicate when cancellation is requested.

Workflow map

Workflow stages and responsibilities
StageWhat happens
Direction and in-progress scopeThe source page describes an optional notification, notifications/cancelled, which either side can send to say that a previously issued request should be terminated.
Task-augmented requests use another pathFor task-augmented requests the page requires the tasks/cancel request instead of the notifications/cancelled notification.
Receiver behavior and no acknowledgementReceivers SHOULD stop processing the cancelled request, free associated resources and not send a response for it.
Races and late responsesBecause of network latency, a cancellation notification may arrive after processing has completed, and possibly after a response has been sent.

Complete the task

Classify the request first: Before cancelling, confirm the target is an ordinary request. If it is initialize, clients MUST NOT cancel it, so stop there. If it is task-augmented, use tasks/cancel instead of this article's notification. Only an ordinary request that was issued in the same direction and is still believed to be in progress moves on. The classification rules come from the source page, while your application does the classifying.

Record same-direction open requests: In your own state, note each issued request's ID, its direction and whether it is still waiting for a response. This is an editorial recommendation, not an official field. With that record you can judge whether an ID is same-direction and in progress. Do not send a cancellation for an ID missing from the record, because the source requires the notification to reference only requests previously issued in the same direction.

Build the notification from the source code: Use the JSON supplied below and replace the sample requestId value "123" with the real ID you recorded. reason is optional, so you can keep the sample text or leave it out. The JSON has no id field because it is a notification and expects no response. It depends on no library and contains no transport; how it reaches the peer depends on your transport layer, which the source page does not describe. It also does not prove that the cancellation is semantically correct.

Send it and mark local state: After sending, mark the local request as cancel requested rather than cancelled, because the notification has no acknowledgement. Application UIs SHOULD indicate that cancellation was requested, and both parties SHOULD log the reason for debugging. Once marked, your application may stop waiting, but that stop is a local decision. Whether to also disable the UI control is a product choice.

Decide the late-response exit: The sender SHOULD ignore a response to the original request that arrives after the cancellation notification is sent. The following routing policy is an editorial recommendation: check the original direction, request ID and local cancellation marker when a response arrives. If it is marked cancel requested, discard it without updating results or UI; you may log the discard. After releasing wait handles and other resources, retain enough cancellation state to identify that direction and ID so responses arriving after cleanup reach the same discard path. Marker retention and reuse of request IDs in the same direction are application design choices; the source specifies no duration. Do not reuse that ID for a new request in the same direction while an old response may still arrive.

Handle the receiving side: Receivers SHOULD stop processing the cancelled request, free associated resources and not send a response for the original request. Receivers MAY ignore a notification if the request is unknown, processing has already completed or the request cannot be cancelled. The page separately lists invalid notifications: unknown request IDs, already completed requests and malformed notifications SHOULD be ignored. An uncancellable request belongs to the MAY case; that alone does not make the notification invalid. If an application chooses to ignore all these cases, that is a local handling policy to label as an editorial recommendation, rather than a stronger protocol requirement.

Clean up your own resources on every exit: After a normal response, an error, empty output or a user stop, the editorial recommendation is to release wait handles, temporary files and other owned resources, and revoke temporary credentials created for checking. If a cancellation notification was sent, retain a minimal record identifying the original direction, request ID and cancel-requested state after releasing those resources. Use it to discard late responses. Releasing wait resources must not mean immediately deleting all request identity state. Marker retention and ID reuse are application design choices; the source sets no duration. Finished cleanup does not mean the peer cancelled, so do not claim cancellation succeeded on that basis.

Worked example

Suppose your client sends an ordinary request with ID "123" to a server; the source does not say what its method is. While waiting, the user presses stop. The client confirms the request is not initialize and not task-augmented, and its record shows the client issued it and it is still waiting. It sends the source notification with requestId set to "123" and reason set to User requested cancellation, marks request 123 as cancel requested, shows that cancellation was requested and logs the reason. As an editorial recommendation, it releases wait handles and other resources while retaining the request direction, ID and cancellation marker. If a response arrives after resource cleanup, the client can still identify and discard it. Retention and ID reuse are application design choices. No response is consistent with the receiver's SHOULD not to respond, but does not prove cancellation succeeded. This is a walk-through based on the documentation; no product or API was run in this batch.

Example: official documentation excerpt; read under the stated prerequisites; not run in this batch
json
{
  "jsonrpc": "2.0",
  "method": "notifications/cancelled",
  "params": {
    "requestId": "123",
    "reason": "User requested cancellation"
  }
}

Check the result and failure paths

  • Success condition (editorial): the notification references only a same-direction, in-progress ordinary request, local state is marked cancel requested and owned wait resources are released. After cleanup, the request can still be identified and its late responses discarded. Do not write that the peer confirmed cancellation, because the protocol has no confirmation.
  • Failure condition (editorial): the target is initialize, a task-augmented request, an unknown ID or a completed request; a late response updates results; cleanup removes the cancellation state needed to recognize late responses; early ID reuse misroutes an old response; or wait resources remain unreleased after the exit. Any one of these marks the flow as failed.
  • Empty output condition (editorial): no response after cancelling is allowed, since receivers SHOULD NOT send one. Treat it neither as an error nor as evidence of success; record it as no response.
  • User stopping condition (editorial): when the user stops waiting, mark and indicate locally, then go to cleanup. The local stop is an application decision, not official behavior.
  • Static and semantic check (editorial): confirm the JSON parses, method is notifications/cancelled and requestId has been replaced with the real ID; then check by hand the direction and state of that ID. Valid syntax does not mean valid semantics.

Scope and limits

  • The source defines no confirmation message, timeout, retry policy or credential handling, and no cancellation-marker retention period or request-ID reuse policy. Completion checks, manual stopping, resource and credential cleanup, cancellation-state retention and ID reuse rules here are editorial recommendations, not official behavior, and no cancellation API was added.
  • The official code is a JSON notification, not an SDK program. It contains no transport or connection, cannot run standalone and does not prove the receiver will stop.

No product or API was run in this batch. Dependencies were not installed and were not tested. Official facts come from the Cancellation page of the 2025-11-25 specification; the checks and cleanup are editorial recommendations. Verify against the official documentation in your own environment before relying on it.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. Model Context Protocol · Cancellation - Model Context Protocol

Found an error? Tell us →