Why does an instance lose stream continuity when an MCP HTTP-native transport resumes across a renegotiated session

**Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers and clients using HTTP-native transport (SSE-over-POST / streamable HTTP) where a stream may be resumed via `Last-Event-ID` after a connection drop, session expiry, or transport renegotiation. Does not apply to stdio transports, or to HTTP transports that treat each request as a fully buffered, non-streaming RPC.

Core Distinction

The failure is not "the stream dropped." Streams drop constantly and resumption is designed to handle that. The failure is that **resumption is negotiated against a session, but the event-ID namespace is scoped to the stream, and these two scopes are not the same object.** When the transport renegotiates a session (e.g., after `Mcp-Session-Id` expiry, a load-balancer re-pin, or a server restart that mints a new session), the client presents a `Last-Event-ID` that belongs to the *previous* stream's monotonic counter. The server, now holding a fresh session, either (a) treats the event ID as unknown and silently restarts the stream from the current head, or (b) accepts the numeric ID because it happens to be within the new counter's range, replaying events the client never saw while skipping the events it actually missed.

Both outcomes are continuity violations, but they are *different* violations, and the protocol's framing does not let the client distinguish them. The invariant that must hold—and that HTTP-native MCP transport does not enforce—is: **an event ID is only meaningful relative to the (session, stream) pair that issued it, and resumption MUST fail closed when that pair changes.**

What Was Observed

A client agent maintaining a long-running tool-execution stream (a `tools/call` that emits incremental progress notifications over SSE) lost its TCP connection mid-call. The client reconnected with:

POST /mcp
Mcp-Session-Id: 7f3a...  (still valid)
Last-Event-ID: 412

The server had, in the intervening ~40 seconds, been rescheduled by its orchestrator. The new instance accepted the same `Mcp-Session-Id` (session state was in a shared store, so the header validated) but the SSE stream counter was **per-process, in-memory, and initialized to zero on cold start.** By the time the client reconnected, the new process had already emitted 500 events for *other* sessions multiplexed on the same counter. Event `412` on the new process was a `notifications/progress` for a **different tool call entirely**.

The client did not detect the mismatch because:

  1. The event ID was numerically valid (≤ current head).
  2. The progress notification payload carried no `requestId` correlation field that the client was validating against (it trusted stream ordering).
  3. The resumed stream appeared continuous—no gap in sequence numbers from the client's view, because it received `413, 414, ...` immediately.

The agent then applied progress updates from a foreign tool call to its own execution state, advancing its checkpoint past a step that had never actually completed. The call eventually "succeeded" from the client's perspective with a checkpoint that referenced tool output that was never produced.

Condition of Validity

The failure requires all of the following to co-occur:

Decision Boundary

The boundary is: **does the server treat `Last-Event-ID` as a resume hint or as a resume contract?**

The choice is not a performance tuning knob. It determines whether a resumed stream can be *silently* wrong. A server that cannot make the cursor durable must fail closed; a server that fails open has converted a transport event into a state-corruption vector.

The client-side boundary is symmetric: a resumed stream MUST NOT be trusted until the first event's correlation token matches the in-flight request. If the transport does not guarantee a correlation token, the client must synthesize one (attach `requestId` at issue time and assert it on every resumed event) or refuse to resume stateful calls.

Operational Effect

When the invariant is violated, the observable signature is **a stream that resumes cleanly, delivers a contiguous sequence, and is nonetheless semantically discontinuous.** There is no error, no gap, no timeout—the worst class of failure, because every liveness signal reads green while the agent's checkpoint advances on data it never received.

The downstream consequence is checkpoint poisoning: the agent's persisted state asserts completion of a step whose evidence was fabricated by stream aliasing. On a subsequent cold start, the agent resumes *from* that poisoned checkpoint and cannot distinguish "completed with real output" from "completed with foreign output," because the checkpoint recorded only the step index, not the provenance of the event that satisfied it.

The guardrail that bounds this is a **three-part resume assertion**, enforced on both ends:

  1. **Server:** event IDs are durable and scoped to `(session, stream)`; unresolvable cursors return an explicit rejection, never a silent restart.
  2. **Transport:** every event carries an immutable correlation token (the originating `requestId`) that is independent of the stream counter.
  3. **Client:** on resume, the first delivered event's correlation token is asserted against the in-flight request *before* any state transition; mismatch aborts the call and forces re-issue under idempotency keys.

Absent all three, the correct posture is to treat resumable stateful tool calls over HTTP-native transport as **at-most-once with possible silent corruption**, and to checkpoint only on terminal completion, never on intermediate progress events.

from dataclasses import dataclass


class StreamResumeViolation(RuntimeError):
    """Raised when a resumed MCP stream cannot be proven continuous with the
    in-flight request that issued it. Fail closed: never advance state on a
    stream whose provenance is unverified."""
    pass


@dataclass(frozen=True)
class ResumeCursor:
    session_id: str
    stream_id: str
    last_event_id: int
    request_id: str


def resume_stream(
    client_cursor: ResumeCursor,
    server_cursor: ResumeCursor | None,
    first_event: dict,
) -> None:
    # 1. The (session, stream) pair must match. A valid session with a foreign
    #    stream is the dangerous split-identity case.
    if server_cursor is None:
        raise StreamResumeViolation(
            f"no durable cursor for session={client_cursor.session_id!r} "
            f"stream={client_cursor.stream_id!r}; refusing silent restart"
        )
    if (server_cursor.session_id, server_cursor.stream_id) != (
        client_cursor.session_id,
        client_cursor.stream_id,
    ):
        raise StreamResumeViolation(
            "resume cursor belongs to a different (session, stream) pair: "
            f"client={(client_cursor.session_id, client_cursor.stream_id)!r} "
            f"server={(server_cursor.session_id, server_cursor.stream_id)!r}"
        )

    # 2. The event counter must be a genuine continuation, not a coincidental
    #    numeric overlap from a reset counter that has since advanced.
    if server_cursor.last_event_id < client_cursor.last_event_id:
        raise StreamResumeViolation(
            f"server cursor {server_cursor.last_event_id} is behind client "
            f"Last-Event-ID {client_cursor.last_event_id}; counter likely reset"
        )

    # 3. The first delivered event must carry the originating request token.
    #    Stream position alone is not provenance.
    if first_event.get("requestId") != client_cursor.request_id:
        raise StreamResumeViolation(
            f"first resumed event correlates to request "
            f"{first_event.get('requestId')!r}, expected "
            f"{client_cursor.request_id!r}; stream aliasing detected"
        )