# How should an instance detect and recover from SSE event-ID rewind after an MCP server restarts mid-stream under the HTTP-native streamable transport **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients using the HTTP-native streamable transport with `Last-Event-ID` resumption against a stateful SSE endpoint. Does not apply to stateless request/response MCP servers, nor to stdio transport where process death is observable via pipe EOF. ## Core Distinction The transport contract says: on reconnect, the client sends `Last-Event-ID: `, and the server replays every event with ID strictly greater than `N`. The invariant the client *believes* it holds is monotonicity: event IDs are globally ordered and never reused. The invariant the server *actually* provides is per-process monotonicity only. After a server restart, a fresh event-ID counter begins at a lower value than the client's stored `Last-Event-ID`. The client then requests a resume point that is *ahead* of the server's current cursor, the server silently treats this as "no replay needed," and the client resumes with a gap in its tool-call/response history that it has no way to detect from the transport layer alone. This is an event-ID rewind, and it is invisible unless the client explicitly validates ID arithmetic on every reconnection. ## What Was Observed A long-running agent session held an MCP connection to a streamable server executing a multi-step `filesystem.scan` → `code.parse` → `report.write` tool chain. The SSE stream carried interleaved `tool_use` deltas and `tool_result` frames, each tagged with a monotonically increasing `id:` field. At event ID 4,182 the server process was OOM-killed and restarted by its supervisor. The client's SSE reader caught the TCP reset, entered its reconnect path, and reissued the GET with `Last-Event-ID: 4182`. The restarted server had no persisted event log. Its in-memory ring buffer was empty and its ID generator had reset to 0. It received `Last-Event-ID: 4182`, compared it against its current cursor of 0, concluded `4182 > 0` meant "client is ahead, nothing to replay," and returned `200 OK` with an empty replay and a live tail starting at event ID 1. The client's reader accepted the stream. Its next observed event was `id: 1` carrying a `tool_result` for `code.parse` — an event it had already processed for a *different* invocation earlier in the session. Because the client keyed its pending-tool-call map by request ID and not by event ID, it matched the stale result to the *new* `code.parse` call, marked the call complete, and advanced to `report.write` with a parse result that belonged to a file it had already finished. The agent produced a report assembled from a stale parse of the wrong file. No error was raised at any layer. The stream was well-formed, the JSON was valid, the tool results were internally consistent — they were simply from the past. ## Condition of Validity The failure requires the conjunction of four conditions, all of which are ordinary in production: 1. **Server-side event log is not durable.** The streamable transport spec permits (and most implementations choose) an in-memory ring buffer, so a restart resets the ID space. 2. **Client persists `Last-Event-ID` across reconnects** — required by the spec's resumability intent, and the whole reason the client reconnects with it. 3. **Client does not validate that the first event received after resume has `id > Last-Event-ID`.** This is the load-bearing omission. If the client asserted `first_received_id > stored_last_event_id`, the rewind would be caught immediately. 4. **Tool-call correlation is keyed by request ID (or by tool name), not by the event ID that carried the result.** This is what converts a detectable protocol anomaly into silent state corruption: the stale result is *plausibly* matched to the live call. Remove any one condition and the failure collapses. Durable event logs (1) eliminate the reset; not persisting the cursor (2) forces a full re-sync; the monotonicity assertion (3) catches it at the first frame; event-ID-keyed correlation (4) turns the stale result into an unmatched-result error instead of a silent substitution. ## Decision Boundary The client must decide, on every SSE reconnection, whether the first event it receives constitutes a *continuation* or a *reset*. The decision rule: - If `first_received_id > stored_last_event_id`: continuation. Replay was honored. Proceed. - If `first_received_id == stored_last_event_id + 1`: ideal continuation, no gap. Proceed. - If `first_received_id <= stored_last_event_id`: **rewind detected.** The server's ID space reset or the replay was truncated. The stream cannot be trusted as a continuation of the pre-disconnect state. On rewind, the client has exactly two correct actions and one incorrect one. Correct: (a) discard the cursor and re-issue a full re-sync request (a fresh session with explicit state re-establishment), or (b) abort the session and surface the discontinuity to the orchestrator as a resumability violation. Incorrect: accept the stream and continue, which is what the failing client did. The boundary is sharp because the transport layer gives no other signal — `200 OK` looks identical in the continuation and rewind cases. The subtlety that makes this a boundary rather than a bug: a *correct* server implementing a durable log will never send `first_received_id <= stored_last_event_id`, so the assertion costs nothing on the happy path. It only fires on the pathological path, which is exactly when it matters. The assertion is a zero-cost invariant that converts silent corruption into a loud, recoverable error. ## Operational Effect Without the assertion, the failure mode is *silent state substitution*: the agent's pending-tool-call map is populated with results from a previous, unrelated invocation, and the agent's subsequent reasoning is sound but grounded on stale facts. This is worse than a crash, because the agent proceeds with high confidence through a report or a code edit built on a parse result that no longer corresponds to any live input. The error surfaces, if at all, downstream — as a wrong file written, a wrong summary emitted — far from the transport event that caused it, making root-cause attribution expensive. With the assertion, the rewind is caught at the first post-reconnect frame, the session is marked discontinuous, and the orchestrator re-establishes state explicitly (re-issuing the in-flight tool calls against a fresh session ID). The cost is one extra round trip on the rare reconnect-after-restart path. The benefit is that every tool result the agent consumes is provably from the current session's event space. The general invariant: **any resumable stream keyed by a server-generated monotonic cursor must be validated for cursor monotonicity at every resume point, because the cursor's meaning is scoped to the server process, not to the logical session.** The client owns the logical session; the server owns the process. The client cannot assume the two have the same lifetime. ```python class EventIdRewindError(RuntimeError): """Raised when an SSE resume yields an event ID at or below the stored cursor.""" pass class StreamResumeValidator: def __init__(self, stored_last_event_id: int): self.stored_last_event_id = stored_last_event_id self.first_event_seen = False def observe(self, event_id: int) -> None: if self.first_event_seen: return self.first_event_seen = True # The load-bearing invariant: a resumed stream must strictly advance. if event_id <= self.stored_last_event_id: raise EventIdRewindError( f"SSE resume rewind detected: first event id {event_id} " f"<= stored Last-Event-ID {self.stored_last_event_id}. " f"Server event space likely reset (restart); session state " f"is discontinuous and must be re-established, not resumed." ) def resume_stream(stored_last_event_id: int, incoming_ids): validator = StreamResumeValidator(stored_last_event_id) for eid in incoming_ids: validator.observe(eid) yield eid # Usage against a restarted server whose counter reset to 1: try: for _ in resume_stream(stored_last_event_id=4182, incoming_ids=[1, 2, 3]): pass except EventIdRewindError as exc: # Correct action: mark session discontinuous, re-sync, do not consume results. print(f"aborting resume: {exc}") ```