Skip to content

The agent that grows with you

fix(mcp): pick the Windows launcher, not the sh script, from an npx cache

John Paul Soliva1a451bfaeb49
diff --git a/tests/tools/test_mcp_npx_cached_bin.py b/tests/tools/test_mcp_npx_cached_bin.py
index 6eecdc40d8c..40a16640d87 100644
--- a/tests/tools/test_mcp_npx_cached_bin.py
+++ b/tests/tools/test_mcp_npx_cached_bin.py
@@ -154,7 +154,55 @@ def test_swap_happens_after_the_osv_call_in_source():
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)")
+ osv_needle = "check_package_for_malware, command, args"
+ swap_needle = "cached = _npx_cached_bin(args)"
+ # Report a rename explicitly: a bare .index() ValueError here reads like a
+ # broken test rather than "someone renamed the thing this guards".
+ assert osv_needle in text, (
+ f"cannot find the OSV preflight call ({osv_needle!r}) — it was renamed; "
+ "update this guard and re-verify the swap still happens after it"
+ )
+ assert swap_needle in text, (
+ f"cannot find the npx swap ({swap_needle!r}) — it was renamed; update "
+ "this guard and re-verify it still happens after the OSV preflight"
+ )
+
+ assert text.index(osv_needle) < text.index(swap_needle), (
+ "the npx swap now precedes the OSV malware preflight, which silently "
+ "disables it: _infer_ecosystem keys off the command basename being "
+ "npx/uvx/pipx, so a rewritten command yields no ecosystem and "
+ "check_package_for_malware returns None"
+ )
+
+
+def test_windows_selects_launchers_never_the_sh_script():
+ """On Windows the extensionless sh script must never be chosen.
+
+ npm lays down three siblings per bin — `<name>`, `<name>.cmd`,
+ `<name>.ps1` — and spawning the sh one from a Windows process fails, while
+ `os.access(X_OK)` there is effectively an existence check and cannot tell
+ them apart. Tested through the injectable helper rather than by patching
+ `os.name`, which breaks path handling process-wide (it took pytest's own
+ traceback formatting down when I tried).
+ """
+ from tools.mcp_tool import _npx_bin_candidates
+
+ win = _npx_bin_candidates("/c/bin", "mcp-linear", windows=True)
+ assert win == ["/c/bin/mcp-linear.cmd", "/c/bin/mcp-linear.exe"]
+ assert not any(c.endswith("mcp-linear") for c in win), "sh script must not be a candidate"
+
+ assert _npx_bin_candidates("/bin", "mcp-linear", windows=False) == ["/bin/mcp-linear"]
+
+
+def test_posix_resolution_uses_the_helper(tmp_path):
+ """The resolver honours the helper's ordering (POSIX path end-to-end)."""
+ target = _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "i.js"})
+
+ assert _npx_cached_bin(["-y", "mcp-linear"]) == (str(target), [])
+
+
+def test_flag_after_the_spec_is_left_to_npx(tmp_path):
+ """`npx pkg -y` would forward -y to the server; that shape stays with npx."""
+ _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "i.js"})
- assert osv_at < swap_at, "the npx swap must not precede the OSV malware preflight"
+ assert _npx_cached_bin(["mcp-linear", "-y"]) is None
diff --git a/tools/mcp_tool.py b/tools/mcp_tool.py
index 56566f65e11..92c8de67c5c 100644
--- a/tools/mcp_tool.py
+++ b/tools/mcp_tool.py
@@ -1073,6 +1073,26 @@ def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
return resolved_command, resolved_env
+def _npx_bin_candidates(bin_dir: str, name: str, *, windows: Optional[bool] = None) -> list:
+ """Launcher paths to try for *name* inside an npx cache's ``.bin``, in order.
+
+ On Windows that directory holds three siblings per bin — the extensionless
+ sh script, ``<name>.cmd`` and ``<name>.ps1``. Spawning the sh one from a
+ Windows process fails, and ``os.access(X_OK)`` there is effectively an
+ existence check, so it cannot tell them apart. Select by extension instead,
+ the same precedence ``hermes_constants._candidate_node_command_names``
+ already uses for npm/npx/node; when no launcher exists the caller falls
+ back to npx rather than spawning something that will not run.
+
+ ``windows`` is injectable so the platform branch is testable without
+ monkeypatching ``os.name`` (which breaks path handling process-wide).
+ """
+ is_windows = os.name == "nt" if windows is None else windows
+ if is_windows:
+ return [os.path.join(bin_dir, name + ext) for ext in (".cmd", ".exe")]
+ return [os.path.join(bin_dir, name)]
+
+
def _npx_cached_bin(args: list) -> Optional[tuple]:
"""Resolve ``npx -y <pkg>`` to the already-installed binary, or None.
@@ -1103,6 +1123,12 @@ def _npx_cached_bin(args: list) -> Optional[tuple]:
if not rest:
return None
+ # `npx pkg -y` (flag AFTER the spec) is an unusual shape: those args are
+ # forwarded verbatim to the resolved binary, which would hand the server a
+ # flag npx would have eaten. Leave anything like that to npx.
+ if any(str(a) in ("-y", "--yes") for a in rest[1:]):
+ 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
@@ -1150,9 +1176,10 @@ def _npx_cached_bin(args: list) -> Optional[tuple]:
# 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:]
+ bin_dir = os.path.join(npx_root, entry, "node_modules", ".bin")
+ for candidate in _npx_bin_candidates(bin_dir, names[0]):
+ if os.path.exists(candidate) and os.access(candidate, os.X_OK):
+ return candidate, rest[1:]
return None