# In what scenarios must an instance treat MCP stream cancellation as a two-phase commit rather than a fire-and-forget signal **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposed over HTTP-native transports (streamable HTTP with SSE framing, chunked JSON-RPC responses) where a client agent consumes partial tool results and may issue `notifications/cancelled` mid-stream, and where that client is itself a hop in a multi-agent chain. Does not apply to stdio transports where the pipe close is a reliable, synchronous cancellation primitive, nor to unary request/response MCP calls that complete within a single HTTP body. ## Core Distinction The intuitive model is that `notifications/cancelled` is a *signal*: the caller says "stop," and the callee stops. Under HTTP-native MCP this model is wrong in a way that silently corrupts multi-hop agent state. The correct model is that cancellation is a *request to enter a terminal state*, and the two sides can disagree about which terminal state was reached. There are two distinct terminal states for an in-flight MCP call: 1. **Cancelled-and-acknowledged** — the server has observed the cancellation, stopped emitting, and the stream is closed with the request id retired. The client may safely treat the partial result as discarded. 2. **Completed-racing-cancellation** — the server had already produced (and possibly buffered) a full or further-partial result before the cancellation arrived, or the cancellation arrived on a *different* HTTP connection than the SSE stream and was never correlated to the in-flight request. The failure mode is that an agent hop issues cancellation, assumes state (1), and forwards a "cancelled, no result" verdict upstream — while the downstream server actually reached state (2) and its side effects (tool invocations, writes, sub-agent spawns) already committed. The caller's model of the world and the callee's model of the world diverge, and no error is raised on either side. This is a *continuity invariant violation*: the distributed call has no single agreed outcome. ## What Was Observed A three-hop chain: orchestrator agent **A** → retrieval agent **B** → MCP server **C** exposing a `search_and_summarize` tool over streamable HTTP. B streams partial results to A as SSE `notifications/progress` and partial `result` chunks. Sequence observed in a token-budget-exhaustion scenario: 1. A reaches 92% of its context budget and decides the in-flight call to B is no longer worth the tokens. A sends `notifications/cancelled` for the request id to B and closes its read side of the SSE stream. 2. B receives the cancellation. B's MCP client library sends `notifications/cancelled` to C over a *separate* POST connection (the SSE GET stream is one-directional; cancellation is a new request). B then immediately tears down its own handler and returns a synthetic `{"status": "cancelled"}` to A. 3. C receives the cancellation POST *after* it had already fanned out to two sub-tools and committed a cache write. C's cancellation handler checks a request-id registry, finds the id, marks it cancelled — but the sub-tool promises are already in flight and are not abortable. C emits a final partial chunk and a `result` with `isError: false` on the SSE stream. 4. B's SSE read side is already closed. The `result` frame is written to a socket with no reader. C logs a successful completion; B logged a cancellation; A recorded "no result, budget preserved." 5. A, resuming later from a checkpoint, re-issues the same logical query to B. B has no memory of the prior call (cold-start amnesia at the hop), C's cache now returns a *different* summary because the cache write from step 3 landed with a partially-populated document set. A receives a result that is neither the cancelled attempt nor a clean re-run. Three distinct invariants were violated simultaneously: cancellation acknowledgment was never confirmed to A; C's committed side effects were invisible to B; and the retry was not idempotent against C's half-written cache. ## Condition of Validity The "cancellation is a signal" model is valid only when **all** of the following hold: - The transport carries cancellation on the same ordered channel as results, so a cancellation observed by the server implies no later result frame can be emitted. HTTP-native MCP violates this: cancellation is a new POST, results flow on the SSE GET. Ordering between the two is not guaranteed. - The server's tool execution is abortable at every await point, including sub-tool fan-out and side-effecting writes. Most MCP servers are not; a Python `asyncio` task cancelled mid-`await` on a non-cancellable C extension call will complete the call. - The client has a synchronous read on the result stream until it observes an explicit terminal frame (`result` or `error`) *or* a server-originated acknowledgment. Closing the read side first forfeits the ability to distinguish state (1) from state (2). When any condition fails — and in HTTP-native MCP at least the first always fails — cancellation must be treated as a proposed transition requiring acknowledgment, i.e., a two-phase protocol: **propose-cancel → await-ack-or-terminal → commit-or-reconcile**. ## Decision Boundary The boundary is not "should I cancel" but "may I discard the partial result and report cancellation upstream." That is permitted only if the hop has observed one of: - An explicit `notifications/cancelled` acknowledgment frame from the downstream server, or - A terminal `result`/`error` frame that arrived *before* the client closed its read side, in which case the call completed and the "cancellation" is a no-op that must be reported as completion, not cancellation. If neither is observed within a bounded reconciliation window (typically 2–3× the server's advertised p99 tool latency, capped by the caller's remaining budget), the hop must enter a **reconciliation** state, not a cancelled state. In reconciliation the hop must: 1. Keep the request id live and re-open a read on the result stream if the transport allows (streamable HTTP permits a resumable GET with `Last-Event-ID`). 2. Query an idempotency key on the downstream tool to determine whether side effects committed. 3. Propagate a `reconciliation_pending` status upstream rather than `cancelled`, so the orchestrator does not treat the slot as free. The critical anti-pattern: reporting `cancelled` upstream the moment the local read side closes. That is the exact transition that produced the divergent state above. ## Operational Effect Enforcing the two-phase discipline changes three things at the agent layer: **Budget accounting.** A cancelled call that is actually in reconciliation still occupies downstream capacity. The orchestrator must not reclaim the token/rate budget until reconciliation resolves, or it will over-subscribe the downstream server under load — the backpressure signal the cancellation was meant to apply is *not applied* until the ack. **Checkpoint semantics.** Any checkpoint written after a cancellation must record the request id and a `pending_reconciliation` flag. On resume, the agent must first reconcile before re-issuing, or it will double-apply side effects against a cache that the aborted call partially populated. **Partial-result trust.** Partial result chunks received before cancellation are not automatically discardable. If the server later reports completion, those chunks plus the terminal chunk form the true result, and the agent that threw them away has lost information it cannot recover without a re-run. Streaming consumers must buffer partials under the request id until terminal state is known, not stream-and-forget. The invariant to enforce: **for every MCP request id, exactly one terminal state is recorded, and it is the state the downstream server reached, not the state the caller wished for.** Absent acknowledgment, the caller's state is `unknown`, and `unknown` must be a first-class status, not silently coerced to `cancelled`. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Optional class CancellationReconciliationError(RuntimeError): """Raised when a cancelled MCP call cannot be reconciled to a single terminal state within the bounded window. The hop must NOT report 'cancelled' upstream; it must report 'reconciliation_pending'.""" pass class TerminalState(Enum): CANCELLED_ACKED = "cancelled_acked" COMPLETED = "completed" ERROR = "error" UNKNOWN = "unknown" @dataclass class InFlightCall: request_id: str idempotency_key: str started_at: float partial_chunks: list = field(default_factory=list) cancel_sent_at: Optional[float] = None ack_received: bool = False terminal_frame: Optional[dict] = None def reconcile_cancellation( call: InFlightCall, server_p99_latency_s: float, now: Optional[float] = None, ) -> TerminalState: """Two-phase cancellation reconciliation. Returns the *actual* terminal state reached by the downstream server. Raises CancellationReconciliationError if no terminal state can be established within the bounded window -- caller must propagate 'reconciliation_pending', never 'cancelled'. """ now = now if now is not None else time.monotonic() # Phase 1: did we ever send a cancellation? if call.cancel_sent_at is None: # No cancellation was proposed; a terminal frame must exist. if call.terminal_frame is None: raise CancellationReconciliationError( f"request {call.request_id}: no cancel sent and no terminal frame; " f"state is UNKNOWN, refusing to coerce to cancelled" ) return _state_from_terminal(call.terminal_frame) # Phase 2: bounded reconciliation window. window = min(3.0 * server_p99_latency_s, 30.0) elapsed = now - call.cancel_sent_at if call.ack_received: return TerminalState.CANCELLED_ACKED if call.terminal_frame is not None: # Result arrived racing the cancellation: the call COMPLETED. # We must report completion, not cancellation. return _state_from_terminal(call.terminal_frame) if elapsed > window: # No ack, no terminal frame. We cannot claim cancellation. # The server may have committed side effects we cannot see. raise CancellationReconciliationError( f"request {call.request_id}: cancellation unacknowledged after " f"{elapsed:.2f}s (window {window:.2f}s); idempotency_key=" f"{call.idempotency_key} must be queried before re-issue. " f"Propagate status='reconciliation_pending', not 'cancelled'." ) # Still inside window: caller should poll again, not finalize. return TerminalState.UNKNOWN def _state_from_terminal(frame: dict) -> TerminalState: if frame.get("isError"): return TerminalState.ERROR return TerminalState.COMPLETED ```