The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): resolve stdio commands without reading or mutating the parent env
Konstantin Khlopkov80c2696422a1
diff --git a/tests/tools/test_mcp_tool_issue_948.py b/tests/tools/test_mcp_tool_issue_948.pyindex 39b3ccac018..eb8bce1946c 100644--- a/tests/tools/test_mcp_tool_issue_948.py+++ b/tests/tools/test_mcp_tool_issue_948.py@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom tools.mcp_tool import MCPServerTask, _MCP_AVAILABLEfrom tools.mcp_tool_errors import _format_connect_errorfrom tools.mcp_tool_config import _node_fallback, _resolve_stdio_command+from tools.mcp_tool_config import _which_with_config_pathext# Ensure the mcp module symbols exist for patching even when the SDK isn't installedif not _MCP_AVAILABLE:@@ -107,6 +108,76 @@ def test_resolve_stdio_command_falls_back_to_usr_local_bin():assert env["PATH"].split(os.pathsep)[0] == os.path.dirname(target)+def test_resolve_stdio_command_absent_path_is_a_miss(tmp_path, monkeypatch):+ """A server env without PATH must not resolve commands against the PARENT's PATH:+ the child would be spawned without it and the lookup would pass on an env the+ child never sees. Bare ``node`` still reaches the explicit well-known dirs."""+ parent_bin = tmp_path / "parent-bin"+ parent_bin.mkdir()+ server_tool = parent_bin / "some-mcp-server"+ server_tool.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ server_tool.chmod(0o755)+ node_tool = tmp_path / "node" / "bin" / "node"+ node_tool.parent.mkdir(parents=True)+ node_tool.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ node_tool.chmod(0o755)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ # the parent PATH contains BOTH names: an ambient hit would resolve either+ monkeypatch.setenv("PATH", str(parent_bin))++ command, _env = _resolve_stdio_command("some-mcp-server", {"OTHER": "1"})++ assert command == "some-mcp-server" # absent child PATH: honest miss, not an ambient hit++ with patch.dict("os.environ", {"PATH": str(parent_bin)}):+ command, _env = _resolve_stdio_command("node", {"OTHER": "1"})+ assert command == str(node_tool) # the explicit Node fallback dirs stay reachable+++def test_resolve_stdio_command_empty_path_is_a_miss(monkeypatch, tmp_path):+ """An explicitly empty child PATH keeps its cwd-only meaning (never the parent's PATH):+ ``which`` sees ``[""]`` -> cwd. The binary lives only in the parent's PATH dir, so the+ lookup must miss rather than silently inheriting the parent's directories."""+ parent_bin = tmp_path / "parent-bin"+ parent_bin.mkdir()+ server_tool = parent_bin / "other-mcp-server"+ server_tool.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ server_tool.chmod(0o755)+ monkeypatch.setenv("PATH", str(parent_bin))++ command, _env = _resolve_stdio_command("other-mcp-server", {"PATH": ""})++ assert command == "other-mcp-server" # cwd-only lookup: no ambient fallback+++def test_config_pathext_lookup_never_touches_parent_environ(tmp_path, monkeypatch):+ """Resolving under a configured PATHEXT must not mutate the parent's ``os.environ``:+ a multiplexed gateway resolves servers for several profiles from one process, and+ any thread reading PATHEXT (or inheriting env for its own subprocess) inside the+ lookup window would otherwise see this server's per-profile value."""+ server_dir = tmp_path / "bin"+ server_dir.mkdir()+ (server_dir / "server.cmd").write_text("@echo off\r\n", encoding="utf-8")+ (server_dir / "server.cmd").chmod(0o755)+ monkeypatch.delenv("PATHEXT", raising=False)+ monkeypatch.setenv("PATH", str(server_dir))+ seen = {}++ import tools.mcp_tool_config as _cfg++ def _spy(cmd, path=None):+ seen["PATHEXT"] = os.environ.get("PATHEXT")+ raise AssertionError("shutil.which must not be the lookup engine here")++ with patch.object(_cfg.shutil, "which", side_effect=_spy):+ cfg_env = {"PATHEXT": ".cmd;.exe"}+ hit = _which_with_config_pathext("server", str(server_dir), cfg_env)++ assert hit == str(server_dir / "server.cmd")+ assert "PATHEXT" not in os.environ # not written, not left behind+ assert seen == {} # and never consulted mid-lookup either++# ---------------------------------------------------------------------------# #29184: OSV malware preflight must not block the asyncio event loop, and a# stalled check must time out fail-open rather than freezing MCP startup.diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex b4a8be01b2c..589d64f6114 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -134,19 +134,31 @@ def _build_safe_env(user_env: Optional[dict]) -> dict:def _which_with_config_pathext(command: str, path_arg, env: dict):- """``shutil.which`` retried under the config env's PATHEXT (Windows only; ``which`` uses the PARENT's)."""+ """Resolve *command* under the config env's PATHEXT (Windows only; ``shutil.which`` uses the PARENT's).++ The extension walk mirrors ``which`` itself (existing-suffix short-circuit, configured+ extensions in order) but reads nothing from and writes nothing to ``os.environ``: swapping+ the parent's PATHEXT around a ``which`` call would publish this server's per-profile value+ to every other thread for the duration, and a ``finally``-restore cannot undo that window."""cfg_pathext = next((v for k, v in env.items() if k.upper() == "PATHEXT" and isinstance(v, str) and v.strip()), None)if not cfg_pathext or cfg_pathext == os.environ.get("PATHEXT"):return None- saved = os.environ.get("PATHEXT")- try:- os.environ["PATHEXT"] = cfg_pathext- return shutil.which(command, path=path_arg)- finally:- if saved is None:- os.environ.pop("PATHEXT", None)- else:- os.environ["PATHEXT"] = saved+ exts = [ext for ext in cfg_pathext.split(";") if ext] # PATHEXT is Windows-defined: ";"-separated even when resolved off-Windows+ candidates = [command + ext for ext in exts]+ if not candidates or any(command.lower().endswith(ext.lower()) for ext in exts):+ candidates = [command]+ directories = str(path_arg or "").split(os.pathsep)+ if sys.platform == "win32" and os.curdir not in directories:+ directories.insert(0, os.curdir) # Windows resolves from the cwd first+ for raw in directories:+ directory = raw or os.curdir # POSIX: an empty PATH component means the cwd+ if not os.path.isdir(directory):+ continue+ for candidate in candidates:+ resolved = os.path.join(directory, candidate)+ if os.path.isfile(resolved) and os.access(resolved, os.F_OK | os.X_OK):+ return resolved+ return Nonedef _node_fallback(command: str, *, windows: Optional[bool] = None) -> str:@@ -166,12 +178,19 @@ def _node_fallback(command: str, *, windows: Optional[bool] = None) -> str:def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:- """Resolve a stdio command against the exact subprocess env (bare ``npx``/``npm``/``node`` under a filtered PATH)."""+ """Resolve a stdio command against the exact subprocess env (bare ``npx``/``npm``/``node`` under a filtered PATH).++ A ``PATH`` lookup only runs when the child env actually carries one: ``shutil.which`` with+ ``path=None`` silently falls back to the PARENT's ``os.environ["PATH"]``, letting a command+ "resolve" against an env the child will never be spawned with. An absent child PATH is a+ miss; an explicitly empty one keeps its cwd-only meaning (same distinction the child's+ ``execvp`` will see). Bare ``npx``/``npm``/``node`` still fall through to the explicit+ well-known Node directories, everything else stays as-written for an honest spawn failure."""resolved_command = os.path.expanduser(str(command).strip())resolved_env = dict(env or {})if os.sep not in resolved_command:path_arg = resolved_env.get("PATH")- which_hit = shutil.which(resolved_command, path=path_arg)+ which_hit = shutil.which(resolved_command, path=path_arg) if path_arg is not None else Noneif which_hit is None and sys.platform == "win32" and resolved_env:which_hit = _which_with_config_pathext(resolved_command, path_arg, resolved_env)if which_hit: