diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index af6af50..a35b273 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -20,6 +20,7 @@ import json import re +import shutil import subprocess from dataclasses import dataclass from pathlib import Path @@ -92,8 +93,17 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: _GEMINI_LIST_NAME_RE = re.compile(r"^[^\sA-Za-z0-9]*\s*([^\s:]+):") +def _run_cli(cmd: list[str]) -> subprocess.CompletedProcess[str]: + """subprocess.run, launching exactly the binary shutil.which found. + Popen ignores PATHEXT on Windows, so a bare "gemini" never finds npm's + `gemini.cmd` shim and raises FileNotFoundError even when the CLI is + installed (same fix as BaseAdapter.run).""" + resolved = shutil.which(cmd[0]) or cmd[0] + return subprocess.run([resolved, *cmd[1:]], capture_output=True, text=True, timeout=30, check=False) + + def _gemini_existing_names() -> set[str]: - proc = subprocess.run(["gemini", "mcp", "list"], capture_output=True, text=True, timeout=30) + proc = _run_cli(["gemini", "mcp", "list"]) names = set() for line in proc.stdout.splitlines(): match = _GEMINI_LIST_NAME_RE.match(line.strip()) @@ -117,13 +127,15 @@ def _gemini_add_command(server: MCPServerConfig) -> list[str]: def sync_gemini(servers: list[MCPServerConfig]) -> list[SyncResult]: + if shutil.which("gemini") is None: + return [SyncResult("*", False, "gemini isn't installed (not found on PATH)")] existing = _gemini_existing_names() results = [] for server in servers: if server.name in existing: results.append(SyncResult(server.name, True, "already configured, skipped")) continue - proc = subprocess.run(_gemini_add_command(server), capture_output=True, text=True, timeout=30) + proc = _run_cli(_gemini_add_command(server)) if proc.returncode == 0: results.append(SyncResult(server.name, True, "added")) else: @@ -135,6 +147,8 @@ def sync_gemini(servers: list[MCPServerConfig]) -> list[SyncResult]: def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: + if shutil.which("agent") is None: + return [SyncResult("*", False, "agent isn't installed (not found on PATH)")] CURSOR_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) root: dict = {} existing: dict = {} @@ -164,7 +178,7 @@ def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: root["mcpServers"] = existing CURSOR_MCP_CONFIG_PATH.write_text(json.dumps(root, indent=2), encoding="utf-8") for name in newly_added: - proc = subprocess.run(["agent", "mcp", "enable", name], capture_output=True, text=True, timeout=30) + proc = _run_cli(["agent", "mcp", "enable", name]) if proc.returncode != 0: for result in results: if result.server_name == name: diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 585648a..7f2ba29 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -8,6 +8,13 @@ from secfoo import mcp from secfoo.settings import MCPServerConfig + +@pytest.fixture(autouse=True) +def _agent_clis_on_path(monkeypatch): + # Existing sync tests assume the gemini/agent CLIs are installed. + monkeypatch.setattr(mcp.shutil, "which", lambda name: f"/usr/bin/{name}") + + STDIO_SERVER = MCPServerConfig( name="Atlassian-Rovo-MCP", command="npx", @@ -98,7 +105,7 @@ def fake_run(cmd, **kwargs): results = mcp.sync_gemini([STDIO_SERVER]) assert results[0].ok is True assert results[0].message == "added" - assert captured["cmd"][:4] == ["gemini", "mcp", "add", "--scope"] + assert captured["cmd"][:4] == ["/usr/bin/gemini", "mcp", "add", "--scope"] assert "Atlassian-Rovo-MCP" in captured["cmd"] @@ -211,3 +218,51 @@ def test_sync_unsupported_agent_raises(): mcp.sync("agy", []) with pytest.raises(ValueError): mcp.sync("claude", []) + + +def test_sync_gemini_reports_missing_cli_instead_of_crashing(monkeypatch): + monkeypatch.setattr(mcp.shutil, "which", lambda name: None) + + def fail_if_called(cmd, **kwargs): + raise AssertionError("should not run gemini when the CLI is missing") + + monkeypatch.setattr(mcp.subprocess, "run", fail_if_called) + results = mcp.sync_gemini([STDIO_SERVER]) + + assert len(results) == 1 + assert results[0].ok is False + assert "gemini" in results[0].message + + +def test_sync_cursor_reports_missing_cli_before_writing_config(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + monkeypatch.setattr(mcp.shutil, "which", lambda name: None) + + def fail_if_called(cmd, **kwargs): + raise AssertionError("should not run agent when the CLI is missing") + + monkeypatch.setattr(mcp.subprocess, "run", fail_if_called) + results = mcp.sync_cursor([STDIO_SERVER]) + + assert len(results) == 1 + assert results[0].ok is False + assert "agent" in results[0].message + assert not cursor_path.exists() + + +def test_sync_launches_the_resolved_cli_path(tmp_path, monkeypatch): + # On Windows npm installs `gemini.cmd`; shutil.which finds it but a bare + # "gemini" passed to subprocess raises FileNotFoundError. + monkeypatch.setattr(mcp.shutil, "which", lambda name: rf"C:\npm\{name}.CMD") + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", tmp_path / "mcp.json") + launched = [] + + def fake_run(cmd, **kwargs): + launched.append(cmd[0]) + return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") + + monkeypatch.setattr(mcp.subprocess, "run", fake_run) + mcp.sync_gemini([STDIO_SERVER]) + mcp.sync_cursor([STDIO_SERVER]) + assert launched == [r"C:\npm\gemini.CMD", r"C:\npm\gemini.CMD", r"C:\npm\agent.CMD"]