The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(mcp): skip npx's resident parent when the package is already cached
John Paul Soliva11ed840431ab
diff --git a/tests/tools/test_mcp_npx_cached_bin.py b/tests/tools/test_mcp_npx_cached_bin.pynew file mode 100644index 00000000000..6eecdc40d8c--- /dev/null+++ b/tests/tools/test_mcp_npx_cached_bin.py@@ -0,0 +1,160 @@+"""``npx -y <pkg>`` should spawn the cached binary, not a resident `npm exec`.++`npx` resolves the package and then FORKS, staying alive as the real server's+parent for the whole process lifetime while doing no work. Measured on a+4-agent host that is ~48 MB of private memory per MCP server — and it buys+nothing, because Hermes already wraps the child in its own parent-death+watchdog, so npx's supervision is a second parent nobody reads.++Removing it must stay conservative: a cache miss, a version-pinned spec, or an+ambiguous ``bin`` map all fall back to plain `npx` so a cold machine still+installs normally.+"""++from __future__ import annotations++import json+import os++import pytest++from tools.mcp_tool import _npx_cached_bin+++def _cache(tmp_path, *, package, deps=None, bin_field, make_bin=True, entry="abc123"):+ """Build a fake npx cache entry the way npm lays one out."""+ root = tmp_path / ".npm" / "_npx" / entry+ (root / "node_modules" / package).mkdir(parents=True)+ (root / "package.json").write_text(+ json.dumps({"dependencies": deps if deps is not None else {package: "^1.0.0"}}),+ encoding="utf-8",+ )+ (root / "node_modules" / package / "package.json").write_text(+ json.dumps({"name": package, "bin": bin_field}), encoding="utf-8"+ )+ bindir = root / "node_modules" / ".bin"+ bindir.mkdir(parents=True, exist_ok=True)+ name = bin_field if isinstance(bin_field, str) else list(bin_field)[0]+ target = bindir / (os.path.basename(package) if isinstance(bin_field, str) else name)+ if make_bin:+ target.write_text("#!/usr/bin/env node\n", encoding="utf-8")+ target.chmod(0o755)+ return target++[email protected](autouse=True)+def _isolate_cache(tmp_path, monkeypatch):+ monkeypatch.setenv("npm_config_cache", str(tmp_path / ".npm"))+ yield+++def test_cached_package_resolves_to_its_binary(tmp_path):+ target = _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "dist/index.js"})++ got = _npx_cached_bin(["-y", "mcp-linear"])++ assert got == (str(target), [])+++def test_scoped_package_and_trailing_args_survive(tmp_path):+ target = _cache(+ tmp_path,+ package="@tacticlaunch/mcp-linear",+ bin_field={"mcp-linear": "dist/index.js"},+ )++ got = _npx_cached_bin(["-y", "@tacticlaunch/mcp-linear", "--port", "7"])++ assert got == (str(target), ["--port", "7"])+++def test_uncached_package_falls_back_to_npx(tmp_path):+ _cache(tmp_path, package="something-else", bin_field={"something-else": "i.js"})++ assert _npx_cached_bin(["-y", "mcp-linear"]) is None+++def test_version_pinned_spec_is_left_to_npx(tmp_path):+ _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "dist/index.js"})++ # The user pinned a build; npx owns that resolution and the cache key for+ # a different version would not match this entry.+ assert _npx_cached_bin(["-y", "[email protected]"]) is None+++def test_ambiguous_bin_map_is_left_to_npx(tmp_path):+ _cache(+ tmp_path,+ package="multi",+ bin_field={"one": "a.js", "two": "b.js"},+ )++ # Which bin npx would choose is not ours to guess.+ assert _npx_cached_bin(["-y", "multi"]) is None+++def test_missing_or_non_executable_binary_falls_back(tmp_path):+ _cache(+ tmp_path,+ package="mcp-linear",+ bin_field={"mcp-linear": "dist/index.js"},+ make_bin=False,+ )++ assert _npx_cached_bin(["-y", "mcp-linear"]) is None+++def test_no_cache_directory_at_all(tmp_path, monkeypatch):+ monkeypatch.setenv("npm_config_cache", str(tmp_path / "nope"))++ assert _npx_cached_bin(["-y", "mcp-linear"]) is None+++def test_corrupt_cache_manifest_is_skipped(tmp_path):+ root = tmp_path / ".npm" / "_npx" / "broken"+ root.mkdir(parents=True)+ (root / "package.json").write_text("{ not json", encoding="utf-8")++ assert _npx_cached_bin(["-y", "mcp-linear"]) is None++[email protected]("args", [[], ["-y"], ["--yes"], ["-p", "x"], None, "notalist"])+def test_unusable_args_are_ignored(args):+ assert _npx_cached_bin(args) is None+++def test_osv_preflight_runs_before_the_swap():+ """The malware gate must still see `npx` + the package name.++ `_infer_ecosystem` keys off the command basename, so a command already+ rewritten to `.../node_modules/.bin/mcp-linear` yields no ecosystem and+ `check_package_for_malware` returns None — the gate silently becomes a+ no-op. This pins the ordering: OSV inspects the original invocation.+ """+ from tools.osv_check import _infer_ecosystem, _parse_package_from_args++ # What the preflight sees today, before any swap.+ assert _infer_ecosystem("npx") == "npm"+ assert _parse_package_from_args(["-y", "@tacticlaunch/mcp-linear"], "npm")[0] == (+ "@tacticlaunch/mcp-linear"+ )++ # What it would see if the swap happened first — nothing.+ assert _infer_ecosystem("/home/u/.npm/_npx/abc/node_modules/.bin/mcp-linear") is None+++def test_swap_happens_after_the_osv_call_in_source():+ """Structural guard for the ordering above.++ The swap and the preflight live in one async function; a future edit that+ moves the swap earlier would disable the malware gate silently, and no+ unit test of either piece alone would notice.+ """+ from pathlib import Path as _P++ src = _P(__file__).resolve().parents[2] / "tools" / "mcp_tool.py"+ text = src.read_text(encoding="utf-8")+ osv_at = text.index("check_package_for_malware, command, args")+ swap_at = text.index("cached = _npx_cached_bin(args)")++ assert osv_at < swap_at, "the npx swap must not precede the OSV malware preflight"diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 744832db1f6..56566f65e11 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -1073,6 +1073,90 @@ def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:return resolved_command, resolved_env+def _npx_cached_bin(args: list) -> Optional[tuple]:+ """Resolve ``npx -y <pkg>`` to the already-installed binary, or None.++ ``npx`` resolves the package and then FORKS: it stays resident as the+ parent of the real server for the whole process lifetime, doing no work.+ Measured on a 4-agent host, that is ~48 MB of private memory per MCP+ server — and it buys nothing here, because Hermes already supervises the+ child itself (the shared death supervisor), so npx's supervision is a+ second parent nobody reads.++ When the package is already in npx's cache we can spawn its binary+ directly and drop the middle process. A cache miss returns None and the+ caller falls back to ``npx`` unchanged, so the first run still installs+ and nothing regresses on a cold machine.++ Deliberately conservative — returns None for anything unusual:+ a version-pinned spec (``[email protected]``), extra npx flags, a package whose+ manifest declares no single obvious bin, or any unreadable cache entry.++ Returns ``(binary_path, remaining_args)`` or None.+ """+ if not isinstance(args, list) or not args:+ return None++ rest = list(args)+ while rest and rest[0] in ("-y", "--yes"):+ rest.pop(0)+ if not rest:+ return None++ spec = str(rest[0])+ # A version pin means the user asked for a specific build; npx owns that+ # resolution and the cache key may not match. Scoped names keep their+ # leading '@', so only an '@' AFTER the scope is a version separator.+ if "@" in (spec[1:] if spec.startswith("@") else spec):+ return None+ if not spec or spec.startswith("-"):+ return None++ cache_root = os.environ.get("npm_config_cache") or os.path.join(+ os.path.expanduser("~"), ".npm"+ )+ npx_root = os.path.join(cache_root, "_npx")+ if not os.path.isdir(npx_root):+ return None++ try:+ entries = os.listdir(npx_root)+ except OSError:+ return None++ for entry in entries:+ manifest = os.path.join(npx_root, entry, "package.json")+ try:+ with open(manifest, "r", encoding="utf-8") as fh:+ deps = (json.load(fh) or {}).get("dependencies") or {}+ except (OSError, ValueError, TypeError):+ continue+ if spec not in deps:+ continue++ pkg_json = os.path.join(npx_root, entry, "node_modules", spec, "package.json")+ try:+ with open(pkg_json, "r", encoding="utf-8") as fh:+ bin_field = (json.load(fh) or {}).get("bin")+ except (OSError, ValueError, TypeError):+ continue++ if isinstance(bin_field, str):+ names = [os.path.basename(spec)]+ elif isinstance(bin_field, dict) and len(bin_field) == 1:+ names = list(bin_field.keys())+ else:+ # Zero or several bins: which one npx would pick is not ours to+ # guess. Let npx decide.+ continue++ candidate = os.path.join(npx_root, entry, "node_modules", ".bin", names[0])+ if os.path.exists(candidate) and os.access(candidate, os.X_OK):+ return candidate, rest[1:]++ return None++# ---------------------------------------------------------------------------# Shared parent-death supervisor# ---------------------------------------------------------------------------@@ -3432,6 +3516,25 @@ class MCPServerTask:f"MCP server '{self.name}': {malware_error}")+ # npx resolves the package and then FORKS, staying resident as the+ # real server's parent for nothing (~48 MB per MCP server, measured).+ # Hermes already supervises the child (shared death supervisor), so+ # when the package is cached we spawn its binary directly and drop+ # that middle process.+ # Deliberately AFTER the OSV preflight: the check keys off the command+ # basename being `npx`, so swapping first would silently turn the+ # malware gate into a no-op. Cache miss leaves npx untouched.+ if os.path.basename(command).lower().startswith("npx"):+ cached = _npx_cached_bin(args)+ if cached:+ direct_command, direct_args = cached+ logger.debug(+ "MCP server '%s': using cached npx binary %s (skipping the "+ "resident `npm exec` parent)",+ self.name, direct_command,+ )+ command, args = direct_command, direct_args+server_params = StdioServerParameters(command=command,args=args,