The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(windows): an MSIX with no Node to copy runs npx MCP servers on its packaged node
ethernet8ef7654bf53e
diff --git a/tests/tools/test_mcp_tool_issue_948.py b/tests/tools/test_mcp_tool_issue_948.pyindex c263fa85586..a5b84d1d4fa 100644--- a/tests/tools/test_mcp_tool_issue_948.py+++ b/tests/tools/test_mcp_tool_issue_948.py@@ -233,6 +233,41 @@ def test_bare_node_launchers_resolve_pm_node_ahead_of_the_users(tmp_path, monkeyassert env["PATH"].split(os.pathsep) == [str(npm_bin), str(node_bin), str(user_bin), "/usr/bin"]+def test_packaged_npx_runs_the_package_bin_on_the_packaged_node(tmp_path, monkeypatch):+ """With only the payload's Node, npx's cmd.exe hop always dies, so Hermes installs the+ package (scripts off) and runs its bin script on the packaged node instead."""+ import pm.user_facing+ from tools.mcp_tool_config import _packaged_npx_entry++ npm_bin = _toolchain_bin(tmp_path / "store" / "npm", "npx")+ (npm_bin / "node_modules" / "npm" / "bin").mkdir(parents=True)+ (npm_bin / "node_modules" / "npm" / "bin" / "npm-cli.js").write_text("", encoding="utf-8")+ node_bin = tmp_path / "store" / "node"+ node_bin.mkdir(parents=True)+ calls = tmp_path / "npm-calls.txt"+ node = node_bin / "node"+ # Stands in for `node npm-cli.js install --prefix <p> ... <spec>`: records argv, lays out the package.+ node.write_text(+ "#!/bin/sh\n"+ f'echo "$@" >> "{calls}"\n'+ 'pkg="$4/node_modules/@scope/srv"; mkdir -p "$pkg"\n'+ "echo '{\"bin\": {\"srv\": \"dist/index.js\"}}' > \"$pkg/package.json\"\n",+ encoding="utf-8")+ node.chmod(0o755)+ monkeypatch.setattr(pm.user_facing, "applies", lambda: True)+ sealed = {"node": [str(node_bin)], "npm": [str(npm_bin)]}+ monkeypatch.setattr(pm.user_facing, "_sealed_dirs", lambda name: sealed.get(name, []))++ args = ["-y", "@scope/srv", "--port", "1"]+ command, argv = _packaged_npx_entry(str(npm_bin / "npx.cmd"), args)+ assert command == str(node)+ assert argv[1:] == ["--port", "1"] and argv[0].endswith(os.path.join("@scope", "srv", "dist", "index.js"))+ assert "--ignore-scripts" in calls.read_text(encoding="utf-8-sig").split()+ assert _packaged_npx_entry(str(npm_bin / "npx.cmd"), args) == (command, argv)+ assert len(calls.read_text(encoding="utf-8-sig").splitlines()) == 1+ assert _packaged_npx_entry(str(tmp_path / "user-node" / "npx.cmd"), args) is None++def test_bare_uvx_resolves_pm_uv_and_an_absolute_command_stays_the_users(tmp_path, monkeypatch):user_bin = _toolchain_bin(tmp_path / "user" / ".local" / "bin", "uvx")uv_dir = _toolchain_bin(tmp_path / "store" / "uv-0.1", "uv", "uvx")diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex b2707acd953..52f21a40bfc 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -24,7 +24,7 @@ from typing import Any, Callable, Dict, List, Optional, Setlogger = logging.getLogger(__name__)from tools.mcp_tool_common import _DEFAULT_TOOL_TIMEOUT, mcp_field-from tools.mcp_tool_config import _get_mcp_stderr_log, _npx_cached_bin+from tools.mcp_tool_config import _get_mcp_stderr_log, _npx_cached_bin, _packaged_npx_entryfrom tools.mcp_tool_sampling import ElicitationHandler, SamplingHandlerfrom tools.mcp_tool_transport import MCPServerTransportMixinfrom tools.mcp_tool_server_run import MCPServerRunMixin@@ -57,6 +57,11 @@ async def _preflight_stdio_command(server_name: str, command: str, args: list) -# nothing (~48 MB per server, measured). Hermes already supervises the child (shared death# supervisor), so a cached package is spawned directly; a cache miss leaves npx untouched.if os.path.basename(command).lower().startswith("npx"):+ # A sealed Windows payload's own npx cannot start its node through cmd.exe.+ packaged = await asyncio.to_thread(_packaged_npx_entry, command, args)+ if packaged:+ logger.debug("MCP server '%s': running %s on the packaged node", server_name, packaged[1][0])+ return packagedcached = _npx_cached_bin(args)if cached:direct_command, direct_args = cacheddiff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex 026f05d67d4..cfbb9240895 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -3,11 +3,13 @@ interpolation, hidden-whitespace and suspicious-entry filtering, the filteredsubprocess env, command resolution, the cached-npx binary shortcut and the shared stderr log."""import codecs+import hashlibimport jsonimport loggingimport osimport reimport shutil+import subprocessimport sysimport threadingfrom pathlib import Path@@ -459,6 +461,60 @@ def _npx_cached_bin(args: list) -> Optional[tuple]:return None+def _packaged_npx_entry(command: str, args: list) -> Optional[tuple]:+ """``(node.exe, [bin script, *args])`` for ``npx [-y] <pkg> ...`` when *command* is a sealed+ Windows payload's own npx, else None.++ That npx starts the package bin through cmd.exe, and cmd.exe cannot start the packaged+ ``node.exe`` (``pm.user_facing``). Hermes gets here only without a host Node and without+ a copy that PM may make. The payload's Python CAN start the packaged ``node.exe``, so the+ package is installed with npm's own script and the bin's script runs on that node.+ Install scripts stay off, because npm runs them through cmd.exe too. None keeps plain+ npx (an honest failure) for any other argv shape, a failed install, or an unclear bin.+ """+ from pm.user_facing import _sealed_dirs, applies++ if not applies() or not isinstance(args, list):+ return None+ npm_dirs = {os.path.normcase(d): d for d in _sealed_dirs("npm")}+ npm_dir = npm_dirs.get(os.path.normcase(os.path.dirname(str(command))))+ node = shutil.which("node", path=os.pathsep.join(_sealed_dirs("node")))+ npm_cli = os.path.join(npm_dir or "", "node_modules", "npm", "bin", "npm-cli.js")+ if npm_dir is None or node is None or not os.path.isfile(npm_cli):+ return None+ rest = list(args)+ while rest and rest[0] in ("-y", "--yes"):+ rest.pop(0)+ spec = str(rest[0]) if rest else ""+ if not spec or spec.startswith("-") or any(str(a) in ("-y", "--yes") for a in rest[1:]):+ return None+ scope, _, bare = spec.rpartition("/") if spec.startswith("@") else ("", "", spec)+ name = (f"{scope}/" if scope else "") + bare.split("@", 1)[0]+ from hermes_constants import get_hermes_home++ prefix = Path(get_hermes_home()) / "cache" / "mcp-npx" / hashlib.sha256(spec.encode()).hexdigest()[:16]+ manifest = prefix / "node_modules" / name / "package.json"+ if not manifest.is_file():+ install = [node, npm_cli, "install", "--prefix", str(prefix), "--no-save", "--ignore-scripts",+ "--no-audit", "--no-fund", "--loglevel=error", spec]+ result = subprocess.run(install, capture_output=True, text=True, encoding="utf-8", errors="replace",+ stdin=subprocess.DEVNULL, timeout=600, check=False)+ if result.returncode != 0 or not manifest.is_file():+ logger.warning("npm install of %s with the packaged node failed: %s", spec,+ (result.stderr or result.stdout).strip()[-500:])+ return None+ try:+ bin_field = (json.loads(manifest.read_text(encoding="utf-8-sig")) or {}).get("bin")+ except (OSError, ValueError):+ return None+ if isinstance(bin_field, dict):+ bin_field = bin_field.get(bare.split("@", 1)[0]) or (+ next(iter(bin_field.values())) if len(bin_field) == 1 else None)+ if not isinstance(bin_field, str):+ return None+ return node, [str(manifest.parent / bin_field), *rest[1:]]++def _interpolate_env_vars(value):"""Recursively resolve ``${VAR}`` / Cursor ``${env:VAR}`` placeholders and context vars. Envrefs resolve from the active profile's secret scope when multiplexing (the routed profile's