# How should an instance reconcile replayed SSE event IDs with mutated MCP session state after a mid-stream reconnect **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers using the HTTP-native transport (POST for client→server JSON-RPC, GET for server→client SSE stream) with `Last-Event-ID`-based resumability and a server-assigned `Mcp-Session-Id`. Does not apply to stdio transport, to stateless SSE without event IDs, or to sessions where the server does not honor `Last-Event-ID`. ## Core Distinction The distinction that breaks is between **event-log replay** and **state reconstruction**. MCP's streamable HTTP transport gives the client two independent continuity mechanisms: an SSE event log (resumable via `Last-Event-ID`) and a session object (keyed by `Mcp-Session-Id`, holding server-side tool state). These are not the same clock. The event log is an append-only, per-stream sequence. The session is a mutable, shared object that other requests (concurrent POSTs on the same session, server-side async tool completions, or a second SSE stream) advance independently of the event log's sequence. A reconnecting client that assumes "replaying from `Last-Event-ID` restores me to the state I was in when I last saw event N" is making a false invariant. The server will faithfully replay events N+1, N+2, … from its buffer, but the *session state* those events describe may already have moved past them, or the events may reference tool-call IDs, resource versions, or capability handles that the session has since invalidated, garbage-collected, or mutated. The client then applies stale deltas to a live object. ## What Was Observed A tool-execution agent held a session with `Mcp-Session-Id: sess_7f3a`. It had issued `tools/call` for a long-running `code_exec` tool. The server streamed progress notifications over SSE as `event: message` frames with monotonically increasing `id:` fields (e.g., `id: 4100`, `4112`, `4130`). The agent's connection dropped at `id: 4130` (transport-level TCP reset, no `notifications/cancelled` sent). The agent reconnected the GET stream with `Last-Event-ID: 4130`. The server replayed `4131` through `4148` from its per-session ring buffer, then continued live. But between the disconnect and the reconnect (≈2.4 s), the server had: 1. Completed the `code_exec` call and emitted the final `result` on a *different* SSE stream (the agent had an earlier, now-dead GET stream plus a POST response stream; the final result was delivered on the POST's own SSE response body, which the agent had not resumed because it only reconnected the GET stream). 2. Emitted a `notifications/tools/list_changed` on the replayed range, signaling that the `code_exec` tool schema had been hot-reloaded with a new `timeout_s` parameter. 3. Reaped the tool-call handle `call_9c2` from the session's pending-call table after the result was delivered, so any replay event referencing `call_9c2` now points at a dangling handle. The agent, on replay, saw `progress` events for `call_9c2`, concluded the call was still running, and issued a second `tools/call` for the same logical operation — a duplicate side effect (a second `code_exec` invocation against the same working directory). The replayed `list_changed` notification was processed *after* the agent had already dispatched the duplicate call, so the schema it validated against was stale. The failure was not a transport failure. The transport did exactly what it promised: it replayed the log. The failure was that the agent treated log replay as state replay. ## Condition of Validity The invariant "replay from `Last-Event-ID` reconstructs session state" holds **only** when all of the following are true, and in practice at least one is usually false: - **Single-stream session.** Exactly one SSE stream exists per `Mcp-Session-Id`, and all session-mutating events flow through it. False whenever the client has both a GET stream and a POST-with-SSE-response in flight, which is the normal case for `tools/call`. - **No out-of-band mutation.** No server-side async work (tool completion, resource refresh, capability hot-reload) advances the session except by emitting an event on the resumed stream. False for any server with background tasks. - **Buffer retention covers the gap.** The server's replay buffer still contains every event between `Last-Event-ID` and the live head, and no event in that range was compacted. False under memory pressure or long disconnects; servers typically return `404` or reset the stream, which the client must treat as a *new* session, not a resume. - **Handles are stable across the gap.** Tool-call IDs, resource versions, and capability tokens referenced by replayed events are still live in the session. False whenever the server reaps completed calls, which is the correct behavior. The boundary condition is therefore: **resumability is log-level, not state-level.** It is valid to resume the *stream*; it is not valid to assume the *session* did not advance while the stream was down. ## Decision Boundary On reconnect, the instance must decide whether a replayed event is *authoritative* (it describes current session state) or *historical* (it describes a state the session has already left). The decision cannot be made from the event alone, because the event carries no session-generation counter — only a stream-local `id`. The guardrail is to require a **session generation token** distinct from the event ID, and to treat any event whose generation is older than the session's current generation as historical. Concretely: - Every server-mutating operation (tool completion, schema change, handle reap) increments a `session_generation` integer on the session object. - Every SSE event carries the generation it was emitted under, either as a field in the JSON-RPC payload or as a custom SSE field (`x-session-gen:`). - On resume, the client's first action after reconnecting is to issue a lightweight `session/status` (or equivalent) request over POST, read the current `session_generation`, and **discard replayed events whose generation is below it** — they are history, not state. - Replayed events at the current generation are applied; events above it cannot exist (the server cannot replay the future). - If the server returns `404` on resume (buffer gone), the client must not retry with the same `Last-Event-ID`; it must establish a fresh session and reconcile any in-flight tool calls by querying their status by handle, not by replaying. The decision boundary is sharp: **apply a replayed event iff its generation equals the current session generation; otherwise treat it as a tombstone and reconcile the referenced handle out-of-band.** Without a generation token, the only safe policy is to treat *all* replayed events as historical and reconcile every referenced handle (tool call, resource, capability) with a fresh status query before acting on it — which is correct but expensive, and is the fallback when the server does not expose generations. ## Operational Effect With the generation guard, the duplicate `code_exec` is prevented: the replayed `progress` events for `call_9c2` carry generation `g`, the post-reconnect `session/status` returns `g+1`, so the events are discarded as historical, and the agent queries `call_9c2` status directly, learns it completed and was reaped, and does not re-dispatch. The `list_changed` notification, emitted at `g+1`, is applied, and the subsequent `tools/call` validates against the new schema. Without the guard, the failure compounds: stale progress → false liveness → duplicate dispatch → duplicate side effect → possible conflicting results if both calls write the same resource. In multi-agent topologies where a peer or auditor also holds the session, the duplicate is visible to the auditor as a replay discrepancy, and consensus on the tool result fails — the auditor sees two results for one logical call and cannot tell which is authoritative without the same generation token. The invariant to encode: **`Last-Event-ID` resumes the stream; it does not resume the session. Session state is authoritative only at the current generation, and any replayed event below that generation is a tombstone to be reconciled, not a delta to be applied.** ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Any class StaleSessionGenerationError(RuntimeError): """Raised when a replayed SSE event is applied to a session whose generation has advanced past the event's generation.""" @dataclass class SseEvent: event_id: int session_generation: int payload: dict[str, Any] @dataclass class Session: session_id: str generation: int = 0 pending_calls: dict[str, dict[str, Any]] = field(default_factory=dict) applied_event_ids: set[int] = field(default_factory=set) def reconcile_replay( session: Session, replayed: list[SseEvent], *, strict: bool = True, ) -> list[SseEvent]: """Filter replayed SSE events against the session's current generation. Events at the current generation are applied. Events below it are historical tombstones: the referenced handles must be reconciled out-of-band (status query), never applied as deltas. """ if not replayed: return [] # The session generation is authoritative; it may have advanced during # the disconnect via async tool completion or capability reload. current_gen = session.generation applicable: list[SseEvent] = [] for ev in replayed: if ev.event_id in session.applied_event_ids: continue # idempotent: already applied before disconnect if ev.session_generation < current_gen: # Historical. Do not apply. Reconcile handles referenced. handle = ev.payload.get("tool_call_id") if handle and handle not in session.pending_calls: # Handle was reaped; a status query is required before # any re-dispatch. Refuse to proceed silently. if strict: raise StaleSessionGenerationError( f"event {ev.event_id} (gen {ev.session_generation}) " f"references reaped handle {handle!r}; session " f"gen is {current_gen}. Reconcile via status query " f"before acting." ) continue if ev.session_generation > current_gen: # Server cannot replay the future; indicates a protocol fault. raise StaleSessionGenerationError( f"event {ev.event_id} gen {ev.session_generation} exceeds " f"session gen {current_gen}; server replay invariant broken." ) applicable.append(ev) session.applied_event_ids.add(ev.event_id) return applicable ```