diff --git a/README.md b/README.md index 5c4254a..62c33c8 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). +Antigravity (`agy`) and the `api` agent cannot use MCP servers (verified +against Antigravity CLI 2.0 as of 2026-11-20). 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..ca18d53 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -961,16 +961,23 @@ 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 — the `agy` CLI has no MCP configuration mechanism as of 2026-11-20 (verified against Antigravity CLI 2.0) | +| `api` | none | Not supported — the `api` agent calls model APIs directly and has no tool-use loop for MCP servers | ```bash secfoo mcp list # show what's configured secfoo mcp sync --agent gemini # register into gemini's own config +secfoo mcp sync # register into all supported persistent agents ``` ## Pattern memory (`secfoo-memory`) @@ -990,8 +997,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). 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..0744eea 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -11,14 +11,15 @@ 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`. | +| `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. MCP is not supported for review runs as of 2026-11-20 (verified against Antigravity CLI 2.0). | +| `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 merged via `secfoo mcp sync --agent copilot` (`~/.copilot/mcp-config.json`). | +| `opencode` | Tested against `opencode 1.18.34`. `opencode run --pure --format json --dir WORKDIR [-m MODEL]` (prompt on stdin). Permissions denied via `OPENCODE_CONFIG_CONTENT`. MCP servers merged 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 merged 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 merged via `secfoo mcp sync --agent devin` (`~/.config/devin/mcp_config.json`, `%APPDATA%\devin\mcp_config.json` on Windows). | +| `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 API calls; no 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/src/secfoo/agents/antigravity.py b/src/secfoo/agents/antigravity.py index 02da146..dc6523f 100644 --- a/src/secfoo/agents/antigravity.py +++ b/src/secfoo/agents/antigravity.py @@ -24,6 +24,9 @@ non-zero exit is captured as status="failed" with the stderr message preserved) -- but this suggests the CLI itself is still unstable this early in its release. If Antigravity runs are unreliable, prefer another agent. + +MCP: the `agy` CLI does not expose an MCP flag or configuration mechanism +for non-interactive review runs as of 2026-11-20 (verified against Antigravity CLI 2.0). """ from __future__ import annotations diff --git a/src/secfoo/agents/codex.py b/src/secfoo/agents/codex.py index f8bed34..9d1a6e3 100644 --- a/src/secfoo/agents/codex.py +++ b/src/secfoo/agents/codex.py @@ -19,9 +19,9 @@ `secfoo cost` then shows the total under "Input tokens", "-" for output, and "-" for cost. -MCP servers from ~/.secfoo/config.toml are not wired up for Codex yet -(`secfoo mcp sync --agent codex` is a follow-up); Codex runs use whatever is -already in the user's own ~/.codex/config.toml. +MCP servers from ~/.secfoo/config.toml reach Codex via `secfoo mcp sync +--agent codex`, which merges them into ~/.codex/config.toml without +clobbering other settings. Codex runs use whatever is configured there. """ from __future__ import annotations diff --git a/src/secfoo/agents/copilot.py b/src/secfoo/agents/copilot.py index 31b36dc..9e46393 100644 --- a/src/secfoo/agents/copilot.py +++ b/src/secfoo/agents/copilot.py @@ -23,6 +23,9 @@ adapters accept (none of claude.py/cursor.py/gemini.py/antigravity.py sandbox writes at the OS level either). +MCP servers from ~/.secfoo/config.toml reach Copilot via `secfoo mcp sync +--agent copilot`, which writes to ~/.copilot/mcp-config.json. + `--output-format json` (JSONL events) replaces the earlier `-s` plain-text mode. SECFOO-10 E2E (Sep 2026, CLI 1.0.89) showed the quirk below is worse than cosmetic: the built-in scanner runs as a *subagent* diff --git a/src/secfoo/agents/devin.py b/src/secfoo/agents/devin.py index 33b5f60..65ee5e7 100644 --- a/src/secfoo/agents/devin.py +++ b/src/secfoo/agents/devin.py @@ -1,4 +1,4 @@ -"""Devin CLI adapter. +r"""Devin CLI adapter. Answers the open question the Q4 sprint plan flagged for this integration ("check whether Devin offers a true local CLI vs. only a cloud session @@ -64,6 +64,10 @@ `failed` status rather than crashing (same shape confirmed for the droid adapter) -- but no real report has been produced or inspected. Re-run the adapter tests plus one real assessment once an account is available. + +MCP servers from ~/.secfoo/config.toml reach Devin via `secfoo mcp sync +--agent devin`, which merges into ~/.config/devin/mcp_config.json +(%APPDATA%\devin\mcp_config.json on Windows). """ from __future__ import annotations diff --git a/src/secfoo/agents/droid.py b/src/secfoo/agents/droid.py index 772a237..759f155 100644 --- a/src/secfoo/agents/droid.py +++ b/src/secfoo/agents/droid.py @@ -38,6 +38,9 @@ against a live account has not been exercised. Re-run the adapter tests plus one real assessment once a key is available, before relying on this in CI. + +MCP servers from ~/.secfoo/config.toml reach Droid via `secfoo mcp sync +--agent droid`, which merges into ~/.factory/mcp.json. """ from __future__ import annotations diff --git a/src/secfoo/agents/opencode.py b/src/secfoo/agents/opencode.py index 8adc1ba..c585b04 100644 --- a/src/secfoo/agents/opencode.py +++ b/src/secfoo/agents/opencode.py @@ -3,6 +3,9 @@ The non-interactive `run` command reads the prompt from stdin and rejects permission requests without --auto. Read-only permissions are configured via OPENCODE_CONFIG_CONTENT and OPENCODE_PERMISSION; --pure disables external plugins. + +MCP servers from ~/.secfoo/config.toml reach OpenCode via `secfoo mcp sync +--agent opencode`, which merges into ~/.config/opencode/opencode.json. """ from __future__ import annotations diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index b9b4011..999467e 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -977,17 +977,19 @@ def serve_key_revoke(key_id: Annotated[int, typer.Argument(help="Key id from `se @app.command() def agents() -> None: - """List known agent adapters and whether their CLI is installed.""" + """List known agent adapters, whether their CLI is installed, and MCP support.""" table = Table(title="Agent adapters") 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_mode = mcp_module.agent_mcp_mechanism(agent_id) + table.add_row(agent_id, adapter.binary, f"[{style}]{'yes' if available else 'no'}[/]", mcp_mode) console.print(table) @@ -2639,19 +2641,22 @@ def mcp_list() -> None: console.print(table) console.print( "\n[bold]claude[/] picks these up automatically on every run (--mcp-config, " - "scoped to that run only).\nFor [bold]gemini[/] or [bold]agent[/] (Cursor), run " - "[bold]secfoo mcp sync --agent [/] once to register them persistently." + "scoped to that run only).\nFor persistent agents ([bold]gemini, agent, codex, copilot, " + "opencode, droid, devin[/]), run [bold]secfoo mcp sync --agent [/] (or [bold]secfoo mcp sync[/] " + "to sync all) to register them persistently." ) @mcp_app.command(name="sync") def mcp_sync( - agent: AgentId = typer.Option(..., "--agent", "-a", help="Which agent's MCP config to update."), + agent: AgentId | None = typer.Option( + None, "--agent", "-a", help="Which agent's MCP config to update. Omit to sync all supported agents." + ), ) -> 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 agent CLI configs. + + claude doesn't need this -- it picks up ~/.secfoo/config.toml automatically + on every run. agy and api are not supported (they have no CLI MCP mechanism). """ try: cfg = load_config() @@ -2664,22 +2669,27 @@ def mcp_sync( console.print(f"No MCP servers configured in {CONFIG_PATH} -- nothing to sync.") return - if agent.value == "claude": + if agent is not None and 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 - + target_agents = [agent.value] if agent is not None else sorted(mcp_module.SYNC_SUPPORTED_AGENTS) 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 + for target in target_agents: + if len(target_agents) > 1: + console.print(f"[bold]{target}:[/]") + try: + results = mcp_module.sync(target, servers) + except ValueError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=1) from None + + 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 b33cd18..a3711e3 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -1,36 +1,68 @@ -"""Bridges secfoo's portable MCP server config (settings.py) to each agent +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 (verified directly -against each `--help` output, Aug 2026): +against each CLI's configuration capabilities, Nov 2026): -- claude: supports `--mcp-config `, which loads servers scoped to just - that one invocation -- no global state touched. Handled automatically by - ClaudeAdapter on every run; no explicit sync step needed. +- claude: supports `--mcp-config ` and `--strict-mcp-config`, which loads + servers scoped to just that one invocation -- no global state touched. Handled + automatically by ClaudeAdapter on every run; no explicit sync step needed. - gemini: has a `gemini mcp add ...` subcommand that registers a server persistently (user or project scope). No per-invocation file flag exists, so this must be done once via `secfoo mcp sync`. -- 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. +- agent (Cursor): has no `mcp add` subcommand -- servers are defined by editing + `~/.cursor/mcp.json` directly, then approved via `agent mcp enable `. + `secfoo mcp sync --agent agent` merges them into `~/.cursor/mcp.json`. +- codex: reads `~/.codex/config.toml` (`[mcp_servers.]`). `secfoo mcp sync + --agent codex` merges servers into `~/.codex/config.toml` without clobbering + other settings. +- copilot: reads `~/.copilot/mcp-config.json` (`mcpServers` with `"type": "local"|"http"`). + `secfoo mcp sync --agent copilot` registers them persistently. +- opencode: reads `~/.config/opencode/opencode.json` (`"mcp": { ... }`). `secfoo mcp + sync --agent opencode` registers them persistently. +- droid: reads `~/.factory/mcp.json` (`mcpServers`). `secfoo mcp sync --agent droid` + merges them into `~/.factory/mcp.json`. +- devin: reads `~/.config/devin/mcp_config.json` (or `%APPDATA%\devin\mcp_config.json` on Windows). + `secfoo mcp sync --agent devin` merges them persistently. +- agy (Antigravity): no MCP subcommand or flag exposed by the CLI for non-interactive + review runs as of 2026-11-20 (verified against Antigravity CLI 2.0). Refuses with + the support matrix. +- api: calls model APIs directly via LiteLLM/LangGraph; no tool-use loop for MCP servers. """ from __future__ import annotations import json +import os import re import subprocess +import sys from dataclasses import dataclass from pathlib import Path +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + from secfoo.config import STORE_DIR from secfoo.settings import MCPServerConfig CLAUDE_MCP_CONFIG_PATH = STORE_DIR / "claude-mcp-config.json" CURSOR_MCP_CONFIG_PATH = Path.home() / ".cursor" / "mcp.json" +CODEX_MCP_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" + -SYNC_SUPPORTED_AGENTS = {"gemini", "agent"} +DEVIN_MCP_CONFIG_PATH = _default_devin_path() + +SYNC_SUPPORTED_AGENTS = {"gemini", "agent", "codex", "copilot", "opencode", "droid", "devin"} @dataclass @@ -40,6 +72,121 @@ 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 — the `agy` CLI has no MCP configuration mechanism as of 2026-11-20 (verified against Antigravity CLI 2.0)", + ), + "api": AgentMCPSupport( + agent_id="api", + mechanism="none", + guidance="Not supported — the `api` agent calls model APIs directly and has no tool-use loop for MCP servers", + ), +} + + +def parse_mcp_support_from_reference_md(text: str) -> dict[str, AgentMCPSupport]: + in_section = False + matrix: dict[str, AgentMCPSupport] = {} + for line in text.splitlines(): + if "How MCP servers reach each agent varies" in line: + in_section = True + continue + if in_section: + stripped = line.strip() + if matrix and (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() + matrix[agent_id] = AgentMCPSupport(agent_id=agent_id, mechanism=mechanism, guidance=guidance) + return matrix + + +def get_mcp_support_matrix() -> dict[str, AgentMCPSupport]: + ref_md = Path(__file__).resolve().parents[2] / "docs" / "REFERENCE.md" + if ref_md.exists(): + try: + parsed = parse_mcp_support_from_reference_md(ref_md.read_text(encoding="utf-8")) + if parsed: + return parsed + except (OSError, UnicodeDecodeError, ValueError): + return CANONICAL_MCP_SUPPORT + return CANONICAL_MCP_SUPPORT + + +def format_mcp_support_table() -> str: + matrix = get_mcp_support_matrix() + header = "| Agent | Mechanism | Guidance |\n|---|---|---|" + rows = [f"| `{item.agent_id}` | {item.mechanism} | {item.guidance} |" for item in matrix.values()] + return "\n".join([header] + rows) + + +def agent_mcp_mechanism(agent_id: str) -> str: + matrix = get_mcp_support_matrix() + if agent_id in matrix: + return matrix[agent_id].mechanism + return "none" + + 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 @@ -56,7 +203,7 @@ def effective_servers(configured: list[MCPServerConfig]) -> list[MCPServerConfig def _server_to_standard_shape(server: MCPServerConfig) -> dict: """The de facto standard mcpServers entry shape shared by Claude Code, - VS Code, and Cursor's own config files.""" + VS Code, Cursor, Droid, and Devin.""" if server.command: entry: dict = {"command": server.command, "args": list(server.args)} if server.env: @@ -84,7 +231,10 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: CLAUDE_MCP_CONFIG_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8") # Header values (the secfoo-memory bearer key, or any user server's # auth header) are secrets -- same 0600 as cloud.toml/memory.toml. - CLAUDE_MCP_CONFIG_PATH.chmod(0o600) + try: + CLAUDE_MCP_CONFIG_PATH.chmod(0o600) + except OSError: + pass return CLAUDE_MCP_CONFIG_PATH @@ -94,7 +244,7 @@ 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) + proc = subprocess.run(["gemini", "mcp", "list"], capture_output=True, text=True, timeout=30, check=False) names = set() for line in proc.stdout.splitlines(): match = _GEMINI_LIST_NAME_RE.match(line.strip()) @@ -124,7 +274,7 @@ 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) + proc = subprocess.run(_gemini_add_command(server), capture_output=True, text=True, timeout=30, check=False) if proc.returncode == 0: results.append(SyncResult(server.name, True, "added")) else: @@ -137,27 +287,34 @@ def sync_gemini(servers: list[MCPServerConfig]) -> list[SyncResult]: def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: CURSOR_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + existing_root: dict = {} existing: dict = {} if CURSOR_MCP_CONFIG_PATH.exists(): try: - existing = json.loads(CURSOR_MCP_CONFIG_PATH.read_text(encoding="utf-8")).get("mcpServers", {}) - except json.JSONDecodeError as exc: + existing_root = json.loads(CURSOR_MCP_CONFIG_PATH.read_text(encoding="utf-8")) + if isinstance(existing_root, dict): + existing = existing_root.get("mcpServers", {}) + if not isinstance(existing, dict): + existing = {} + except (json.JSONDecodeError, OSError) as exc: return [SyncResult("*", False, f"{CURSOR_MCP_CONFIG_PATH} is not valid JSON: {exc}")] results = [] newly_added: list[str] = [] for server in servers: - if server.name in existing: + shape = _server_to_standard_shape(server) + if server.name in existing and existing[server.name] == shape: results.append(SyncResult(server.name, True, "already configured, skipped")) continue - existing[server.name] = _server_to_standard_shape(server) + existing[server.name] = shape newly_added.append(server.name) results.append(SyncResult(server.name, True, f"added to {CURSOR_MCP_CONFIG_PATH}")) if newly_added: - CURSOR_MCP_CONFIG_PATH.write_text(json.dumps({"mcpServers": existing}, indent=2), encoding="utf-8") + existing_root["mcpServers"] = existing + CURSOR_MCP_CONFIG_PATH.write_text(json.dumps(existing_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 = 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: @@ -166,14 +323,291 @@ def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: return results +# ---------- codex: persistent, via ~/.codex/config.toml merge ---------- + + +def _toml_key(key: str) -> str: + if re.fullmatch(r"[A-Za-z0-9_-]+", key): + return key + escaped = key.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + + +def _dump_toml_val(val: object) -> str: + if isinstance(val, bool): + return "true" if val else "false" + if isinstance(val, (int, float)): + return str(val) + if isinstance(val, str): + escaped = val.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + return f'"{escaped}"' + if isinstance(val, (list, tuple)): + return "[" + ", ".join(_dump_toml_val(x) for x in val) + "]" + if isinstance(val, dict): + return "{ " + ", ".join(f"{_toml_key(k)} = {_dump_toml_val(v)}" for k, v in val.items()) + " }" + raise TypeError(f"Unsupported TOML value type: {type(val)}") + + +def _dumps_toml(data: dict) -> str: + lines = [] + # 1. Top-level scalars/lists/inline-tables + for k, v in data.items(): + if not isinstance(v, dict): + lines.append(f"{_toml_key(k)} = {_dump_toml_val(v)}") + # 2. Tables & subtables + for k, v in data.items(): + if isinstance(v, dict): + scalars = {sk: sv for sk, sv in v.items() if not isinstance(sv, dict)} + nested = {sk: sv for sk, sv in v.items() if isinstance(sv, dict)} + if scalars: + lines.append(f"\n[{_toml_key(k)}]") + for sk, sv in scalars.items(): + lines.append(f"{_toml_key(sk)} = {_dump_toml_val(sv)}") + for sub_k, sub_v in nested.items(): + lines.append(f"\n[{_toml_key(k)}.{_toml_key(sub_k)}]") + for sk, sv in sub_v.items(): + lines.append(f"{_toml_key(sk)} = {_dump_toml_val(sv)}") + return "\n".join(lines).strip() + "\n" + + +def _server_to_codex_shape(server: MCPServerConfig) -> dict: + if server.command: + entry: dict = {"command": server.command, "args": list(server.args)} + if server.env: + entry["env"] = dict(server.env) + return entry + entry = {"url": server.url} + if server.transport != "stdio": + entry["transport"] = server.transport + if server.headers: + entry["headers"] = dict(server.headers) + return entry + + +def sync_codex(servers: list[MCPServerConfig]) -> list[SyncResult]: + CODEX_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + existing: dict = {} + if CODEX_MCP_CONFIG_PATH.exists(): + try: + existing = tomllib.loads(CODEX_MCP_CONFIG_PATH.read_text(encoding="utf-8")) + except (tomllib.TOMLDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{CODEX_MCP_CONFIG_PATH} is not valid TOML: {exc}")] + + mcp_servers = existing.setdefault("mcp_servers", {}) + if not isinstance(mcp_servers, dict): + mcp_servers = {} + existing["mcp_servers"] = mcp_servers + + results = [] + newly_added: list[str] = [] + for server in servers: + shape = _server_to_codex_shape(server) + if server.name in mcp_servers and mcp_servers[server.name] == shape: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + mcp_servers[server.name] = shape + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {CODEX_MCP_CONFIG_PATH}")) + + if newly_added: + CODEX_MCP_CONFIG_PATH.write_text(_dumps_toml(existing), encoding="utf-8") + 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": "http" if server.transport in ("http", "sse") else server.transport, + "url": server.url, + "tools": ["*"], + } + if server.headers: + entry["headers"] = dict(server.headers) + return entry + + +def sync_copilot(servers: list[MCPServerConfig]) -> list[SyncResult]: + COPILOT_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + existing_root: dict = {} + existing: dict = {} + if COPILOT_MCP_CONFIG_PATH.exists(): + try: + existing_root = json.loads(COPILOT_MCP_CONFIG_PATH.read_text(encoding="utf-8")) + if isinstance(existing_root, dict): + existing = existing_root.get("mcpServers", {}) + if not isinstance(existing, dict): + existing = {} + except (json.JSONDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{COPILOT_MCP_CONFIG_PATH} is not valid JSON: {exc}")] + + results = [] + newly_added: list[str] = [] + for server in servers: + shape = _server_to_copilot_shape(server) + if server.name in existing and existing[server.name] == shape: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + existing[server.name] = shape + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {COPILOT_MCP_CONFIG_PATH}")) + + if newly_added: + existing_root["mcpServers"] = existing + COPILOT_MCP_CONFIG_PATH.write_text(json.dumps(existing_root, indent=2), encoding="utf-8") + return results + + +# ---------- opencode: persistent, via ~/.config/opencode/opencode.json merge ---------- + + +def _server_to_opencode_shape(server: MCPServerConfig) -> dict: + if server.command: + entry: dict = { + "type": "local", + "command": [server.command, *server.args], + "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]: + OPENCODE_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + existing_root: dict = {} + existing: dict = {} + if OPENCODE_MCP_CONFIG_PATH.exists(): + try: + existing_root = json.loads(OPENCODE_MCP_CONFIG_PATH.read_text(encoding="utf-8")) + if isinstance(existing_root, dict): + existing = existing_root.get("mcp", {}) + if not isinstance(existing, dict): + existing = {} + except (json.JSONDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{OPENCODE_MCP_CONFIG_PATH} is not valid JSON: {exc}")] + + results = [] + newly_added: list[str] = [] + for server in servers: + shape = _server_to_opencode_shape(server) + if server.name in existing and existing[server.name] == shape: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + existing[server.name] = shape + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {OPENCODE_MCP_CONFIG_PATH}")) + + if newly_added: + existing_root["mcp"] = existing + OPENCODE_MCP_CONFIG_PATH.write_text(json.dumps(existing_root, indent=2), encoding="utf-8") + return results + + +# ---------- droid: persistent, via ~/.factory/mcp.json merge ---------- + + +def sync_droid(servers: list[MCPServerConfig]) -> list[SyncResult]: + DROID_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + existing_root: dict = {} + existing: dict = {} + if DROID_MCP_CONFIG_PATH.exists(): + try: + existing_root = json.loads(DROID_MCP_CONFIG_PATH.read_text(encoding="utf-8")) + if isinstance(existing_root, dict): + existing = existing_root.get("mcpServers", {}) + if not isinstance(existing, dict): + existing = {} + except (json.JSONDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{DROID_MCP_CONFIG_PATH} is not valid JSON: {exc}")] + + results = [] + newly_added: list[str] = [] + for server in servers: + shape = _server_to_standard_shape(server) + if server.name in existing and existing[server.name] == shape: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + existing[server.name] = shape + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {DROID_MCP_CONFIG_PATH}")) + + if newly_added: + existing_root["mcpServers"] = existing + DROID_MCP_CONFIG_PATH.write_text(json.dumps(existing_root, indent=2), encoding="utf-8") + return results + + +# ---------- devin: persistent, via mcp_config.json merge ---------- + + +def sync_devin(servers: list[MCPServerConfig]) -> list[SyncResult]: + DEVIN_MCP_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + existing_root: dict = {} + existing: dict = {} + if DEVIN_MCP_CONFIG_PATH.exists(): + try: + existing_root = json.loads(DEVIN_MCP_CONFIG_PATH.read_text(encoding="utf-8")) + if isinstance(existing_root, dict): + existing = existing_root.get("mcpServers", {}) + if not isinstance(existing, dict): + existing = {} + except (json.JSONDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{DEVIN_MCP_CONFIG_PATH} is not valid JSON: {exc}")] + + results = [] + newly_added: list[str] = [] + for server in servers: + shape = _server_to_standard_shape(server) + if server.name in existing and existing[server.name] == shape: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + existing[server.name] = shape + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {DEVIN_MCP_CONFIG_PATH}")) + + if newly_added: + existing_root["mcpServers"] = existing + DEVIN_MCP_CONFIG_PATH.write_text(json.dumps(existing_root, indent=2), encoding="utf-8") + return results + + 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 matrix (from docs/REFERENCE.md):\n\n" + f"{format_mcp_support_table()}" ) diff --git a/tests/test_cli.py b/tests/test_cli.py index c065671..463c173 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -208,6 +208,10 @@ def fake_execute_runs(**kwargs): def test_agents_command_lists_all_adapters(): 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 for agent_id in ["claude", "agent", "agy", "gemini", "codex"]: assert agent_id in result.stdout @@ -609,16 +613,39 @@ def test_mcp_sync_unsupported_agent_exits_nonzero(monkeypatch): ) result = runner.invoke(app, ["mcp", "sync", "--agent", "agy"]) assert result.exit_code == 1 + assert "docs/REFERENCE.md" in result.output + assert "per-run" in result.output -def test_mcp_sync_codex_is_reported_unsupported(monkeypatch): +def test_mcp_sync_codex_dispatches_successfully(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.output + + +def test_mcp_sync_without_agent_syncs_all_supported_agents(monkeypatch): + servers = [MCPServerConfig(name="s", command="npx")] + monkeypatch.setattr( + "secfoo.cli.load_config", lambda: SecfooConfig(defaults=Defaults(), mcp_servers=servers) + ) + synced = [] + monkeypatch.setattr( + mcp_module, + "sync", + lambda agent_id, servers: [ + synced.append(agent_id) or mcp_module.SyncResult("s", True, "added") + ], + ) + result = runner.invoke(app, ["mcp", "sync"]) + assert result.exit_code == 0 + assert set(synced) == mcp_module.SYNC_SUPPORTED_AGENTS @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..1016b55 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -2,16 +2,26 @@ import json import subprocess +import sys +from pathlib import Path import pytest +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + from secfoo import mcp +from secfoo.agents import ADAPTERS +from secfoo.agents.claude import ClaudeAdapter from secfoo.settings import MCPServerConfig STDIO_SERVER = MCPServerConfig( name="Atlassian-Rovo-MCP", command="npx", args=["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"], + env={"ATLASSIAN_API_KEY": "secret-123"}, ) REMOTE_SERVER = MCPServerConfig( name="example", @@ -43,6 +53,7 @@ def test_write_claude_mcp_config_stdio_shape(tmp_path, monkeypatch): "Atlassian-Rovo-MCP": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"], + "env": {"ATLASSIAN_API_KEY": "secret-123"}, } } } @@ -62,6 +73,24 @@ def test_write_claude_mcp_config_remote_shape(tmp_path, monkeypatch): } +def test_claude_build_command_per_run_mcp_scoping(tmp_path, monkeypatch): + config_path = tmp_path / "claude-mcp-config.json" + monkeypatch.setattr(mcp, "STORE_DIR", tmp_path) + monkeypatch.setattr(mcp, "CLAUDE_MCP_CONFIG_PATH", config_path) + monkeypatch.setattr( + "secfoo.agents.claude.load_config", + lambda: type("Cfg", (), {"mcp_servers": [STDIO_SERVER]})(), + ) + monkeypatch.setattr("secfoo.memory.memory_server", lambda: None) + + cmd = ClaudeAdapter().build_command("run review", workdir=tmp_path) + assert "--mcp-config" in cmd + idx = cmd.index("--mcp-config") + assert cmd[idx + 1] == str(config_path) + assert "--strict-mcp-config" in cmd + assert any("mcp__Atlassian-Rovo-MCP" in arg for arg in cmd) + + # ---------- gemini: persistent via `gemini mcp add` ---------- @@ -126,23 +155,37 @@ def test_sync_cursor_creates_new_config_file(tmp_path, monkeypatch): assert results[0].ok is True payload = json.loads(cursor_path.read_text()) assert payload["mcpServers"]["Atlassian-Rovo-MCP"]["command"] == "npx" + assert payload["mcpServers"]["Atlassian-Rovo-MCP"]["env"] == {"ATLASSIAN_API_KEY": "secret-123"} def test_sync_cursor_preserves_existing_unrelated_entries(tmp_path, monkeypatch): cursor_path = tmp_path / "mcp.json" - cursor_path.write_text(json.dumps({"mcpServers": {"other-server": {"command": "foo"}}})) + cursor_path.write_text(json.dumps({"unrelated": "setting", "mcpServers": {"other-server": {"command": "foo"}}})) monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) monkeypatch.setattr(mcp.subprocess, "run", lambda cmd, **kw: subprocess.CompletedProcess(cmd, 0, "", "")) mcp.sync_cursor([STDIO_SERVER]) payload = json.loads(cursor_path.read_text()) + assert payload.get("unrelated") == "setting" assert "other-server" in payload["mcpServers"] assert "Atlassian-Rovo-MCP" in payload["mcpServers"] 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"}}})) + cursor_path.write_text( + json.dumps( + { + "mcpServers": { + "Atlassian-Rovo-MCP": { + "command": "npx", + "args": ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"], + "env": {"ATLASSIAN_API_KEY": "secret-123"}, + } + } + } + ) + ) monkeypatch.setattr(mcp, "CURSOR_MCP_CONFIG_PATH", cursor_path) def fail_if_called(cmd, **kwargs): @@ -163,18 +206,334 @@ def test_sync_cursor_reports_enable_failure(tmp_path, monkeypatch): assert "denied" in results[0].message -# ---------- dispatch ---------- +# ---------- codex: persistent via ~/.codex/config.toml ---------- + + +def test_sync_codex_creates_new_config_file(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_MCP_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + assert "added to" in results[0].message + data = tomllib.loads(codex_path.read_text(encoding="utf-8")) + server = data["mcp_servers"]["Atlassian-Rovo-MCP"] + assert server["command"] == "npx" + assert server["args"] == ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"] + assert server["env"] == {"ATLASSIAN_API_KEY": "secret-123"} + + +def test_sync_codex_preserves_existing_unrelated_entries_and_servers(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + initial_toml = ( + 'model = "gpt-4o"\n\n' + '[sandbox]\n' + 'mode = "read-only"\n\n' + '[mcp_servers.preexisting]\n' + 'command = "node"\n' + 'args = ["index.js"]\n' + ) + codex_path.write_text(initial_toml, encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_MCP_CONFIG_PATH", codex_path) + + mcp.sync_codex([STDIO_SERVER]) + data = tomllib.loads(codex_path.read_text(encoding="utf-8")) + assert data["model"] == "gpt-4o" + assert data["sandbox"]["mode"] == "read-only" + assert "preexisting" in data["mcp_servers"] + assert "Atlassian-Rovo-MCP" in data["mcp_servers"] + + +def test_sync_codex_is_idempotent(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_MCP_CONFIG_PATH", codex_path) + + res1 = mcp.sync_codex([STDIO_SERVER]) + assert res1[0].ok is True + assert "added to" in res1[0].message + + res2 = mcp.sync_codex([STDIO_SERVER]) + assert res2[0].ok is True + assert res2[0].message == "already configured, skipped" + + +def test_sync_codex_serializes_url_transport_headers_and_env(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_MCP_CONFIG_PATH", codex_path) + + mcp.sync_codex([REMOTE_SERVER]) + data = tomllib.loads(codex_path.read_text(encoding="utf-8")) + server = data["mcp_servers"]["example"] + assert server["url"] == "https://example.com/mcp" + assert server["transport"] == "http" + assert server["headers"] == {"Authorization": "Bearer abc"} + + +def test_sync_codex_reports_invalid_toml(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + codex_path.write_text("invalid = [toml", encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_MCP_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is False + assert "not valid TOML" in results[0].message + + +# ---------- copilot: persistent via ~/.copilot/mcp-config.json ---------- + + +def test_sync_copilot_creates_new_config_file(tmp_path, monkeypatch): + copilot_path = tmp_path / "mcp-config.json" + monkeypatch.setattr(mcp, "COPILOT_MCP_CONFIG_PATH", copilot_path) + + results = mcp.sync_copilot([STDIO_SERVER]) + assert results[0].ok is True + data = json.loads(copilot_path.read_text(encoding="utf-8")) + server = data["mcpServers"]["Atlassian-Rovo-MCP"] + assert server["type"] == "local" + assert server["command"] == "npx" + assert server["tools"] == ["*"] + assert server["env"] == {"ATLASSIAN_API_KEY": "secret-123"} + + +def test_sync_copilot_preserves_existing_unrelated_entries(tmp_path, monkeypatch): + copilot_path = tmp_path / "mcp-config.json" + copilot_path.write_text( + json.dumps({"unrelated": "val", "mcpServers": {"other": {"command": "tool"}}}), + encoding="utf-8", + ) + monkeypatch.setattr(mcp, "COPILOT_MCP_CONFIG_PATH", copilot_path) + + mcp.sync_copilot([STDIO_SERVER]) + data = json.loads(copilot_path.read_text(encoding="utf-8")) + assert data["unrelated"] == "val" + assert "other" in data["mcpServers"] + assert "Atlassian-Rovo-MCP" in data["mcpServers"] + + +def test_sync_copilot_is_idempotent(tmp_path, monkeypatch): + copilot_path = tmp_path / "mcp-config.json" + monkeypatch.setattr(mcp, "COPILOT_MCP_CONFIG_PATH", copilot_path) + + res1 = mcp.sync_copilot([STDIO_SERVER]) + assert res1[0].ok is True + assert "added to" in res1[0].message + + res2 = mcp.sync_copilot([STDIO_SERVER]) + assert res2[0].ok is True + assert res2[0].message == "already configured, skipped" + + +def test_sync_copilot_serializes_url_headers_and_env(tmp_path, monkeypatch): + copilot_path = tmp_path / "mcp-config.json" + monkeypatch.setattr(mcp, "COPILOT_MCP_CONFIG_PATH", copilot_path) + + mcp.sync_copilot([REMOTE_SERVER]) + data = json.loads(copilot_path.read_text(encoding="utf-8")) + server = data["mcpServers"]["example"] + assert server["type"] == "http" + assert server["url"] == "https://example.com/mcp" + assert server["headers"] == {"Authorization": "Bearer abc"} + assert server["tools"] == ["*"] + + +# ---------- opencode: persistent via ~/.config/opencode/opencode.json ---------- + + +def test_sync_opencode_creates_new_config_file(tmp_path, monkeypatch): + opencode_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_MCP_CONFIG_PATH", opencode_path) + + results = mcp.sync_opencode([STDIO_SERVER]) + assert results[0].ok is True + data = json.loads(opencode_path.read_text(encoding="utf-8")) + server = data["mcp"]["Atlassian-Rovo-MCP"] + assert server["type"] == "local" + assert server["command"] == ["npx", "-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"] + assert server["environment"] == {"ATLASSIAN_API_KEY": "secret-123"} + assert server["enabled"] is True + + +def test_sync_opencode_preserves_existing_unrelated_entries(tmp_path, monkeypatch): + opencode_path = tmp_path / "opencode.json" + opencode_path.write_text( + json.dumps({"$schema": "https://opencode.ai/config.json", "mcp": {"other": {"enabled": True}}}), + encoding="utf-8", + ) + monkeypatch.setattr(mcp, "OPENCODE_MCP_CONFIG_PATH", opencode_path) + + mcp.sync_opencode([STDIO_SERVER]) + data = json.loads(opencode_path.read_text(encoding="utf-8")) + assert "$schema" in data + assert "other" in data["mcp"] + assert "Atlassian-Rovo-MCP" in data["mcp"] + + +def test_sync_opencode_is_idempotent(tmp_path, monkeypatch): + opencode_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_MCP_CONFIG_PATH", opencode_path) + + res1 = mcp.sync_opencode([STDIO_SERVER]) + assert res1[0].ok is True + res2 = mcp.sync_opencode([STDIO_SERVER]) + assert res2[0].ok is True + assert res2[0].message == "already configured, skipped" -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") - assert mcp.sync("gemini", []) == "gemini-result" - assert mcp.sync("agent", []) == "cursor-result" +def test_sync_opencode_serializes_url_headers_and_env(tmp_path, monkeypatch): + opencode_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_MCP_CONFIG_PATH", opencode_path) + mcp.sync_opencode([REMOTE_SERVER]) + data = json.loads(opencode_path.read_text(encoding="utf-8")) + server = data["mcp"]["example"] + assert server["type"] == "remote" + assert server["url"] == "https://example.com/mcp" + assert server["enabled"] is True + assert server["headers"] == {"Authorization": "Bearer abc"} -def test_sync_unsupported_agent_raises(): - with pytest.raises(ValueError): + +# ---------- droid: persistent via ~/.factory/mcp.json ---------- + + +def test_sync_droid_creates_new_config_file(tmp_path, monkeypatch): + droid_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "DROID_MCP_CONFIG_PATH", droid_path) + + results = mcp.sync_droid([STDIO_SERVER]) + assert results[0].ok is True + data = json.loads(droid_path.read_text(encoding="utf-8")) + server = data["mcpServers"]["Atlassian-Rovo-MCP"] + assert server["command"] == "npx" + assert server["env"] == {"ATLASSIAN_API_KEY": "secret-123"} + + +def test_sync_droid_preserves_existing_unrelated_entries(tmp_path, monkeypatch): + droid_path = tmp_path / "mcp.json" + droid_path.write_text(json.dumps({"version": 1, "mcpServers": {"other": {"command": "tool"}}}), encoding="utf-8") + monkeypatch.setattr(mcp, "DROID_MCP_CONFIG_PATH", droid_path) + + mcp.sync_droid([STDIO_SERVER]) + data = json.loads(droid_path.read_text(encoding="utf-8")) + assert data["version"] == 1 + assert "other" in data["mcpServers"] + assert "Atlassian-Rovo-MCP" in data["mcpServers"] + + +def test_sync_droid_is_idempotent(tmp_path, monkeypatch): + droid_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "DROID_MCP_CONFIG_PATH", droid_path) + + res1 = mcp.sync_droid([STDIO_SERVER]) + assert res1[0].ok is True + res2 = mcp.sync_droid([STDIO_SERVER]) + assert res2[0].ok is True + assert res2[0].message == "already configured, skipped" + + +def test_sync_droid_serializes_url_headers_and_env(tmp_path, monkeypatch): + droid_path = tmp_path / "mcp.json" + monkeypatch.setattr(mcp, "DROID_MCP_CONFIG_PATH", droid_path) + + mcp.sync_droid([REMOTE_SERVER]) + data = json.loads(droid_path.read_text(encoding="utf-8")) + server = data["mcpServers"]["example"] + assert server["type"] == "http" + assert server["url"] == "https://example.com/mcp" + assert server["headers"] == {"Authorization": "Bearer abc"} + + +# ---------- devin: persistent via mcp_config.json ---------- + + +def test_sync_devin_creates_new_config_file(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]) + assert results[0].ok is True + data = json.loads(devin_path.read_text(encoding="utf-8")) + server = data["mcpServers"]["Atlassian-Rovo-MCP"] + assert server["command"] == "npx" + assert server["env"] == {"ATLASSIAN_API_KEY": "secret-123"} + + +def test_sync_devin_preserves_existing_unrelated_entries(tmp_path, monkeypatch): + devin_path = tmp_path / "mcp_config.json" + devin_path.write_text(json.dumps({"global_key": "val", "mcpServers": {"other": {"command": "tool"}}}), encoding="utf-8") + monkeypatch.setattr(mcp, "DEVIN_MCP_CONFIG_PATH", devin_path) + + mcp.sync_devin([STDIO_SERVER]) + data = json.loads(devin_path.read_text(encoding="utf-8")) + assert data["global_key"] == "val" + assert "other" in data["mcpServers"] + assert "Atlassian-Rovo-MCP" in data["mcpServers"] + + +def test_sync_devin_is_idempotent(tmp_path, monkeypatch): + devin_path = tmp_path / "mcp_config.json" + monkeypatch.setattr(mcp, "DEVIN_MCP_CONFIG_PATH", devin_path) + + res1 = mcp.sync_devin([STDIO_SERVER]) + assert res1[0].ok is True + res2 = mcp.sync_devin([STDIO_SERVER]) + assert res2[0].ok is True + assert res2[0].message == "already configured, skipped" + + +def test_sync_devin_serializes_url_headers_and_env(tmp_path, monkeypatch): + devin_path = tmp_path / "mcp_config.json" + monkeypatch.setattr(mcp, "DEVIN_MCP_CONFIG_PATH", devin_path) + + mcp.sync_devin([REMOTE_SERVER]) + data = json.loads(devin_path.read_text(encoding="utf-8")) + server = data["mcpServers"]["example"] + assert server["type"] == "http" + assert server["url"] == "https://example.com/mcp" + assert server["headers"] == {"Authorization": "Bearer abc"} + + +# ---------- dispatch & error reporting ---------- + + +def test_sync_dispatches_all_supported_agents(monkeypatch): + called = [] + for agent_id in mcp.SYNC_SUPPORTED_AGENTS: + monkeypatch.setattr(mcp, f"sync_{'cursor' if agent_id == 'agent' else agent_id}", lambda servers, aid=agent_id: called.append(aid)) + for agent_id in mcp.SYNC_SUPPORTED_AGENTS: + mcp.sync(agent_id, [STDIO_SERVER]) + assert set(called) == mcp.SYNC_SUPPORTED_AGENTS + + +def test_sync_unsupported_agent_message_includes_matrix(): + with pytest.raises(ValueError) as excinfo: mcp.sync("agy", []) - with pytest.raises(ValueError): - mcp.sync("claude", []) + msg = str(excinfo.value) + assert "isn't supported for 'agy'" in msg + assert "docs/REFERENCE.md" 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("api", []) + assert "isn't supported for 'api'" in str(excinfo.value) + + +# ---------- 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") + parsed = mcp.parse_mcp_support_from_reference_md(content) + + # Must cover all 10 adapters defined in ADAPTERS + assert set(parsed.keys()) == set(ADAPTERS.keys()), f"Missing adapters in docs/REFERENCE.md table: {set(ADAPTERS.keys()) - set(parsed.keys())}" + + # Must match canonical matrix + for agent_id, support in mcp.CANONICAL_MCP_SUPPORT.items(): + assert agent_id in parsed + assert parsed[agent_id].mechanism == support.mechanism