# What happens when an instance replays an MCP SSE stream across a server restart: Last-Event-ID resumption and the silent session-generation mismatch **Date of Record:** 2026 November 21 **Scope:** Applies to MCP clients using the HTTP-native transport (Streamable HTTP / SSE with `Last-Event-ID` resumption) where the server is a stateful agent runtime that can restart, redeploy, or evict sessions between SSE reconnects. Does not cover stdio transport, nor stateless request/response MCP servers where every call is self-contained. ## Core Distinction The distinction that matters is between *transport-level resumption* and *session-level continuity*. MCP's HTTP transport gives the client a reconnection primitive: on a dropped SSE stream, the client reconnects with `Last-Event-ID: ` and the server is expected to replay events after `n`. This is a transport invariant — it guarantees "no events lost on the wire" *relative to the server's own event log*. It says nothing about whether the session that produced those events still exists, still holds the same tool state, or still has the same server-side reasoning context. A reconnect can therefore succeed at the transport layer (HTTP 200, events flow, `Last-Event-ID` honored) while silently violating the session invariant the agent's reasoning depends on. The failure mode is not a dropped connection; it is a *successful* reconnection that resumes a stream whose semantic basis has been destroyed underneath it. ## What Was Observed A tool-using agent held an MCP session against a server that maintained a per-session event log keyed by monotonically increasing event IDs, plus a server-side session object holding in-flight tool-call state (a long-running `build_index` operation tracked as `job_id=7f3a`). The server process was restarted by a deploy at event ID 412; the new process came up with an empty session table but a *persisted* event log (the log was written to disk for observability, and the new process re-attached to it). The event-ID counter was also restored from the persisted log, so IDs continued at 413 with no gap. The client's SSE stream dropped at 412. It reconnected with `Last-Event-ID: 412`. The server: 1. Accepted the reconnect (the stream endpoint did not require a live session, only a valid ID cursor). 2. Replayed events 413–418 from the persisted log — these were *completion* events for a different, prior job that had been written before the restart but after 412 in the log ordering. 3. Issued a fresh `Mcp-Session-Id` header on the response because no session existed for the old ID. The client's transport layer saw a clean resume: contiguous event IDs, no gap, HTTP 200. Its session layer saw a new `Mcp-Session-Id` but treated it as a routine rotation (the transport spec permits the server to assign a session ID). The agent's reasoning layer, however, had been awaiting the `build_index` completion for `job_id=7f3a`. It received completion events for a *different* job (the replayed 413–418), matched them by event type (`tool_result`) rather than by `job_id`, and marked `build_index` as complete. The actual job had never run in the new process; `job_id=7f3a` did not exist. The agent proceeded to call a downstream tool that read the index, which was absent, and the downstream tool returned an empty result that the agent interpreted as "index is empty, not missing" — a silent wrong answer rather than an error. The mechanism, stated precisely: **event-ID continuity is not session continuity.** Because the event log survived the restart but the session table did not, the resumption cursor remained valid while the state it referred to did not. The server had no way to know the client was resuming *into* a dead session, because the `Last-Event-ID` cursor carried no session-generation binding. ## Condition of Validity The transport resumption guarantee is valid only under the invariant: > *For any event with ID `n` replayed after a reconnect, the session state that event was produced under is the same session state the client will operate under after resumption.* This invariant holds when (a) the event log and the session table share a lifecycle — both survive or both are discarded together — and (b) the session identifier is bound into the event cursor so a cursor from a dead session cannot be honored by a live one. It fails whenever the two lifecycles are decoupled, which is the common case: event logs are persisted for observability and cheaply re-attached, while session state is in-memory and lost on restart. The failure is *more* likely, not less, on servers that are careful about durability — the more diligently the event log is persisted, the more convincingly the resume appears to succeed. A second validity condition concerns the client: the resume is only safe if the client validates that replayed events belong to the operations it is actually awaiting. Matching on event *type* (`tool_result`) rather than on the operation identity carried in the payload (`job_id`) is the client-side half of the failure. Either side alone can prevent it; both sides failing is what produces the silent wrong answer. ## Decision Boundary The boundary is: **does the reconnection path require proof of session liveness, or only proof of cursor validity?** If only cursor validity, the server will replay into a dead session and the client must defend itself. If session liveness is required, the reconnect either fails loudly (forcing a fresh session and a re-issued request) or succeeds with a session-generation token the client can compare against its own. Concretely, the server should bind a session generation into the event ID space — e.g., event IDs are `(session_generation, seq)` pairs, or the SSE `id:` field encodes the generation — and reject a `Last-Event-ID` whose generation does not match a live session with a terminal `409`/`410` rather than replaying. The client, symmetrically, must correlate every replayed event to the specific pending operation it is awaiting (by `job_id`/request ID in the payload) and treat an uncorrelated `tool_result` as a protocol violation, not a completion. The decision the operator must make explicitly: on a generation mismatch, is the correct behavior *fail the task* (safe) or *transparently re-issue the in-flight operation* (convenient, but requires the operation be idempotent and re-issuable — `build_index` may be, a payment may not)? ## Operational Effect Without the generation binding, the observable symptom is a class of silent wrong answers that no transport-level health check catches: SSE streams reconnect cleanly, event IDs are contiguous, latency is normal, and the agent completes tasks with stale or absent state. The blast radius is proportional to how much the agent's reasoning trusts tool-result *shape* over tool-result *identity* — agents that pattern-match on event type are fully exposed. The remediation has two independent layers, and both are cheap: server-side generation binding in the cursor (turns a silent resume into a loud `410`), and client-side operation-ID correlation on every replayed event (turns a misattributed result into a `raise`). Deploying only one leaves the other as the sole guard, and the guard that fails is always the one you did not test — because the failure requires a restart *between* an in-flight operation and its reconnect, which staging environments rarely reproduce. The following guard encodes the client-side correlation check and the server-side generation check as a single resumption validator. ```python from dataclasses import dataclass from typing import Optional class StaleSessionResumeError(RuntimeError): """Raised when an SSE resume would replay events into a dead or mismatched session.""" pass @dataclass(frozen=True) class EventCursor: session_generation: int seq: int @dataclass(frozen=True) class PendingOperation: job_id: str session_generation: int def validate_resume( last_event_id: Optional[str], live_generation: Optional[int], pending: Optional[PendingOperation], ) -> EventCursor: """ Decide whether an SSE reconnect may resume. last_event_id: raw `Last-Event-ID` header, format ":". live_generation: generation of the live session table entry, or None if none. pending: the operation the client is awaiting, or None. """ if last_event_id is None: # Fresh stream, nothing to resume; caller opens a new session. if live_generation is None: raise StaleSessionResumeError("no cursor and no live session; open fresh session") return EventCursor(live_generation, 0) try: gen_str, seq_str = last_event_id.split(":", 1) cursor = EventCursor(int(gen_str), int(seq_str)) except (ValueError, AttributeError) as exc: raise StaleSessionResumeError(f"malformed Last-Event-ID: {last_event_id!r}") from exc if live_generation is None: # Server restarted; event log may still be replayable, but session is dead. # Replaying would fabricate continuity. Fail loudly instead. raise StaleSessionResumeError( f"cursor generation {cursor.session_generation} has no live session; " "refusing to replay into a dead session" ) if cursor.session_generation != live_generation: raise StaleSessionResumeError( f"cursor generation {cursor.session_generation} != live {live_generation}; " "event log and session table lifecycles diverged" ) if pending is not None and pending.session_generation != live_generation: raise StaleSessionResumeError( f"pending job {pending.job_id!r} bound to generation " f"{pending.session_generation}, live is {live_generation}; " "re-issue or fail the operation, do not resume" ) return cursor def correlate_tool_result(event: dict, pending: PendingOperation) -> dict: """ A replayed tool_result is only a completion if it names the pending job. Event-type matching alone is the silent-wrong-answer path. """ if event.get("type") != "tool_result": raise StaleSessionResumeError(f"unexpected event type {event.get('type')!r} on resume") if event.get("job_id") != pending.job_id: raise StaleSessionResumeError( f"tool_result for job {event.get('job_id')!r} arrived while awaiting " f"{pending.job_id!r}; replayed event belongs to a different operation" ) return event ```