The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): stdio servers default to the session working directory
CoolStar08ac080441be
diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 469ad51a7dc..25c9e16c5e7 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -10,6 +10,7 @@ import osimport sysimport threadingimport time+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -1134,6 +1135,112 @@ class TestMCPServerTask:asyncio.run(_test())+ def test_start_defaults_stdio_cwd_to_session_cwd(self, tmp_path, monkeypatch):+ """A pinned session working directory becomes the stdio default cwd.++ Hosted/multiplexed sessions (ACP, gateway) pin their logical cwd; a stdio+ server spawned there inherits the Hermes process dir instead, so+ relative-path servers resolve against the wrong tree.+ """+ from agent.runtime_cwd import clear_session_cwd, set_session_cwd+ from tools.mcp_tool import MCPServerTask++ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ workspace = tmp_path / "workspace"+ workspace.mkdir()++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock()+ mock_session.list_tools = AsyncMock(return_value=SimpleNamespace(tools=[]))+ p_stdio, p_cs, _, _ = self._mock_stdio_and_session(mock_session)++ async def _test():+ set_session_cwd(str(workspace))+ try:+ with patch("tools.mcp_tool.StdioServerParameters") as params, p_stdio, p_cs:+ server = MCPServerTask("session_cwd")+ await server.start({"command": "npx", "args": ["-y", "test"]})+ assert Path(params.call_args.kwargs["cwd"]) == workspace+ await server.shutdown()+ finally:+ clear_session_cwd()++ asyncio.run(_test())++ def test_start_defaults_stdio_cwd_to_terminal_cwd(self, tmp_path, monkeypatch):+ """Without a session pin, the TERMINAL_CWD bridge anchors the stdio default."""+ from agent.runtime_cwd import clear_session_cwd+ from tools.mcp_tool import MCPServerTask++ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock()+ mock_session.list_tools = AsyncMock(return_value=SimpleNamespace(tools=[]))+ p_stdio, p_cs, _, _ = self._mock_stdio_and_session(mock_session)++ async def _test():+ clear_session_cwd()+ with patch("tools.mcp_tool.StdioServerParameters") as params, p_stdio, p_cs:+ server = MCPServerTask("terminal_cwd")+ await server.start({"command": "npx", "args": ["-y", "test"]})+ assert Path(params.call_args.kwargs["cwd"]) == tmp_path+ await server.shutdown()++ asyncio.run(_test())++ def test_start_configured_cwd_overrides_session_cwd(self, tmp_path, monkeypatch):+ """An explicit per-server `cwd` in config always wins over the session anchor."""+ from agent.runtime_cwd import clear_session_cwd, set_session_cwd+ from tools.mcp_tool import MCPServerTask++ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ workspace = tmp_path / "workspace"+ workspace.mkdir()++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock()+ mock_session.list_tools = AsyncMock(return_value=SimpleNamespace(tools=[]))+ p_stdio, p_cs, _, _ = self._mock_stdio_and_session(mock_session)++ async def _test():+ set_session_cwd(str(workspace))+ try:+ with patch("tools.mcp_tool.StdioServerParameters") as params, p_stdio, p_cs:+ server = MCPServerTask("explicit_wins")+ await server.start({"command": "npx", "args": ["-y", "test"], "cwd": "/plugin"})+ assert params.call_args.kwargs["cwd"] == "/plugin"+ await server.shutdown()+ finally:+ clear_session_cwd()++ asyncio.run(_test())++ def test_start_missing_session_cwd_keeps_native_default(self, tmp_path, monkeypatch):+ """A session pin pointing at a deleted directory yields None, not a stale anchor."""+ from agent.runtime_cwd import clear_session_cwd, set_session_cwd+ from tools.mcp_tool import MCPServerTask++ monkeypatch.delenv("TERMINAL_CWD", raising=False)++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock()+ mock_session.list_tools = AsyncMock(return_value=SimpleNamespace(tools=[]))+ p_stdio, p_cs, _, _ = self._mock_stdio_and_session(mock_session)++ async def _test():+ set_session_cwd(str(tmp_path / "gone"))+ try:+ with patch("tools.mcp_tool.StdioServerParameters") as params, p_stdio, p_cs:+ server = MCPServerTask("gone")+ await server.start({"command": "npx", "args": ["-y", "test"]})+ assert params.call_args.kwargs["cwd"] is None+ await server.shutdown()+ finally:+ clear_session_cwd()++ asyncio.run(_test())+def test_stdio_recycle_deadline_pauses_while_rpc_active(self):from tools.mcp_tool import MCPServerTaskdiff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex 32aa2618732..1c4372f1806 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -11,6 +11,7 @@ from contextlib import asynccontextmanagerfrom typing import Dict, Optional, Setfrom utils import normalize_proxy_urlfrom agent.proxy_bypass import is_loopback_host, should_bypass_proxy+from agent import runtime_cwd as _runtime_cwdfrom tools.mcp_tool_errors import NonMcpEndpointError, _apply_identity_header, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_groupfrom tools.mcp_tool_lifecycle import _filter_mcp_children, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pidsfrom tools.mcp_tool_common import _core@@ -258,8 +259,15 @@ class MCPServerTransportMixin:command, safe_env = _config._resolve_stdio_command(command, _config._build_safe_env(config.get("env")))# OSV malware preflight, then the cached-npx swap (ordering enforced there).command, args = await _core._preflight_stdio_command(self.name, command, config.get("args", []))+ # A stdio child inherits this process's cwd when none is configured. Hosted sessions (ACP,+ # gateway) pin a logical cwd via agent.runtime_cwd; without it the child resolves relative+ # paths against the daemon's launch dir, not the session workspace. Explicit config always+ # wins; an existing session/TERMINAL_CWD anchor becomes the default; else native (None).+ stdio_cwd = config.get("cwd")+ if stdio_cwd is None:+ stdio_cwd = _runtime_cwd.resolve_context_cwd() or Noneserver_params = _core.StdioServerParameters(- command=command, args=args, env=safe_env or None, cwd=config.get("cwd"),+ command=command, args=args, env=safe_env or None, cwd=stdio_cwd,# Windows pipes can split non-UTF-8 bytes at chunk boundaries; substitute, don't raise.encoding_error_handler="replace")# Reap orphans of prior attempts first (else retries pile up zombie pairs); unscoped on purpose;