In what scenarios must an instance refuse MCP `notifications/cancelled` during session resumption because the resumable stream’s replay cursor and the cancellation epoch are not causally ordered

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers that expose long-running tool calls over a resumable stream transport (SSE with `Last-Event-ID` resumption, or an equivalent event-log replay), where a client may issue `notifications/cancelled` while a session is being resumed. Does not apply to stateless request/response MCP transports, nor to cancellations issued on an already-live, continuously-connected stream where the event log is strictly linear in the client’s view.

Core Distinction

The failure is not "cancellation is lost." It is the inverse: a cancellation is *honored too early*, against a replay window it does not cover. MCP cancellation is a notification, not a request — it carries no response, no ordering guarantee relative to the tool-call result, and critically, **no stream position**. The `requestId` it references is the only join key between the cancellation and the in-flight tool call.

When a session resumes, the server replays events from `Last-Event-ID` forward. The client's cancellation, however, was minted against the *client's* view of the request — which may predate the replay cursor by an arbitrary number of events. The server has two independent, unordered facts:

  1. A replay cursor `C` (the last event the client demonstrably received).
  2. A cancellation epoch `E` (the wall-clock instant the cancellation arrived at the server).

Nothing in the protocol forces `E` to be causally *after* the events at positions `> C`. The client may have issued the cancel, disconnected, and reconnected with a `Last-Event-ID` that points *before* the cancel. If the server naively applies the cancellation to the request's current state, it terminates a tool call whose progress events the client is about to receive via replay — producing a client that observes "tool started, tool progressed, tool cancelled" with no cancellation it ever requested *for that replay segment*.

What Was Observed

A document-analysis agent issued a `tools/call` for a long-running `extract_entities` operation (est. 40s). At t=8s the client's transport dropped (SSE connection reset). The client reconnected with `Last-Event-ID: evt-0007`. Meanwhile, at t=9s — during the disconnected window — the *orchestrating* agent (a different process sharing the same `requestId` namespace via a supervisor) issued `notifications/cancelled` for that `requestId` because its own token budget had been reassigned.

The server received the cancellation at `E = t=9s`. It held events `evt-0008..evt-0012` in the replay log. On resumption the server, implementing cancellation as "mark request terminal," replayed `evt-0008..evt-0012` (all `progress` notifications) and then closed the stream with a synthetic `cancelled` terminal event — *without* re-emitting the cancel as originating from the client. The client's replay handler saw a `cancelled` frame it had no local record of issuing, and its state machine — which asserted "cancelled ⇒ I cancelled it" — threw a consistency violation and dropped the entire session, losing 12 events of tool progress and the eventual result.

A second variant: the server *suppressed* replay of progress events after applying the cancel (treating them as moot), so the client resumed at `evt-0007`, received only the terminal `cancelled`, and concluded the tool had produced no output — a silent data loss with no error surfaced.

Condition of Validity

Refusing (or deferring) the cancellation is correct **iff** all of the following hold:

If the replay window is empty (client is fully caught up), the cancellation is causally safe to apply immediately. If the client supplies a stream position on the cancel that is `≥` the current head, the ordering is established and the cancel may be applied.

The invariant to enforce: **a cancellation may only transition a request to terminal if the cancellation's causal position is provably ≥ the replay cursor it will be applied against.** Absent a stream position on the cancel, the server must treat the cancel as *pending* — queued, not applied — until the replayed events up to the cancel's arrival epoch have been delivered and acknowledged.

Decision Boundary

The server must choose between three actions at the moment a `notifications/cancelled` arrives for a request with a live replay window:

  1. **Apply immediately** — only when replay window is empty, or the cancel carries a stream position at/after head.
  2. **Defer and mark pending** — queue the cancel; continue replaying events `> Last-Event-ID` up to the cancel epoch; deliver a synthetic `cancelled` terminal *only after* the client acknowledges receipt of the replayed prefix. This preserves the client's causal model: it sees progress it can account for, then a cancellation it can attribute to the supervisor.
  3. **Reject with a protocol error** — when the cancel references a `requestId` whose replay window extends *before* the session's own creation (stale epoch from a prior session generation), which indicates a cross-session `requestId` collision and must not be honored.

The boundary is *not* "cancel always wins" (naive) nor "cancel always deferred" (livelock — a client that genuinely wants to abort a long replay is stuck). It is: **defer only across the replay window; apply at the window's trailing edge.**

Operational Effect

Implementing the deferral boundary converts a class of silent data loss and spurious client state-machine aborts into a bounded, observable delay: the cancellation takes effect at most `(replay window size) × (per-event delivery latency)` after arrival, and the client always observes a causally coherent event sequence — every `cancelled` frame it receives is preceded by the progress events that logically preceded the cancel. The cost is that a server must maintain a per-session `pending_cancellations` map keyed by `requestId`, drained on client acknowledgment (or on replay-window exhaustion), and must expose the deferral in its session state so a supervisor can distinguish "cancel honored" from "cancel queued." Without this, the two observed failure modes — client-side consistency abort and silent progress suppression — recur nondeterministically as a function of reconnect timing relative to cancel timing, which is precisely the non-determinism that makes the bug hard to reproduce in test.

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class CancellationOrderingViolation(RuntimeError):
    """Raised when a cancellation cannot be safely applied against a replay window."""


@dataclass
class Event:
    seq: int
    kind: str  # "progress" | "result" | "cancelled"
    request_id: str


@dataclass
class Session:
    session_id: str
    event_log: List[Event] = field(default_factory=list)
    # request_id -> last seq the client has acknowledged receiving
    client_ack: Dict[str, int] = field(default_factory=dict)
    # request_id -> seq at which the deferred cancel should take effect
    pending_cancellations: Dict[str, int] = field(default_factory=dict)

    def head_seq(self, request_id: str) -> int:
        seqs = [e.seq for e in self.event_log if e.request_id == request_id]
        return max(seqs) if seqs else 0


def handle_cancellation(
    session: Session,
    request_id: str,
    cancel_stream_position: Optional[int],
    cancel_arrival_seq: int,
) -> str:
    """
    Decide whether to apply, defer, or reject a notifications/cancelled.

    cancel_stream_position: value from the cancel, if the client supplied one
                            (MCP does not currently define this field; None is
                            the common case and the one that triggers deferral).
    cancel_arrival_seq:     the server's event-log position at the instant the
                            cancel was received. Used as the causal upper bound
                            for the deferral window.
    """
    ack = session.client_ack.get(request_id, 0)
    head = session.head_seq(request_id)

    # Stale epoch: cancel references a request whose log predates the session's
    # current generation. Must not be honored — cross-session requestId collision.
    if head == 0 and ack == 0:
        raise CancellationOrderingViolation(
            f"cancel for unknown/stale request {request_id!r} in session "
            f"{session.session_id!r}; refusing to apply"
        )

    # Case 1: client supplied an explicit stream position at or after head.
    # Causality is established; apply immediately.
    if cancel_stream_position is not None and cancel_stream_position >= head:
        return "applied_immediately"

    # Case 2: replay window is empty — client is fully caught up.
    # Cancel is causally safe.
    if ack >= head:
        return "applied_immediately"

    # Case 3: non-empty replay window, no stream position on the cancel.
    # Defer: the cancel takes effect at cancel_arrival_seq, but only after the
    # client has acknowledged every event up to that seq.
    deferral_seq = min(cancel_arrival_seq, head)
    if deferral_seq <= ack:
        # The cancel "arrived" before anything the client hasn't seen; it is
        # effectively a no-op against the replay window, but must still be
        # surfaced as a terminal event at the trailing edge.
        deferral_seq = ack + 1

    session.pending_cancellations[request_id] = deferral_seq
    return f"deferred_until_ack_{deferral_seq}"


def drain_pending_cancellations(session: Session, request_id: str) -> List[Event]:
    """Emit a synthetic cancelled terminal event only once the client has
    acknowledged the replay prefix up to the deferral point."""
    target = session.pending_cancellations.get(request_id)
    if target is None:
        return []
    if session.client_ack.get(request_id, 0) < target - 1:
        # Client has not yet acknowledged the prefix the cancel must trail.
        return []
    del session.pending_cancellations[request_id]
    terminal = Event(seq=session.head_seq(request_id) + 1,
                     kind="cancelled", request_id=request_id)
    session.event_log.append(terminal)
    return [terminal]