MCP: park single-instance stdio servers quietly instead of self-probing forever
A stdio MCP server that owns a single-writer resource (a PGLite datastore lock, a
device, a pid file) can only ever have ONE live child system-wide. When a second
Hermes context starts, its own copy of the child dies before the MCP handshake
because the resource is already held:
GBrain's local database is already open through 'gbrain serve' (MCP, PID 2509385)
The initial-connect ladder then burns its 3 attempts, the server parks, and
_PARKED_RETRY_INTERVAL makes the parked server self-probe every 300s - each probe
spawning another child that is guaranteed to lose the same race. The loop is
unbounded and never converges: measured here at ~285 park events/day over 18 days
(16,068 spawn attempts). The functional damage is to triage - errors.log fills with
"parked until a reconnect is requested" lines and buries real failures.
Two changes:
- New `single_instance: true` stdio server option. When the initial ladder is
exhausted and the child never reached the handshake, the server parks QUIETLY:
no timed self-probe at all, because the conflict is provably unwinnable (the
resource is held by another process). Only an explicit reconnect
(/reload-mcp, `hermes mcp` refresh) revives it, which is the correct trigger -
that is what happens once the owning instance exits.
- The parked self-probe now backs off for everyone: _PARKED_RETRY_INTERVAL (300s)
doubling per consecutive still-failed probe, capped at _PARKED_PROBE_BACKOFF_MAX
(3600s), and reset by _mark_session_proven() once a session is healthy again.
A transient park keeps its original cadence, so nothing recovers more slowly
than before in the ordinary network-blip case.
Tests: tests/tools/test_mcp_single_instance_park.py (new) covers the quiet park and
the backoff ladder, cap and reset.
Verified on a566d20d22 (upstream main at the time of writing), diff applies clean:
- 16/16 in the targeted set: the new file plus test_mcp_parked_self_probe.py,
test_mcp_parked_probe_no_browser.py, test_mcp_rapid_drop_budget.py,
test_mcp_reconnect_log_hygiene.py.
- The wider tests/tools/test_mcp_* + connectors run shows only PRE-EXISTING
failures in test_mcp_oauth_manager.py (24 failed / 6 passed) - identical on a
pristine checkout with the patch reverted, so not a regression from this change.
This commit is contained in:
125
tests/tools/test_mcp_single_instance_park.py
Normal file
125
tests/tools/test_mcp_single_instance_park.py
Normal file
@@ -0,0 +1,125 @@
|
||||
"""Single-instance MCP stdio servers must not hammer a timed self-probe when a duplicate
|
||||
process already holds their single-writer resource (e.g. a PGLite datastore lock).
|
||||
|
||||
A stdio server marked ``single_instance: true`` has exactly one live child system-wide. When a
|
||||
second Hermes context discovers it, its own spawn dies before the MCP handshake because the
|
||||
resource is already taken; after the initial-connect ladder that is provably unwinnable, so the
|
||||
server must park QUIETLY (no timed self-probe) instead of re-spawning a doomed child every
|
||||
``_PARKED_RETRY_INTERVAL``. Explicit reconnect still revives it once the owner exits.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from tools.mcp_tool import MCPServerTask
|
||||
|
||||
|
||||
@pytest.mark.no_isolate
|
||||
def test_single_instance_conflict_parks_quietly_and_never_self_probes(monkeypatch, tmp_path):
|
||||
"""A single-instance server that dies before the handshake parks without a timed self-probe,
|
||||
and is revived only by an explicit reconnect."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
|
||||
from tools import mcp_tool
|
||||
|
||||
monkeypatch.setattr(mcp_tool, "_MAX_INITIAL_CONNECT_RETRIES", 1)
|
||||
# Tiny so a regression (a self-probe firing) would be caught fast.
|
||||
monkeypatch.setattr(mcp_tool, "_PARKED_RETRY_INTERVAL", 0.02)
|
||||
|
||||
_real_sleep = asyncio.sleep
|
||||
|
||||
async def _fast_sleep(_delay, *a, **kw):
|
||||
await _real_sleep(0)
|
||||
|
||||
monkeypatch.setattr(mcp_tool.asyncio, "sleep", _fast_sleep)
|
||||
|
||||
state = {"transport_calls": 0, "deregistered": 0, "park_timeout": "unset"}
|
||||
|
||||
_real_wait = MCPServerTask._wait_for_reconnect_or_shutdown
|
||||
|
||||
async def _recording_wait(self, timeout=None):
|
||||
state["park_timeout"] = timeout
|
||||
return await _real_wait(self, timeout=timeout)
|
||||
|
||||
monkeypatch.setattr(MCPServerTask, "_wait_for_reconnect_or_shutdown", _recording_wait)
|
||||
|
||||
async def _scenario():
|
||||
class _Task(MCPServerTask):
|
||||
def _is_http(self):
|
||||
return False
|
||||
|
||||
def _deregister_tools(self):
|
||||
state["deregistered"] += 1
|
||||
self._registered_tool_names = []
|
||||
|
||||
async def _run_stdio(self, config):
|
||||
state["transport_calls"] += 1
|
||||
raise RuntimeError("child exited: duplicate holds the datastore lock")
|
||||
|
||||
task = _Task("gbrain")
|
||||
run_task = asyncio.ensure_future(
|
||||
task.run({"command": "gbrain", "args": ["serve"], "single_instance": True})
|
||||
)
|
||||
|
||||
for _ in range(1000):
|
||||
await _real_sleep(0)
|
||||
if state["deregistered"] >= 1:
|
||||
break
|
||||
|
||||
assert state["deregistered"] >= 1, "single-instance server never parked"
|
||||
assert state["park_timeout"] is None, (
|
||||
"resource-conflict park must wait without a timed self-probe"
|
||||
)
|
||||
calls_at_park = state["transport_calls"]
|
||||
assert calls_at_park == 2, (
|
||||
f"expected initial attempt + 1 retry before parking, got {calls_at_park}"
|
||||
)
|
||||
|
||||
# A quiet park must not re-spawn: give any stray self-probe ample time to fire.
|
||||
for _ in range(200):
|
||||
await _real_sleep(0.01)
|
||||
assert state["transport_calls"] == calls_at_park, (
|
||||
"single-instance server self-probed after a resource conflict — the storm is back"
|
||||
)
|
||||
|
||||
# An explicit reconnect (`hermes mcp` refresh) must still revive it.
|
||||
task._reconnect_event.set()
|
||||
for _ in range(1000):
|
||||
await _real_sleep(0)
|
||||
if state["transport_calls"] > calls_at_park:
|
||||
break
|
||||
assert state["transport_calls"] > calls_at_park, (
|
||||
"explicit reconnect did not revive the quiet-parked server"
|
||||
)
|
||||
|
||||
task._shutdown_event.set()
|
||||
task._reconnect_event.set()
|
||||
try:
|
||||
await asyncio.wait_for(run_task, timeout=15)
|
||||
except (TimeoutError, asyncio.CancelledError, Exception):
|
||||
run_task.cancel()
|
||||
|
||||
asyncio.run(_scenario())
|
||||
|
||||
|
||||
def test_park_probe_backoff_doubles_and_caps(monkeypatch):
|
||||
"""The parked self-probe wait doubles per consecutive still-failed probe and caps, then
|
||||
resets once a session proves healthy — so a non-single-instance server also stops hammering."""
|
||||
from tools import mcp_tool
|
||||
|
||||
monkeypatch.setattr(mcp_tool, "_PARKED_RETRY_INTERVAL", 300)
|
||||
monkeypatch.setattr(mcp_tool, "_PARKED_PROBE_BACKOFF_MAX", 1000)
|
||||
|
||||
srv = MCPServerTask("srv")
|
||||
assert srv._next_park_probe_timeout() == 300 # first probe at base cadence
|
||||
srv._parked_probe_failures = 1
|
||||
assert srv._next_park_probe_timeout() == 600
|
||||
srv._parked_probe_failures = 2
|
||||
assert srv._next_park_probe_timeout() == 1000 # 1200 capped
|
||||
srv._parked_probe_failures = 20
|
||||
assert srv._next_park_probe_timeout() == 1000
|
||||
|
||||
srv._mark_session_proven()
|
||||
assert srv._parked_probe_failures == 0
|
||||
assert srv._next_park_probe_timeout() == 300
|
||||
@@ -323,6 +323,10 @@ _MAX_BACKOFF_SECONDS = 60
|
||||
_RECYCLED_RECONNECT_TIMEOUT = 15.0
|
||||
# Parked servers (tools deregistered) self-probe on this cadence: nothing else can revive them.
|
||||
_PARKED_RETRY_INTERVAL = 300
|
||||
# Cap for the parked self-probe backoff: each consecutive still-failed probe doubles the wait from
|
||||
# _PARKED_RETRY_INTERVAL up to this ceiling, so a server whose failure is provably persistent (a
|
||||
# duplicate stdio instance holding a single-writer lock) stops re-spawning a doomed child forever.
|
||||
_PARKED_PROBE_BACKOFF_MAX = 3600
|
||||
# Bounded wait for a respawned stdio child when a call finds it dead (gateway restarts kill
|
||||
# every MCP child); bounded so a broken server still parks via run()'s rapid-drop budget.
|
||||
_STDIO_RESPAWN_WAIT_SEC = 15.0
|
||||
@@ -440,6 +444,11 @@ class MCPServerTask(MCPServerRunMixin, MCPServerTransportMixin, MCPServerHealthM
|
||||
# Digest of the resolved inputs the transport last connected with; a cross-profile adopter
|
||||
# must resolve the same digest in its own scope. None until the transport publishes it.
|
||||
self._resolved_identity: Optional[str] = None
|
||||
# True when this stdio server must have exactly ONE live child system-wide (a single-writer
|
||||
# datastore). A non-owner that finds the resource taken parks quietly instead of self-probing.
|
||||
self._single_instance: bool = False
|
||||
# Consecutive self-probes that came back still-broken; drives the parked-probe backoff.
|
||||
self._parked_probe_failures: int = 0
|
||||
# In-flight RPC tasks so a deliberate teardown fails them fast; _reconnecting is True
|
||||
# during that teardown so _track_inflight_rpc turns the cancel into a retryable error.
|
||||
# In-flight RPC bookkeeping (#48069 salvage): user-visible requests registered while running so a
|
||||
|
||||
@@ -212,6 +212,7 @@ class MCPServerHealthMixin:
|
||||
self._session_proven = True
|
||||
self._reconnect_retries = 0
|
||||
self._park_reason = None
|
||||
self._parked_probe_failures = 0
|
||||
if self._was_parked:
|
||||
self._was_parked = False
|
||||
logger.warning("MCP server '%s': revived — session healthy again after "
|
||||
|
||||
@@ -185,19 +185,14 @@ class MCPServerRunMixin:
|
||||
self._last_park_line = line
|
||||
logger.warning(msg, *args)
|
||||
|
||||
async def _park(self, revival_reason: str) -> bool:
|
||||
async def _park(self, revival_reason: str, quiet: bool = False) -> bool:
|
||||
"""Drop this server's tools and wait for a reconnect request; True when shutdown came instead.
|
||||
The run task must NOT exit (it is the only ``_reconnect_event`` listener, so returning
|
||||
leaves the server unrevivable). With tools deregistered no call can reach the breaker
|
||||
probe, so the wait is TIMED (one self-probe per ``_PARKED_RETRY_INTERVAL``); an explicit
|
||||
``_reconnect_event.set()`` wakes it immediately."""
|
||||
# Do NOT return — exiting the task orphans the server: nothing would ever listen for
|
||||
# _reconnect_event again and the server would be permanently wedged for the life of the process
|
||||
# (#16788). Instead, drop the phantom tools from the registry and park. Because parking deregisters
|
||||
# the tools, no tool call can reach the circuit-breaker half-open probe or _signal_reconnect — so
|
||||
# the park is a TIMED wait: every _PARKED_RETRY_INTERVAL we wake and attempt one reconnect ourselves
|
||||
# (#57129). An explicit _reconnect_event.set() (OAuth recovery, manual /mcp refresh) still wakes us
|
||||
# immediately.
|
||||
probe, so the wait is TIMED (one self-probe per ``_next_park_probe_timeout``); an explicit
|
||||
``_reconnect_event.set()`` wakes it immediately. ``quiet=True`` parks WITHOUT any timed
|
||||
self-probe — the failure is a provably unwinnable resource conflict (a duplicate instance
|
||||
holds a single-writer resource), so only an explicit reconnect can revive it."""
|
||||
self._was_parked = True
|
||||
self._park_reason = revival_reason
|
||||
self._deregister_tools()
|
||||
@@ -205,7 +200,7 @@ class MCPServerRunMixin:
|
||||
paused = False
|
||||
while True:
|
||||
outcome = await self._wait_for_reconnect_or_shutdown(
|
||||
timeout=_core._PARKED_RETRY_INTERVAL)
|
||||
timeout=None if quiet else self._next_park_probe_timeout())
|
||||
if outcome == "shutdown":
|
||||
return True
|
||||
# A disabled or deleted config entry must stop the self-probe here: the probe
|
||||
@@ -231,6 +226,9 @@ class MCPServerRunMixin:
|
||||
from tools.mcp_oauth import _oauth_interactive_enabled
|
||||
|
||||
_oauth_interactive_enabled.set(False)
|
||||
# The probe we are about to launch is a re-attempt of a still-failed server: count it
|
||||
# now so the NEXT park waits longer (backoff) instead of hammering at a fixed cadence.
|
||||
self._parked_probe_failures += 1
|
||||
logger.debug(
|
||||
"MCP server '%s': attempting revival %s (%s); rebuilding transport.",
|
||||
self.name,
|
||||
@@ -254,6 +252,15 @@ class MCPServerRunMixin:
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
def _next_park_probe_timeout(self) -> float:
|
||||
"""Self-probe wait for the current park: ``_PARKED_RETRY_INTERVAL``, doubling per
|
||||
consecutive still-failed probe, capped at ``_PARKED_PROBE_BACKOFF_MAX``. Resets once a
|
||||
session proves healthy (``_mark_session_proven``)."""
|
||||
base = _core._PARKED_RETRY_INTERVAL
|
||||
if self._parked_probe_failures <= 0:
|
||||
return base
|
||||
return min(base * (2 ** self._parked_probe_failures), _core._PARKED_PROBE_BACKOFF_MAX)
|
||||
|
||||
async def _prepare_run(self, config: dict) -> bool:
|
||||
"""Bind config, build sampling/elicitation handlers, validate HTTP. False when the server
|
||||
must not start (bad remote URL / non-MCP endpoint: fail fast with ``_error`` set and
|
||||
@@ -261,6 +268,10 @@ class MCPServerRunMixin:
|
||||
self._config = config
|
||||
self.tool_timeout = _resolve_tool_timeout(config)
|
||||
self._auth_type = (config.get("auth") or "").lower().strip()
|
||||
# single_instance: exactly one live child system-wide (single-writer datastore). A stdio
|
||||
# server whose child dies before the handshake after the initial ladder is a duplicate that
|
||||
# found the resource taken — park quietly instead of self-probing a doomed spawn forever.
|
||||
self._single_instance = bool(config.get("single_instance"))
|
||||
self._idle_timeout_seconds = _get_lifecycle_seconds(config, "idle_timeout_seconds")
|
||||
self._max_lifetime_seconds = _get_lifecycle_seconds(config, "max_lifetime_seconds")
|
||||
# The _MCP_*_TYPES flags are False until the lazy SDK import runs.
|
||||
@@ -425,10 +436,12 @@ class MCPServerRunMixin:
|
||||
self._reconnect_retries, budget.backoff = _core._MAX_RECONNECT_RETRIES, 1.0
|
||||
return True
|
||||
|
||||
async def _park_initial_failure(self, exc: Exception, revival_reason: str, budget: _RetryBudget) -> bool:
|
||||
"""Publish ``exc`` to ``start()``, park, and on revival reset every counter. False on shutdown."""
|
||||
async def _park_initial_failure(self, exc: Exception, revival_reason: str, budget: _RetryBudget,
|
||||
quiet: bool = False) -> bool:
|
||||
"""Publish ``exc`` to ``start()``, park, and on revival reset every counter. False on shutdown.
|
||||
``quiet=True`` parks without a timed self-probe (a provably unwinnable resource conflict)."""
|
||||
self._publish_error(exc)
|
||||
if await self._park(revival_reason):
|
||||
if await self._park(revival_reason, quiet=quiet):
|
||||
return False
|
||||
budget.initial_retries = self._reconnect_retries = 0
|
||||
budget.backoff = 1.0
|
||||
@@ -492,6 +505,19 @@ class MCPServerRunMixin:
|
||||
return await self._park_initial_failure(exc, "after permanent initial failure", budget)
|
||||
budget.initial_retries += 1
|
||||
if budget.initial_retries > _core._MAX_INITIAL_CONNECT_RETRIES:
|
||||
# A single-instance stdio server whose child died before the handshake after the whole
|
||||
# initial ladder is a duplicate that found the single-writer resource taken: self-probing
|
||||
# just re-spawns the same doomed child forever. Park QUIETLY (no timed self-probe) — only
|
||||
# an explicit reconnect (`hermes mcp` refresh / `_reconnect_event`) revives it once the
|
||||
# owning instance exits.
|
||||
if self._single_instance and not self._is_http():
|
||||
logger.warning(
|
||||
"MCP server '%s' failed initial connection after %d attempts and is marked "
|
||||
"single_instance; another process likely holds its resource, parking quietly "
|
||||
"(no self-probe; an explicit `hermes mcp` refresh or reconnect revives it): %s: %s",
|
||||
self.name, _core._MAX_INITIAL_CONNECT_RETRIES, type(root).__name__, root)
|
||||
return await self._park_initial_failure(
|
||||
exc, "after single-instance resource conflict", budget, quiet=True)
|
||||
self._log_park(
|
||||
"MCP server '%s' failed initial connection after %d attempts, parking until a reconnect is "
|
||||
"requested (state: connecting → parked): %s: %s",
|
||||
|
||||
@@ -58,6 +58,7 @@ mcp_servers:
|
||||
| `connect_timeout` | number | both | Initial connection timeout in seconds (default: `60`) |
|
||||
| `protocol` | string | both | Protocol-era negotiation: `auto` (default — legacy `initialize` handshake first, falling back to the 2026-07-28 `server/discover` stateless probe when the server rejects the handshake as modern-only), `stateless` (probe `server/discover` first; one legacy retry), or `legacy` (handshake only, no fallback) |
|
||||
| `supports_parallel_tool_calls` | bool | both | Allow tools from this server to run concurrently |
|
||||
| `single_instance` | bool | stdio | Only one live child may exist system-wide (single-writer datastore). A second context that finds the resource already held parks quietly (no timed self-probe) and revives on an explicit reconnect — see the MCP guide |
|
||||
| `skip_preflight` | bool | HTTP | Bypass the fail-fast content-type probe for valid Streamable HTTP endpoints whose HEAD/GET answers a non-MCP content type (default: `false`) |
|
||||
| `transport` | string | HTTP | Set to `sse` to use the SSE transport instead of Streamable HTTP |
|
||||
| `keepalive_interval` | number | both | Liveness ping cadence in seconds (floored at 5s). HTTP defaults to `180`; set it below the server's session TTL when the server GC's idle sessions quickly. Stdio disables keepalive when omitted; set a value to opt in explicitly |
|
||||
|
||||
@@ -504,6 +504,7 @@ Hermes reads MCP config from `~/.hermes/config.yaml` under `mcp_servers`.
|
||||
| `enabled` | bool | If `false`, Hermes skips the server entirely |
|
||||
| `supports_parallel_tool_calls` | bool | If `true`, tools from this server may run concurrently |
|
||||
| `events` | bool | If `true`, register the experimental MCP events tools for this server (default `false`). See [MCP Events](#mcp-events-experimental) |
|
||||
| `single_instance` | bool | If `true`, this stdio server must have exactly one live child system-wide (a single-writer datastore). A second Hermes context that finds the resource already held parks quietly — no timed self-probe — and is revived by an explicit reconnect (`/reload-mcp` or `hermes mcp` refresh) once the owning instance exits. |
|
||||
| `tools` | mapping | Per-server tool filtering and utility policy |
|
||||
|
||||
### Minimal stdio example
|
||||
|
||||
Reference in New Issue
Block a user