The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): report lazily registered servers as lazy, not configured or failed
John Paul Solivaa17d0409be15
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex 1ffce168d84..8e33e7b0b1b 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -752,6 +752,11 @@ def _mcp_server_line(srv: dict, *, dim: str, text: str) -> str:name, transport = srv["name"], srv["transport"]if srv["connected"]:return f"[dim {dim}]{name}[/] [{text}]({transport})[/] [dim {dim}]—[/] [{text}]{srv['tools']} tool(s)[/]"+ # Needs srv['tools'], so it cannot live in the suffix dict below. A registered but unspawned+ # server has callable tools; falling through to the red "failed" line misreports a working setup.+ if srv.get("status") == "lazy" and not srv.get("disabled"):+ return (f"[dim {dim}]{name}[/] [{text}]({transport})[/] [dim {dim}]—[/] "+ f"[{text}]{srv['tools']} tool(s)[/] [dim {dim}](lazy, starts on first use)[/]")status = "disabled" if srv.get("disabled") else srv.get("status")suffix = {"disabled": f"[dim {dim}]— disabled[/]", "connecting": "[yellow]— connecting[/]","configured": f"[dim {dim}]— configured[/]"}.get(status)diff --git a/hermes_cli/mcp_startup.py b/hermes_cli/mcp_startup.pyindex 42f781a89a2..cfe1b6ac6d8 100644--- a/hermes_cli/mcp_startup.py+++ b/hermes_cli/mcp_startup.py@@ -65,10 +65,21 @@ def _has_configured_mcp_servers() -> bool:return True # conservative: still try discovery in the background; startup can't block+def _discovery_registered_servers(status) -> bool:+ """True when a discovery run left servers usable: a live session OR a lazy registration.++ A ``lazy: true`` server never connects until first use, so an all-lazy config (the+ memory-saving setup the feature exists for) looked like a run that achieved nothing:+ the zero-connected warning fired on every startup and the retry path re-ran discovery+ on every later call (#111717).+ """+ return any(entry.get("connected") or entry.get("status") == "lazy" for entry in (status or []))++def _any_mcp_connected() -> bool:from tools.mcp_tool_discovery import get_mcp_status- return any(entry.get("connected") for entry in (get_mcp_status() or []))+ return _discovery_registered_servers(get_mcp_status() or [])def start_background_mcp_discovery(*, logger, thread_name: str) -> None:diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.pyindex 8a0429c2a7d..cd65bccac98 100644--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@ -16,7 +16,7 @@ from tools import mcp_tool_lifecycle as _lifecyclefrom tools import mcp_tool_loop as _loopfrom tools import mcp_tool_registration as _registrationfrom tools.mcp_tool_schema import MCP_TOOL_NAME_PREFIX-from tools.mcp_tool_scope import _key_name, _key_scope, _resolve_server_key, _server_key+from tools.mcp_tool_scope import _key_name, _key_scope, _key_visible_in_scope, _resolve_server_key, _server_keylogger = logging.getLogger("tools.mcp_tool")@@ -367,10 +367,12 @@ def _connected_summary(names, *, lazy_tools: int = 0, lazy_servers: int = 0) ->def _log_summary(prefix: str, names, **lazy) -> None:"""Log ``<prefix> N tool(s) from M server(s) (K failed)`` when anything happened."""new_tool_count, connected_count, failed = _connected_summary(names, **lazy)- if new_tool_count or failed:+ if new_tool_count or failed or lazy.get("lazy_servers"):summary = f"{prefix} {new_tool_count} tool(s) from {connected_count} server(s)"if failed:summary += f" ({failed} failed)"+ if lazy.get("lazy_servers"):+ summary += f" ({lazy['lazy_servers']} lazy, not spawned yet)"logger.info(summary)@@ -468,9 +470,19 @@ def discover_mcp_tools(allowed_mcp_names: Optional[List[str]] = None) -> List[stnew_server_names = [name for name, cfg in servers.items()if keys[name] not in _core._servers and keys[name] not in _core._server_connectingand _enabled(cfg)]+ prior_lazy = set(_core._lazy_server_configs)tool_names = register_mcp_servers(servers)if new_server_names:- _log_summary(" MCP:", new_server_names)+ # A lazily registered server never connected, so it must not be counted as failed+ # (the old summary read "N failed" for a healthy all-lazy config, #111717). Reporting+ # it separately also keeps an already-lazy server from being re-announced on a+ # repeat discovery. Lazy state is keyed by resolved server key, not by name.+ with _core._lock:+ lazy_now = [n for n in new_server_names if keys[n] in _core._lazy_server_configs]+ newly_lazy = [n for n in lazy_now if keys[n] not in prior_lazy]+ lazy_tools = sum(len(_core._lazy_server_tool_names.get(keys[n], [])) for n in newly_lazy)+ _log_summary(" MCP:", [n for n in new_server_names if n not in lazy_now],+ lazy_tools=lazy_tools, lazy_servers=len(newly_lazy))return tool_namesfinally:if cookie not in (None, _core._LOCK_UNAVAILABLE):@@ -535,8 +547,12 @@ def is_mcp_tool_parallel_safe(tool_name: str) -> bool:def get_mcp_status(configured: Optional[Dict[str, dict]] = None, *, include_runtime: bool = True) -> List[dict]:"""Per-server status dicts for banner/TUI: name, transport, tools, connected, disabled,- status (connected / disabled / connecting / failed / configured) and error for failed.- Reads cached runtime state only; never connects."""+ status (connected / disabled / connecting / failed / lazy / configured) and error for failed.+ Reads cached runtime state only; never connects.++ ``lazy`` is a registered-but-not-spawned server (``lazy: true``, tools from the schema+ cache): its tools are callable and the process starts on first use. Reporting it as+ ``configured`` (never registered) misreads a working setup (#111717)."""configured = _config._load_mcp_config() if configured is None else dict(configured)if not configured:return []@@ -551,14 +567,22 @@ def get_mcp_status(configured: Optional[Dict[str, dict]] = None, *, include_runtactive_servers = {_key_name(k): s for k, s in _core._servers.items() if visible(k)}connecting = {_key_name(k) for k in _core._server_connecting if visible(k)}connect_errors = {_key_name(k): e for k, e in _core._server_connect_errors.items() if visible(k)}+ # A lazy registration is not a live connection: ``_server_visible_in_scope`` reads the+ # adoption/teardown maps a lazy server never populates, so use the registration-level+ # predicate ``_resolve_server_key`` already relies on for this state.+ lazy_tools = {_key_name(k): len(v) for k, v in _core._lazy_server_tool_names.items()+ if include_runtime and _key_visible_in_scope(k, current_scope)+ and k in _core._lazy_server_configs}result: List[dict] = []for name, cfg in configured.items():enabled = _enabled(cfg) # evaluated unconditionally: malformed values warn even when connectedserver = active_servers.get(name)live = server is not None and server.session is not None+ # An in-flight or failed first-use connect outranks "lazy": that server is no longer+ # merely waiting to be spawned, and the error is the actionable part.status = ("connected" if live else "disabled" if not enabled else "connecting" if name in connecting- else "failed" if name in connect_errors else "configured")+ else "failed" if name in connect_errors else "lazy" if name in lazy_tools else "configured")entry = {"name": name, "transport": cfg.get("transport", "http") if "url" in cfg else "stdio","tools": 0, "connected": False, "disabled": status == "disabled", "status": status}if live:@@ -569,6 +593,8 @@ def get_mcp_status(configured: Optional[Dict[str, dict]] = None, *, include_runtentry["sampling"] = dict(server._sampling.metrics)elif status == "failed":entry["error"] = connect_errors[name]+ elif status == "lazy":+ entry["tools"] = lazy_tools[name]result.append(entry)return result