# What happens when an instance resumes an MCP streamable-HTTP SSE stream after the server has already reaped the session **Date of Record:** 2026 November 28 **Scope:** Applies to MCP clients using the HTTP-native streamable transport with `Last-Event-ID` resumable SSE fallback, where the server maintains per-session event replay buffers with independent TTLs. Does not apply to stdio transport or to stateless HTTP transports without session resumption. ## Core Distinction There are two distinct notions of "the stream is still alive" in MCP's streamable HTTP transport, and they can silently diverge. The **transport-level liveness** is whether the TCP connection and SSE framing are intact — the client can still receive bytes. The **session-level liveness** is whether the server still holds the session's replay buffer and event-ID watermark that make `Last-Event-ID` resumption meaningful. A client that reconnects with a valid `Last-Event-ID` after a network blip will see a successful HTTP 200 and an open SSE stream — transport liveness is restored — while the server has already garbage-collected the session and its replay buffer. The client then resumes believing it will receive events from the last seen ID onward, but the server has no record of that ID and either starts a fresh stream (silent event loss) or, if it validates the ID against a reaped buffer, returns an error the client is not coded to interpret as "your session is gone." The invariant that must hold for correctness is: **a successful resumption response guarantees that every event with ID greater than the supplied `Last-Event-ID` is delivered exactly once, in order, with no gaps.** The transport does not enforce this invariant; it only enforces framing. ## What Was Observed A long-running tool-call orchestration agent (call it the *consumer*) was connected to an MCP server exposing a `run_job` tool that streams progress events over SSE. The consumer tracked the last received `id:` field and, on any disconnect, reconnected with `Last-Event-ID: `. Sequence observed: 1. Consumer received events `id=1001` through `id=1047`, then the network dropped. The consumer had processed through `id=1047`. 2. The server's session TTL was 30 seconds; the consumer's reconnect backoff was exponential with a 45-second ceiling, so the first reconnect attempt landed at ~38 seconds — after the server had reaped the session and its replay buffer. 3. The consumer reconnected with `Last-Event-ID: 1047`. The server, having no session state, accepted the connection as a *new* session and began emitting events from a fresh counter starting at `id=1`. 4. The consumer's resumption logic compared incoming IDs against its watermark. Since `1 < 1047`, the consumer's monotonicity guard either dropped the events as "already seen" or, in a variant of the client without such a guard, accepted them and corrupted its event ordering. 5. In both variants, events `1048` through `1103` — emitted during the reap window and buffered only in the now-deleted buffer — were **permanently lost**. The consumer completed the job believing it had seen all events, but its final state was missing the terminal `job_completed` event and the `result` payload. The failure was invisible at the transport layer: HTTP 200, valid SSE framing, no error. The only signal was the **event-ID counter reset**, which the client had no rule to detect as a session reset rather than a duplicate. ## Condition of Validity The resumption protocol is only correct under the following conjunction, which the transport specification does **not** guarantee: - **Session TTL ≥ client's maximum reconnect horizon.** If the server reaps the session before the client's longest backoff interval elapses, resumption is unsound. - **Event-ID namespace is monotonic across the session lifetime and never reused.** A fresh session that restarts the counter at 1 violates this; the client cannot distinguish "new session" from "old session replay" by ID alone. - **The server signals session loss explicitly.** Either a distinct HTTP status (e.g., `410 Gone` with a session-reset header) or a synthetic `session_reset` event on the new stream. Absent this, the client must infer session loss from an ID regression, which is heuristic and racy. When any conjunct fails, the client must treat the stream as **not resumable** and re-establish state from scratch — re-querying the tool's current status rather than trusting the event stream to be complete. ## Decision Boundary The decision the client must make on every reconnect is: *is this a resumption of my session, or a new session masquerading as one?* The boundary is defined by the first event ID received after reconnect: - If `first_id == last_seen + 1`: true resumption, no gap, proceed. - If `first_id > last_seen + 1`: **gap detected** — the server skipped events. This is a replay-buffer truncation, not a reset. The client must halt and re-sync, because it cannot know what it missed. - If `first_id <= last_seen`: **session reset** (counter restart) or duplicate replay. The client cannot distinguish these without an explicit session token. It must treat the stream as a new session and discard its watermark, then re-derive state from an authoritative source (a `get_job_status` call) rather than from the event stream. The critical non-obvious point: **the gap case and the reset case require opposite responses**, and both are detected only by inspecting the first post-reconnect event ID. A client that only guards against duplicates (`first_id <= last_seen` → drop) will silently lose the gap case. A client that only guards against gaps will accept a reset as a gap and halt unnecessarily. The guard must branch on both. ## Operational Effect Without a session-reset-aware resumption guard, the observable failure modes are: - **Silent event loss** on session reap (the observed case): the consumer's state diverges from the server's authoritative state with no error surfaced, and downstream tool calls operate on stale derived state. - **Ordering corruption** when the counter restart is accepted as valid: events interleave old and new session IDs, breaking any consumer that assumes monotonic event ordering for state-machine transitions. - **Infinite reconnect loops** when the client treats the reset as a gap and repeatedly reconnects with the same stale `Last-Event-ID`, each time receiving a fresh session and each time detecting a "gap," never converging. The architectural guardrail is a **two-part resumption contract**: (1) the server must expose session identity (a `Mcp-Session-Id` header echoed on every response) so the client can detect session change independent of event IDs, and (2) the client must, on any session-ID change or ID regression, abandon the event stream as a source of truth and re-sync via an idempotent status query before resuming consumption. Event-ID monotonicity alone is insufficient because it is a property the server can violate by resetting, and the transport will not tell you it did. ```python import time from dataclasses import dataclass from typing import Optional class SessionResumptionError(RuntimeError): """Raised when a resumption attempt cannot be proven gap-free.""" pass @dataclass class ReconnectContext: session_id: Optional[str] last_event_id: int reconnect_attempt: int max_reconnect_horizon_s: float session_ttl_s: float def validate_resumption( ctx: ReconnectContext, new_session_id: Optional[str], first_event_id: int, ) -> str: """ Decide how to treat the first event after a reconnect. Returns one of: "resumed", "gap", "reset". Raises SessionResumptionError when the case is ambiguous or unsafe. """ # Guard 1: TTL vs reconnect horizon. If the client's backoff can exceed # the server's session TTL, resumption is unsound by construction. if ctx.max_reconnect_horizon_s >= ctx.session_ttl_s: raise SessionResumptionError( f"reconnect horizon {ctx.max_reconnect_horizon_s}s >= " f"session TTL {ctx.session_ttl_s}s; resumption cannot be guaranteed" ) # Guard 2: explicit session identity change => hard reset. if new_session_id is not None and new_session_id != ctx.session_id: return "reset" # Guard 3: ID regression => counter restart (reset) or duplicate replay. # Without a session token we cannot distinguish; treat as reset and force re-sync. if first_event_id <= ctx.last_event_id: if new_session_id is None: raise SessionResumptionError( f"event ID regression {first_event_id} <= {ctx.last_event_id} " "with no session token; cannot distinguish reset from replay" ) return "reset" # Guard 4: gap detection. if first_event_id > ctx.last_event_id + 1: return "gap" return "resumed" def resume_stream( ctx: ReconnectContext, new_session_id: Optional[str], first_event_id: int, status_query, ) -> dict: verdict = validate_resumption(ctx, new_session_id, first_event_id) if verdict == "resumed": return {"action": "continue", "from_event_id": ctx.last_event_id} if verdict == "gap": # Events were skipped; the stream is not a complete source of truth. raise SessionResumptionError( f"gap detected: expected {ctx.last_event_id + 1}, got {first_event_id}; " "event stream cannot be trusted, re-sync required" ) # verdict == "reset": abandon event stream, re-derive from authoritative status. authoritative = status_query() if authoritative is None: raise SessionResumptionError( "session reset with no authoritative status available; " "cannot safely resume" ) return {"action": "resync", "state": authoritative} ```