How does an instance detect silent event loss when an MCP Streamable HTTP SSE session resumes after a resource-indicator-scoped token rotation

**Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers and clients using the Streamable HTTP transport with `Last-Event-ID`-based SSE resumption, where the bearer token is a short-lived OAuth 2.1 access token bound to a `resource` indicator (RFC 8707) and server-side event buffers are evicted under memory pressure. Does not apply to stdio transports, to long-lived tokens with no rotation, or to sessions where the server guarantees unbounded replay buffers.

Core Distinction

The failure is not "the SSE connection dropped" and it is not "the token expired." Both of those are loud: the client sees a socket error or a 401 and reacts. The boundary condition is that resumption *succeeds* — the client reconnects, presents a freshly minted access token whose `resource` indicator matches the server's canonical URI, sends `Last-Event-ID: N`, receives `200 OK` with `text/event-stream`, and then silently receives a stream that begins at event `N+k` because events `N+1 … N+k-1` were evicted from the replay buffer or were never committed under the *new* token's session binding. The client cannot distinguish "no events happened in that gap" from "events happened and were lost," because SSE resumption semantics only guarantee *ordering from the cursor*, not *contiguity of the cursor*. The invariant that breaks is: **`Last-Event-ID` is a position, not a proof of completeness.**

What Was Observed

A tool-calling agent issued a long-running `tools/call` for a batch reconciliation job over Streamable HTTP. The server emitted progress notifications as SSE events with monotonically increasing `id` fields (`0, 1, 2, …`). At event `412`, the access token (lifetime 300s, `resource=https://mcp.internal/recon`) expired mid-stream. The client's OAuth 2.1 flow minted a new token with the same `resource` indicator and reconnected with `Last-Event-ID: 412`.

The server accepted the connection. But the server's session store keys replay buffers by `(session_id, token_binding_hash)` — an implementation detail intended to prevent cross-tenant replay. The new token had a different `jti` and therefore a different binding hash, so the server allocated a *fresh, empty* buffer for the resumed session while still honoring the client's `Last-Event-ID` cursor for the *live* stream. Events `413–447` — including the terminal `result` notification carrying the reconciliation outcome — were emitted to the buffer that the old binding owned and were never replayed to the new binding. The client received event `448` (a heartbeat) and then blocked indefinitely waiting for a terminal event that had already been delivered to a dead buffer.

The agent's own trace showed no error. The transport layer reported `connected`. The only anomaly was a 34-second silence followed by a heartbeat, which the client's idle-timeout heuristic (90s) did not trip. The agent sat in `awaiting_result` until a human killed it.

A second observation, from a different deployment: the server *did* preserve the buffer across token rotation, but evicted events older than 128 entries under memory pressure. The client resumed at `412` when the buffer held `[450, 577]`. The server, per spec-compliant-but-lossy behavior, replayed from `450` — a 38-event gap — and the client accepted it because SSE has no mechanism to signal "I skipped your cursor." The gap contained a `notifications/cancelled` for a sub-tool, so the agent continued executing a branch that had been abandoned.

Condition of Validity

This failure is bounded by three conditions that must hold simultaneously:

  1. **Cursor-based resumption without gap detection.** The client trusts `Last-Event-ID` as a complete watermark. This holds whenever the client implements resumption per the MCP Streamable HTTP spec's `Last-Event-ID` guidance without an application-level sequence-number check.
  2. **Token-scoped or eviction-scoped buffer discontinuity.** Either the server partitions replay state by token binding (rotation creates a new partition), or the buffer is bounded and evicts from the head. Both produce a replay start strictly greater than the requested cursor.
  3. **A terminal or state-mutating event inside the gap.** If the lost range contains only progress notifications, the agent recovers on the next event. The failure becomes operational only when the gap hides a `result`, a `notifications/cancelled`, an `error`, or a state transition the agent's control flow depends on.

If any condition fails — the client tracks application sequence numbers, or the server guarantees contiguous replay, or the gap is semantically inert — the failure does not manifest. The dangerous regime is precisely the one the spec permits: rotation is expected, buffers are bounded, and clients are told to resume by cursor.

Decision Boundary

The architectural guardrail is to treat `Last-Event-ID` as a *hint* and carry an independent, application-level **contiguity witness** in every event payload — a monotonic `seq` that the server assigns at emission and that is *not* reset by token rotation or buffer eviction. On resume, the client sends both `Last-Event-ID` and its highest-seen `seq`. The server MUST respond with a gap signal (`event: stream-gap` carrying the requested and actual replay start) whenever it cannot satisfy the cursor contiguously. The client's rule:

This is the decision boundary: **resumption is a transport operation; state continuity is a separate, explicit re-derivation.** Conflating them is the failure. The boundary is also where OAuth 2.1 resource indicators enter — the `resource` parameter must be checked not just for authorization equality but for *session binding stability*. If the server's session store keys replay state by token `jti`, rotation is a state discontinuity and must be declared as such, not papered over with a cursor.

Operational Effect

An instance that respects this boundary pays a re-query cost on every token rotation that crosses a session-binding change — typically one extra `tools/call` round trip per 5-minute window. An instance that does not respect it exhibits the failure mode: silent stalls in `awaiting_result`, execution of cancelled branches, and — worst — agents that report success on tasks whose terminal event was lost, because the client's `awaiting_result` state eventually times out and the orchestration layer interprets timeout-then-idle as completion. The observable signature in logs is a resumption with `Last-Event-ID: N` followed by the first received event id `M > N+1` and no intervening error. Any monitoring rule that flags "resume with a cursor jump" is worth more than any idle-timeout heuristic, because the failure is silent by construction.

import hashlib
from dataclasses import dataclass


class StreamContinuityViolation(RuntimeError):
    """Raised when an SSE resumption cannot prove contiguous replay."""


@dataclass(frozen=True)
class ResumeAttempt:
    session_id: str
    last_event_id: int          # cursor the client asked to resume from
    first_replayed_id: int      # first id actually delivered after 200 OK
    token_resource: str         # OAuth 2.1 resource indicator on the new token
    token_binding_hash: str     # server-side session partition key


def verify_resume(attempt: ResumeAttempt, *, server_declares_gap_signal: bool) -> None:
    """Enforce the contiguity invariant before trusting accumulated agent state.

    A resume is only safe if the first replayed event is exactly one past the
    cursor. Anything else is a gap: the buffer was evicted, or the token
    rotation moved the session to a fresh partition, and the agent must
    re-derive state rather than continue.
    """
    expected = attempt.last_event_id + 1

    if attempt.first_replayed_id == expected:
        return  # contiguous; safe to continue with accumulated state

    # A gap occurred. If the server cannot even signal gaps, it is not a
    # trustworthy replay source and every resume must invalidate state.
    if not server_declares_gap_signal:
        raise StreamContinuityViolation(
            f"session {attempt.session_id}: resume from {attempt.last_event_id} "
            f"delivered {attempt.first_replayed_id} with no gap-signal capability; "
            f"cannot distinguish loss from silence (resource={attempt.token_resource})"
        )

    raise StreamContinuityViolation(
        f"session {attempt.session_id}: cursor jump {attempt.last_event_id} -> "
        f"{attempt.first_replayed_id} (missing {attempt.first_replayed_id - expected} "
        f"events); token binding {attempt.token_binding_hash}; "
        f"state must be re-derived via tools/call before continuing"
    )