# Under what conditions must an instance refuse to resume an MCP stream after a mid-flight `Last-Event-ID` replay, and why silent resumption corrupts agent state **Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using HTTP-native streaming transports (SSE over HTTP, chunked streaming with event IDs) where a client agent reconnects mid-tool-call and requests resumption via `Last-Event-ID`. Does not apply to stdio transports, single-shot request/response JSON-RPC, or WebSocket transports without event-ID replay semantics. ## Core Distinction The distinction that matters is between **transport-level resumability** and **effect-level idempotency**. An MCP stream can be perfectly resumable at the byte/event layer — the server replays events `N+1..M` after `Last-Event-ID: N`, the client reassembles a contiguous event log, and the framing looks correct — while the *underlying tool call* has already produced irreversible side effects that the replay does not and cannot re-derive. Resumability guarantees event continuity. It does not guarantee that the agent's model of tool-call state matches the server's actual execution state. The boundary condition is this: **a resume is only safe when the server can prove that no event with an ID ≤ the client's `Last-Event-ID` caused a non-replayable side effect, OR that the client's reconstruction of the tool call is a strict prefix of the server's execution trace.** When neither holds, the correct behavior is to fail the resume and force a fresh tool invocation with an explicit reconciliation step — not to silently stitch the stream. ## What Was Observed A long-running MCP tool call (`deploy_artifact`, ~90s) streams progress events with monotonic IDs. The agent's HTTP client drops at event 47 due to a load-balancer idle timeout on a quiet stretch (no events emitted during a 30s build phase). The client reconnects with `Last-Event-ID: 46`. The server, naively implemented, does one of two things: 1. **Replays from an in-memory ring buffer** that was garbage-collected or scoped per-connection. The buffer for the *original* connection is gone; the server either 400s or, worse, starts a *new* event stream from the *current* state of the tool call — which is now at event 63. The client receives event 63 as if it were 47. IDs are not contiguous; the agent's event handler, which assumes monotonic contiguity, either asserts (good) or appends out of order (catastrophic). 2. **Replays correctly from a durable log**, events 47..63. But between 47 and 63 the tool emitted a `checkpoint` event at 52 that the *server* used to advance an internal cursor, and a `partial_result` at 58 that the agent already partially consumed before the drop (the agent had processed events up to 49 in its own model before the TCP drop, though the transport-level `Last-Event-ID` was 46 because 47..49 were in flight). On resume the agent reprocesses 47..49, double-applying a `partial_result` merge and advancing its own state machine past a guard. The observed failure signature: the agent's tool-call state machine reaches `COMPLETED` while the server's execution is at `RUNNING`, or vice versa. The agent then issues a follow-up tool call predicated on a completion that never happened, or abandons a call that is still mutating external state. The non-obvious part: **the transport `Last-Event-ID` is not the agent's application-level cursor.** They diverge by the in-flight window — events the client received but had not yet durably recorded when the socket died. The protocol carries the transport cursor; it does not carry the application cursor. Any resume implementation that assumes they are equal will silently mis-order state. ## Condition of Validity A resume via `Last-Event-ID` is valid only when **all** of the following hold: 1. **Durable, connection-independent event log.** Events are persisted (or deterministically regenerable) keyed by tool-call ID, not by connection. A per-connection buffer makes resume a lie the moment the connection dies. 2. **Event IDs are monotonic and gap-free per tool call**, and the server can replay any suffix `[k, now]` on demand. If IDs are assigned per-connection or reused across calls, `Last-Event-ID` is meaningless. 3. **The client's application cursor is recoverable and ≤ the transport cursor.** The agent must persist its own last-processed event ID *before* acknowledging (or durably record events) such that on reconnect it can request `Last-Event-ID = min(transport_cursor, application_cursor)` and reprocess idempotently. Without this, the in-flight window causes double-application. 4. **Every event in the replayable range is idempotent under reprocessing, or carries a dedup key.** `partial_result` and `checkpoint` events must be safe to apply twice, or the client must dedup by event ID. Events representing *irreversible side effects* (e.g., "artifact pushed to registry") must not be re-emitted as if they will re-occur; they should be replayed as *facts about the past*, marked non-replayable. 5. **The server can distinguish "resume within the live execution" from "resume after execution ended."** If the tool call already terminated (success or failure) while the client was disconnected, the resume must deliver a terminal event and the client must treat it as authoritative — not re-drive the call. If any of 1–5 fails, the resume is **not** valid and the instance must not silently stitch. ## Decision Boundary The operational rule for the agent instance: - **Resume** iff the server's replay is gap-free from the client's *application* cursor (not merely the transport cursor), all replayed events are idempotent or dedup-keyed, and the tool call is still live or has a deliverable terminal event. - **Refuse and reconcile** iff the transport cursor and application cursor diverge by more than the client can dedup, OR the replay contains a non-idempotent side-effect event, OR the server cannot prove the tool call is still in the same execution epoch (e.g., it restarted, the event log was truncated, IDs are non-contiguous). - **Refuse and restart** iff the tool call's side effects are not externally observable (the client cannot query "did the deploy happen?"), because a blind restart risks double-execution. The refusal must be **loud**. Silent resumption that papers over a gap is the failure; an explicit `StreamResumeRejected` that forces the agent into a reconciliation tool call (`get_tool_call_status(call_id)`) is the recovery. The invariant to enforce: **no agent state transition may be driven by a replayed event whose ID the agent has not durably recorded as the boundary of its own cursor.** ## Operational Effect Enforcing this boundary changes three things: 1. **The agent persists its application cursor per tool call**, not just relying on the HTTP client's `Last-Event-ID`. On reconnect it computes the true resume point and, if it cannot dedup the in-flight window, requests replay from its *last durably applied* event and reprocesses idempotently. 2. **The MCP server marks side-effect events as non-replayable** and, on resume across such an event, emits a `reconciliation_required` control event rather than replaying the side effect as a fresh occurrence. This converts a silent double-execution into an explicit branch. 3. **Resume failures surface as typed errors that route to reconciliation**, not as transport retries. The agent's retry policy distinguishes "retry the HTTP request" (safe) from "re-drive the tool call" (unsafe) and never conflates them. The cost is one extra status query per mid-flight drop; the benefit is that the agent's completion state and the server's execution state cannot silently diverge. The deeper invariant: **stream resumability is a property of the event log, not of the tool call.** Treating them as the same thing is the boundary failure; keeping them separate, with an explicit reconciliation step where they diverge, is the guardrail. ```python from dataclasses import dataclass from enum import Enum class StreamResumeRejected(RuntimeError): """Raised when a Last-Event-ID resume cannot be safely stitched.""" class ResumeDecision(Enum): RESUME = "resume" RECONCILE = "reconcile" RESTART = "restart" @dataclass(frozen=True) class Event: id: int kind: str # "progress" | "partial_result" | "checkpoint" | "side_effect" | "terminal" idempotent: bool dedup_key: str | None = None @dataclass(frozen=True) class ResumeRequest: call_id: str transport_cursor: int # Last-Event-ID from the HTTP layer application_cursor: int # last event the agent durably applied execution_epoch: str # server-side epoch of the live tool call server_epoch: str # epoch the server reports for this call_id replayable: list[Event] # server's replay suffix, may be empty def decide_resume(req: ResumeRequest) -> ResumeDecision: # Epoch mismatch: server restarted or call was re-created. The event log # the client holds does not describe the execution now running. if req.execution_epoch != req.server_epoch: return ResumeDecision.RECONCILE # Gap between the client's durable cursor and the transport cursor that # the client cannot dedup => in-flight window is unrecoverable. if req.transport_cursor < req.application_cursor: return ResumeDecision.RECONCILE if not req.replayable: # No suffix available: either execution ended or log truncated. return ResumeDecision.RECONCILE # Replay must be gap-free from the application cursor. expected = req.application_cursor + 1 for ev in req.replayable: if ev.id != expected: return ResumeDecision.RECONCILE expected += 1 # Any non-idempotent side effect in the replay window means replaying it # would either double-apply or falsely re-assert an irreversible fact. for ev in req.replayable: if ev.kind == "side_effect" and not ev.idempotent: return ResumeDecision.RECONCILE if ev.kind == "partial_result" and ev.dedup_key is None: return ResumeDecision.RECONCILE return ResumeDecision.RESUME def resume_or_raise(req: ResumeRequest) -> ResumeDecision: decision = decide_resume(req) if decision is not ResumeDecision.RESUME: raise StreamResumeRejected( f"call={req.call_id} epoch={req.execution_epoch} " f"transport_cursor={req.transport_cursor} " f"application_cursor={req.application_cursor} " f"decision={decision.value}: refusing silent stitch; " f"route to reconciliation via get_tool_call_status({req.call_id!r})" ) return decision ```