The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): name the rebuild when a stdio server's native addon was built for another Node
teknium15b770c8bf515
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.pyindex 8a7c6121ffd..dcb68aee3a9 100644--- a/hermes_cli/mcp_config.py+++ b/hermes_cli/mcp_config.py@@ -771,9 +771,12 @@ def _probe_failure_reason(exc: BaseException) -> str:def _probe_failure_next_step(name: str, exc: BaseException) -> str:"""The one command that fixes the common probe failures (sign-in, missing command, everything else)."""from tools.mcp_tool_errors import _format_connect_error, _is_auth_error, _unwrap_exception_group+ from tools.mcp_tool_node_abi import NodeAbiMismatchErrorroot = _unwrap_exception_group(exc)if _is_auth_error(root) or getattr(getattr(root, "response", None), "status_code", None) in (401, 403):return f"The server rejected the sign-in. Run: hermes mcp login {name}"+ if isinstance(root, NodeAbiMismatchError):+ return f"After rebuilding it under Hermes's Node as above, run: hermes mcp test {name}"if "missing executable" in _format_connect_error(exc):return (f"Install that command, or set mcp_servers.{name}.command in {display_hermes_home()}/config.yaml ""to its full path.")diff --git a/tests/e2e/core/upgrade/hosts/test_path_shapes.py b/tests/e2e/core/upgrade/hosts/test_path_shapes.pyindex ca1fd43ffa6..6ab0c8ebba2 100644--- a/tests/e2e/core/upgrade/hosts/test_path_shapes.py+++ b/tests/e2e/core/upgrade/hosts/test_path_shapes.py@@ -6,16 +6,19 @@ Failure class: PATH shapes. Two things users report once the install "works":already put it on PATH with a bare ``PATH=...`` assignment (Fedora ``.bashrc``, Debian``.profile``), so a login shell carries it more than once (gated on #123424); a re-run of theinstaller must not edit the startup files again;-* a node/npm the user already has, earlier on PATH, either shadows the managed toolchain where- Hermes needs the managed one (the TUI/web builds), or the managed node is forced onto an MCP- server the user configured with their own ``node`` (gated on #124264).+* a node/npm the user already has, earlier on PATH, must never stand in for the managed toolchain:+ not for the TUI/web builds and not for an MCP server configured with a bare ``command: node``.+ Hermes only ever runs its own packaged node/npm; when such a server's native addon was built by+ the user's Node it fails under Hermes's, and that failure must reach the user with the remedy+ (rebuild it under Hermes's Node) instead of a silent park (#124264).One real install through HEAD's ``scripts/install.sh`` into a HOME carrying Fedora's stock``.bashrc`` / ``.bash_profile``, with a user-owned ``node``/``npm`` first on PATH. That nodeis a stand-in (the external edge): it answers version probes as v22 and logs every call; anything-else it refuses loudly, except the user's own MCP server script, which it serves as a minimal+else it refuses loudly, except the user's own MCP server script, which it would serve as a minimalstdio MCP server. The managed node running the same script instead exits the way a native addon-built for the user's node does (``NODE_MODULE_VERSION`` mismatch) and records which node ran it.+built for the user's node does (``NODE_MODULE_VERSION`` mismatch on an addon in an ``~/.npm/_npx``+entry) and records which node ran it."""from __future__ import annotations@@ -61,6 +64,8 @@ FEDORA_SKEL = {),}USER_NODE_VERSION = "v22.11.0"+NPX_ENTRY = ".npm/_npx/0e2eab1c"+ADDON_IN_NPX_CACHE = f"{NPX_ENTRY}/node_modules/better-sqlite3/build/Release/better_sqlite3.node"MINIMAL_MCP_SERVER = r'''import json, sysfor line in sys.stdin:@@ -97,8 +102,10 @@ def _user_toolchain(root: Path) -> dict[str, Path]:server_js = mcp_dir / "server.js"server_js.write_text("require('fs').writeFileSync(" + repr(str(marker)) + ", process.execPath + ' ' + process.version);\n"- "console.error(\"Error: The module 'better_sqlite3.node' was compiled against a different Node.js version "- "using NODE_MODULE_VERSION 127. This version of Node.js requires NODE_MODULE_VERSION \" + process.versions.modules);\n"+ "const addon = require('path').join(require('os').homedir(), " + repr(ADDON_IN_NPX_CACHE) + ");\n"+ "console.error(\"Error: The module '\" + addon + \"'\\nwas compiled against a different Node.js version using\\n"+ "NODE_MODULE_VERSION 127. This version of Node.js requires\\nNODE_MODULE_VERSION \" + process.versions.modules"+ " + \"\\n code: 'ERR_DLOPEN_FAILED'\");\n""process.exit(1);\n", encoding="utf-8")python = shutil.which("python3") or sys.executableversions = {"node": USER_NODE_VERSION, "npm": "10.9.0", "npx": "10.9.0"}@@ -187,7 +194,7 @@ def test_login_shell_has_local_bin_once_with_stock_fedora_startup_files(world):f"{line_rerun}\n(startup files the installer changed: {changed})")-def test_mcp_server_configured_with_the_users_node_runs_on_the_users_node(world, provider):+def test_mcp_server_runs_on_the_managed_node_and_an_abi_mismatch_names_the_rebuild(world, provider):sb, user = world["sb"], world["user"]assert world["install"].returncode == 0, I.describe(world["install"])X.configure(sb, provider)@@ -197,13 +204,17 @@ def test_mcp_server_configured_with_the_users_node_runs_on_the_users_node(world,encoding="utf-8")before = len(_calls(world))probe = sb.cli("mcp", "test", "usernode", timeout=180)+ out = " ".join(re.sub(r"\x1b\[[0-9;]*m", "", probe.stdout + probe.stderr).split())ran_js = [c for c in _calls(world)[before:] if c.startswith("node ") and c.endswith("server.js")]- managed = user["marker"].read_text(encoding="utf-8") if user["marker"].exists() else ""- assert I.TRACEBACK not in probe.stdout + probe.stderr, I.describe(probe)- assert ran_js or managed, "harness: neither the user's node nor any other node ran the MCP server\n" + I.describe(probe)- with known_failure(r"MCP server configured with `command: node` ran on .*not the user's node",- "gated on #124264: the managed node is prepended to MCP stdio children's PATH"):- assert not managed and ran_js, (- f"MCP server configured with `command: node` ran on {managed!r}, not the user's node "- f"({user['bin'] / 'node'}, {USER_NODE_VERSION}):\n" + I.describe(probe))- assert probe.returncode == 0, "`hermes mcp test` failed although the user's node served the MCP server:\n" + I.describe(probe)+ managed = user["marker"].read_text(encoding="utf-8").split()[0] if user["marker"].exists() else ""+ assert I.TRACEBACK not in out, I.describe(probe)+ assert not ran_js, f"the user's node ({USER_NODE_VERSION}) ran the MCP server instead of Hermes's: {ran_js}"+ assert managed.startswith(str(sb.home / ".hermes")), (+ f"the MCP server did not run on Hermes's managed node (ran on {managed!r}):\n" + I.describe(probe))+ assert probe.returncode == 1, "`hermes mcp test` passed for a server that died at startup:\n" + I.describe(probe)+ # The failure reaches the user with the remedy: drop the npx entry, or rebuild with Hermes's own npm+ # under Hermes's own node (never "point the server at your node").+ assert "NODE_MODULE_VERSION 127" in out and f"rm -rf {sb.home / NPX_ENTRY}" in out, (+ "the ABI mismatch was not surfaced with the npx-cache remedy:\n" + I.describe(probe))+ assert f"PATH={Path(managed).parent}:" in out and " rebuild better-sqlite3 --prefix " in out, (+ "the rebuild command does not run Hermes's npm under Hermes's node:\n" + I.describe(probe))diff --git a/tests/tools/test_mcp_node_abi.py b/tests/tools/test_mcp_node_abi.pynew file mode 100644index 00000000000..a4a8b89add0--- /dev/null+++ b/tests/tools/test_mcp_node_abi.py@@ -0,0 +1,79 @@+"""A stdio MCP server whose native addon was built by another Node.js (#124264).++Hermes runs stdio servers on its own Node only. When such a server dies at startup with a+``NODE_MODULE_VERSION`` mismatch, the user must be told, with the rebuild under Hermes's Node,+instead of an opaque "Connection closed" and a silent park.+"""++import sys+from pathlib import Path++import pytest++# The remedy is rendered in the host shell's syntax; these pin the POSIX form.+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell remedy")++_DIES_ON_ABI = """+import pathlib, sys+pathlib.Path(sys.argv[1]).open("a").write("spawn\\n")+addon = sys.argv[2]+sys.stderr.write(+ "node:internal/modules/cjs/loader:1921\\n return process.dlopen(module, path.toNamespacedPath(filename));\\n\\n"+ f"Error: The module '{addon}'\\nwas compiled against a different Node.js version using\\n"+ "NODE_MODULE_VERSION 127. This version of Node.js requires\\nNODE_MODULE_VERSION 147. Please try "+ "re-compiling or re-installing\\n code: 'ERR_DLOPEN_FAILED'\\n}\\n\\nNode.js v26.7.0\\n")+sys.exit(1)+"""+++def managed_node(tmp_path, monkeypatch):+ """Hermes's PM-installed node/npm, as PM would report them."""+ store = tmp_path / "tools"+ node, npm = store / "node-26.7.0-linux-x64" / "bin" / "node", store / "npm-12.0.2-linux-x64" / "bin" / "npm"+ from tools import mcp_tool_node_abi+ monkeypatch.setattr(mcp_tool_node_abi, "_managed",+ lambda name: {"node": (node, "26.7.0"), "npm": (npm, "12.0.2")}[name])+ return node, npm+++def test_stdio_server_dying_on_a_node_abi_mismatch_names_the_rebuild_under_hermes_node(tmp_path, monkeypatch,+ managed_node):+ from hermes_cli.mcp_config import _probe_failure_reason, _probe_single_server++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ node, npm = managed_node+ entry = tmp_path / ".npm" / "_npx" / "0e2eab1c"+ addon = entry / "node_modules" / "better-sqlite3" / "build" / "Release" / "better_sqlite3.node"+ spawns, server = tmp_path / "spawns.log", tmp_path / "server.py"+ server.write_text(_DIES_ON_ABI, encoding="utf-8")++ with pytest.raises(Exception) as caught:+ _probe_single_server("sqlite", {"command": sys.executable, "args": [str(server), str(spawns), str(addon)],+ "connect_timeout": 20})++ reason = _probe_failure_reason(caught.value)+ assert "NODE_MODULE_VERSION 127; Hermes's Node 26.7.0 needs 147" in reason+ assert f"rm -rf {entry}" in reason+ assert f"PATH={node.parent}:\"$PATH\" {npm} rebuild better-sqlite3 --prefix {entry}" in reason+ # Every retry loads the same binary: parked at once, not walked through the retry ladder.+ assert spawns.read_text().count("spawn") == 1+ # The shared stderr log still receives the child's output.+ assert "ERR_DLOPEN_FAILED" in (tmp_path / "home" / "logs" / "mcp-stderr.log").read_text()+++def test_the_remedy_never_points_the_server_at_another_node(managed_node):+ """A module outside an npx cache gets the rebuild alone, still with Hermes's npm under Hermes's node,+ and nothing suggests pinning ``command:`` to the user's Node."""+ from tools.mcp_tool_node_abi import node_abi_error++ node, npm = managed_node+ pkg_root = Path("/usr/lib/node_modules/@acme/mcp-server")+ stderr = (f"Error: The module '{pkg_root}/node_modules/sharp/build/Release/sharp.node'\nwas compiled against a "+ "different Node.js version using\nNODE_MODULE_VERSION 127. This version of Node.js requires\n"+ "NODE_MODULE_VERSION 147.\n code: 'ERR_DLOPEN_FAILED'\n")++ message = str(node_abi_error("imgs", stderr))++ assert f"{npm}" in message and f"{node.parent}" in message and " rebuild sharp --prefix " in message+ assert str(pkg_root) in message and "rm -rf" not in message and "command:" not in messagediff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex fe6c821d359..d59d1be9f9e 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -2,6 +2,7 @@interpolation, hidden-whitespace and suspicious-entry filtering, the filteredsubprocess env, command resolution, the cached-npx binary shortcut and the shared stderr log."""+import codecsimport jsonimport loggingimport os@@ -59,6 +60,39 @@ def _close_mcp_stderr_logs(*, scope: Optional[str] = None) -> None:logger.warning("Could not close MCP stderr log for %s", key, exc_info=True)+class _StderrTee:+ """A stdio child's stderr, copied into the shared log as it arrives while the last few KB stay+ readable, so a server that dies at startup can say why on the MCP status surfaces instead of only in+ the log (#124264). ``sink`` is handed to the child; ``close()`` returns the captured tail."""++ _TAIL_BYTES = 16384++ def __init__(self, log_fh: Any):+ read_fd, write_fd = os.pipe()+ self.sink = os.fdopen(write_fd, "wb", buffering=0)+ self._log, self._tail = log_fh, bytearray()+ self._reader = threading.Thread(target=self._pump, args=(read_fd,), name="mcp-stderr", daemon=True)+ self._reader.start()++ def _pump(self, read_fd: int) -> None:+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")+ with os.fdopen(read_fd, "rb", buffering=0) as source:+ while chunk := source.read(65536):+ self._tail = (self._tail + chunk)[-self._TAIL_BYTES:]+ try:+ self._log.write(decoder.decode(chunk))+ self._log.flush()+ except (OSError, ValueError): # log closed at shutdown: keep draining the child+ pass++ def close(self, timeout: float = 2.0) -> str:+ """Close our write end and give the reader *timeout* to drain (a surviving grandchild can keep+ the pipe open); the tail read so far."""+ self.sink.close()+ self._reader.join(timeout)+ return self._tail.decode("utf-8", errors="replace")++def _write_stderr_log_header(server_name: str) -> None:"""Session marker so operators can find each server's output in the shared log(per-line prefixes would need a pipe + reader thread)."""diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.pyindex 1d73820eedf..0003d5a4a70 100644--- a/tools/mcp_tool_errors.py+++ b/tools/mcp_tool_errors.py@@ -12,6 +12,7 @@ import refrom typing import Any, List, Optionalfrom urllib.parse import urlparsefrom tools.mcp_tool_common import _sanitize_error, _core+from tools.mcp_tool_node_abi import NodeAbiMismatchErrorlogger = logging.getLogger("tools.mcp_tool")@@ -155,10 +156,11 @@ def _contains_only_cancellation(exc: BaseException) -> bool:def _classify_mcp_failure(exc: BaseException) -> str:"""``'permanent'`` (``run()`` parks instead of burning the retry ladder: auth 401/403,- NonMcpEndpointError, InvalidMcpUrlError, missing stdio command) or ``'transient'`` (backoff retry)."""+ NonMcpEndpointError, InvalidMcpUrlError, missing stdio command, native addon built for another+ Node) or ``'transient'`` (backoff retry)."""root = _unwrap_exception_group(exc)permanent = (_is_auth_error(root)- or isinstance(root, (NonMcpEndpointError, InvalidMcpUrlError, FileNotFoundError))+ or isinstance(root, (NonMcpEndpointError, InvalidMcpUrlError, FileNotFoundError, NodeAbiMismatchError))or (isinstance(root, OSError) and getattr(root, "errno", None) == errno.ENOENT)# 401/403 HTTPStatusError that _is_auth_error's type-gate missed (auth types not importable here)or getattr(getattr(root, "response", None), "status_code", None) in (401, 403))@@ -436,6 +438,9 @@ def _format_connect_error(exc: BaseException) -> str:messages.append(current.__class__.__name__)return messages or [exc.__class__.__name__]+ abi = next((node for node in nodes if isinstance(node, NodeAbiMismatchError)), None)+ if abi is not None: # already the whole story, remedy included; the SDK's "Connection closed" adds nothing+ return _sanitize_error(str(abi))missing = _find_missing()if not missing:return _sanitize_error("; ".join(list(dict.fromkeys(_flatten_messages()))[:3]))diff --git a/tools/mcp_tool_node_abi.py b/tools/mcp_tool_node_abi.pynew file mode 100644index 00000000000..c47420130a8--- /dev/null+++ b/tools/mcp_tool_node_abi.py@@ -0,0 +1,88 @@+"""Stdio MCP servers whose native addon was built for a different Node.js (#124264).++Hermes runs every stdio MCP server on its own managed Node, never the user's. A server whose+``.node`` addon was compiled under another Node (typically through the ``~/.npm/_npx`` cache the+user's ``npx`` shares with ours) dies at startup with ``NODE_MODULE_VERSION`` /+``ERR_DLOPEN_FAILED`` and only its stderr says so. This module turns that stderr into an error that+names the remedy: rebuild the server under Hermes's Node.+"""++import os+import re+import shlex+from pathlib import Path+from typing import Optional++_ABI_MARKERS = ("NODE_MODULE_VERSION", "ERR_DLOPEN_FAILED")+_MODULE_PATH = re.compile(r"'([^'\n]+?\.node)'|(\S+?\.node):")+_ABI_VERSIONS = re.compile(r"using\s+NODE_MODULE_VERSION (\d+)\..*?requires\s+NODE_MODULE_VERSION (\d+)", re.S)+++class NodeAbiMismatchError(RuntimeError):+ """A stdio server's native addon does not load under Hermes's Node. Permanent: every retry+ loads the same binary, so the server parks until the user rebuilds it."""+++def _managed(name: str) -> tuple[Optional[Path], str]:+ """``(binary, version)`` of Hermes's own node/npm, or ``(None, "")`` when PM has none."""+ try:+ from pm import installed_package+ installed = installed_package(name)+ except Exception:+ return None, ""+ return (installed.binary, installed.version) if installed and installed.binary else (None, "")+++def _package_of(module_path: str) -> tuple[Optional[Path], str]:+ """``(project root, package name)`` owning *module_path*: the directory above its innermost+ ``node_modules`` and the (possibly scoped) package under it."""+ parts = Path(module_path).parts+ marks = [i for i, part in enumerate(parts) if part == "node_modules"]+ if not marks or marks[-1] + 1 >= len(parts):+ return None, ""+ at = marks[-1]+ package = parts[at + 1]+ if package.startswith("@") and at + 2 < len(parts):+ package = f"{package}/{parts[at + 2]}"+ return Path(*parts[:at]), package+++def _remedy(root: Optional[Path], package: str, node: Path, npm: Path) -> str:+ """The fix in the host shell's syntax: delete an npx cache entry (Hermes's npx reinstalls it on the+ next start) or rebuild with Hermes's npm, Hermes's Node first on PATH because npm's shebang and its+ lifecycle scripts both run the first ``node`` there."""+ windows = os.name == "nt"+ q = (lambda p: "'" + str(p).replace("'", "''") + "'") if windows else (lambda p: shlex.quote(str(p)))+ target = f" {q(package)} --prefix {q(root)}" if root is not None else ""+ if windows:+ rebuild = f"$env:Path = {q(str(node.parent) + ';')} + $env:Path; & {q(npm)} rebuild{target}"+ else:+ rebuild = f"PATH={q(node.parent)}:\"$PATH\" {q(npm)} rebuild{target}"+ if root is None:+ return f"in the server's package directory run {rebuild}"+ if root.parent.name != "_npx":+ return rebuild+ delete = f"Remove-Item -Recurse -Force {q(root)}" if windows else f"rm -rf {q(root)}"+ return f"{delete} (Hermes reinstalls it on the next start), or {rebuild}"+++def node_abi_error(server_name: str, stderr_text: str) -> Optional[NodeAbiMismatchError]:+ """The remedy-naming error for a server whose stderr shows a native-addon load failure, else None."""+ if not stderr_text or not any(marker in stderr_text for marker in _ABI_MARKERS):+ return None+ found = _MODULE_PATH.search(stderr_text)+ module = (found.group(1) or found.group(2)) if found else ""+ versions = _ABI_VERSIONS.search(stderr_text)+ node, node_version = _managed("node")+ npm, _ = _managed("npm")+ ours = f"Hermes's Node {node_version}".strip() if node_version else "Hermes's Node"+ built = (f"NODE_MODULE_VERSION {versions.group(1)}; {ours} needs {versions.group(2)}" if versions+ else f"it does not load under {ours}")+ # Diagnosis first: the startup banner keeps only the first ~120 characters.+ head = (f"native addon built for a different Node.js ({built}): {module or 'see logs/mcp-stderr.log'}. "+ "Hermes runs MCP servers on its own Node; rebuild the server under it")+ if node is None or npm is None:+ return NodeAbiMismatchError(f"{head}: install Hermes's Node with `hermes pm install npm`, then run "+ f"`hermes mcp test {server_name}`")+ root, package = _package_of(module) if module else (None, "")+ return NodeAbiMismatchError(f"{head}: {_remedy(root, package, node, npm)}")diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex dbc1254413b..cd69f548a6a 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -15,6 +15,7 @@ from agent import runtime_cwd as _runtime_cwdfrom tools.mcp_tool_errors import NonMcpEndpointError, _apply_identity_header, _describe_http_failure, _handshake_answered_with_unsupported_version, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_http_rejection_recorder, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_groupfrom tools.mcp_tool_lifecycle import _filter_mcp_children, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pidsfrom tools.mcp_tool_common import _core+from tools.mcp_tool_node_abi import node_abi_errorfrom tools import mcp_tool_config as _configfrom tools import mcp_tool_lifecycle as _lifecyclefrom tools import mcp_tool_registration as _registration@@ -389,9 +390,9 @@ class MCPServerTransportMixin:new_pids: set = set()# Subprocess stderr goes to ~/.hermes/logs/mcp-stderr.log so banners can't corrupt the TUI._config._write_stderr_log_header(self.name)+ stderr = _config._StderrTee(_config._get_mcp_stderr_log())try:- errlog = _config._get_mcp_stderr_log()- async with _core.stdio_client(server_params, errlog=errlog) as (read_stream, write_stream):+ async with _core.stdio_client(server_params, errlog=stderr.sink) as (read_stream, write_stream):# New PIDs for force-kill cleanup, minus non-MCP children (slash_worker, LSP) racing# into the window: they share the TUI's pgid — leaking them would killpg() the TUI.new_pids = _filter_mcp_children(_lifecycle._snapshot_child_pids() - pids_before)@@ -403,7 +404,14 @@ class MCPServerTransportMixin:# a server that never answers ``initialize`` would leak child + pipes per retry until EMFILE.connect_timeout = float(config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT))return await self._serve_session(session, connect_timeout, mark_lifecycle=True)+ except Exception as exc:+ # The SDK only sees "Connection closed"; the child's stderr says why (#124264).+ abi_error = node_abi_error(self.name, await asyncio.to_thread(stderr.close))+ if abi_error is not None:+ raise abi_error from exc+ raisefinally: # clean exit, exceptions AND cancellation+ stderr.close(timeout=0)if new_pids:self._release_spawned_children(new_pids)