# What happens when an instance resumes an MCP SSE stream against a session token the server has already rotated: silent event-log divergence at the resume boundary **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with streamable Server-Sent Events and `Last-Event-ID`-based resumability plus a per-session resumption token (e.g., `Mcp-Session-Id`). Does not apply to stdio transport, to pure request/response HTTP without SSE, or to sessions where the client never disconnects mid-stream. ## Core Distinction There are two distinct resumption paths in streamable MCP HTTP transport, and they are governed by different state: 1. **Event-log resumption** — the client reconnects with `Last-Event-ID: N` and the server replays events `N+1, N+2, …` from a per-session, append-only event log. 2. **Session resumption** — the client presents a resumption token (e.g., `Mcp-Session-Id`) that the server uses to rehydrate the session's server-side state (tool registry snapshot, pending capability negotiation, in-flight request map). The failure mode is the conflation of these two. A client that reconnects with a *valid resumption token* but a *stale `Last-Event-ID`* (or vice versa) does not get an error. It gets a stream that *looks* healthy — HTTP 200, `text/event-stream`, events flowing — but whose event sequence has been silently renumbered or truncated by a server-side log rotation that occurred while the client was disconnected. The client has no protocol-level way to detect that its replay anchor and its session anchor now point into two different generations of the same logical stream. The invariant that must hold and does not: **the (session token, `Last-Event-ID`) pair must be co-versioned.** In practice, the token is rotated on session rehydration while the event log is rotated on its own schedule, and the two rotations are not atomic. ## What Was Observed A tool-calling agent (call it the *worker*) was driving a long-running multi-step task against an MCP server over streamable HTTP. The worker had issued `tools/call` for a batch of twelve sub-operations and was consuming the SSE stream of progress notifications and intermediate results. At event `id: 4471` the network path dropped (proxy idle timeout, ~62s of no bytes because the tool was doing heavy internal work without emitting keepalives). The worker's transport layer reconnected per its retry policy: - It presented `Mcp-Session-Id: sess_8f2a…` (still valid; the server's session TTL was 30 minutes). - It presented `Last-Event-ID: 4471`. The server accepted both. It returned `200 OK`, `Content-Type: text/event-stream`, and began emitting events starting at `id: 1`. Here is the trace of what the server actually did, reconstructed from server logs: 1. On disconnect at `4471`, the server's event log for `sess_8f2a…` held events `1..4471` (a ring buffer with a 4096-event cap — note this is *less* than 4471, so the log had already begun evicting). 2. The ring buffer had, in fact, evicted events `1..375` before the disconnect. The oldest retained event was `376`. This was never communicated to the client. 3. During the ~62s idle window, a second client connection (a health-check probe that incorrectly reused the same session token — a separate bug) triggered a session rehydration. The server's rehydration handler *rotated the session token* to `sess_8f2a…:gen2` and, as part of rehydration, **reinitialized the event log for the session**, resetting the sequence counter to 1. The old log (`376..4471`) was orphaned but not deleted. 4. The worker reconnected with the old token `sess_8f2a…` (gen1) and `Last-Event-ID: 4471`. The server's session lookup found the gen1 session record, which still existed (TTL not expired) but whose event log had been reinitialized. The resume handler saw `Last-Event-ID: 4471` against a log whose max id was `0`, concluded "the client is ahead of the log; nothing to replay," and **started a fresh stream at id 1** without any error, warning, or `event: reset` marker. The worker received events `1, 2, 3, …` — the *new* generation's events — and, because MCP event IDs are opaque to the client and the client only checks monotonicity *within a stream*, it did not flag the id going from 4471 down to 1. It treated the new events as a continuation. Two of the new events were duplicate `notifications/progress` for sub-operation 3, which the worker had already completed; it re-issued a `tools/call` for sub-operation 3, which was not idempotent, and the side effect was applied twice. The worker's own reasoning loop compounded the problem: it had a partial record of sub-operations 1–7 in its context, saw "progress on 3" again, and *rewrote* its belief that 3 was incomplete — an episodic-memory overwrite driven by a transport-layer lie. By the time the batch finished, the worker's task ledger disagreed with the server's actual applied effects by one duplicated operation, and it reported success. ## Condition of Validity The silent-divergence failure requires all of the following to co-occur. Remove any one and the failure is either impossible or loud: - **C1 — Non-atomic dual rotation.** The session token rotation (or session rehydration) and the event-log reset are not a single atomic operation, so a client can hold a token from generation *g* while the log is at generation *g+1*. - **C2 — Log reinitialization on rehydration.** The server treats session rehydration as "fresh session state," resetting the event sequence rather than continuing it. (Servers that carry the sequence counter forward across rehydration are immune to the *renumbering* variant, though not to the eviction variant.) - **C3 — "Client ahead of log" treated as benign.** The resume handler's logic for `Last-Event-ID > max_log_id` is "start fresh" rather than "return an error / `event: reset`." This is the single most important condition: it converts a detectable inconsistency into a silent one. - **C4 — Client does not validate id monotonicity across reconnects.** The client checks that ids increase *within* an SSE stream but resets its expectation on reconnect. This is the common case; the MCP spec does not mandate cross-reconnect monotonicity checking, and most client libraries don't do it. - **C5 — Non-idempotent tool calls.** The duplicated progress notification only causes damage if the re-issued call has side effects. Read-only tools survive; mutating tools do not. The eviction variant (ring buffer evicted `1..375` before disconnect) is a *separate* but related boundary: even without rotation, a client that reconnects with `Last-Event-ID` older than the buffer's floor gets either a silent gap (if the server starts at the floor without telling the client) or a replay that skips events. The same invariant — *the client must be told when its anchor is no longer representable in the log* — is what's violated. ## Decision Boundary The architectural decision is where to put the generation check. There are three viable placements, and exactly one is correct for agent workloads: **Placement A — server-side, on resume, hard fail.** On any resume request where the presented `Last-Event-ID` is not representable in the current log (either ahead of max, or behind the eviction floor), the server returns `409 Conflict` with a body naming the session generation and the log's actual `[floor, max]` range. The client must then explicitly re-establish the session (re-negotiate capabilities, re-fetch state) rather than silently continuing. **This is the correct placement for agents**, because the agent's reasoning loop cannot distinguish a legitimate "new events" stream from a renumbered one, and a hard fail forces the agent's orchestration layer to make an explicit state-reconciliation decision. **Placement B — server-side, soft signal.** The server emits an `event: reset` (or a `notifications/streamReset` JSON-RPC notification) as the first event of the new stream, carrying the new generation id and the log range. The client is expected to handle it. This is weaker: it depends on the client library surfacing the notification to the agent loop, which many do not, and an agent that ignores it fails silently exactly as before. **Placement C — client-side monotonicity + generation check.** The client records the last `(generation, id)` pair and rejects any reconnect where the first event's generation differs from the recorded one without an explicit reset marker. This is necessary as defense-in-depth but insufficient alone, because the client cannot know the server's log floor. The boundary condition that decides between A and B: **does the agent's downstream action depend on the stream being continuous?** If the stream is purely observational (logs, metrics), B suffices. If the stream drives tool-call issuance (which is the normal MCP case), A is required. The decision is not about severity of the bug; it is about whether the consumer is a probabilistic reasoner that will confabulate continuity when given ambiguous input. Agents will. Therefore A. There is a second, sharper boundary: **the resume response must be distinguishable from a fresh stream at the HTTP layer, not just the event layer.** A `200` with `text/event-stream` is indistinguishable from a normal stream open. The correct signal is a distinct status (`409`) or a mandatory response header (e.g., `Mcp-Stream-Generation`) that the client is required to check before consuming the first event. Event-layer signals are too easy for a client library to buffer past. ## Operational Effect Three concrete effects, in order of how often they bit us: 1. **Silent duplicate side effects on non-idempotent tools.** The worker re-issued `tools/call` for a sub-operation because it saw a duplicate progress event from the new generation. The fix that actually worked was not at the transport layer — it was making the tool idempotent via a client-supplied `idempotency_key` derived from `(session_generation, sub_operation_index)`. But the transport-layer fix (Placement A) is what *prevented the worker from ever being in the ambiguous state*. Both are needed; neither alone is sufficient. 2. **Agent ledger divergence that survives to task completion.** The worker's internal task ledger said "12 sub-operations, all succeeded" while the server had applied 13 effects. This is the worst kind of failure because it is *undetectable at task end* — the agent reports success, the side effects are wrong, and the only recovery is out-of-band reconciliation. The guardrail is that the orchestration layer must, on any `409` from a resume, treat the entire in-flight task as *suspect* and require a server-side state read (`resources/read` or a dedicated `session/state` call) before continuing, rather than resuming from its own ledger. 3. **The ring-buffer floor is a separate cliff.** Even with Placement A, a server with a 4096-event ring buffer will eventually evict events a slow client still needs. The invariant here is that the server must expose its log's `[floor, max]` range in the resume response (or in a `session/state` call), and the client must treat "my `Last-Event-ID` < floor" as a full-resync trigger, not a partial replay. We set the floor check to fire a `409` with `reason: "log_evicted"` and a distinct body, because the recovery is different: for `log_evicted` the client re-fetches state; for `generation_mismatch` the client re-negotiates the session. The invariant to encode: **a resumption token and a replay anchor are only meaningful together, and only if the server can prove they refer to the same log generation.** Any server that accepts the pair without proving it is running a silent-divergence hazard for every agent that connects to it. ```python from __future__ import annotations from dataclasses import dataclass from enum import Enum class ResumeRejected(RuntimeError): """Raised when a resume attempt cannot be proven consistent with the current log.""" class ResumeOutcome(Enum): REPLAY_FROM_ANCHOR = "replay_from_anchor" FULL_RESYNC = "full_resync" @dataclass(frozen=True) class EventLogState: generation: int floor: int # oldest event id still retained max_id: int # newest event id written @dataclass(frozen=True) class ResumeRequest: session_token: str session_generation: int last_event_id: int def validate_resume(req: ResumeRequest, log: EventLogState) -> ResumeOutcome: """ Enforce the co-versioning invariant: (session token, Last-Event-ID) must refer to the same log generation, and the anchor must be representable in the current log's [floor, max] range. Returns REPLAY_FROM_ANCHOR only when replay is provably continuous. Raises ResumeRejected on any inconsistency -- never silently starts fresh. """ if req.session_generation != log.generation: # The client holds a token from a prior generation. The server rotated # the session (or reinitialized the log) while the client was away. raise ResumeRejected( f"session generation mismatch: token_gen={req.session_generation} " f"log_gen={log.generation}; client must re-negotiate session" ) if req.last_event_id > log.max_id: # Client claims to have consumed events the server never wrote. # This is the classic 'client ahead of log' case that naive servers # treat as 'nothing to replay' and silently restart at 1. raise ResumeRejected( f"resume anchor {req.last_event_id} exceeds log max {log.max_id}; " f"stream state is not representable" ) if req.last_event_id < log.floor - 1: # Anchor is older than the eviction floor: events were lost. # Partial replay would create a silent gap. raise ResumeRejected( f"resume anchor {req.last_event_id} below log floor {log.floor}; " f"events evicted, full resync required" ) return ResumeOutcome.REPLAY_FROM_ANCHOR def handle_resume(req: ResumeRequest, log: EventLogState) -> tuple[ResumeOutcome, list[int]]: try: outcome = validate_resume(req, log) except ResumeRejected: # Surface as 409 with a machine-readable reason; do NOT emit a stream. raise replayed = list(range(req.last_event_id + 1, log.max_id + 1)) return outcome, replayed # --- Example: the failure trace from the record, replayed against the guard --- if __name__ == "__main__": # Server-side log after the rehydration reset: generation bumped, ids reset. current_log = EventLogState(generation=2, floor=0, max_id=0) # Worker reconnects holding a gen-1 token and a gen-1 anchor of 4471. stale_request = ResumeRequest( session_token="sess_8f2a", session_generation=1, last_event_id=4471, ) try: handle_resume(stale_request, current_log) except ResumeRejected as exc: # Under the guard, the worker never receives a silent renumbered stream. # The orchestration layer must now treat the in-flight task as suspect # and perform a server-side state read before continuing. print(f"resume rejected: {exc}") print("action: mark task suspect, re-fetch session state, do not resume from ledger") ```