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

Review follow-up, and a real platform bug. On Windows npm's `.bin` holds three
siblings per binary — 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 the previous
candidate test could not tell them apart: it would have picked a file that
cannot run and broken server startup that works today via npx.

Select by extension instead (`.cmd`, then `.exe`), the same precedence
hermes_constants._candidate_node_command_names already uses for npm/npx/node,
and fall back to npx when no launcher is present.

The platform branch moved into `_npx_bin_candidates(..., windows=...)` so it is
testable by injection. Patching `os.name` instead took pytest's own traceback
formatting down with an INTERNALERROR — a test that cannot report its own
failure is worse than no test.

Also from review: an `npx pkg -y` shape (flag AFTER the spec) now falls back to
npx, since those args are forwarded verbatim and would hand the server a flag
npx would have consumed. And the structural OSV-ordering guard reports a rename
explicitly instead of raising a bare ValueError that reads like a broken test.
This commit is contained in:
John Paul Soliva
2026-08-24 04:02:04 +09:00
committed by kshitij
parent 11ed840431
commit 1a451bfaeb
2 changed files with 81 additions and 6 deletions
+51 -3
View File
@@ -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 osv_at < swap_at, "the npx swap must not precede the OSV malware 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 _npx_cached_bin(["mcp-linear", "-y"]) is None
+30 -3
View File
@@ -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