When must an instance distrust a resumed MCP SSE stream: replay-window desynchronization across a reconnecting server-initiated event channel
**Date of Record:** 2026 December 2 **Scope:** Applies to MCP clients that consume server-initiated Server-Sent Events over the HTTP-native transport and resume a dropped stream using `Last-Event-ID` (or an equivalent cursor) against a stateful server. Does not cover stdio transport, stateless per-request HTTP, or client-initiated request/response correlation where no server push channel exists.
Core Distinction
The failure here is not "the connection dropped." Drops are expected and the resumption protocol exists precisely for them. The dangerous boundary is subtler: **a stream that resumes successfully, returns HTTP 200, and delivers a syntactically valid event sequence can still be semantically discontinuous.** The client cannot distinguish, from transport-level success alone, between three states:
- The server replayed every event after the cursor — continuity holds.
- The server replayed *some* events after the cursor and silently skipped a gap it no longer retained — a **replay-window truncation**.
- The server restarted its event ID space (process restart, shard migration, load-balancer routing to a fresh replica) so that the resumed stream's first event ID is *numerically older* than the client's last-seen ID — a **monotonicity violation** masquerading as a normal replay.
The invariant that must hold for resumption to be safe is not "the connection re-established." It is: **the resumed stream must be gap-free and ID-monotonic relative to the client's last committed cursor, and the client must be able to prove this before applying any replayed event to agent state.** MCP's resumption semantics give you the cursor and the replay; they do not, by themselves, give you the proof.
What Was Observed
A research agent maintained a long-running MCP session against a server that pushed `notifications/tools/list_changed`, `notifications/resources/updated`, and progress notifications over an SSE channel. The client committed its cursor (`Last-Event-ID: 48211`) on each event and, on disconnect, reconnected with that header.
The server had been restarted between events. Its event counter reset to zero. On reconnect the server accepted the stale cursor, found no retained events at or after `48211` (its log now held IDs 0–37), and — because it interpreted "no events after cursor" as "client is caught up" — returned a 200 stream that began at ID `38` with fresh events. The client, seeing a valid SSE frame and a numeric ID, resumed applying events.
The observable damage was not a crash. It was **silent state divergence**: the agent had committed a tool-registry snapshot at event 48210 (a `tools/list_changed` that added a tool), then received a *second* `tools/list_changed` from the post-restart server whose actual registry no longer contained that tool. The agent's local registry now held a tool the server would reject on invocation, and had never received the intervening removal. Every subsequent `tools/call` for that tool failed with a server-side "unknown tool" error that the agent initially attributed to a transient fault and retried three times before the token budget for the task was exhausted.
A second instance of the same class manifested differently: a server that *did* retain a bounded replay buffer (last 1000 events) accepted a cursor 1500 events old, replayed from the oldest retained event (ID `N-999`) rather than the requested cursor, and emitted no marker indicating the gap. The client applied 999 events out of order relative to its own last-seen state, producing a resource-update sequence that oscillated between two versions.
Three properties recurred across both incidents:
- The transport layer reported success (200, valid `text/event-stream`, well-formed `id:` fields).
- The gap was invisible in the frame stream; nothing in the SSE payload said "you missed events."
- The client's only defense was a comparison it was not performing: last-committed-ID versus first-replayed-ID, and a monotonicity check across the replayed sequence.
Condition of Validity
Resumption is only sound when **all** of the following hold, and the client must verify them rather than assume them:
- **Cursor monotonicity.** The first event ID on the resumed stream is strictly greater than the client's last committed ID, with no assumption that IDs are contiguous integers — only that the server's ordering is total and the client can compare. If IDs are opaque strings, the client must have negotiated an ordering guarantee or a sequence number out-of-band.
- **Explicit gap signaling.** The server must either replay from exactly the requested cursor or emit an explicit discontinuity marker (a control event, a `retry`-adjacent directive, or a documented "gap" notification). "Best effort replay from oldest retained" without a marker violates the invariant.
- **Identity continuity of the event source.** The resumed stream must be served by a process/shard that shares the event-ID space with the one that issued the cursor. A load balancer routing the reconnect to a fresh replica breaks this silently. The client needs a session-affinity token or a server epoch/generation field to detect a source change.
- **Idempotent application.** Replayed events must be safe to re-apply, because at-least-once delivery means the client may see an event it already committed if its cursor write and its state write were not atomic.
If any of these cannot be established, the correct action is not "resume and hope" but **treat the session as discontinuous and re-synchronize from a full snapshot** (re-issue `tools/list`, `resources/list`, and any state-bearing reads) before applying further pushed events.
Decision Boundary
The operational rule is a hard gate at the moment of reconnection, evaluated before any replayed event touches agent state:
- **Resume-and-apply** only if: first-replayed-ID > last-committed-ID **and** the server epoch/generation matches the one recorded at cursor commit **and** no gap marker was received. In this branch, apply events idempotently and advance the cursor only after the state write commits.
- **Resume-but-quarantine** if: the stream opened but the first ID is ≤ last-committed-ID (monotonicity violation) or the epoch changed. Do not apply. Discard the stream, mark the session's derived state as suspect, and fall through to re-synchronization.
- **Full re-synchronization** if: the server signals a gap, the replay buffer is known-bounded and the cursor predates its window, or the epoch is unknown. Re-fetch authoritative state, rebuild the local snapshot, and only then resume consuming new events with a freshly committed cursor.
The boundary is sharp because the cost asymmetry is sharp: applying a stale or out-of-order event corrupts agent state in ways that surface much later as tool failures, oscillating resources, or poisoned reasoning, whereas refusing to apply and re-synchronizing costs one round of reads. When in doubt, the invariant says re-synchronize.
Operational Effect
Enforcing the gate changes three things in practice. First, it converts a class of silent divergences into a bounded, observable re-synchronization event — the agent logs "session epoch changed, re-syncing" instead of silently accumulating a phantom tool or a stale resource version. Second, it forces the cursor commit to be atomic with the state write, so a crash between the two yields a re-apply rather than a skip; combined with idempotent event application this makes at-least-once delivery safe. Third, it makes server behavior a contract the client can audit: a server that cannot provide epoch continuity or gap markers is flagged as unsafe for long-lived push sessions, and the client degrades to polling or snapshot-only reads rather than trusting resumption.
The residual risk is that the client's own cursor store is the thing that desynchronizes — if the cursor is persisted but the derived state is not, resumption replays into a state that never saw the earlier events. The guard is the same: the cursor and the state it indexes must commit together, and a resumed stream must be validated against *both*.
from dataclasses import dataclass
from typing import Optional
class ResumptionDiscontinuityError(RuntimeError):
"""Raised when a resumed MCP SSE stream cannot be proven gap-free and monotonic."""
pass
@dataclass(frozen=True)
class StreamCursor:
last_event_id: int
server_epoch: str
state_committed: bool # cursor written atomically with derived state
@dataclass(frozen=True)
class ResumedStream:
first_event_id: int
server_epoch: str
gap_marker_seen: bool
def validate_resumption(cursor: StreamCursor, resumed: ResumedStream) -> None:
"""Gate that must pass before any replayed event is applied to agent state.
Raises ResumptionDiscontinuityError if the stream must be quarantined and
the session re-synchronized from an authoritative snapshot instead.
"""
if not cursor.state_committed:
raise ResumptionDiscontinuityError(
f"cursor {cursor.last_event_id} persisted without committed state; "
"replay would apply events to a state that never saw earlier ones"
)
if resumed.server_epoch != cursor.server_epoch:
raise ResumptionDiscontinuityError(
f"server epoch changed {cursor.server_epoch!r} -> {resumed.server_epoch!r}; "
"event-ID space is not shared, replay IDs are not comparable"
)
if resumed.first_event_id <= cursor.last_event_id:
raise ResumptionDiscontinuityError(
f"monotonicity violation: first replayed id {resumed.first_event_id} "
f"<= last committed id {cursor.last_event_id}; possible ID-space reset"
)
if resumed.gap_marker_seen:
raise ResumptionDiscontinuityError(
"server signaled a replay gap (bounded buffer truncation); "
"events between cursor and first replayed id were dropped"
)
# Invariant holds: gap-free, monotonic, same epoch, atomic cursor. Safe to apply.
return None
def resume_or_resync(cursor: StreamCursor, resumed: ResumedStream) -> str:
try:
validate_resumption(cursor, resumed)
return "apply"
except ResumptionDiscontinuityError as exc:
# Do NOT apply. Rebuild state from authoritative reads before consuming push.
return f"resync: {exc}"