Skip to content

The agent that grows with you

fix(gateway): reconcile MCP on drift, not only on a config edit

Yongcheng Mu31d3b948de6b
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index 181fbfec066..f5a890bc113 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -237,19 +237,33 @@ def _mcp_config_reconciler(runner=None):
def _reconcile_current(label: str) -> None:
from tools.mcp_oauth import suppress_interactive_oauth
- from tools.mcp_tool_discovery import reconcile_mcp_servers_with_config
+ from tools.mcp_tool_discovery import mcp_servers_missing_from_live, reconcile_mcp_servers_with_config
sig = _sig(get_config_path())
prev = seen.get(label)
seen[label] = sig
- if label not in retry and (prev is None or prev == sig):
+ if prev is None:
return # first tick just records the baseline; startup discovery already ran
+ changed = prev != sig
+ # Also reconcile on DRIFT, not only on an edit: a server whose first connect failed never
+ # reached ``_servers``, its config never changes, and nothing else comes back for it — the
+ # parked self-probe belongs to a task that connected at least once. Without this a transient
+ # failure at boot (a cold ``npx`` start, a remote server mid-deploy, an OAuth prompt nobody
+ # can answer on a headless host) costs those tools for the life of the gateway, silently:
+ # the model simply does not have them. The check is a set compare, and the connect it may
+ # trigger is already rate-limited per server by the connect cooldown (30s→600s backoff), so
+ # a chronically failing server is retried on that schedule, not on every tick.
+ drifted = not changed and bool(mcp_servers_missing_from_live())
+ if label not in retry and not changed and not drifted:
+ return
with suppress_interactive_oauth():
result = reconcile_mcp_servers_with_config()
retry.discard(label)
if result["pending"]:
retry.add(label)
if result["removed"] or result["added"]:
- logger.info("MCP config changed (%s): removed=%s added=%s", label, result["removed"], result["added"])
+ logger.info("MCP %s (%s): removed=%s added=%s",
+ "config changed" if changed else "server(s) missing", label,
+ result["removed"], result["added"])
def _tick() -> None:
from gateway.run import _multiplex_profile_homes, _profile_runtime_scope
diff --git a/tests/gateway/test_gateway_mcp_oauth_unattended.py b/tests/gateway/test_gateway_mcp_oauth_unattended.py
index 52a69d34f0b..81d7ae1ef28 100644
--- a/tests/gateway/test_gateway_mcp_oauth_unattended.py
+++ b/tests/gateway/test_gateway_mcp_oauth_unattended.py
@@ -39,6 +39,9 @@ def test_mcp_config_reconciler_runs_only_when_config_changes(monkeypatch, tmp_pa
pending: list = []
monkeypatch.setattr(_mcp_discovery, "reconcile_mcp_servers_with_config", fake_reconcile)
+ # Nothing is missing here: this test covers the config-EDIT trigger. The drift trigger
+ # (a configured server that never connected) is exercised below.
+ monkeypatch.setattr(_mcp_discovery, "mcp_servers_missing_from_live", lambda: [])
tick = _mcp_config_reconciler(runner=None)
tick() # baseline only: startup discovery already reflects this file
@@ -56,3 +59,39 @@ def test_mcp_config_reconciler_runs_only_when_config_changes(monkeypatch, tmp_pa
tick()
tick()
assert calls == [False, False, False], "one retry after a pending teardown, then quiet again"
+
+
+def test_mcp_config_reconciler_retries_a_server_that_never_connected(monkeypatch, tmp_path: Path):
+ """A server whose FIRST connect failed is retried without the config changing.
+
+ It never reached ``_servers``, so the parked self-probe — which belongs to a task that
+ connected at least once — cannot bring it back, and its config file never changes. Before
+ this, a transient failure at boot (cold ``npx`` start, remote server mid-deploy, an OAuth
+ prompt nobody can answer on a headless host) cost those tools for the life of the gateway.
+ """
+ from gateway.run_profile_reconcile import _mcp_config_reconciler
+ from tools import mcp_tool_discovery as _mcp_discovery
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ cfg = tmp_path / "config.yaml"
+ cfg.write_text("mcp_servers:\n linear:\n url: https://x/mcp\n")
+ calls: list = []
+ missing: list = ["linear"] # enabled in config, never connected
+
+ monkeypatch.setattr(_mcp_discovery, "mcp_servers_missing_from_live", lambda: list(missing))
+
+ def fake_reconcile():
+ calls.append(list(missing))
+ return {"removed": [], "added": list(missing), "pending": []}
+
+ monkeypatch.setattr(_mcp_discovery, "reconcile_mcp_servers_with_config", fake_reconcile)
+ tick = _mcp_config_reconciler(runner=None)
+
+ tick() # baseline only, exactly as before: startup discovery is still authoritative
+ assert calls == []
+ tick()
+ assert calls == [["linear"]], "an enabled server that is not live must be retried"
+ missing.clear() # it connected
+ tick()
+ tick()
+ assert calls == [["linear"]], "and once it is live the chore goes quiet again"
diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py
index cd65bccac98..572efb1894b 100644
--- a/tools/mcp_tool_discovery.py
+++ b/tools/mcp_tool_discovery.py
@@ -524,6 +524,22 @@ def reconcile_mcp_servers_with_config() -> Dict[str, List[str]]:
"pending": sorted(connecting - wanted)}
+def mcp_servers_missing_from_live() -> List[str]:
+ """Names this scope's config enables that are neither live nor mid-connect — the set
+ :func:`reconcile_mcp_servers_with_config` would connect, computed without connecting anything
+ (the mtime-cached config read plus one locked set compare). Lets a caller reconcile on DRIFT and
+ not only on a config EDIT: a server whose first connect failed never reached ``_servers``, and
+ nothing retries it on its own — a parked server self-probes, one that never connected cannot."""
+ servers = _config._load_mcp_config()
+ wanted = {name for name, cfg in servers.items() if _enabled(cfg)}
+ scope = _core._mcp_registry_scope()
+ with _core._lock:
+ known = {_key_name(key) for key, owner in _core._server_scope_keys.items()
+ if owner == scope and (key in _core._servers or key in _core._server_connecting)}
+ known |= {_key_name(key) for key in _core._lazy_server_configs}
+ return sorted(wanted - known)
+
+
def _forget_lazy_server(key) -> None:
"""Drop a schema-cache (lazy) registration whose config entry is gone: its cached tools would
otherwise stay callable and spawn the server on first use."""