# Why does an instance lose its server-initiated SSE backchannel when an MCP streamable-session resumes after transport-level reconnect **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients and servers using the HTTP-native "streamable" transport with `Mcp-Session-Id` resumption, where the server pushes notifications (resource updates, sampling requests, progress, logging) over a long-lived SSE backchannel. Does not apply to stdio transports or to pure request/response polling without a server-initiated channel. ## Core Distinction The distinction that matters is between **session identity** and **stream binding**. In the MCP streamable HTTP transport, a session is identified by the `Mcp-Session-Id` header and is logically durable across HTTP connections. The SSE backchannel, however, is a *physical* binding: a specific HTTP response body held open on a specific TCP connection, tied to a specific `Last-Event-ID` cursor. Resumption semantics conflate these two. A client that reconnects with a valid `Mcp-Session-Id` and a valid `Last-Event-ID` will be told the session is alive and the event cursor is accepted—yet the server's internal dispatcher may not have re-registered the new response stream as the destination for server-initiated messages. The session is *valid*; the backchannel is *orphaned*. Every subsequent `notifications/*`, `sampling/createMessage`, and `roots/list_changed` message is emitted into a stale writer that drains to a closed socket, and the client observes silence without any protocol-level error. The non-obvious part: resumption *succeeds* by every spec-visible signal. `200 OK`, valid session, accepted cursor, replayed events. The failure is invisible until the first server-initiated message that isn't a replay. ## What Was Observed A tool-using agent held an MCP session against a server that emits `notifications/resources/updated` when a watched file changes, and `sampling/createMessage` when it needs the agent's model to summarize a diff. The client used streamable HTTP with automatic reconnect on socket close (idle timeout at a load balancer, 60s). Trace of the failure: 1. Agent opens session `S`, receives `Mcp-Session-Id: S`. Server registers SSE writer `W1` bound to response stream `R1`. Client stores `Last-Event-ID: 0`. 2. Load balancer drops the idle TCP connection at t=60s. `R1` closes. Server's `W1` is now a dead writer but the session map still holds `S → W1`. 3. Client reconnects: `GET /mcp` with `Mcp-Session-Id: S`, `Last-Event-ID: 0`. Server validates session, replays events `1..N` from its ring buffer, and opens new response stream `R2`. 4. **Server bug (and common implementation shortcut):** replay path constructs a fresh writer `W2` for `R2` to flush the backlog, but the *notification dispatcher* is keyed on the session object and still holds `W1`. `W2` is used only for the replay loop and then abandoned by the dispatch layer. 5. File changes at t=90s. Dispatcher calls `session.emit(notification)` → writes to `W1` → `W1`'s socket is closed → write is swallowed (async write to closed stream often resolves without raising on the server side, or raises into a detached task). 6. Agent waits. No notification. Its file-watch cache is now stale. At t=300s it makes a tool call based on the stale cache and produces a wrong diff summary. 7. Server later needs `sampling/createMessage`. It writes to `W1`. The request never reaches the agent. The server's sampling call blocks until its own timeout, then the tool call fails with a generic `-32000` timeout—*not* a transport error, so the agent retries the tool, not the session. The observable signature is asymmetry: client-initiated requests work fine (they open new POST streams), server-initiated messages vanish. The session appears healthy from the client's request path. ## Condition of Validity The invariant that must hold for streamable-session resumption to be correct is: > **After any successful resume, the session's dispatch target for server-initiated messages must be the writer bound to the most recent accepted response stream, and every prior writer for that session must be marked terminal.** This invariant is *not* implied by the spec's resumption contract, which only requires that (a) the session id is honored and (b) events after `Last-Event-ID` are replayed. A conforming implementation can satisfy both and still violate the invariant, because replay and live dispatch are separate code paths that both touch the session object. The failure is bounded by three conditions, all of which must be present: - The server maintains a session→writer mapping that is *not* atomically replaced on resume. - Writes to a closed writer fail silently or into a detached task (typical for asyncio `StreamWriter.write` + `drain` after peer close, or Node `res.write` after `'close'`). - The server emits at least one server-initiated message that is *not* in the replay buffer (i.e., generated after the resume). If all traffic is replayed, the stale writer is never exercised and the bug hides. Remove any one and the failure does not manifest. This is why it survives testing: short sessions that never idle past the LB timeout, or test harnesses that reconnect and immediately trigger a replayed event, pass clean. ## Decision Boundary The boundary an operator must decide on is **whether to treat the backchannel as resumable state or as disposable transport**. Two coherent policies, and the failure lives in the incoherent middle: - **Disposable backchannel (recommended for most deployments):** On resume, the server *tears down* the old writer unconditionally, rebinds the session to the new stream, and replays only events after `Last-Event-ID`. Any server-initiated message generated while no stream is attached is *dropped and logged*, not buffered indefinitely. The client must treat absence of expected notifications as a signal to re-issue a `resources/read` or a liveness probe—never to trust cached state across a reconnect. - **Durable backchannel:** The server buffers *all* server-initiated messages (including `sampling/createMessage`) in the replay ring, keyed by sequence number, and on resume rebinds dispatch to the new writer *before* flushing the backlog. This requires the sampling request to carry a sequence id and the client to dedupe by it, because a request in flight at disconnect may be replayed. The decision boundary is: if the server cannot guarantee atomic writer rebind + backlog flush ordering, it must adopt the disposable policy and make the client responsible for post-resume reconciliation. The dangerous configuration is "we replay events, so the client can trust continuity"—that claim is only true for messages that were *already in the buffer at disconnect*. ## Operational Effect Concretely, on the agent side, the guardrail is a **post-resume reconciliation barrier**: after any reconnect that returns a new stream, the agent must (1) invalidate any cache populated by server-initiated notifications, (2) issue an explicit read/probe for each resource it depends on, and (3) start a watchdog timer for expected `sampling/createMessage` responses that, on expiry, forces a full session re-establishment (new `Mcp-Session-Id`) rather than a resume. On the server side, the guardrail is a **single-writer invariant enforced at the session object**: `session.attach(writer)` must synchronously mark the prior writer terminal and raise if the prior writer is still the dispatch target after return. Any emit to a terminal writer must raise a typed error that surfaces to the request handler, converting a silent drop into a visible `-32001` backchannel-unavailable error the client can act on. The compounding failure to watch for: without the reconciliation barrier, the agent's stale cache produces a *wrong* tool result, and the wrong result is fed into the next reasoning step. The error is not a transport error—it is a semantic error that looks like a model mistake. The agent will retry the tool call (which succeeds, against the same stale cache) rather than the session, and the divergence persists until the episode ends. ```python import asyncio import time from dataclasses import dataclass, field from typing import Optional class BackchannelOrphanedError(RuntimeError): """Raised when a server-initiated message targets a terminal SSE writer. Signals that the session resumed but the dispatch target was not rebound to the new response stream. Client must re-establish the session. """ class StaleCacheError(RuntimeError): """Raised when the agent reads a resource populated by an orphaned backchannel.""" @dataclass class SSEWriter: stream_id: str closed: bool = False terminal: bool = False def write(self, msg: str) -> None: if self.terminal or self.closed: # Silent-drop path that causes the bug; guardrail converts to raise. raise BackchannelOrphanedError( f"emit to terminal writer {self.stream_id}; session dispatch target stale" ) @dataclass class Session: session_id: str writer: Optional[SSEWriter] = None last_event_id: int = 0 reconciliation_required: bool = False cache: dict = field(default_factory=dict) def attach(self, new_writer: SSEWriter) -> None: # Single-writer invariant: rebind atomically, mark prior terminal. if self.writer is not None and not self.writer.terminal: self.writer.terminal = True self.writer = new_writer self.reconciliation_required = True def emit(self, msg: str) -> None: if self.writer is None: raise BackchannelOrphanedError(f"session {self.session_id} has no writer") self.writer.write(msg) # raises if terminal def resume(self, new_writer: SSEWriter, last_event_id: int) -> None: if last_event_id > self.last_event_id: self.last_event_id = last_event_id self.attach(new_writer) def reconcile(session: Session, resources: list[str], reader) -> None: """Post-resume barrier: invalidate cache and re-read every dependency.""" if not session.reconciliation_required: return session.cache.clear() for r in resources: try: session.cache[r] = reader(r) except Exception as e: raise StaleCacheError(f"reconciliation failed for {r}: {e}") from e session.reconciliation_required = False async def sampling_watchdog(session: Session, expected_by: float, on_expire) -> None: """Force full re-establishment if a sampling response never arrives.""" await asyncio.sleep(max(0.0, expected_by - time.time())) if session.reconciliation_required or session.writer is None or session.writer.terminal: on_expire(session.session_id) raise BackchannelOrphanedError( f"sampling response missing for session {session.session_id}; " "backchannel likely orphaned, re-establish session" ) # Minimal demonstration of the failure and the guardrail. async def demo() -> None: s = Session(session_id="S") w1 = SSEWriter("R1") s.attach(w1) # Simulate LB idle drop. w1.closed = True # Resume: new stream, but a naive server leaves dispatch on W1. w2 = SSEWriter("R2") s.resume(w2, last_event_id=0) # Guardrail: emit now targets W2 because attach() rebound dispatch. s.emit("notifications/resources/updated") # ok # Naive server path (the bug) would have called w1.write directly: try: w1.write("sampling/createMessage") except BackchannelOrphanedError as e: print(f"guardrail caught orphaned emit: {e}") # Reconciliation barrier after resume. reconcile(s, resources=["file:///watched"], reader=lambda r: "fresh-content") assert s.cache["file:///watched"] == "fresh-content" if __name__ == "__main__": asyncio.run(demo()) ```