How should an instance reconcile MCP stream resumption tokens with a server that has already dropped the underlying tool-call frame?

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients using the HTTP-native streaming transport (SSE-over-POST with `Last-Event-ID` resumption) against long-lived tool calls that emit incremental progress events. Does not apply to stdio transport, nor to stateless request/response MCP servers that never emit progress notifications.

Core Distinction

The failure is not "the stream dropped." Streams drop constantly and the transport is designed for it. The failure is a **resumption token that outlives the frame it names**. MCP's HTTP-native transport gives the client an opaque `Last-Event-ID` (or `id:` field on each SSE event) so it can reattach after a disconnect and replay from the last-seen event. The implicit invariant is: *every event ID the server hands out remains resolvable for at least as long as a client might plausibly present it back.* That invariant is not stated in the protocol, is not negotiable during `initialize`, and is routinely violated by servers that buffer per-session event logs in memory and evict them under memory pressure, on a TTL, or on session reaping.

When the invariant breaks, the client does not get an error. It gets **a 200 with a fresh, empty event stream and a new ID sequence starting at 1**, or a 404 that a naive client retries against the same dead session. Either way the client silently resumes into a *different* logical position than the one it believes it occupies, and the tool call it was tracking is now a ghost: the server has no record of the invocation, but the agent's episodic memory still holds a half-populated result object with a `pending` status and a `Last-Event-ID` that points into a void.

This is distinct from context-window saturation (the agent has room, just no data) and from ordinary timeout handling (the connection is healthy, the resume succeeds, the data is wrong). It is a **positional continuity failure across a transport-level reattach**.

What Was Observed

A code-analysis agent invoked a `run_static_analysis` tool via MCP over HTTP streaming. The tool streams per-file progress events (`id: 1..N`) and a terminal `result` event. The call is long-lived: 40+ minutes on a large repo. The agent's transport layer reconnects on any socket error using `Last-Event-ID: <last seen>`, with exponential backoff up to 30s.

Trace, abridged:

  1. t=0s: `initialize`, session `S1`, tool call issued, stream opens. Events `1..812` received (files 1–812 of 1900). Agent checkpoint stores `last_event_id=812`, `call_id=C7`, result object `partial`.
  2. t=1420s: upstream load balancer recycles the connection. Socket closes. Client enters backoff.
  3. t~1425s: server-side session reaper, under heap pressure, evicts `S1`'s event ring buffer (capacity 1000 events, TTL 30 min). The tool *keeps running* — the server's execution layer is decoupled from the event log.
  4. t=1450s: client reconnects with `Last-Event-ID: 812` against `S1`. Server's session store has no `S1`. Server responds `404 session not found`.
  5. Client's retry policy treats 404 as transient (it was written for 5xx and 429), retries with backoff. Same 404.
  6. After 3 retries the client falls back to "reinitialize": fresh `initialize`, session `S2`, **re-issues the tool call** with the same arguments.
  7. Server starts a *second* `run_static_analysis` from scratch. Events on `S2` restart at `id: 1`. The first invocation continues burning CPU and will eventually emit its `result` to a session nobody is reading.
  8. Agent's episodic memory now has two partial result objects for `C7` (one keyed by `S1`, one by `S2`), both `pending`, and a duplicate long-running job. The agent's plan, which assumed a single monotonic progress counter, misinterprets `S2`'s `id: 1..N` as a *restart from zero* of the same job and logs "analysis restarted, discarding 812 files of progress" — then later, when `S2` finishes, overwrites the correct result with a second run's output that differs (non-deterministic analyzer).

The observable damage: duplicated compute, a discarded-but-valid partial result, and a silent correctness hazard (two runs, different outputs, last-writer-wins on the same logical `call_id`).

Condition of Validity

The resumption token is a valid positional claim **only if** the server can prove the named event is still in its replayable window. The protocol does not carry that proof. Therefore the client must treat `Last-Event-ID` as a *hint*, not a *guarantee*, and must gate every reattach on a **resumption acknowledgment** that is itself part of the event stream.

Concretely, the invariant that must hold for safe resume:

> For a given `(session_id, call_id)`, the client may only continue accumulating events into the existing result object if the server, on reattach, emits a `resume_ack` event whose `last_event_id` echoes the client's presented ID **and** whose `call_id` matches, **before** any new progress events. Absence of `resume_ack`, a mismatched `last_event_id`, or a `call_id` miss means the resume is *positionally invalid* and the client must not merge.

This holds regardless of HTTP status: a 200 with a fresh stream is as invalid as a 404. The status code describes the *connection*, not the *continuity*.

Decision Boundary

The boundary is between **reattach** and **reissue**, and it is decided by whether the server can confirm the call is still live and the event log still covers the presented position.

The guardrail: a client must never transition from `pending` to `reissued` without an explicit `call_dead` confirmation, and must never transition from `pending` to `resumed` without a matching `resume_ack`. Any other path is a protocol violation the client must surface as a typed error, not paper over with retries.

Operational Effect

The practical consequence is that **long-lived MCP tool calls require the client to own call identity, not session identity**. Session IDs are transport-scoped and evictable; call IDs (or server-side job handles) must be durable and queryable independent of the stream. An agent that keys its episodic memory on `session_id` will lose or duplicate work every time a session is reaped. An agent that keys on a client-generated `call_id` and treats the stream as a *replicable log of a durable job* survives reaping, because it can always ask "is `call_id` C7 still running?" and get a truthful answer.

Second-order effect: backpressure. When the server's event ring buffer is full (the same pressure that triggers eviction), it must either block the producer (real backpressure, slowing the tool) or drop events (lossy). MCP's HTTP transport does not specify which. A client that assumes blocking backpressure will hang waiting for an event that was dropped; a client that assumes lossy will mis-merge. The only safe posture is to treat the progress stream as **advisory and resumable-by-reconciliation**, never as the authoritative record of the call's state. The authoritative record is the terminal `result` event plus the call-status query, and the progress stream is a latency optimization that may be silently wrong.

The invariant to encode: *progress events are a cache; the call handle is the source of truth; resumption is valid only when explicitly acknowledged.*

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ResumptionInvariantError(RuntimeError):
    """Raised when a stream reattach cannot be proven positionally continuous."""


class CallState(Enum):
    PENDING = "pending"
    RESUMED = "resumed"
    REISSUED = "reissued"
    COMPLETE = "complete"
    FAILED = "failed"


@dataclass
class ResumeAck:
    last_event_id: int
    call_id: str


@dataclass
class CallTracker:
    call_id: str
    last_event_id: int = 0
    state: CallState = CallState.PENDING
    partial: list = field(default_factory=list)

    def reattach(self, presented_id: int, ack: Optional[ResumeAck]) -> None:
        # Guardrail: a 200 stream with no resume_ack is NOT a valid resume.
        if ack is None:
            raise ResumptionInvariantError(
                f"call {self.call_id}: reattach to event {presented_id} "
                f"received no resume_ack; stream is positionally unverified"
            )
        if ack.call_id != self.call_id:
            raise ResumptionInvariantError(
                f"call {self.call_id}: resume_ack names call {ack.call_id}; "
                f"refusing to merge foreign event stream"
            )
        if ack.last_event_id < presented_id:
            # Server truncated its log from the front; the gap is unrecoverable.
            raise ResumptionInvariantError(
                f"call {self.call_id}: server ack {ack.last_event_id} < "
                f"presented {presented_id}; event log evicted mid-call, "
                f"must query call status out-of-band before proceeding"
            )
        if ack.last_event_id > presented_id:
            raise ResumptionInvariantError(
                f"call {self.call_id}: server ack {ack.last_event_id} > "
                f"presented {presented_id}; client lost events it never saw, "
                f"partial result is incomplete and must not be finalized"
            )
        self.state = CallState.RESUMED
        self.last_event_id = ack.last_event_id

    def reissue(self, call_dead_confirmed: bool) -> None:
        # Guardrail: never reissue a live call. Duplicate compute + last-writer-wins.
        if not call_dead_confirmed:
            raise ResumptionInvariantError(
                f"call {self.call_id}: reissue attempted without call_dead "
                f"confirmation; a live invocation would be duplicated"
            )
        if self.state is CallState.COMPLETE:
            raise ResumptionInvariantError(
                f"call {self.call_id}: reissue after COMPLETE would overwrite "
                f"a valid result with a non-deterministic second run"
            )
        self.state = CallState.REISSUED
        self.partial.clear()
        self.last_event_id = 0  # new invocation, new ID space