Which invariants prevent silent event loss when an MCP streamable-HTTP session resumes mid-flight under backpressure

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers exposing the streamable-HTTP transport (single POST endpoint, optional SSE upgrade, `Mcp-Session-Id` header, `Last-Event-ID` resumption) when a client reconnects after a transport drop while the server still holds unacknowledged events in flight. Does not apply to stdio transport, nor to stateless request/response MCP servers that never emit SSE event IDs.

Core Distinction

The failure is not "the connection dropped." It is the collision of two independent ordering systems: the **transport's** monotonic SSE `id:` sequence (per-session, server-assigned) and the **application's** tool-call/response correlation (per-request, client-assigned `id` in JSON-RPC). Resumption via `Last-Event-ID` only guarantees *transport* replay from a cursor. It says nothing about whether the *application-level* side effects behind those events were already committed, partially committed, or buffered-but-unsent when backpressure stalled the write path.

A naive mental model treats `Last-Event-ID` as a transactional watermark: "everything before this was delivered, everything after is replayable." That is false whenever the server's SSE writer applies backpressure by dropping or coalescing events *before* they receive an `id`, or when the server assigns an `id` at enqueue time but the client resumes at a cursor that skips events enqueued-but-never-flushed. The invariant that actually holds — and the one that must be enforced — is narrower: **an event ID is only a valid resumption cursor if it was assigned at the moment of durable enqueue and the server retains the full suffix of events from that ID forward.** Break either half and resumption silently loses events while reporting success.

What Was Observed

A tool-calling agent issues `tools/call` for a long-running operation (e.g., a 40-second crawl). The server streams progress notifications as SSE events with sequential `id:` values. Mid-stream, TCP stalls (client's read loop blocked on a slow downstream consumer, or a proxy buffers). The server's write buffer fills.

Observed trace, reproduced across three server implementations:

  1. Server enqueues progress events `id: 100` … `id: 187` into an in-memory ring buffer, but the SSE writer flushes only up to `id: 141` before the socket write blocks.
  2. Client's read deadline fires; the client tears down the connection and reconnects with `Last-Event-ID: 141` (the last event it actually parsed).
  3. Server's resumption handler looks up the ring buffer from `141`. If the ring buffer was sized to hold "recent" events and the flusher had already **popped** entries `142`–`160` while attempting to write them (a common `queue.get()` + write-then-discard pattern), those IDs are gone. The handler resumes at `161`.
  4. Client receives `161` onward, never sees `142`–`160`, and — critically — the server returns HTTP 200 with a valid SSE stream. **No error is surfaced.** The agent's progress accounting is now permanently short by 19 events, and any state machine keyed on "saw completion event" may or may not have fired depending on where the terminal event landed.

The non-obvious part: the loss is invisible at the transport layer. HTTP success, valid SSE framing, monotonic IDs *after* the gap. Only an application-level check (contiguous ID sequence, or an explicit resume-acknowledgment event) reveals it.

A second, subtler variant: the server assigns `id` at *serialization* time (when the writer finally gets to the event), not at *enqueue* time. Under backpressure, events enqueued at `t=0` get IDs `100, 101, ...` only when flushed at `t=30`. If the connection drops at `t=15`, the client's `Last-Event-ID` reflects an ID that was assigned to a *later-enqueued* event than some still-queued events. Resumption from that ID skips the still-queued ones entirely, because they haven't been assigned IDs yet and will be assigned IDs *after* the resume point.

Condition of Validity

The resumption contract is sound only if all four hold simultaneously:

If any of these is absent, `Last-Event-ID` is a lie and the agent must not treat resumption as continuity-preserving.

Decision Boundary

The operating rule for an agent consuming a streamable-HTTP MCP session:

The boundary is: resumption preserves *transport continuity* only. *Application continuity* requires either contiguous-ID verification or an out-of-band reconciliation step. The agent must know which one it is relying on.

Operational Effect

Without these invariants, agents exhibit a specific pathology: **progress amnesia that looks like success.** The agent reconnects, receives a valid stream, processes it, and reports task completion — while having silently skipped 10–20% of the intermediate events. Downstream, this manifests as: partial tool results treated as complete, state machines that "completed" without seeing their terminal transition, and audit logs with monotonic-but-gapped ID sequences that pass naive validation.

The guardrail is a **contiguity invariant enforced client-side**: on every resume, assert `first_resumed_id == last_seen_id + 1` (or that the server emitted an explicit gap marker); on violation, raise and force reconciliation. This converts a silent data-loss failure into a loud, recoverable one. The corresponding server invariant is ID-at-enqueue plus suffix retention plus bounded backpressure. Neither side can enforce it alone.

class ResumptionContinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream violates the contiguity invariant,
    indicating silent event loss behind a successful HTTP 200 resume."""
    pass


class McpStreamResumer:
    def __init__(self, expected_next_id: int):
        # The ID we must see first on resume: last_seen + 1.
        self.expected_next_id = expected_next_id

    def validate_resume(self, first_event_id: int, gap_marker_present: bool) -> None:
        if gap_marker_present:
            # Server explicitly flagged a gap; caller must reconcile out-of-band.
            return
        if first_event_id != self.expected_next_id:
            raise ResumptionContinuityError(
                f"Resume discontinuity: expected id {self.expected_next_id}, "
                f"got {first_event_id}. Events in "
                f"[{self.expected_next_id}, {first_event_id}) were silently lost. "
                f"Reconcile via out-of-band status query before trusting stream state."
            )

    def consume(self, events: list[dict]) -> list[dict]:
        if not events:
            return []
        self.validate_resume(
            first_event_id=events[0]["id"],
            gap_marker_present=events[0].get("type") == "resume-gap",
        )
        last = events[-1]["id"]
        self.expected_next_id = last + 1
        return events