diff --git a/README.md b/README.md index 5c4254a..a956692 100644 --- a/README.md +++ b/README.md @@ -82,9 +82,11 @@ headers = { Authorization = "Bearer ..." } With `--agent claude` the configured servers are attached to each run automatically and nothing else (your global Claude config is not touched and -the target's own `.mcp.json` is not loaded). For Gemini CLI and Cursor run -`secfoo mcp sync --agent ` once. Codex, Antigravity and the `api` -agent cannot use MCP servers yet. Details in +the target's own `.mcp.json` is not loaded). For persistent agents (`gemini`, +`agent` (Cursor), `codex`, `copilot`, `opencode`, `droid`, `devin`), run +`secfoo mcp sync --agent ` once (or `secfoo mcp sync` to sync all installed). +Antigravity (`agy`) and the `api` agent are not wired up for MCP (no mechanism is +documented for the agy CLI; not re-verified against a current release). Details in [docs/REFERENCE.md](https://github.com/secfoo-com/secfoo/blob/main/docs/REFERENCE.md#configuration-secfooconfigtoml). ## A 30-second look at the dashboard diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index dd80e68..9053ffc 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -961,18 +961,52 @@ your installed CLI version; an invalid ID is reported by that CLI. How MCP servers reach each agent varies by what its CLI actually supports: -| Agent | Mechanism | -|---|---| -| `claude` | Automatic on every `secfoo run` (`--mcp-config`, scoped to that invocation only — your global Claude config is never touched). These are the only MCP servers loaded during a scan (`--strict-mcp-config`): servers from your global Claude config or from the target's `.mcp.json` are not started | -| `gemini`, `agent` (Cursor) | Run `secfoo mcp sync --agent ` once to register persistently in that tool's own config | -| `codex` | Not wired up yet — Codex reads MCP servers from its own `~/.codex/config.toml` | -| `agy` (Antigravity) | Not supported yet — its CLI has no MCP configuration mechanism as of this writing | +| Agent | Mechanism | Guidance | +|---|---|---| +| `claude` | per-run | Automatic on every `secfoo run` (`--mcp-config`, scoped to that invocation only — your global Claude config is never touched). These are the only MCP servers loaded during a scan (`--strict-mcp-config`): servers from your global Claude config or from the target's `.mcp.json` are not started | +| `agent` | sync | Run `secfoo mcp sync --agent agent` once to register persistently in `~/.cursor/mcp.json` | +| `gemini` | sync | Run `secfoo mcp sync --agent gemini` once to register persistently via `gemini mcp add` | +| `codex` | sync | Run `secfoo mcp sync --agent codex` once to merge persistently into `~/.codex/config.toml` without clobbering other settings | +| `copilot` | sync | Run `secfoo mcp sync --agent copilot` once to register persistently in `~/.copilot/mcp-config.json` | +| `opencode` | sync | Run `secfoo mcp sync --agent opencode` once to register persistently in `~/.config/opencode/opencode.json` | +| `droid` | sync | Run `secfoo mcp sync --agent droid` once to register persistently in `~/.factory/mcp.json` | +| `devin` | sync | Run `secfoo mcp sync --agent devin` once to register persistently in `~/.config/devin/mcp_config.json` (%APPDATA%\devin\mcp_config.json on Windows) | +| `agy` | none | Not supported by secfoo: no MCP configuration mechanism is documented for the agy CLI, and this has not been re-verified against a current release | +| `api` | none | Not applicable — the API adapter calls model endpoints directly and has no tool loop | + +`claude` is the only agent whose MCP servers are scoped to a single run. For the others, secfoo's adapters currently pass no MCP configuration per run, so secfoo writes those files at 0600 (for gemini, the Gemini CLI performs the write). Those servers then load for every use of that CLI, not just secfoo scans, and secrets in them are stored in plaintext at rest. ```bash secfoo mcp list # show what's configured +secfoo mcp sync # register into all installed agents secfoo mcp sync --agent gemini # register into gemini's own config ``` +### Write-tool security guidance + +MCP servers can expose both read-only operations (e.g. searching Confluence, +querying Jira issues) and state-mutating write tools (e.g. creating tickets, +editing documents, executing actions). Because secfoo performs read-only +assessments, write tools should never be executed during a review: + +- **Claude:** Uses `--allowedTools`. Note that `--allowedTools mcp__` + grants all tools exposed by that server (including any write tools on it). + To restrict write tools, use server-level read-only API tokens or fine-grained + per-tool allowlisting (`mcp____`) if supported by your Claude Code version. +- **Copilot:** Synchronizes servers with `tools: ["*"]` so all tools exposed by + the server are available. Since non-interactive Copilot runs require + `--allow-all-tools`, read-only behavior relies on secfoo's review prompt + instructions rather than an OS-level or CLI sandbox. +- **Codex:** Configured via `~/.codex/config.toml`. secfoo invokes Codex with + `--sandbox read-only`. For remote servers or tools outside the local sandbox, + use read-only credentials or server-side access controls. +- **OpenCode:** Permissions can be restricted via `permission` settings in + `opencode.json` or `OPENCODE_PERMISSION` (e.g. `{"permission": {"edit": "deny"}}`). +- **Principle of least privilege:** For remote MCP servers with authentication + (such as Atlassian Rovo, GitHub, or enterprise APIs), always issue read-only + API tokens or scoped credentials so write operations cannot execute even if + invoked. + ## Pattern memory (`secfoo-memory`) secfoo-memory is a hosted service of curated, generalized vulnerability @@ -990,8 +1024,9 @@ secfoo memory logout Once a key is saved, secfoo registers `secfoo-memory` as a default MCP server. `secfoo mcp list` shows it next to your own servers. `claude` picks -it up on every run. For `gemini` or Cursor (`agent`), run -`secfoo mcp sync --agent ` once. The `api` agent has no tool loop, +it up on every run. For persistent agents (`gemini`, `agent`, `codex`, `copilot`, +`opencode`, `droid`, `devin`), run `secfoo mcp sync --agent ` once (or +`secfoo mcp sync` to sync all installed). The `api` agent has no tool loop, so memory doesn't apply to it. When memory is on, the prompt tells the agent when to use the three tools (`lookup_patterns`, `get_remediation`, `check_false_positive`) and how to phrase a query. diff --git a/docs/agents.md b/docs/agents.md index d48c781..a012beb 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -10,15 +10,16 @@ brackets indicate optional arguments. All CLI processes run in `WORKDIR`. | `--agent` | Setup and command | | --- | --- | -| `claude` | Install command unverified; subscription login is supported. `claude [--model MODEL] -p --output-format json --allowedTools TOOLS --permission-mode default --setting-sources user --strict-mcp-config --no-session-persistence [--mcp-config PATH]` (prompt on stdin). `TOOLS` starts with `Read,Grep,Glob,Bash(git log:*),Bash(git diff:*)` and includes configured MCP servers when present. The tool grant is read-only, not an OS sandbox. | -| `agent` (Cursor) | Install and authentication commands unverified. `agent [--model MODEL] -p PROMPT` | -| `agy` (Antigravity) | Install and authentication commands unverified. `agy --print PROMPT --print-timeout Ns` (`N` is the effective timeout in seconds). Headless mode denies tool calls requiring approval. | -| `gemini` | Install and authentication commands unverified. `gemini [--model MODEL] -p PROMPT --output-format json --skip-trust`. No `--yolo` write auto-approval is passed. | -| `codex` | Install and authentication commands unverified. `codex exec [--model MODEL] --sandbox read-only [-c windows.sandbox="unelevated"] --skip-git-repo-check --ephemeral --color never --cd WORKDIR -` (prompt on stdin; `-c` is Windows-only). | -| `copilot` | The adapter identifies the npm package as `@github/copilot`; install and authentication commands are unverified. `copilot [--model MODEL] --output-format json --allow-all-tools` (prompt on stdin). Tools, including writes, are auto-approved: read-only behavior relies on review instructions, not a sandbox. | -| `droid` | Install command unverified. Set `FACTORY_API_KEY` for noninteractive use. `droid exec [-m MODEL] --output-format json --cwd WORKDIR -- PROMPT`. Droid defaults to read-only; a full authenticated secfoo run was not verified in the adapter. | -| `devin` | The adapter identifies the official Homebrew cask as `devin-cli`; install command unverified. Authenticate beforehand with `devin auth login`; credential reuse for headless runs is unverified. `devin -p PROMPT --respect-workspace-trust false --permission-mode auto`. The combined command and an authenticated end-to-end run are unverified; `auto` is documented by the CLI as approving read-only tools. | -| `api` | No agent binary is invoked. `litellm` and `langgraph` are installed with secfoo; if importing them fails, reinstall secfoo the way you installed it (`pipx reinstall secfoo` or `pip install --force-reinstall secfoo`). Set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GEMINI_API_KEY`. Source files are included in the API prompt. Model selection uses the configured model, then `SECFOO_API_MODEL`, then `openai/gpt-4.1-mini`. | +| `claude` | Install command unverified; subscription login is supported. `claude [--model MODEL] -p --output-format json --allowedTools TOOLS --permission-mode default --setting-sources user --strict-mcp-config --no-session-persistence [--mcp-config PATH]` (prompt on stdin). `TOOLS` starts with `Read,Grep,Glob,Bash(git log:*),Bash(git diff:*)` and includes configured MCP servers when present. MCP servers loaded automatically via `--mcp-config` on every run. The tool grant is read-only, not an OS sandbox. | +| `agent` (Cursor) | Install and authentication commands unverified. `agent [--model MODEL] -p PROMPT`. MCP servers registered via `secfoo mcp sync --agent agent` (`~/.cursor/mcp.json`). | +| `agy` (Antigravity) | Install and authentication commands unverified. `agy --print PROMPT --print-timeout Ns` (`N` is the effective timeout in seconds). Headless mode denies tool calls requiring approval. secfoo does not configure MCP for agy: none is documented for its CLI; not re-verified against a current release. | +| `gemini` | Install and authentication commands unverified. `gemini [--model MODEL] -p PROMPT --output-format json --skip-trust`. No `--yolo` write auto-approval is passed. MCP servers registered via `secfoo mcp sync --agent gemini`. | +| `codex` | Install and authentication commands unverified. `codex exec [--model MODEL] --sandbox read-only [-c windows.sandbox="unelevated"] --skip-git-repo-check --ephemeral --color never --cd WORKDIR -` (prompt on stdin; `-c` is Windows-only). MCP servers merged via `secfoo mcp sync --agent codex` (`~/.codex/config.toml`). | +| `copilot` | The adapter identifies the npm package as `@github/copilot`; install and authentication commands are unverified. `copilot [--model MODEL] --output-format json --allow-all-tools` (prompt on stdin). Tools, including writes, are auto-approved: read-only behavior relies on review instructions, not a sandbox. MCP servers registered via `secfoo mcp sync --agent copilot` (`~/.copilot/mcp-config.json`). | +| `opencode` | Install command unverified. `opencode run --pure --format json --dir WORKDIR [-m MODEL]` (prompt on stdin). Read-only permissions set via `OPENCODE_PERMISSION`. MCP servers registered via `secfoo mcp sync --agent opencode` (`~/.config/opencode/opencode.json`). | +| `droid` | Install command unverified. Set `FACTORY_API_KEY` for noninteractive use. `droid exec [-m MODEL] --output-format json --cwd WORKDIR -- PROMPT`. Droid defaults to read-only; a full authenticated secfoo run was not verified in the adapter. MCP servers registered via `secfoo mcp sync --agent droid` (`~/.factory/mcp.json`). | +| `devin` | The adapter identifies the official Homebrew cask as `devin-cli`; install command unverified. Authenticate beforehand with `devin auth login`; credential reuse for headless runs is unverified. `devin -p PROMPT --respect-workspace-trust false --permission-mode auto`. The combined command and an authenticated end-to-end run are unverified; `auto` is documented by the CLI as approving read-only tools. MCP servers registered via `secfoo mcp sync --agent devin` (`~/.config/devin/mcp_config.json` or `%APPDATA%\devin\mcp_config.json`). | +| `api` | No agent binary is invoked. `litellm` and `langgraph` are installed with secfoo; if importing them fails, reinstall secfoo the way you installed it (`pipx reinstall secfoo` or `pip install --force-reinstall secfoo`). Set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GEMINI_API_KEY`. Source files are included in the API prompt. Model selection uses the configured model, then `SECFOO_API_MODEL`, then `openai/gpt-4.1-mini`. No MCP support; direct model API without tool loop. | `agy` and `devin` do not support adapter model selection; secfoo warns and ignores a requested model. Other CLI model flags are shown above. diff --git a/pyproject.toml b/pyproject.toml index 6045df8..836a665 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,6 +64,7 @@ dependencies = [ "python-pptx>=1.0.2", "langgraph>=1.2.21", "litellm>=1.109.1", + "tomlkit>=0.13.0", ] [project.optional-dependencies] diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index b9b4011..f58ae15 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -982,12 +982,15 @@ def agents() -> None: table.add_column("Agent ID") table.add_column("Binary") table.add_column("Available") + table.add_column("MCP") for agent_id in ADAPTERS: adapter = get_adapter(agent_id) available = adapter.is_available() style = "green" if available else "red" - table.add_row(agent_id, adapter.binary, f"[{style}]{'yes' if available else 'no'}[/]") + mcp_info = mcp_module.CANONICAL_MCP_SUPPORT.get(agent_id) + mcp_val = mcp_info.mechanism if mcp_info else "none" + table.add_row(agent_id, adapter.binary, f"[{style}]{'yes' if available else 'no'}[/]", mcp_val) console.print(table) @@ -2646,12 +2649,15 @@ def mcp_list() -> None: @mcp_app.command(name="sync") def mcp_sync( - agent: AgentId = typer.Option(..., "--agent", "-a", help="Which agent's MCP config to update."), + agent: Annotated[ + AgentId | None, + typer.Option("--agent", "-a", help="Which agent's MCP config to update."), + ] = None, ) -> None: - """Register configured MCP servers persistently into gemini's or Cursor's own - config. claude doesn't need this -- it picks up ~/.secfoo/config.toml - automatically on every run. agy isn't supported (its CLI has no MCP - configuration mechanism yet). + """Register configured MCP servers persistently into an agent's own config. + claude doesn't need this -- it picks up ~/.secfoo/config.toml + automatically on every run. When --agent is omitted, syncs all available + agents on PATH. """ try: cfg = load_config() @@ -2664,22 +2670,50 @@ def mcp_sync( console.print(f"No MCP servers configured in {CONFIG_PATH} -- nothing to sync.") return - if agent.value == "claude": - console.print("[yellow]claude doesn't need syncing[/] -- it loads MCP servers automatically on every run.") + if agent is not None: + if agent.value == "claude": + console.print("[yellow]claude doesn't need syncing[/] -- it loads MCP servers automatically on every run.") + return + + try: + results = mcp_module.sync(agent.value, servers) + except ValueError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=1) from None + + any_failed = False + for result in results: + style = "green" if result.ok else "red" + console.print(f" [{style}]{'ok' if result.ok else 'failed'}[/] {result.server_name}: {result.message}") + if not result.ok: + any_failed = True + if any_failed: + raise typer.Exit(code=1) return - try: - results = mcp_module.sync(agent.value, servers) - except ValueError as exc: - err_console.print(f"[red]Error:[/] {exc}") - raise typer.Exit(code=1) from None + installed_targets = [ + aid for aid in sorted(mcp_module.SYNC_SUPPORTED_AGENTS) + if get_adapter(aid).is_available() + ] + if not installed_targets: + console.print("No sync-supported agent CLIs installed on PATH -- nothing to sync.") + return any_failed = False - for result in results: - style = "green" if result.ok else "red" - console.print(f" [{style}]{'ok' if result.ok else 'failed'}[/] {result.server_name}: {result.message}") - if not result.ok: + for aid in installed_targets: + console.print(f"[bold]{aid}:[/]") + try: + results = mcp_module.sync(aid, servers) + except ValueError as exc: + err_console.print(f" [red]Error:[/] {exc}") any_failed = True + continue + for result in results: + style = "green" if result.ok else "red" + console.print(f" [{style}]{'ok' if result.ok else 'failed'}[/] {result.server_name}: {result.message}") + if not result.ok: + any_failed = True + if any_failed: raise typer.Exit(code=1) diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index 36b4f25..23f4526 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -1,6 +1,8 @@ -"""Bridges secfoo's portable MCP server config (settings.py) to each agent -CLI's own mechanism for it. These differ a lot by CLI (verified directly -against each `--help` output, Aug 2026): +r"""Bridges secfoo's portable MCP server config (settings.py) to each agent +CLI's own mechanism for it. These differ a lot by CLI. The claude, gemini and +agent entries were verified directly against each `--help` output (Aug 2026); +the codex, copilot, opencode, droid, devin and agy entries describe what +secfoo's adapters currently do and have not been verified against those CLIs: - claude: supports `--mcp-config `, which loads servers scoped to just that one invocation -- no global state touched. Handled automatically by @@ -11,26 +13,77 @@ - agent (Cursor): has no `mcp add` subcommand at all -- servers are defined by editing `~/.cursor/mcp.json` directly, then approved via `agent mcp enable `. `secfoo mcp sync` does that merge. -- agy (Antigravity): no MCP subcommand or flag exposed by the CLI at all as - of this writing. Not supported; `secfoo mcp sync --agent agy` refuses with - a clear error rather than silently doing nothing. +- codex: reads `~/.codex/config.toml` (`[mcp_servers.]`). secfoo does not + use per-run `-c` overrides: command, URL and header values would appear in the + process table (`ps`). `secfoo mcp sync` instead merges them into config.toml + (comments and formatting preserved) with 0600 permissions. Values are still + stored in plaintext at rest. +- copilot: reads `~/.copilot/mcp-config.json` (`mcpServers`). secfoo's copilot + adapter currently passes no MCP flag, so servers are registered with + `secfoo mcp sync`. +- opencode: reads `~/.config/opencode/opencode.json` (`mcp` table). secfoo's + opencode adapter currently passes no MCP configuration per run, so servers are + registered with `secfoo mcp sync`. +- droid: reads `~/.factory/mcp.json` (`mcpServers`). secfoo's droid adapter + currently passes no MCP flag; servers are registered with `secfoo mcp sync`. +- devin: reads `%APPDATA%\devin\mcp_config.json` (Windows) or + `~/.config/devin/mcp_config.json` (Unix). secfoo's devin adapter currently + passes no MCP flag; servers are registered with `secfoo mcp sync`. +- agy (Antigravity): secfoo does not configure MCP for agy. No MCP mechanism is + documented for its CLI, and this has not been re-verified against a current + release. `secfoo mcp sync --agent agy` refuses with a clean error. """ from __future__ import annotations +import contextlib import json +import logging +import os import re import subprocess +import time +from collections.abc import Callable from dataclasses import dataclass from pathlib import Path -from secfoo.config import STORE_DIR, write_private_text +import tomlkit +from tomlkit.exceptions import TOMLKitError + +from secfoo.config import STORE_DIR from secfoo.settings import MCPServerConfig +logger = logging.getLogger(__name__) + CLAUDE_MCP_CONFIG_PATH = STORE_DIR / "claude-mcp-config.json" CURSOR_MCP_CONFIG_PATH = Path.home() / ".cursor" / "mcp.json" +CODEX_CONFIG_PATH = Path.home() / ".codex" / "config.toml" +COPILOT_MCP_CONFIG_PATH = Path.home() / ".copilot" / "mcp-config.json" +OPENCODE_MCP_CONFIG_PATH = Path.home() / ".config" / "opencode" / "opencode.json" +DROID_MCP_CONFIG_PATH = Path.home() / ".factory" / "mcp.json" + + +def _default_devin_path() -> Path: + if os.name == "nt" and "APPDATA" in os.environ: + return Path(os.environ["APPDATA"]) / "devin" / "mcp_config.json" + return Path.home() / ".config" / "devin" / "mcp_config.json" + + +DEVIN_MCP_CONFIG_PATH = _default_devin_path() -SYNC_SUPPORTED_AGENTS = {"gemini", "agent"} +SYNC_SUPPORTED_AGENTS = { + "gemini", + "agent", + "codex", + "copilot", + "opencode", + "droid", + "devin", +} + + +class MCPSyncError(ValueError): + """Raised when an MCP config cannot be synchronized.""" @dataclass @@ -40,6 +93,107 @@ class SyncResult: message: str +@dataclass(frozen=True) +class AgentMCPSupport: + agent_id: str + mechanism: str # "per-run" | "sync" | "none" + guidance: str + + +CANONICAL_MCP_SUPPORT: dict[str, AgentMCPSupport] = { + "claude": AgentMCPSupport( + agent_id="claude", + mechanism="per-run", + guidance=( + "Automatic on every `secfoo run` (`--mcp-config`, scoped to that invocation only — " + "your global Claude config is never touched). These are the only MCP servers loaded " + "during a scan (`--strict-mcp-config`): servers from your global Claude config or " + "from the target's `.mcp.json` are not started" + ), + ), + "agent": AgentMCPSupport( + agent_id="agent", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent agent` once to register persistently in `~/.cursor/mcp.json`", + ), + "gemini": AgentMCPSupport( + agent_id="gemini", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent gemini` once to register persistently via `gemini mcp add`", + ), + "codex": AgentMCPSupport( + agent_id="codex", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent codex` once to merge persistently into `~/.codex/config.toml` without clobbering other settings", + ), + "copilot": AgentMCPSupport( + agent_id="copilot", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent copilot` once to register persistently in `~/.copilot/mcp-config.json`", + ), + "opencode": AgentMCPSupport( + agent_id="opencode", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent opencode` once to register persistently in `~/.config/opencode/opencode.json`", + ), + "droid": AgentMCPSupport( + agent_id="droid", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent droid` once to register persistently in `~/.factory/mcp.json`", + ), + "devin": AgentMCPSupport( + agent_id="devin", + mechanism="sync", + guidance=( + "Run `secfoo mcp sync --agent devin` once to register persistently in " + "`~/.config/devin/mcp_config.json` (%APPDATA%\\devin\\mcp_config.json on Windows)" + ), + ), + "agy": AgentMCPSupport( + agent_id="agy", + mechanism="none", + guidance="Not supported by secfoo: no MCP configuration mechanism is documented for the agy CLI, and this has not been re-verified against a current release", + ), + "api": AgentMCPSupport( + agent_id="api", + mechanism="none", + guidance="Not applicable — the API adapter calls model endpoints directly and has no tool loop", + ), +} + + +def format_mcp_support_text() -> str: + lines = [] + for support in CANONICAL_MCP_SUPPORT.values(): + lines.append(f" {support.agent_id} ({support.mechanism}): {support.guidance}") + return "\n".join(lines) + + +def _write_private_file(path: Path, content: str) -> None: + """Atomically write a file with 0600 permissions inside path.parent.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = path.parent / f".{path.name}.{os.getpid()}.{time.time_ns()}.tmp" + fd = os.open(tmp_path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600) + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle: + fd = -1 + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + try: + os.chmod(tmp_path, 0o600) + except OSError as exc: + logger.warning("Failed to chmod 0600 on %s: %s", tmp_path, exc) + os.replace(tmp_path, path) + finally: + if fd != -1: + with contextlib.suppress(OSError): + os.close(fd) + if tmp_path.exists(): + with contextlib.suppress(OSError): + tmp_path.unlink() + + def effective_servers(configured: list[MCPServerConfig]) -> list[MCPServerConfig]: """The user's own [[mcp_servers]] plus the default secfoo-memory server when memory is on (memory.memory_server). A user-defined server @@ -68,6 +222,55 @@ def _server_to_standard_shape(server: MCPServerConfig) -> dict: return entry +def _sync_json_mcp_config( + path: Path, + root_key: str, + servers: list[MCPServerConfig], + shape_fn: Callable[[MCPServerConfig], dict], + *, + post_add_hook: Callable[[list[str], list[SyncResult]], None] | None = None, +) -> list[SyncResult]: + """Generic format-preserving JSON sync helper for agents using JSON config.""" + data: dict = {} + if path.exists(): + try: + raw = path.read_bytes().decode("utf-8") + parsed = json.loads(raw) + except UnicodeDecodeError as exc: + return [SyncResult("*", False, f"{path} is not valid UTF-8: {exc}")] + except (json.JSONDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{path} is not valid JSON: {exc}")] + if not isinstance(parsed, dict): + raise MCPSyncError( + f"{path} does not contain a JSON object (got {type(parsed).__name__})" + ) + data = parsed + + existing_servers = data.get(root_key) + if existing_servers is None: + existing_servers = {} + data[root_key] = existing_servers + elif not isinstance(existing_servers, dict): + raise MCPSyncError(f"'{root_key}' in {path} is not a JSON object") + + results: list[SyncResult] = [] + newly_added: list[str] = [] + for server in servers: + if server.name in existing_servers: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + existing_servers[server.name] = shape_fn(server) + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {path}")) + + if newly_added: + _write_private_file(path, json.dumps(data, indent=2) + "\n") + if post_add_hook is not None: + post_add_hook(newly_added, results) + + return results + + # ---------- claude: ephemeral, per-invocation ---------- @@ -80,10 +283,7 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: if not servers: return None payload = {"mcpServers": {s.name: _server_to_standard_shape(s) for s in servers}} - STORE_DIR.mkdir(parents=True, exist_ok=True) - # Header values (the secfoo-memory bearer key, or any user server's - # auth header) are secrets -- same 0600 as cloud.toml/memory.toml. - write_private_text(CLAUDE_MCP_CONFIG_PATH, json.dumps(payload, indent=2)) + _write_private_file(CLAUDE_MCP_CONFIG_PATH, json.dumps(payload, indent=2) + "\n") return CLAUDE_MCP_CONFIG_PATH @@ -93,7 +293,18 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: def _gemini_existing_names() -> set[str]: - proc = subprocess.run(["gemini", "mcp", "list"], capture_output=True, text=True, timeout=30) + try: + proc = subprocess.run( + ["gemini", "mcp", "list"], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + except FileNotFoundError: + raise MCPSyncError( + "Gemini CLI ('gemini') is not installed or not on PATH" + ) from None names = set() for line in proc.stdout.splitlines(): match = _GEMINI_LIST_NAME_RE.match(line.strip()) @@ -123,7 +334,18 @@ def sync_gemini(servers: list[MCPServerConfig]) -> list[SyncResult]: 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) + try: + proc = subprocess.run( + _gemini_add_command(server), + capture_output=True, + text=True, + timeout=30, + check=False, + ) + except FileNotFoundError: + raise MCPSyncError( + "Gemini CLI ('gemini') is not installed or not on PATH" + ) from None if proc.returncode == 0: results.append(SyncResult(server.name, True, "added")) else: @@ -134,45 +356,231 @@ def sync_gemini(servers: list[MCPServerConfig]) -> list[SyncResult]: # ---------- agent (Cursor): persistent, via ~/.cursor/mcp.json merge ---------- -def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: - CURSOR_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - existing: dict = {} - if CURSOR_MCP_CONFIG_PATH.exists(): +def _cursor_post_add(newly_added: list[str], results: list[SyncResult]) -> None: + for name in newly_added: try: - existing = json.loads(CURSOR_MCP_CONFIG_PATH.read_text(encoding="utf-8")).get("mcpServers", {}) - except json.JSONDecodeError as exc: - return [SyncResult("*", False, f"{CURSOR_MCP_CONFIG_PATH} is not valid JSON: {exc}")] + proc = subprocess.run( + ["agent", "mcp", "enable", name], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + if proc.returncode != 0: + for result in results: + if result.server_name == name: + result.ok = False + result.message += f" (enable failed: {proc.stderr.strip()})" + except FileNotFoundError: + for result in results: + if result.server_name == name: + result.ok = False + result.message += " (written, but agent binary not found on PATH to enable)" + except (OSError, subprocess.TimeoutExpired) as exc: + for result in results: + if result.server_name == name: + result.ok = False + result.message += f" (written, but agent mcp enable could not run: {exc})" - results = [] - newly_added: list[str] = [] + +def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: + return _sync_json_mcp_config( + CURSOR_MCP_CONFIG_PATH, + "mcpServers", + servers, + _server_to_standard_shape, + post_add_hook=_cursor_post_add, + ) + + +# ---------- codex: persistent, via ~/.codex/config.toml merge ---------- + + +def sync_codex(servers: list[MCPServerConfig]) -> list[SyncResult]: + if CODEX_CONFIG_PATH.exists(): + try: + raw = CODEX_CONFIG_PATH.read_bytes().decode("utf-8") + doc = tomlkit.parse(raw) + except UnicodeDecodeError as exc: + return [ + SyncResult("*", False, f"{CODEX_CONFIG_PATH} is not valid UTF-8: {exc}") + ] + except (TOMLKitError, OSError) as exc: + return [ + SyncResult("*", False, f"{CODEX_CONFIG_PATH} is not valid TOML: {exc}") + ] + if not isinstance(doc, dict): + raise MCPSyncError(f"{CODEX_CONFIG_PATH} does not contain a TOML table") + else: + doc = tomlkit.document() + + if "mcp_servers" not in doc: + doc["mcp_servers"] = tomlkit.table(is_super_table=True) + elif isinstance(doc["mcp_servers"], tomlkit.items.InlineTable): + super_table = tomlkit.table(is_super_table=True) + for k, v in doc["mcp_servers"].value.items(): + super_table[k] = v + doc["mcp_servers"] = super_table + + mcp_servers_table = doc["mcp_servers"] + if not isinstance(mcp_servers_table, dict): + raise MCPSyncError(f"'mcp_servers' in {CODEX_CONFIG_PATH} is not a TOML table") + + results: list[SyncResult] = [] + newly_added = False for server in servers: - if server.name in existing: + if server.name in mcp_servers_table: results.append(SyncResult(server.name, True, "already configured, skipped")) continue - existing[server.name] = _server_to_standard_shape(server) - newly_added.append(server.name) - results.append(SyncResult(server.name, True, f"added to {CURSOR_MCP_CONFIG_PATH}")) + + if server.command: + server_tbl = tomlkit.table() + server_tbl["command"] = server.command + server_tbl["args"] = list(server.args) + if server.env: + env_tbl = tomlkit.table() + for k, v in server.env.items(): + env_tbl[k] = v + server_tbl["env"] = env_tbl + mcp_servers_table[server.name] = server_tbl + newly_added = True + results.append( + SyncResult(server.name, True, f"added to {CODEX_CONFIG_PATH}") + ) + elif server.url: + if server.transport == "sse": + results.append( + SyncResult( + server.name, + False, + "Codex does not support SSE transport for remote MCP servers (only streamable-HTTP is supported)", + ) + ) + continue + server_tbl = tomlkit.table() + server_tbl["url"] = server.url + if server.headers: + headers_tbl = tomlkit.table() + for k, v in server.headers.items(): + headers_tbl[k] = v + server_tbl["http_headers"] = headers_tbl + mcp_servers_table[server.name] = server_tbl + newly_added = True + results.append( + SyncResult(server.name, True, f"added to {CODEX_CONFIG_PATH}") + ) + else: + results.append( + SyncResult( + server.name, False, "server must define either 'command' or 'url'" + ) + ) if newly_added: - CURSOR_MCP_CONFIG_PATH.write_text(json.dumps({"mcpServers": existing}, indent=2), encoding="utf-8") - for name in newly_added: - proc = subprocess.run(["agent", "mcp", "enable", name], capture_output=True, text=True, timeout=30) - if proc.returncode != 0: - for result in results: - if result.server_name == name: - result.ok = False - result.message += f" (enable failed: {proc.stderr.strip()})" + _write_private_file(CODEX_CONFIG_PATH, tomlkit.dumps(doc)) + return results +# ---------- copilot: persistent, via ~/.copilot/mcp-config.json merge ---------- + + +def _server_to_copilot_shape(server: MCPServerConfig) -> dict: + if server.command: + entry: dict = { + "type": "local", + "command": server.command, + "args": list(server.args), + "tools": ["*"], + } + if server.env: + entry["env"] = dict(server.env) + return entry + entry = { + "type": "sse" if server.transport == "sse" else "http", + "url": server.url, + "tools": ["*"], + } + if server.headers: + entry["headers"] = dict(server.headers) + return entry + + +def sync_copilot(servers: list[MCPServerConfig]) -> list[SyncResult]: + return _sync_json_mcp_config( + COPILOT_MCP_CONFIG_PATH, + "mcpServers", + servers, + _server_to_copilot_shape, + ) + + +# ---------- opencode: persistent, via ~/.config/opencode/opencode.json merge ---------- + + +def _server_to_opencode_shape(server: MCPServerConfig) -> dict: + if server.command: + cmd_list = [server.command, *server.args] + entry: dict = {"type": "local", "command": cmd_list, "enabled": True} + if server.env: + entry["environment"] = dict(server.env) + return entry + entry = {"type": "remote", "url": server.url, "enabled": True} + if server.headers: + entry["headers"] = dict(server.headers) + return entry + + +def sync_opencode(servers: list[MCPServerConfig]) -> list[SyncResult]: + return _sync_json_mcp_config( + OPENCODE_MCP_CONFIG_PATH, + "mcp", + servers, + _server_to_opencode_shape, + ) + + +# ---------- droid: persistent, via ~/.factory/mcp.json merge ---------- + + +def sync_droid(servers: list[MCPServerConfig]) -> list[SyncResult]: + return _sync_json_mcp_config( + DROID_MCP_CONFIG_PATH, + "mcpServers", + servers, + _server_to_standard_shape, + ) + + +# ---------- devin: persistent, via mcp_config.json merge ---------- + + +def sync_devin(servers: list[MCPServerConfig]) -> list[SyncResult]: + return _sync_json_mcp_config( + DEVIN_MCP_CONFIG_PATH, + "mcpServers", + servers, + _server_to_standard_shape, + ) + + def sync(agent_id: str, servers: list[MCPServerConfig]) -> list[SyncResult]: if agent_id == "gemini": return sync_gemini(servers) if agent_id == "agent": return sync_cursor(servers) + if agent_id == "codex": + return sync_codex(servers) + if agent_id == "copilot": + return sync_copilot(servers) + if agent_id == "opencode": + return sync_opencode(servers) + if agent_id == "droid": + return sync_droid(servers) + if agent_id == "devin": + return sync_devin(servers) raise ValueError( - f"secfoo mcp sync isn't supported for {agent_id!r}. " - f"claude uses --mcp-config automatically on every run (no sync needed); " - f"agy doesn't expose any MCP configuration mechanism via its CLI yet; " - f"codex isn't wired up for it yet (it reads ~/.codex/config.toml directly)." + f"secfoo mcp sync isn't supported for {agent_id!r}.\n\n" + f"Agent MCP support:\n\n" + f"{format_mcp_support_text()}" ) diff --git a/tests/test_cli.py b/tests/test_cli.py index c065671..88180c6 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import pytest from typer.testing import CliRunner @@ -609,16 +610,102 @@ def test_mcp_sync_unsupported_agent_exits_nonzero(monkeypatch): ) result = runner.invoke(app, ["mcp", "sync", "--agent", "agy"]) assert result.exit_code == 1 + assert "Agent MCP support:" in result.output + assert "REFERENCE.md" not in result.output + assert "claude" in result.output + assert "per-run" in result.output -def test_mcp_sync_codex_is_reported_unsupported(monkeypatch): +def test_mcp_sync_codex_is_supported(monkeypatch): servers = [MCPServerConfig(name="s", command="npx")] monkeypatch.setattr( "secfoo.cli.load_config", lambda: SecfooConfig(defaults=Defaults(), mcp_servers=servers) ) + monkeypatch.setattr( + mcp_module, "sync", lambda agent_id, servers: [mcp_module.SyncResult("s", True, "added")] + ) result = runner.invoke(app, ["mcp", "sync", "--agent", "codex"]) - assert result.exit_code == 1 - assert "codex" in result.output + assert result.exit_code == 0 + assert "s: added" in result.stdout + + +def test_mcp_sync_omitted_agent_syncs_only_available_clis(tmp_path, monkeypatch): + servers = [MCPServerConfig(name="s", command="npx")] + monkeypatch.setattr( + "secfoo.cli.load_config", lambda: SecfooConfig(defaults=Defaults(), mcp_servers=servers) + ) + fake_home = tmp_path / "home" + fake_home.mkdir() + + monkeypatch.setattr(mcp_module, "CURSOR_MCP_CONFIG_PATH", fake_home / ".cursor" / "mcp.json") + monkeypatch.setattr(mcp_module, "CODEX_CONFIG_PATH", fake_home / ".codex" / "config.toml") + monkeypatch.setattr(mcp_module, "COPILOT_MCP_CONFIG_PATH", fake_home / ".copilot" / "mcp-config.json") + monkeypatch.setattr(mcp_module, "DROID_MCP_CONFIG_PATH", fake_home / ".factory" / "mcp.json") + monkeypatch.setattr(mcp_module, "OPENCODE_MCP_CONFIG_PATH", fake_home / ".config" / "opencode" / "opencode.json") + monkeypatch.setattr(mcp_module, "DEVIN_MCP_CONFIG_PATH", fake_home / ".config" / "devin" / "mcp_config.json") + + class FakeAdapter: + def __init__(self, name: str): + self.name = name + + def is_available(self) -> bool: + return self.name == "codex" + + monkeypatch.setattr("secfoo.cli.get_adapter", lambda aid: FakeAdapter(aid)) + + result = runner.invoke(app, ["mcp", "sync"]) + assert result.exit_code == 0 + codex_conf = fake_home / ".codex" / "config.toml" + assert codex_conf.exists() + if os.name != "nt": + assert oct(codex_conf.stat().st_mode & 0o777) == "0o600" + assert not (fake_home / ".cursor").exists() + assert not (fake_home / ".copilot").exists() + assert not (fake_home / ".factory").exists() + assert not (fake_home / ".config").exists() + + +def test_mcp_sync_omitted_agent_no_installed_clis(tmp_path, monkeypatch): + servers = [MCPServerConfig(name="s", command="npx")] + monkeypatch.setattr( + "secfoo.cli.load_config", lambda: SecfooConfig(defaults=Defaults(), mcp_servers=servers) + ) + fake_home = tmp_path / "home" + fake_home.mkdir() + + monkeypatch.setattr(mcp_module, "CURSOR_MCP_CONFIG_PATH", fake_home / ".cursor" / "mcp.json") + monkeypatch.setattr(mcp_module, "CODEX_CONFIG_PATH", fake_home / ".codex" / "config.toml") + monkeypatch.setattr(mcp_module, "COPILOT_MCP_CONFIG_PATH", fake_home / ".copilot" / "mcp-config.json") + monkeypatch.setattr(mcp_module, "DROID_MCP_CONFIG_PATH", fake_home / ".factory" / "mcp.json") + monkeypatch.setattr(mcp_module, "OPENCODE_MCP_CONFIG_PATH", fake_home / ".config" / "opencode" / "opencode.json") + monkeypatch.setattr(mcp_module, "DEVIN_MCP_CONFIG_PATH", fake_home / ".config" / "devin" / "mcp_config.json") + + class FakeAdapter: + def __init__(self, name: str): + self.name = name + + def is_available(self) -> bool: + return False + + monkeypatch.setattr("secfoo.cli.get_adapter", lambda aid: FakeAdapter(aid)) + + result = runner.invoke(app, ["mcp", "sync"]) + assert result.exit_code == 0 + assert "No sync-supported agent CLIs installed on PATH -- nothing to sync." in result.stdout + assert not (fake_home / ".cursor").exists() + assert not (fake_home / ".codex").exists() + assert not (fake_home / ".copilot").exists() + assert not (fake_home / ".factory").exists() + assert not (fake_home / ".config").exists() + + +def test_agents_displays_mcp_column(): + result = runner.invoke(app, ["agents"]) + assert result.exit_code == 0 + assert "MCP" in result.stdout + assert "per-run" in result.stdout + assert "sync" in result.stdout + assert "none" in result.stdout @pytest.mark.parametrize("override,expected", [(None, "config-model"), ("override-model", "override-model")]) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 6ec8ccc..e3ed754 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -1,9 +1,14 @@ from __future__ import annotations import json +import logging +import os +import re import subprocess +from pathlib import Path import pytest +import tomlkit from secfoo import mcp from secfoo.settings import MCPServerConfig @@ -21,6 +26,34 @@ ) +# ---------- storage primitives ---------- + + +def test_write_private_file_creates_file_with_0600(tmp_path): + target = tmp_path / "private.txt" + mcp._write_private_file(target, "secret content") + assert target.exists() + assert target.read_text(encoding="utf-8") == "secret content" + if os.name != "nt": + mode = target.stat().st_mode & 0o777 + assert mode == 0o600 + + +def test_write_private_file_logs_warning_on_chmod_failure( + tmp_path, monkeypatch, caplog +): + target = tmp_path / "private_fail.txt" + + def fail_chmod(path, mode): + raise OSError("chmod failed") + + monkeypatch.setattr(os, "chmod", fail_chmod) + with caplog.at_level(logging.WARNING): + mcp._write_private_file(target, "test") + assert target.exists() + assert any("Failed to chmod 0600" in record.message for record in caplog.records) + + # ---------- claude: ephemeral config ---------- @@ -37,6 +70,8 @@ def test_write_claude_mcp_config_stdio_shape(tmp_path, monkeypatch): result_path = mcp.write_claude_mcp_config([STDIO_SERVER]) assert result_path == config_path + if os.name != "nt": + assert config_path.stat().st_mode & 0o777 == 0o600 payload = json.loads(config_path.read_text()) assert payload == { "mcpServers": { @@ -114,13 +149,54 @@ def fake_run(cmd, **kwargs): assert "boom" in results[0].message +def test_sync_gemini_raises_clean_error_when_cli_missing(monkeypatch): + def fake_run(*args, **kwargs): + raise FileNotFoundError("gemini not found") + + monkeypatch.setattr(mcp.subprocess, "run", fake_run) + with pytest.raises(mcp.MCPSyncError, match="Gemini CLI .* is not installed"): + mcp.sync_gemini([STDIO_SERVER]) + + # ---------- agent (Cursor): persistent via ~/.cursor/mcp.json ---------- +def test_sync_json_mcp_config_rejects_non_dict_json(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + cursor_path.write_text("[]", encoding="utf-8") + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + with pytest.raises(mcp.MCPSyncError, match="does not contain a JSON object"): + mcp.sync_cursor([STDIO_SERVER]) + + +def test_sync_json_mcp_config_rejects_null_json(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + cursor_path.write_text("null", encoding="utf-8") + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + with pytest.raises(mcp.MCPSyncError, match="does not contain a JSON object"): + mcp.sync_cursor([STDIO_SERVER]) + + +def test_sync_json_mcp_config_handles_non_utf8_file(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + cursor_path.write_bytes(b"\xff\xfe\x00\x00") + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + results = mcp.sync_cursor([STDIO_SERVER]) + assert results[0].ok is False + assert "is not valid UTF-8" in results[0].message + + def test_sync_cursor_creates_new_config_file(tmp_path, monkeypatch): cursor_path = tmp_path / "mcp.json" monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) - monkeypatch.setattr(mcp.subprocess, "run", lambda cmd, **kw: subprocess.CompletedProcess(cmd, 0, "", "")) + monkeypatch.setattr( + mcp.subprocess, + "run", + lambda cmd, **kw: subprocess.CompletedProcess(cmd, 0, "", ""), + ) results = mcp.sync_cursor([STDIO_SERVER]) assert results[0].ok is True @@ -140,6 +216,29 @@ def test_sync_cursor_preserves_existing_unrelated_entries(tmp_path, monkeypatch) assert "Atlassian-Rovo-MCP" in payload["mcpServers"] +def test_sync_cursor_preserves_disabled_server(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + initial_content = { + "mcpServers": { + "Atlassian-Rovo-MCP": { + "command": "original-command", + "disabled": True, + } + } + } + cursor_path.write_text(json.dumps(initial_content), encoding="utf-8") + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + results = mcp.sync_cursor([STDIO_SERVER]) + assert results == [ + mcp.SyncResult("Atlassian-Rovo-MCP", True, "already configured, skipped") + ] + + saved = json.loads(cursor_path.read_text(encoding="utf-8")) + assert saved["mcpServers"]["Atlassian-Rovo-MCP"]["disabled"] is True + assert saved["mcpServers"]["Atlassian-Rovo-MCP"]["command"] == "original-command" + + def test_sync_cursor_skips_already_configured(tmp_path, monkeypatch): cursor_path = tmp_path / "mcp.json" cursor_path.write_text(json.dumps({"mcpServers": {"Atlassian-Rovo-MCP": {"command": "npx"}}})) @@ -163,18 +262,474 @@ def test_sync_cursor_reports_enable_failure(tmp_path, monkeypatch): assert "denied" in results[0].message +def test_sync_cursor_reports_binary_missing_on_enable(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + def fake_run(*args, **kwargs): + raise FileNotFoundError("agent not found") + + monkeypatch.setattr(mcp.subprocess, "run", fake_run) + results = mcp.sync_cursor([STDIO_SERVER]) + assert results[0].ok is False + assert cursor_path.exists() + assert "written, but agent binary not found on PATH to enable" in results[0].message + + +def test_sync_cursor_reports_command_error_on_enable(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + def fake_run(*args, **kwargs): + raise OSError("permission denied executing agent") + + monkeypatch.setattr(mcp.subprocess, "run", fake_run) + results = mcp.sync_cursor([STDIO_SERVER]) + assert results[0].ok is False + assert cursor_path.exists() + assert ( + "written, but agent mcp enable could not run: permission denied executing agent" + in results[0].message + ) + + +def test_sync_cursor_reports_timeout_on_enable(tmp_path, monkeypatch): + cursor_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) + + def fake_run(*args, **kwargs): + raise subprocess.TimeoutExpired( + cmd=["agent", "mcp", "enable", "Atlassian-Rovo-MCP"], timeout=30 + ) + + monkeypatch.setattr(mcp.subprocess, "run", fake_run) + results = mcp.sync_cursor([STDIO_SERVER]) + assert results[0].ok is False + assert cursor_path.exists() + assert ( + "written, but agent mcp enable could not run: Command '['agent', 'mcp', 'enable', 'Atlassian-Rovo-MCP']' timed out after 30 seconds" + in results[0].message + ) + + +# ---------- codex: persistent via ~/.codex/config.toml ---------- + + +def test_sync_codex_creates_fresh_file(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + assert codex_path.exists() + if os.name != "nt": + assert codex_path.stat().st_mode & 0o777 == 0o600 + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + assert doc["mcp_servers"]["Atlassian-Rovo-MCP"]["command"] == "npx" + + +def test_sync_codex_preserves_formatting_comments_and_empty_tables( + tmp_path, monkeypatch +): + codex_path = tmp_path / ".codex" / "config.toml" + initial = """# Global comment +created_at = 2026-11-20T20:00:00Z + +[features] + +[mcp_servers.user_server] +command = "my-tool" +""" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_text(initial, encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + text = codex_path.read_text(encoding="utf-8") + assert "# Global comment" in text + assert "created_at = 2026-11-20T20:00:00Z" in text + assert "[features]" in text + assert "user_server" in text + assert "Atlassian-Rovo-MCP" in text + + +def test_sync_codex_remote_server_mapping(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + remote = MCPServerConfig( + name="remote-http", + url="https://api.example.com/mcp", + transport="http", + headers={"Authorization": "Bearer token123"}, + ) + results = mcp.sync_codex([remote]) + assert results[0].ok is True + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + server_tbl = doc["mcp_servers"]["remote-http"] + assert server_tbl["url"] == "https://api.example.com/mcp" + assert server_tbl["http_headers"]["Authorization"] == "Bearer token123" + assert "transport" not in server_tbl + + +def test_sync_codex_skips_sse_remote_server(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + sse_server = MCPServerConfig( + name="remote-sse", + url="https://api.example.com/sse", + transport="sse", + ) + results = mcp.sync_codex([sse_server]) + assert results[0].ok is False + assert "SSE" in results[0].message + assert not codex_path.exists() + + +def test_sync_codex_idempotent(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + mcp.sync_codex([STDIO_SERVER]) + results2 = mcp.sync_codex([STDIO_SERVER]) + assert results2 == [ + mcp.SyncResult("Atlassian-Rovo-MCP", True, "already configured, skipped") + ] + + +def test_sync_codex_handles_invalid_toml(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_text("invalid = [toml", encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is False + assert "is not valid TOML" in results[0].message + + +def test_sync_codex_rejects_non_table_mcp_servers(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_text("mcp_servers = 5\n", encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + with pytest.raises(mcp.MCPSyncError, match="'mcp_servers' .* is not a TOML table"): + mcp.sync_codex([STDIO_SERVER]) + + +def test_sync_codex_handles_non_utf8_file(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_bytes(b"\xff\xfe\x00\x00") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is False + assert "is not valid UTF-8" in results[0].message + + +def test_sync_codex_converts_inline_mcp_servers_table(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_text("mcp_servers = {}\n", encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + assert doc["mcp_servers"]["Atlassian-Rovo-MCP"]["command"] == "npx" + + +def test_sync_codex_preserves_crlf_line_endings(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_bytes(b"# c\r\n[features]\r\n\r\n") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + assert codex_path.read_bytes().startswith(b"# c\r\n[features]\r\n") + + +def test_sync_codex_converts_non_empty_inline_table(tmp_path, monkeypatch): + codex_path = tmp_path / ".codex" / "config.toml" + codex_path.parent.mkdir(parents=True, exist_ok=True) + codex_path.write_text('mcp_servers = { a = { command = "x" } }\n', encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + server_b = MCPServerConfig(name="b", command="y") + results = mcp.sync_codex([server_b]) + assert results[0].ok is True + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + assert doc["mcp_servers"]["a"]["command"] == "x" + assert doc["mcp_servers"]["b"]["command"] == "y" + + # ---------- dispatch ---------- def test_sync_dispatches_by_agent_id(monkeypatch): monkeypatch.setattr(mcp, "sync_gemini", lambda servers: "gemini-result") monkeypatch.setattr(mcp, "sync_cursor", lambda servers: "cursor-result") + monkeypatch.setattr(mcp, "sync_codex", lambda servers: "codex-result") + monkeypatch.setattr(mcp, "sync_copilot", lambda servers: "copilot-result") + monkeypatch.setattr(mcp, "sync_opencode", lambda servers: "opencode-result") + monkeypatch.setattr(mcp, "sync_droid", lambda servers: "droid-result") + monkeypatch.setattr(mcp, "sync_devin", lambda servers: "devin-result") assert mcp.sync("gemini", []) == "gemini-result" assert mcp.sync("agent", []) == "cursor-result" + assert mcp.sync("codex", []) == "codex-result" + assert mcp.sync("copilot", []) == "copilot-result" + assert mcp.sync("opencode", []) == "opencode-result" + assert mcp.sync("droid", []) == "droid-result" + assert mcp.sync("devin", []) == "devin-result" + + +# ---------- copilot: persistent via ~/.copilot/mcp-config.json ---------- + + +def test_sync_copilot_stdio_and_remote(tmp_path, monkeypatch): + copilot_path = tmp_path / "mcp-config.json" + monkeypatch.setattr(mcp, "COPILOT_MCP_CONFIG_PATH", copilot_path) + + sse_server = MCPServerConfig( + name="sse-server", + url="https://api.example.com/sse", + transport="sse", + ) + results = mcp.sync_copilot([STDIO_SERVER, REMOTE_SERVER, sse_server]) + assert len(results) == 3 + assert all(r.ok for r in results) + + doc = json.loads(copilot_path.read_text(encoding="utf-8")) + assert doc["mcpServers"]["Atlassian-Rovo-MCP"] == { + "type": "local", + "command": "npx", + "args": ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"], + "tools": ["*"], + } + assert doc["mcpServers"]["example"] == { + "type": "http", + "url": "https://example.com/mcp", + "tools": ["*"], + "headers": {"Authorization": "Bearer abc"}, + } + assert doc["mcpServers"]["sse-server"] == { + "type": "sse", + "url": "https://api.example.com/sse", + "tools": ["*"], + } + if os.name != "nt": + assert copilot_path.stat().st_mode & 0o777 == 0o600 + + +def test_sync_copilot_preserves_and_idempotent(tmp_path, monkeypatch): + copilot_path = tmp_path / "mcp-config.json" + initial = { + "otherKey": "custom", + "mcpServers": { + "existing": {"type": "local", "command": "echo", "tools": ["*"]}, + "Atlassian-Rovo-MCP": { + "type": "local", + "command": "custom-cmd", + "tools": ["read"], + }, + }, + } + copilot_path.write_text(json.dumps(initial), encoding="utf-8") + monkeypatch.setattr(mcp, "COPILOT_MCP_CONFIG_PATH", copilot_path) + + results = mcp.sync_copilot([STDIO_SERVER]) + assert results == [ + mcp.SyncResult("Atlassian-Rovo-MCP", True, "already configured, skipped") + ] + + doc = json.loads(copilot_path.read_text(encoding="utf-8")) + assert doc["otherKey"] == "custom" + assert doc["mcpServers"]["existing"]["command"] == "echo" + assert doc["mcpServers"]["Atlassian-Rovo-MCP"]["command"] == "custom-cmd" + assert doc["mcpServers"]["Atlassian-Rovo-MCP"]["tools"] == ["read"] + + +# ---------- opencode: persistent via ~/.config/opencode/opencode.json ---------- + + +def test_sync_opencode_stdio_and_remote(tmp_path, monkeypatch): + opencode_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_MCP_CONFIG_PATH", opencode_path) + + env_server = MCPServerConfig( + name="env-server", + command="python", + args=["-m", "server"], + env={"API_KEY": "123"}, + ) + results = mcp.sync_opencode([env_server, REMOTE_SERVER]) + assert len(results) == 2 + assert all(r.ok for r in results) + + doc = json.loads(opencode_path.read_text(encoding="utf-8")) + assert doc["mcp"]["env-server"] == { + "type": "local", + "command": ["python", "-m", "server"], + "enabled": True, + "environment": {"API_KEY": "123"}, + } + assert doc["mcp"]["example"] == { + "type": "remote", + "url": "https://example.com/mcp", + "enabled": True, + "headers": {"Authorization": "Bearer abc"}, + } + if os.name != "nt": + assert opencode_path.stat().st_mode & 0o777 == 0o600 + + +def test_sync_opencode_preserves_and_idempotent(tmp_path, monkeypatch): + opencode_path = tmp_path / "opencode.json" + initial = { + "permission": {"bash": "deny"}, + "mcp": { + "existing": {"type": "local", "command": ["echo"], "enabled": False}, + }, + } + opencode_path.write_text(json.dumps(initial), encoding="utf-8") + monkeypatch.setattr(mcp, "OPENCODE_MCP_CONFIG_PATH", opencode_path) + + results = mcp.sync_opencode([STDIO_SERVER]) + assert results[0].ok is True + + doc = json.loads(opencode_path.read_text(encoding="utf-8")) + assert doc["permission"] == {"bash": "deny"} + assert doc["mcp"]["existing"]["enabled"] is False + + results2 = mcp.sync_opencode([STDIO_SERVER]) + assert results2 == [ + mcp.SyncResult("Atlassian-Rovo-MCP", True, "already configured, skipped") + ] + + +# ---------- droid: persistent via ~/.factory/mcp.json ---------- + + +def test_sync_droid_creates_config(tmp_path, monkeypatch): + droid_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "DROID_MCP_CONFIG_PATH", droid_path) + + results = mcp.sync_droid([STDIO_SERVER, REMOTE_SERVER]) + assert all(r.ok for r in results) + + doc = json.loads(droid_path.read_text(encoding="utf-8")) + assert doc["mcpServers"]["Atlassian-Rovo-MCP"]["command"] == "npx" + assert doc["mcpServers"]["example"]["url"] == "https://example.com/mcp" + if os.name != "nt": + assert droid_path.stat().st_mode & 0o777 == 0o600 + + +def test_sync_droid_preserves_and_idempotent(tmp_path, monkeypatch): + droid_path = tmp_path / "mcp.json" + initial = {"mcpServers": {"existing": {"command": "tool"}}} + droid_path.write_text(json.dumps(initial), encoding="utf-8") + monkeypatch.setattr(mcp, "DROID_MCP_CONFIG_PATH", droid_path) + + mcp.sync_droid([STDIO_SERVER]) + results2 = mcp.sync_droid([STDIO_SERVER]) + assert results2 == [ + mcp.SyncResult("Atlassian-Rovo-MCP", True, "already configured, skipped") + ] + + doc = json.loads(droid_path.read_text(encoding="utf-8")) + assert "existing" in doc["mcpServers"] + assert "Atlassian-Rovo-MCP" in doc["mcpServers"] + + +# ---------- devin: persistent via mcp_config.json ---------- + + +def test_sync_devin_creates_config(tmp_path, monkeypatch): + devin_path = tmp_path / "mcp_config.json" + monkeypatch.setattr(mcp, "DEVIN_MCP_CONFIG_PATH", devin_path) + + results = mcp.sync_devin([STDIO_SERVER, REMOTE_SERVER]) + assert all(r.ok for r in results) + + doc = json.loads(devin_path.read_text(encoding="utf-8")) + assert doc["mcpServers"]["Atlassian-Rovo-MCP"]["command"] == "npx" + assert doc["mcpServers"]["example"]["url"] == "https://example.com/mcp" + if os.name != "nt": + assert devin_path.stat().st_mode & 0o777 == 0o600 + + +def test_sync_devin_preserves_and_idempotent(tmp_path, monkeypatch): + devin_path = tmp_path / "mcp_config.json" + initial = {"custom": True, "mcpServers": {"existing": {"command": "custom"}}} + devin_path.write_text(json.dumps(initial), encoding="utf-8") + monkeypatch.setattr(mcp, "DEVIN_MCP_CONFIG_PATH", devin_path) + + mcp.sync_devin([STDIO_SERVER]) + results2 = mcp.sync_devin([STDIO_SERVER]) + assert results2 == [ + mcp.SyncResult("Atlassian-Rovo-MCP", True, "already configured, skipped") + ] + + doc = json.loads(devin_path.read_text(encoding="utf-8")) + assert doc["custom"] is True + assert doc["mcpServers"]["existing"]["command"] == "custom" def test_sync_unsupported_agent_raises(): - with pytest.raises(ValueError): + with pytest.raises(ValueError) as excinfo: mcp.sync("agy", []) - with pytest.raises(ValueError): + msg = str(excinfo.value) + assert "isn't supported for 'agy'" in msg + assert "Agent MCP support:" in msg + assert "REFERENCE.md" not in msg + assert "claude" in msg + assert "per-run" in msg + assert "sync" in msg + assert "none" in msg + + with pytest.raises(ValueError) as excinfo: mcp.sync("claude", []) + msg = str(excinfo.value) + assert "Agent MCP support:" in msg + assert "REFERENCE.md" not in msg + + +# ---------- consistency: docs/REFERENCE.md vs canonical matrix ---------- + + +def test_reference_md_mcp_matrix_consistency(): + ref_path = Path(__file__).resolve().parents[1] / "docs" / "REFERENCE.md" + assert ref_path.exists(), "docs/REFERENCE.md must exist in repository root" + content = ref_path.read_text(encoding="utf-8") + + in_table = False + parsed: dict[str, dict[str, str]] = {} + for line in content.splitlines(): + if "How MCP servers reach each agent varies" in line: + in_table = True + continue + if in_table: + stripped = line.strip() + if stripped.startswith("```") or ( + stripped.startswith("#") and not stripped.startswith("###") + ): + break + if stripped.startswith("|") and not stripped.startswith("|---"): + parts = [p.strip() for p in stripped.split("|")[1:-1]] + if len(parts) >= 3 and parts[0] != "Agent": + raw_id = parts[0] + match = re.search(r"`([^`]+)`", raw_id) + agent_id = match.group(1).split()[0] if match else raw_id.split()[0] + mechanism = parts[1].strip() + guidance = parts[2].strip() + parsed[agent_id] = {"mechanism": mechanism, "guidance": guidance} + + assert set(parsed.keys()) == set(mcp.CANONICAL_MCP_SUPPORT.keys()) + for agent_id, canonical in mcp.CANONICAL_MCP_SUPPORT.items(): + assert parsed[agent_id]["mechanism"] == canonical.mechanism + assert parsed[agent_id]["guidance"] == canonical.guidance