# How should an instance distinguish a replayed SSE event from a fresh one when resuming an MCP stream after a session-scoped capability downgrade **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients that reconnect to a streamable HTTP transport using `Last-Event-ID` resumption against a server whose session-scoped capability set may have changed between the original connection and the resume. Does not apply to stateless single-request tools or to transports without event-ID replay (e.g., pure stdio). ## Core Distinction A resumable SSE stream carries two independent pieces of state that protocol implementations routinely conflate: the **event cursor** (the `id:` field, replayed by the server from a durable buffer) and the **session capability snapshot** (the negotiated `capabilities` object bound to the `Mcp-Session-Id` at `initialize` time). The cursor is monotonic and server-authoritative. The capability snapshot is *not* monotonic — it can be downgraded mid-session by a server that loses a backend, revokes a tool, or re-negotiates after a restart. The failure mode is that a client resuming at `Last-Event-ID: N` will happily replay events `N+1..M` that were emitted under the *old* capability snapshot, while the server now advertises a *narrower* snapshot. The replayed events reference tool invocations, sampling requests, or resource notifications that are no longer legal under the current session. The client's replay handler, which was written to trust the cursor, applies them anyway. The invariant that is silently violated: **event IDs are only meaningful relative to the capability epoch that produced them.** An event ID is not a global sequence number; it is a position within a stream whose semantics depend on the negotiated capability set at emission time. Resumption across an epoch boundary is not a resumption — it is a replay of foreign history. ## What Was Observed A client agent held an MCP session against a server exposing `tools`, `resources`, and `sampling`. The negotiated snapshot at `initialize` was `{tools: {listChanged: true}, resources: {subscribe: true}, sampling: {}}`. Mid-task, the server's sampling backend (a separate inference service) became unavailable; the server emitted a `notifications/capabilities/changed` event downgrading `sampling` to absent, then continued emitting events under the new snapshot. The client's SSE connection dropped (proxy idle timeout) before it processed the capability-change notification. On reconnect, the client sent `Last-Event-ID: 4471`. The server replayed events `4472..4490` from its ring buffer — including three `sampling/createMessage` requests that had been emitted *before* the downgrade but were buffered after event 4471. The client, whose in-memory capability snapshot still contained `sampling`, executed the three sampling requests and dispatched them to its own inference backend. Two of them succeeded and returned content that the server had already abandoned; the third blocked for 40 seconds on a model call, during which the server's session GC reclaimed the session. The client's subsequent `tools/call` returned `404 Session Not Found`. The trace, compactly: ``` t0 initialize -> snapshot S1 {tools, resources, sampling} t1 ... events 4400..4470 processed under S1 t2 sampling backend dies t3 server emits capabilities/changed -> S2 {tools, resources} [event 4471] t4 server emits sampling/createMessage x3 (pre-downgrade, buffered) [events 4472..4474] t5 SSE connection drops (client cursor = 4470, event 4471 unread) t6 client reconnects, Last-Event-ID: 4470 t7 server replays 4471..4490 from ring buffer t8 client processes 4472..4474 as sampling requests under stale S1 t9 client blocks on inference; session GC fires t10 tools/call -> 404 ``` The critical detail: the server *did* emit the capability change. The client *would* have honored it. The downgrade was lost not by omission but by **interleaving** — the change notification and the now-illegal events were adjacent in the buffer, and the client's replay loop drained the buffer faster than it applied the state transition. ## Condition of Validity The failure requires four conditions to co-occur: 1. **Resumable replay buffer spans a capability epoch boundary.** If the server flushes its buffer on capability change (epoch-fencing the event IDs), the bug cannot occur. Most implementations do not flush, because flushing loses legitimate in-flight events. 2. **The capability-change notification is itself an SSE event with an ID.** If the change is communicated out-of-band (e.g., a separate `GET /capabilities` the client must poll, or an HTTP header on the resume response), the client cannot miss it by cursor racing. 3. **The client applies replayed events without re-validating them against its *current* snapshot.** The client's replay handler trusts the cursor as a proxy for "these events are valid for me." 4. **The client's capability snapshot is updated only by the `capabilities/changed` handler, which runs in the same loop as event application.** If the handler is deferred or batched, the ordering hazard is live. If any one condition is absent, the failure degrades to a benign inconsistency or a clean error. The dangerous case is the conjunction, which is the *default* configuration for a naive but reasonable implementation: durable ring buffer, in-band change notifications, single-threaded event loop, cursor-based resume. ## Decision Boundary The boundary is not "should I resume" but **"what must be true before I apply a replayed event."** The decision rule an instance must enforce: > A replayed event may be applied only if its emission-time capability epoch matches the epoch the client currently holds, or if the event is epoch-agnostic (a plain notification with no capability dependency). If the event's epoch is unknown or older than the current epoch, the event must be **discarded and the cursor advanced**, not applied. This requires the server to stamp events with an epoch identifier. The MCP spec does not mandate this, so the client must either (a) require a server extension that includes an epoch field or a capability-snapshot hash in each event's `data`, or (b) reconstruct the epoch by treating every `capabilities/changed` event as a **barrier**: on resume, the client must scan the replayed range for capability-change events *first*, apply them in order, and only then apply the non-barrier events that follow the last barrier. This is a two-pass replay, and it is the minimum correct behavior when the server does not stamp epochs. The second decision boundary is **session lifetime vs. replay horizon**. If the server's session GC can reclaim a session while the client is mid-replay (as in the trace above), then resumption is not safe unless the client can detect the reclaim before committing side effects. The correct guard is a `Mcp-Session-Id` validity check *before* the first side-effecting replayed event, not after — a cheap `HEAD` or a no-op `ping` on the session, and an abort if `404`. ## Operational Effect The observable effect is **silent divergence with a delayed 404**. The client believes it completed a task; the server has discarded the session and any state the client's replayed actions were supposed to mutate. Because the replayed sampling calls *succeeded* on the client side (they ran against the client's own backend), there is no error to catch at the call site — the failure surfaces only at the next session-scoped operation, by which point the agent has committed downstream work. The architectural guardrail is to make resumption **epoch-aware and barrier-ordered**, and to make session validity a precondition of replay rather than a postcondition of the next call. Concretely: on any resume, (1) probe session liveness, (2) fetch or reconstruct the capability epoch, (3) two-pass replay with capability-change events as barriers, (4) discard events whose epoch predates the current snapshot, (5) only then resume normal processing. The cursor is a hint, not an authority. ```python from dataclasses import dataclass, field from typing import Iterable, Optional class StaleEpochReplayError(RuntimeError): """Raised when a replayed SSE event belongs to a capability epoch older than the client's current session snapshot, or when the session is no longer valid at replay time.""" pass @dataclass class CapabilitySnapshot: epoch: int tools: bool = True resources: bool = True sampling: bool = False @dataclass class SSEEvent: event_id: int kind: str # e.g. "sampling/createMessage", "capabilities/changed", "notification" epoch: Optional[int] # None if server does not stamp epochs payload: dict = field(default_factory=dict) def probe_session_valid(session_id: str, ping) -> bool: """Cheap liveness check before committing to replay side effects.""" try: return ping(session_id) == 200 except Exception: return False def resume_stream( session_id: str, last_event_id: int, current: CapabilitySnapshot, replay: Iterable[SSEEvent], ping, ) -> CapabilitySnapshot: # Guard 1: session must still exist before we replay anything. if not probe_session_valid(session_id, ping): raise StaleEpochReplayError( f"session {session_id} reclaimed before replay at cursor {last_event_id}" ) events = sorted(replay, key=lambda e: e.event_id) # Guard 2: two-pass replay. First pass applies only capability barriers # so that the snapshot is correct before any dependent event is applied. snapshot = CapabilitySnapshot(**vars(current)) for ev in events: if ev.kind == "capabilities/changed": new_epoch = ev.payload.get("epoch", snapshot.epoch + 1) if new_epoch <= snapshot.epoch: continue snapshot = CapabilitySnapshot( epoch=new_epoch, tools=ev.payload.get("tools", snapshot.tools), resources=ev.payload.get("resources", snapshot.resources), sampling=ev.payload.get("sampling", snapshot.sampling), ) # Guard 3: second pass applies non-barrier events, discarding any whose # emission epoch predates the post-barrier snapshot. for ev in events: if ev.kind == "capabilities/changed": continue if ev.epoch is not None and ev.epoch < snapshot.epoch: # Event was emitted under a superseded capability set; drop it # and advance the cursor rather than applying it. continue if ev.kind == "sampling/createMessage" and not snapshot.sampling: raise StaleEpochReplayError( f"event {ev.event_id} requests sampling but current epoch " f"{snapshot.epoch} has sampling disabled" ) # ... dispatch ev under snapshot ... return snapshot ```