Skip to content

The agent that grows with you

fix(mcp): keep a bare stdio command on the user's PATH semantics

liuhao10244227e36a0993
diff --git a/tests/tools/test_mcp_tool_issue_948.py b/tests/tools/test_mcp_tool_issue_948.py
index b1f13b1e7d0..5571b8b5c9f 100644
--- a/tests/tools/test_mcp_tool_issue_948.py
+++ b/tests/tools/test_mcp_tool_issue_948.py
@@ -245,3 +245,129 @@ def test_bare_uvx_resolves_pm_uv_and_an_absolute_command_stays_the_users(tmp_pat
explicit = str(user_bin / "uvx")
command, _env = _resolve_stdio_command(explicit, {"PATH": "/usr/bin"})
assert command == explicit
+
+
+def test_resolve_stdio_command_displaces_a_system_node_already_on_path(tmp_path, monkeypatch):
+ """End-to-end: with the managed dir already on the child PATH behind a system
+ Node dir, the resolved env must put the managed dir first so the spawned
+ launcher's shebang/children (`/usr/bin/env node`) get the managed Node."""
+ node_bin = tmp_path / "node" / "bin"
+ node_bin.mkdir(parents=True)
+ npx_path = node_bin / "npx"
+ npx_path.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ npx_path.chmod(0o755)
+ system_bin = tmp_path / "system-node"
+ system_bin.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ inherited = os.pathsep.join([str(system_bin), "/usr/bin", str(node_bin)])
+
+ with patch("tools.mcp_tool_config.shutil.which", return_value=None):
+ command, env = _resolve_stdio_command("npx", {"PATH": inherited})
+
+ assert command == str(npx_path)
+ assert env["PATH"].split(os.pathsep) == [str(node_bin), str(system_bin), "/usr/bin"]
+
+
+# ---------------------------------------------------------------------------
+# #125300: bootstrap prepends the managed runtime's bin dir to this process's
+# PATH, so a bare `python3` resolved to the bundled interpreter, which lacks
+# the user's packages — the server died on import and the agent log only said
+# "Connection closed". A bare command must keep the USER's PATH semantics.
+# ---------------------------------------------------------------------------
+
+
+def test_bare_python3_steps_past_the_managed_runtime_to_the_user_hit(tmp_path, monkeypatch):
+ """Two PATH hits for a bare non-launcher command: the managed runtime's and the
+ user's. The user's wins; the resolved env prepends the user's dir (helpers the
+ server spawns resolve against the same interpreter). The user dir must sit OUTSIDE
+ the hermes home — everything under it counts as managed."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ home = tmp_path / "home"
+ managed_bin = home / "bin" # <HERMES_HOME>/bin — a managed dir by definition
+ managed_bin.mkdir(parents=True)
+ user_bin = tmp_path / "user-bin"
+ user_bin.mkdir()
+ for directory in (managed_bin, user_bin):
+ exe = directory / "python3"
+ exe.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ exe.chmod(0o755)
+ token = set_hermes_home_override(home)
+ try:
+ command, env = _resolve_stdio_command("python3", {
+ "PATH": os.pathsep.join([str(managed_bin), str(user_bin)])})
+ finally:
+ reset_hermes_home_override(token)
+
+ assert command == str(user_bin / "python3")
+ assert env["PATH"].split(os.pathsep)[0] == str(user_bin)
+
+
+def test_bare_python3_keeps_the_managed_hit_when_the_user_has_none(tmp_path, monkeypatch):
+ """A managed-only PATH keeps the managed hit: no user hit exists to prefer, and a
+ resolved absolute path still beats an ENOENT at execvp. The trailing user dir is a
+ real directory with no executables — not /usr/bin, which may genuinely carry one."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ home = tmp_path / "home"
+ managed_bin = home / "bin"
+ managed_bin.mkdir(parents=True)
+ exe = managed_bin / "python3"
+ exe.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ exe.chmod(0o755)
+ empty_bin = tmp_path / "user-bin"
+ empty_bin.mkdir()
+ token = set_hermes_home_override(home)
+ try:
+ command, _env = _resolve_stdio_command("python3", {
+ "PATH": os.pathsep.join([str(managed_bin), str(empty_bin)])})
+ finally:
+ reset_hermes_home_override(token)
+
+ assert command == str(exe)
+
+
+def test_bare_launcher_commands_keep_the_managed_first_resolution(tmp_path, monkeypatch):
+ """The launcher family is exempt from the user-hit step: resolving npx/node/uv/uvx
+ to the managed tree is the point of the managed-first policy (#37589, #111937)."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ home = tmp_path / "home"
+ managed_bin = home / "bin"
+ managed_bin.mkdir(parents=True)
+ user_bin = tmp_path / "user-bin"
+ user_bin.mkdir()
+ for directory in (managed_bin, user_bin):
+ exe = directory / "npx"
+ exe.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ exe.chmod(0o755)
+ token = set_hermes_home_override(home)
+ try:
+ command, _env = _resolve_stdio_command("npx", {
+ "PATH": os.pathsep.join([str(managed_bin), str(user_bin)])})
+ finally:
+ reset_hermes_home_override(token)
+
+ assert command == str(managed_bin / "npx")
+
+
+def test_tail_server_stderr_scopes_to_the_named_server(tmp_path, monkeypatch):
+ """The connect-failure log line quotes the child's last stderr lines; a server that
+ never started has no segment and gets nothing (not another server's output)."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from tools import mcp_tool_config as cfg
+
+ token = set_hermes_home_override(tmp_path)
+ try:
+ cfg._close_mcp_stderr_logs()
+ cfg._write_stderr_log_header("beta")
+ fh = cfg._get_mcp_stderr_log()
+ fh.write("beta noise\n")
+ fh.flush()
+ cfg._write_stderr_log_header("alpha")
+ fh.write("ModuleNotFoundError: No module named 'requests'\n")
+ fh.flush()
+
+ assert "ModuleNotFoundError" in cfg._tail_server_stderr("alpha")
+ assert "beta noise" not in cfg._tail_server_stderr("alpha")
+ assert cfg._tail_server_stderr("never-started") == ""
+ finally:
+ cfg._close_mcp_stderr_logs()
+ reset_hermes_home_override(token)
diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.py
index e08f102d37a..264f60ff4ae 100644
--- a/tools/mcp_tool_config.py
+++ b/tools/mcp_tool_config.py
@@ -10,6 +10,7 @@ import re
import shutil
import sys
import threading
+from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
from hermes_cli.stderr_timestamp import stamp_line, timestamp
from tools.mcp_tool_common import _env_ref_name, _prepend_path
@@ -114,6 +115,32 @@ def _write_stderr_log_header(server_name: str) -> None:
pass
+def _tail_server_stderr(server_name: str, *, max_bytes: int = 8192, max_lines: int = 8) -> str:
+ """Trailing lines this server last wrote to the shared stderr log; ``''`` when none.
+
+ A connect failure that only says ``Connection closed`` hides why the child died
+ (#125300: a ``ModuleNotFoundError`` sat in the log while the agent log stayed mute).
+ Best-effort: the segment header must still be inside the read window, and another
+ server's output past that header is fair game — the header lines carry the name."""
+ try:
+ fh = _get_mcp_stderr_log()
+ path = getattr(fh, "name", None)
+ if not path or path == os.devnull:
+ return ""
+ with open(path, "rb") as raw:
+ raw.seek(0, os.SEEK_END)
+ size = raw.tell()
+ raw.seek(max(0, size - max_bytes))
+ chunk = raw.read().decode("utf-8", "replace")
+ cut = chunk.rfind(f"starting MCP server '{server_name}'")
+ if cut < 0:
+ return ""
+ lines = [line for line in chunk[cut:].splitlines() if line.strip()]
+ return "\n".join(lines[-max_lines:]) if lines else ""
+ except Exception:
+ return ""
+
+
# Env vars safe to pass to stdio subprocesses (no secrets).
_SAFE_ENV_KEYS = frozenset({"PATH", "HOME", "USER", "LANG", "LC_ALL", "TERM", "SHELL", "TMPDIR"})
@@ -234,6 +261,39 @@ def _managed_launcher(command: str) -> Optional[tuple[str, list[str]]]:
return executable, dirs
+def _is_hermes_managed_bin_dir(directory: str) -> bool:
+ """True for the bin dirs Hermes' bootstrap prepends to this process's PATH: anything
+ under the active hermes home (the sealed payload's venv, ``<home>/bin``, PM store
+ runtimes) plus the running interpreter's own bin dir (a repo checkout's venv)."""
+ try:
+ resolved = Path(directory).resolve()
+ except OSError:
+ return False
+ if resolved == Path(sys.executable).resolve().parent:
+ return True
+ from hermes_constants import get_hermes_home
+ try:
+ home = Path(get_hermes_home()).resolve()
+ except Exception:
+ return False
+ return resolved == home / "bin" or home in resolved.parents
+
+
+def _first_user_which_hit(command: str, path_arg: Optional[str]) -> Optional[str]:
+ """First PATH hit for *command* OUTSIDE Hermes-managed bin dirs, or ``None``.
+
+ ``shutil.which`` stops at the first hit, and bootstrap prepends the managed runtime's
+ bin dir, so a bare ``python3`` resolves to the bundled interpreter — which lacks the
+ user's packages and kills the server on import (#125300)."""
+ for directory in str(path_arg or "").split(os.pathsep):
+ if not directory or _is_hermes_managed_bin_dir(directory):
+ continue
+ for candidate in _npx_bin_candidates(directory, command):
+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
+ return candidate
+ return None
+
+
def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
"""Resolve a stdio command against the exact subprocess env (bare launchers under a filtered PATH).
@@ -260,6 +320,14 @@ def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
which_hit = shutil.which(resolved_command, path=path_arg) if path_arg is not None else None
if which_hit is None and sys.platform == "win32" and resolved_env:
which_hit = _which_with_config_pathext(resolved_command, path_arg, resolved_env)
+ # A bare command keeps the USER's PATH semantics: bootstrap prepends the managed
+ # runtime's bin dir to this process's PATH, so the first hit for a bare ``python3``
+ # is Hermes' bundled interpreter, which lacks the user's packages and dies on import
+ # (#125300). Step past managed dirs to the user's own hit; the explicit launcher
+ # family keeps the managed-first resolution (that is the point of
+ # ``_launcher_fallback``), and a managed-only PATH keeps the managed hit.
+ if which_hit and resolved_command not in {"npx", "npm", "node", "uv", "uvx"}:
+ which_hit = _first_user_which_hit(resolved_command, path_arg) or which_hit
if which_hit:
resolved_command = which_hit
command_dir = os.path.dirname(resolved_command)
diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py
index d113a8f6e62..84c6c0c6729 100644
--- a/tools/mcp_tool_discovery.py
+++ b/tools/mcp_tool_discovery.py
@@ -226,6 +226,20 @@ def _note_connect_failure(name: str, exc: BaseException) -> str:
return message
+def _stderr_tail_note(name: str) -> str:
+ """Operator-facing stderr tail for a connect-failure log line (#125300).
+
+ ``Connection closed`` alone hides why the child died — the reason sits in the shared
+ mcp-stderr.log. The stored status message stays single-line; only the log line quotes
+ the child's output."""
+ from tools.mcp_tool_config import _tail_server_stderr
+ tail = _tail_server_stderr(name)
+ if not tail:
+ return ""
+ indented = "\n".join(f" {line}" for line in tail.splitlines())
+ return f"\n child stderr tail (full log: mcp-stderr.log):\n{indented}"
+
+
def _note_connect_success(name: str) -> None:
"""Clear connecting/error/cooldown state after a successful connect (under ``_lock``)."""
with _core._lock:
@@ -268,7 +282,8 @@ def _ensure_lazy_server_connected(server_name: str) -> bool:
_loop._run_on_mcp_loop(lambda: _discover_and_register_server(server_name, config),
timeout=float(connect_timeout) + 30.0)
except BaseException as exc:
- logger.warning("Lazy MCP connect failed for '%s': %s", server_name, _note_connect_failure(server_name, exc))
+ logger.warning("Lazy MCP connect failed for '%s': %s%s",
+ server_name, _note_connect_failure(server_name, exc), _stderr_tail_note(server_name))
return False
_note_connect_success(server_name)
with _core._lock:
@@ -438,8 +453,9 @@ async def _discover_all(new_servers: Dict[str, dict]) -> None:
if isinstance(result, BaseException):
command = new_servers.get(name, {}).get("command")
message = _note_connect_failure(name, result)
- logger.warning("Failed to connect to MCP server '%s'%s: %s",
- name, f" (command={command})" if command else "", message)
+ logger.warning("Failed to connect to MCP server '%s'%s: %s%s",
+ name, f" (command={command})" if command else "", message,
+ _stderr_tail_note(name))
else:
_note_connect_success(name)