What happens when an instance resumes an MCP Streamable HTTP SSE stream against a server that has already garbage-collected the session: silent event replay divergence and the Last-Event-ID contract violation

**Date of Record:** 2026 December 2

**Scope:** Applies to MCP clients and servers using the Streamable HTTP transport with resumable Server-Sent Events (`Last-Event-ID` reconnection) and stateless or semi-stateless session semantics. Does not apply to pure stdio transports or to long-lived stateful sessions where the server guarantees session lifetime exceeds client retry horizon.

Core Distinction

There are two distinct notions of "resumption" that Streamable HTTP conflates at the protocol layer, and the conflation is where the failure lives:

  1. **Transport resumption** — the client reopens the SSE stream, presents `Last-Event-ID`, and the server replays events with IDs strictly greater than the presented value. This is a byte-stream continuity guarantee.
  2. **Session resumption** — the server still holds the logical session (tool-call state, in-flight request context, event log) that produced those event IDs. This is a semantic continuity guarantee.

The MCP Streamable HTTP spec requires the server to support (1) when it advertises resumability, but says nothing enforceable about (2) across arbitrary time gaps in stateless deployments. A server that has evicted the session's event log — common in horizontally scaled, memory-bounded, or TTL-swept deployments — will still accept the reconnect at the HTTP layer. The client, seeing a `200` and a live `text/event-stream`, has no protocol-level signal that the event IDs it is about to receive belong to a *different* logical stream that happens to reuse the same ID namespace. The result is that the agent resumes with a coherent-looking but semantically discontinuous event history: it believes it is continuing, while the server has silently restarted the ID sequence or, worse, is serving a different session's events under a colliding ID space.

What Was Observed

An agent instance executing a multi-step tool workflow over Streamable HTTP issued a POST with `Accept: application/json, text/event-stream`, received an SSE stream, and processed events `id: 41` through `id: 57` before a network partition (NAT rebind) dropped the TCP connection mid-stream. The client's resumption logic, per spec, reconnected with `Last-Event-ID: 57`.

The server was a stateless deployment: sessions were keyed by `Mcp-Session-Id` and stored in a process-local map with a 90-second idle TTL, fronted by a load balancer with no session affinity. The reconnect landed on a *different* server process. That process had no record of session `Mcp-Session-Id: s_9f2c...`, so it treated the request as a fresh session initialization and began emitting events starting at `id: 1` — but critically, it did **not** return `404` or `400` for the unknown session, because the implementation treated an unknown `Mcp-Session-Id` on a GET/reconnect as "create new." The client received `200 OK`, a fresh `text/event-stream`, and events beginning at `id: 1`.

Three failure signatures were observed downstream in the agent's reasoning trace:

The compounding agent effect: the agent, mid-task, resumed with a corrupted belief state — it believed `search_index` had not completed (event dropped), so it re-issued the call, while simultaneously holding a `read_file` result that belonged to a different session's file. Token budget was consumed on a duplicate tool call; the final answer cited a file the agent never actually read in this session.

Condition of Validity

The invariant that must hold for Streamable HTTP resumption to be semantically safe is:

> **For any reconnect presenting `Last-Event-ID: N` on session `S`, either the server holds `S`'s event log and can emit the exact successor events `N+1, N+2, ...`, or it must reject the reconnect with a distinguishable, non-`200` signal (e.g., `404` for unknown session, or a terminal SSE `event: error` with a `session_expired` code) *before* emitting any event whose ID is `<= N` or belongs to a different log.**

This invariant is **violated** whenever any of the following hold, and resumption is unsafe:

The condition of validity is therefore: **resumption is only sound if session lifetime ≥ client retry horizon AND the session store is shared across all server instances that can receive the reconnect AND the client enforces ID monotonicity as a hard precondition.** Absent any one, the protocol layer will happily deliver a `200` and a stream that is semantically a different conversation.

Decision Boundary

The operational decision is: **on reconnect, does the client trust the stream, or does it verify session identity before consuming events?**

The boundary is crossed at the first event received after reconnect. The client must make a binary decision *before* processing that event:

The boundary is *not* at the HTTP status code — a `200` is not proof of continuity. It is at the **first event ID comparison**. The client must treat ID regression as a hard failure, not a dedup opportunity. A dedup layer that silently drops `id <= N` is the specific anti-pattern that converts a detectable discontinuity into an undetectable one: it hides the regression instead of surfacing it.

Operational Effect

When the invariant is enforced (client checks ID monotonicity and treats regression as session loss), the effect is that the agent **fails loudly and re-derives state from a checkpoint** rather than silently corrupting its episodic log. The cost is a re-execution of in-flight tool calls and a token-budget hit; the benefit is that the agent's belief state remains consistent with a single logical session, and any answer it produces is traceable to events it actually observed.

When the invariant is not enforced, the observed effect is **silent state divergence**: the agent's memory contains events from two different logical sessions under a shared ID namespace, tool-call results are misattributed, and the agent may re-issue calls whose results it already holds (wasting budget) or cite results it never received (producing ungrounded output). Because the transport layer returned `200` and a well-formed SSE stream, no error surfaces to the agent's error-handling path; the corruption is only detectable by replaying the event log against the server's actual session history — which, in a stateless deployment, no longer exists.

The architectural guardrail required to bound this is threefold: (1) **globally unique event IDs** (e.g., `session_id:seq` or ULID) so a new session's events can never collide with an old session's; (2) **shared session store with lifetime ≥ client retry horizon**, or an explicit `session_expired` terminal event on eviction; and (3) **client-side monotonicity enforcement** that raises on `id <= Last-Event-ID` rather than deduping. The third is the cheapest and the one most commonly omitted — it is the last line of defense when the first two fail, and it is the only one the agent controls.

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class SessionContinuityError(RuntimeError):
    """Raised when an MCP Streamable HTTP SSE resumption violates the
    Last-Event-ID monotonicity invariant, indicating the server has
    silently restarted or evicted the session's event log."""


@dataclass
class SSEEvent:
    id: int
    event: str
    data: str


@dataclass
class ResumableStreamClient:
    session_id: str
    last_event_id: int = 0
    log: list[SSEEvent] = field(default_factory=list)

    def resume(self, events: Iterable[SSEEvent]) -> None:
        """Consume a reconnected SSE stream, enforcing continuity.

        The invariant: the first event after reconnect MUST have
        id > last_event_id. Any regression means the server is serving a
        different logical stream under a colliding ID namespace, and the
        session must be treated as lost -- not deduped.
        """
        first = True
        for ev in events:
            if first:
                first = False
                if ev.id <= self.last_event_id:
                    raise SessionContinuityError(
                        f"session {self.session_id!r} resumed with event id "
                        f"{ev.id} <= Last-Event-ID {self.last_event_id}; "
                        f"server event log was evicted or restarted. "
                        f"Refusing to append; re-initialize from checkpoint."
                    )
            if ev.id <= self.last_event_id:
                # Mid-stream regression is equally fatal.
                raise SessionContinuityError(
                    f"non-monotonic event id {ev.id} after "
                    f"{self.last_event_id} on session {self.session_id!r}"
                )
            self.log.append(ev)
            self.last_event_id = ev.id


def handle_reconnect(
    client: ResumableStreamClient, reconnected_events: Iterable[SSEEvent]
) -> None:
    try:
        client.resume(reconnected_events)
    except SessionContinuityError:
        # Surface to the agent's control loop: do NOT silently continue.
        # Discard the stream and re-initialize the session from a checkpoint.
        raise SessionContinuityError(
            f"aborting resumption for session {client.session_id!r}; "
            f"agent must re-derive state from last known-good checkpoint"
        )