How does an instance detect a stale MCP capability lease after a partial-failure stream reconnect?
**Date of Record:** 2026 December 1 **Scope:** Applies to LLM agent instances consuming MCP servers over a stateful streaming transport (SSE or streamable HTTP) where the server advertises capabilities via `initialize` and can emit mid-stream tool/resource notifications. Does not apply to stateless one-shot request/response transports or to capability sets that are renegotiated on every request.
Core Distinction
The naive model treats MCP capability negotiation as a single handshake at session start: the client sends `initialize`, the server returns `{capabilities, serverInfo}`, and the client caches that capability set for the life of the session. The failure mode lives in the gap between *transport liveness* and *capability validity*. A stream can reconnect at the transport layer—TCP re-established, SSE `Last-Event-ID` honored, heartbeats flowing—while the server has silently swapped its backend, reloaded its tool registry, or dropped a sub-capability (e.g., `resources.subscribe` or `tools.listChanged`) that the client still believes it holds. The reconnect succeeds; the capability lease is stale. Detecting this is not a transport problem and not a schema-validation problem. It is a *lease-fencing* problem: the client must be able to prove that the capability set it is about to use is the one the current server incarnation is actually willing to honor.
What Was Observed
A client agent held a negotiated set: `tools: {listChanged: true}`, `resources: {subscribe: true, listChanged: true}`, `prompts: {}`. It subscribed to `notifications/tools/list_changed` and `notifications/resources/updated` and had been receiving them for ~40 minutes. The upstream MCP server ran behind a load balancer fronting two server instances. Instance A held the subscription state; instance B did not. When A was drained for a rolling deploy, the SSE connection dropped with a `502` mid-event. The client's reconnect logic fired: it re-issued the HTTP GET with `Last-Event-ID`, the LB routed to instance B, and B accepted the stream and replayed from its own event log—which contained no subscription registrations, because subscriptions are per-instance in-memory state. The HTTP layer returned `200`, the stream stayed open, and heartbeats arrived on schedule.
For the next 11 minutes the agent continued to *believe* it held `resources.subscribe`. It issued `resources/read` on files it expected to be pushed updates for; updates stopped arriving. It did not error—absence of a `notifications/resources/updated` message is indistinguishable from "no change occurred." The agent's world model drifted: it reasoned over a file's contents from a snapshot taken before the reconnect, while the file had been rewritten twice. The failure was silent, semantically plausible, and only surfaced when a downstream verification step compared the agent's cited content against the actual file and found a hash mismatch. The transport had never been unhealthy; the capability lease had been void for 11 minutes with zero signal.
The key observation: `Last-Event-ID` replay semantics guarantee *event continuity*, not *subscription continuity*. The server replayed events it had; it had no events for subscriptions it never knew about. The client's reconnect logic validated the transport (stream open, heartbeats) and skipped capability revalidation because the MCP spec's `initialize` is a session-scoped handshake, and the session ID was unchanged across the reconnect.
Condition of Validity
The stale-lease failure is bounded by a specific invariant that must hold for the client to safely skip renegotiation:
> **Capability-lease invariant:** A cached capability set `C` is valid for a request `R` iff (a) the session incarnation that produced `C` is the same incarnation currently serving the stream, *and* (b) no `notifications/*/list_changed` invalidating a member of `C` has been missed since `C` was cached, *and* (c) any sub-capability with per-instance state (subscriptions, cursors, `roots` bindings) has been re-established on the current incarnation.
Condition (a) is the one that fails on partial-failure reconnect. The session ID is *not* a sufficient incarnation witness: many MCP deployments preserve the session ID across backend swaps to keep client reconnect logic simple, which is precisely what makes the lease stale without any observable session discontinuity. The only sound witness is a server-generated incarnation token that changes whenever the capability-serving state resets—typically a monotonically increasing epoch or a deployment UUID returned in `initialize` and echoed in every stream frame or in a `notifications/server/incarnation_changed` event.
If the transport does not carry an incarnation witness, the client cannot distinguish a benign reconnect (same incarnation, replay is complete) from a poisoned reconnect (new incarnation, replay is incomplete with respect to subscriptions). In that case the invariant is unprovable and the client must treat *every* reconnect as a full renegotiation—re-issue `initialize`, re-subscribe to all `list_changed` and `updated` streams, and re-bind any `roots` or cursor state. The cost is a round-trip and a burst of re-subscriptions; the alternative is silent semantic drift.
Decision Boundary
The boundary is: **on reconnect, do you renegotiate or trust the lease?** The decision is not "did the connection drop" (it did) and not "did the session ID change" (it may not have). The decision is whether the client can *fence* the cached lease against the current incarnation.
Concretely, on every stream reconnect the client must evaluate:
- If `initialize` is re-issued and returns a different incarnation token → **hard renegotiate**: drop `C`, re-subscribe, re-bind. Treat all in-flight tool calls whose results depended on subscription state as suspect.
- If `initialize` returns the *same* incarnation token and the server supports `Last-Event-ID` replay with a complete log → **soft resume**: replay, then re-validate that every member of `C` is still present in the returned capabilities; any member absent is revoked.
- If the server returns no incarnation token → **fail closed to renegotiate**. Absence of a witness is not evidence of continuity. This is the case that bit the observed agent: it had no epoch to check, assumed continuity from session-ID stability, and lost 11 minutes of subscription state.
- If reconnect succeeds but the server rejects a request that `C` says is supported (e.g., `resources/subscribe` returns `-32601 Method not found`) → **lease is definitively stale**, regardless of what `initialize` claimed. The negative response is ground truth; the cached capability was a lie. Emit a lease-revocation event and force full renegotiation.
The subtle boundary: a reconnect that *looks* healthy (200, heartbeats, replay) but whose replayed event log is shorter than the client's last-seen sequence for a subscription channel. A gap in `Last-Event-ID` continuity for a *subscribed* channel is a lease-invalidation signal even when the transport is fine. The client must track per-channel sequence high-water marks, not a single global `Last-Event-ID`.
Operational Effect
The operational consequence is that capability caching must be modeled as a *fenced lease with a per-channel continuity witness*, not as a session-scoped constant. Three guardrails bound the failure:
- **Incarnation fencing.** The client stores the incarnation token from `initialize` and refuses to honor any cached capability unless a post-reconnect `initialize` (or an explicit `incarnation_changed` notification) confirms the same token. A token change forces full renegotiation and marks all subscription-derived context as stale.
- **Per-channel sequence tracking.** The client maintains a high-water mark per notification channel (`tools/list_changed`, `resources/updated:<uri>`, etc.). On reconnect, if the server's replay cannot cover the high-water mark for a channel backing a cached capability, that capability is demoted to "unverified" and any request relying on it is blocked until re-established.
- **Negative-response demotion.** Any `-32601` / capability-mismatch error on a request the cache said was valid immediately revokes the cache entry and triggers renegotiation. The cache must be falsifiable by observed behavior, not only by explicit notifications.
Without these, the agent operates on a lease that the server has already voided, and the only detector is a downstream semantic check that may not exist. The failure is not loud; it is a quiet divergence between what the agent believes it is subscribed to and what the current server incarnation is actually pushing. The invariant to hold: *a capability is only usable while the client can prove the current incarnation is honoring it—and after any partial-failure reconnect, that proof must be re-established, not assumed.*
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict, Optional
class StaleCapabilityLease(RuntimeError):
"""Raised when a cached MCP capability cannot be fenced against the
current server incarnation after a stream reconnect."""
@dataclass
class CapabilityLease:
incarnation: Optional[str] # server epoch/UUID; None == no witness
capabilities: Dict[str, bool] # e.g. {"resources.subscribe": True}
channel_hwm: Dict[str, int] = field(default_factory=dict) # per-channel high-water marks
@dataclass
class ReconnectResult:
session_id: str
incarnation: Optional[str]
replayed_hwm: Dict[str, int] # what the server could replay per channel
capabilities: Dict[str, bool]
def validate_lease_after_reconnect(
lease: CapabilityLease, reconnect: ReconnectResult
) -> CapabilityLease:
"""Fence a cached capability lease against a post-reconnect server state.
Returns a (possibly narrowed) lease that is safe to use. Raises
StaleCapabilityLease when the lease cannot be proven valid and the caller
must perform a full renegotiation before issuing dependent requests.
"""
# Guardrail 1: incarnation fencing. No witness == no proof == fail closed.
if lease.incarnation is None or reconnect.incarnation is None:
raise StaleCapabilityLease(
"no incarnation witness; cannot distinguish benign reconnect from "
"backend swap; full renegotiation required"
)
if lease.incarnation != reconnect.incarnation:
raise StaleCapabilityLease(
f"incarnation changed {lease.incarnation!r} -> "
f"{reconnect.incarnation!r}; cached capabilities are void"
)
# Guardrail 2: per-channel continuity. A channel whose replay cannot cover
# the client's high-water mark has silently lost events; any capability
# backed by that channel is unverified.
narrowed: Dict[str, bool] = dict(reconnect.capabilities)
for channel, hwm in lease.channel_hwm.items():
replayed = reconnect.replayed_hwm.get(channel, -1)
if replayed < hwm:
backing = _capability_backing(channel)
if backing and narrowed.get(backing, False):
narrowed[backing] = False # demote to unverified
raise StaleCapabilityLease(
f"channel {channel!r} replay gap (hwm={hwm}, "
f"replayed={replayed}); capability {backing!r} demoted, "
f"renegotiate before use"
)
return CapabilityLease(
incarnation=reconnect.incarnation,
capabilities=narrowed,
channel_hwm=dict(reconnect.replayed_hwm),
)
def _capability_backing(channel: str) -> Optional[str]:
if channel.startswith("resources/updated:"):
return "resources.subscribe"
if channel == "tools/list_changed":
return "tools.listChanged"
if channel == "resources/list_changed":
return "resources.listChanged"
return None
def guarded_request(
lease: CapabilityLease, capability: str, negative_response: bool
) -> None:
"""Issue a request gated on the lease; demote on negative response."""
if not lease.capabilities.get(capability, False):
raise StaleCapabilityLease(
f"capability {capability!r} not held under current lease; "
f"renegotiate before issuing request"
)
# Guardrail 3: observed -32601 / mismatch is ground truth over the cache.
if negative_response:
raise StaleCapabilityLease(
f"server returned method-not-found for {capability!r} despite cached "
f"lease; cache is stale, revoke and renegotiate"
)