diff --git a/README.md b/README.md index 18c5f53..ecfaaa7 100644 --- a/README.md +++ b/README.md @@ -86,8 +86,8 @@ the target's own `.mcp.json` is not loaded). The `api` agent (the GitHub Action's default) connects to the same servers itself and offers their read-only tools to the model, within a budget of 20 calls per run (`[agents.api].tool_call_budget`) and a cap on the tokens resent. For Gemini -CLI and Cursor run `secfoo mcp sync --agent ` once. Codex and -Antigravity cannot use MCP servers yet. Details in +CLI, Cursor and Codex run `secfoo mcp sync --agent ` (or +`secfoo mcp sync`) once. Antigravity cannot use MCP servers yet. 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 1cbbc31..9ff4cff 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -1067,9 +1067,11 @@ How MCP servers reach each agent varies by what its CLI actually supports: |---|---| | `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 | | `api` | Automatic on every `secfoo run`: secfoo connects to each server itself (stdio, HTTP or SSE) and offers its tools to the model as function tools. Only tools the server annotates `readOnlyHint: true` are offered, unless the server's entry lists tools by name in `tools = [...]`, which then offers exactly those. At most 20 tool calls per run (`[agents.api].tool_call_budget`; `0` turns tools off) and 5 minutes of tool use, counted from the first tool call. Because every model turn resends the whole conversation, target source included, the tool phase also ends once the input tokens sent so far reach 4× those of the first call, and the model is asked to batch independent lookups into one turn. When any of these limits is reached the model is told the budget is spent and asked to finish the report. `stderr.log` records the number of tool rounds, the input tokens sent in total and which limit ended the tool phase. Results count toward `--max-input-tokens`, and a result over 40,000 characters is cut with a visible marker. Every call (server, tool, arguments, bytes returned) is logged to the run's `stderr.log`, and the log is shown to the model, so the coverage section can only claim pages a tool actually returned | -| `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 | +| `gemini`, `agent` (Cursor), `codex` | Run `secfoo mcp sync --agent ` (or `secfoo mcp sync` to sync all installed agents) once to register persistently in that tool's own config | +| `agy` (Antigravity) | `agy 1.5.3` has an `agy mcp` subcommand, but secfoo does not yet automate syncing with agy's configuration | +| `copilot`, `opencode`, `droid`, `devin` | Not yet automated in `secfoo mcp sync` (planned for follow-up) | + +Existing same-named servers are preserved and skipped to prevent overwriting user edits or credentials. When rotating API keys or tokens (such as `secfoo-memory`), remove the server entry from the agent's config, then run sync again. ```bash secfoo mcp list # show what's configured @@ -1093,8 +1095,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, and so does the `api` agent. For `gemini` or Cursor -(`agent`), run `secfoo mcp sync --agent ` once. When memory is on, the prompt tells the +it up on every run, and so does the `api` agent. For `gemini`, Cursor +(`agent`) or `codex`, run `secfoo mcp sync --agent ` (or `secfoo mcp sync`) +once. 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 cfa1c8d..9345822 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -10,12 +10,11 @@ brackets indicate optional arguments. All CLI processes run in `WORKDIR`. | `--agent` | Setup and command | Models | | --- | --- | --- | -| `--agent` | Setup and command | Models | | `claude` | Install via `npm install -g @anthropic-ai/claude-code` or `curl -fsSL https://claude.ai/install.sh \| bash` ([docs](https://docs.anthropic.com/en/docs/claude-code/setup)). Authenticate with `claude auth login`. For non-interactive use, set `ANTHROPIC_API_KEY`, or with a Claude subscription run `claude setup-token` once and set the token it prints as `CLAUDE_CODE_OAUTH_TOKEN` (verified `2.1.329 (Claude Code)` on 2026-11-21, macOS Darwin arm64). `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. | `secfoo models --agent claude`. Examples: `claude-sonnet-4-6`, `sonnet`. Live via `ANTHROPIC_API_KEY` (Anthropic models API), else curated. | | `agent` (Cursor) | Install via `curl https://cursor.com/install -fsS \| bash` ([docs](https://cursor.com/docs/cli/overview)). Authenticate with `agent login` or set `CURSOR_API_KEY` for non-interactive use (login and `CURSOR_API_KEY` confirmed in `agent --help` for `2026.08.11-e8db854` on 2026-11-21, macOS arm64; install command from the official docs). `agent [--model MODEL] -p PROMPT` | `secfoo models --agent agent`. Examples: `auto`, `claude-4.5-sonnet`. Live via CLI if supported, else curated. | | `agy` (Antigravity) | Install the `agy` CLI from the Antigravity distribution ([docs](https://antigravity.google)), then run `agy install` to add it to `PATH`. The CLI has no login subcommand: sign in through Antigravity before headless runs (checked against `agy --help` for `1.5.3` on 2026-11-21, macOS arm64). `agy --print PROMPT --print-timeout Ns` (`N` is the effective timeout in seconds). Headless mode denies tool calls requiring approval. | Not supported (`--model` fails fast). | | `gemini` | Install via `npm install -g @google/gemini-cli` ([docs](https://github.com/google-gemini/gemini-cli)). Authenticate interactively with `gemini` or set `GEMINI_API_KEY` for non-interactive use (verified `0.38.1` on 2026-11-21, macOS Darwin arm64). `gemini [--model MODEL] -p PROMPT --output-format json --skip-trust`. No `--yolo` write auto-approval is passed. | `secfoo models --agent gemini`. Examples: `gemini-2.5-pro`, `gemini-2.5-flash`. Live via `GEMINI_API_KEY`, else curated. | -| `codex` | Install via `npm install -g @openai/codex` ([docs](https://github.com/openai/codex)). Authenticate with `codex login` or set `OPENAI_API_KEY` for non-interactive use (verified `codex-cli 0.159.0` on 2026-11-21, macOS Darwin arm64). `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). | `secfoo models --agent codex`. Examples: `gpt-5.4`, `o4-mini`. Live via `OPENAI_API_KEY` (or CLI), else curated. | +| `codex` | Install via `npm install -g @openai/codex` ([docs](https://github.com/openai/codex)). Authenticate with `codex login` or set `OPENAI_API_KEY` for non-interactive use (verified `codex-cli 0.159.0` on 2026-11-21, macOS Darwin arm64; `codex-cli 0.172.0` on Windows). `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 are registered into `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`) via `secfoo mcp sync --agent codex` (or `secfoo mcp sync`). | `secfoo models --agent codex`. Examples: `gpt-5.4`, `o4-mini`. Live via `OPENAI_API_KEY` (or CLI), else curated. | | `copilot` | Install via `npm install -g @github/copilot` ([docs](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/use-copilot-cli)). Authenticate by running `copilot` and using its `/login` command, or set `GH_TOKEN` / `GITHUB_TOKEN` (a fine-grained token with the Copilot Requests permission) for non-interactive use (verified against the real CLI 1.0.117 on 2026-11-29, Windows: `gh auth login` plus `GH_TOKEN` from `gh auth token` worked; see the matrix below). `copilot [--model MODEL] --output-format json --allow-all-tools --usage-output-file PATH` (prompt on stdin). Token counts come from the usage file; premium requests / AI credits are not USD, so `cost_usd` stays unknown. Tools, including writes, are auto-approved: read-only behavior relies on review instructions, not a sandbox. | `secfoo models --agent copilot`. Examples: `claude-sonnet-4.5`, `gpt-5`. Curated (live via CLI if supported). | | `droid` | Install via `curl -fsSL https://app.factory.ai/cli \| sh` ([docs](https://docs.factory.ai/cli/getting-started/overview)). Set `FACTORY_API_KEY` for non-interactive use or run `droid` to sign in interactively (checked against official docs on 2026-11-21, not on an installed CLI). `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. | `secfoo models --agent droid`. Examples: `claude-sonnet-4-5-20250929`, `gpt-5`. Curated (live via CLI if supported). | | `devin` | Install via `brew install --cask devin-cli` ([docs](https://docs.devin.ai)). Authenticate beforehand with `devin auth login`; credential reuse for headless runs is unverified (install and login checked against official docs on 2026-11-21, not on an installed CLI). `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. | Not supported (`--model` fails fast). | diff --git a/pyproject.toml b/pyproject.toml index b3c9022..fa2bd75 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,6 +55,7 @@ dependencies = [ "markdown-it-py>=4.3.0", "python-multipart>=0.0.32", "tomli>=2.0; python_version < '3.11'", + "tomlkit>=0.13.0", # Pure-Python text extraction for uploaded third-party vendor documents # (docext.py) -- deliberately no system-level binaries (no poppler, no # LibreOffice) so the Docker/Kubernetes image stays lean and doesn't diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 94f790c..5640cc5 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -1155,17 +1155,31 @@ 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 their 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'}[/]") + avail_style = "green" if available else "red" + mcp_support = mcp_module.CANONICAL_MCP_SUPPORT.get(agent_id) + mechanism = mcp_support.mechanism if mcp_support else "none" + if mechanism == "per-run": + mcp_style = "green" + elif mechanism == "sync": + mcp_style = "cyan" + else: + mcp_style = "dim" + table.add_row( + agent_id, + adapter.binary, + f"[{avail_style}]{'yes' if available else 'no'}[/]", + f"[{mcp_style}]{mechanism}[/]", + ) console.print(table) @@ -3041,19 +3055,27 @@ 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 " + "scoped to that run only).\nFor [bold]gemini[/], [bold]agent[/] (Cursor) or [bold]codex[/], run " "[bold]secfoo mcp sync --agent [/] once 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. If omitted, syncs all installed sync-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 gemini, Cursor or Codex config. + claude doesn't need this -- it picks up ~/.secfoo/config.toml automatically on every run. + Other agents are not yet supported for automated sync. + + Existing same-named servers are preserved and skipped to prevent overwriting user edits. + To update credentials after rotating keys (e.g. secfoo-memory), remove the server entry + from the agent's config, then run sync again. """ try: cfg = load_config() @@ -3066,6 +3088,29 @@ def mcp_sync( console.print(f"No MCP servers configured in {CONFIG_PATH} -- nothing to sync.") return + if agent is None: + targets = [ + aid for aid in sorted(mcp_module.SYNC_SUPPORTED_AGENTS) + if get_adapter(aid).is_available() + ] + if not targets: + console.print("[yellow]No sync-supported agent CLIs are installed on PATH.[/]") + return + any_failed = False + for aid in targets: + console.print(f"\n[bold]Syncing {aid}...[/]") + results = mcp_module.sync(aid, servers) + 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 + if agent.value == "claude": console.print("[yellow]claude doesn't need syncing[/] -- it loads MCP servers automatically on every run.") return diff --git a/src/secfoo/config.py b/src/secfoo/config.py index 72c5923..fe3525c 100644 --- a/src/secfoo/config.py +++ b/src/secfoo/config.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import time from pathlib import Path STORE_DIR = Path(os.environ.get("SECFOO_HOME", Path.home() / ".secfoo")) @@ -40,19 +41,30 @@ def _make_private(directory: Path) -> None: def write_private_text(path: Path, text: str) -> None: - """Write a secret-bearing file that is never readable by others, not even - between creation and a later chmod (and tighten an existing file first).""" - path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + """Write a secret-bearing file atomically and symlink-safely so it is never + readable by others, not even between creation and replacement. + + Resolves symlinks first so that dotfile managers (e.g. stow, chezmoi) + do not have their symlink replaced with a regular file, and writes via a + temporary file in the target directory before atomically replacing it. + """ + target = path.resolve() + target.parent.mkdir(parents=True, exist_ok=True) + tmp_path = target.with_name(f".{target.name}.tmp.{os.getpid()}.{time.time_ns()}") + fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: - if hasattr(os, "fchmod"): # POSIX; O_CREAT's mode does not apply to an existing file + # POSIX: O_CREAT's mode does not apply to an existing file + if hasattr(os, "fchmod"): os.fchmod(fd, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: fd = -1 handle.write(text) + os.replace(tmp_path, target) finally: if fd != -1: os.close(fd) + if tmp_path.exists(): + tmp_path.unlink(missing_ok=True) def run_dir(run_uuid: str) -> Path: diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index ba3fbe4..d2c861e 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -11,14 +11,19 @@ - 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. +- agy (Antigravity): agy 1.5.3 exposes an `agy mcp` subcommand, but secfoo does + not yet automate syncing with agy's configuration. `secfoo mcp sync --agent agy` + refuses with a clear error. """ from __future__ import annotations import json +import logging import os import re import shutil @@ -26,13 +31,29 @@ from dataclasses import dataclass from pathlib import Path +import tomlkit +from tomlkit.exceptions import TOMLKitError + from secfoo.config import STORE_DIR, write_private_text 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" +# None = resolve at call time from $CODEX_HOME (Codex's own override), falling +# back to ~/.codex. Tests set this to a fixed path. +CODEX_CONFIG_PATH: Path | None = None + -SYNC_SUPPORTED_AGENTS = {"gemini", "agent"} +def codex_config_path() -> Path: + """The config.toml Codex itself reads: $CODEX_HOME/config.toml when set.""" + if CODEX_CONFIG_PATH is not None: + return CODEX_CONFIG_PATH + home = os.environ.get("CODEX_HOME") + return (Path(home).expanduser() if home else Path.home() / ".codex") / "config.toml" + +SYNC_SUPPORTED_AGENTS = {"gemini", "agent", "codex"} @dataclass @@ -42,6 +63,76 @@ 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 invocation; global config untouched)", + ), + "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 register persistently in $CODEX_HOME/config.toml (default ~/.codex/config.toml)", + ), + "copilot": AgentMCPSupport( + agent_id="copilot", + mechanism="none", + guidance="Not yet automated in secfoo mcp sync (planned for follow-up)", + ), + "opencode": AgentMCPSupport( + agent_id="opencode", + mechanism="none", + guidance="Not yet automated in secfoo mcp sync (planned for follow-up)", + ), + "droid": AgentMCPSupport( + agent_id="droid", + mechanism="none", + guidance="Not yet automated in secfoo mcp sync (planned for follow-up)", + ), + "devin": AgentMCPSupport( + agent_id="devin", + mechanism="none", + guidance="Not yet automated in secfoo mcp sync (planned for follow-up)", + ), + "agy": AgentMCPSupport( + agent_id="agy", + mechanism="none", + guidance="agy 1.5.3 exposes an 'agy mcp' subcommand, but secfoo does not yet automate syncing with agy", + ), + "api": AgentMCPSupport( + agent_id="api", + mechanism="none", + guidance="API adapter invokes LLMs directly without a CLI agent or MCP client", + ), +} + + +def format_mcp_support_text() -> str: + """Returns a readable summary of MCP support across all agents.""" + lines = [] + for agent_id in sorted(CANONICAL_MCP_SUPPORT): + support = CANONICAL_MCP_SUPPORT[agent_id] + lines.append(f"- {agent_id} ({support.mechanism}): {support.guidance}") + return "\n".join(lines) + + 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 @@ -196,14 +287,104 @@ def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: return results +# ---------- codex: persistent, via ~/.codex/config.toml merge ---------- + + +def sync_codex(servers: list[MCPServerConfig]) -> list[SyncResult]: + if shutil.which("codex") is None: + return [SyncResult("*", False, "codex isn't installed (not found on PATH)")] + + config_path = codex_config_path() + doc = tomlkit.document() + if config_path.exists(): + try: + content = config_path.read_text(encoding="utf-8") + parsed = tomlkit.parse(content) + except (TOMLKitError, OSError) as exc: + return [SyncResult("*", False, f"{config_path} is not valid TOML: {exc}")] + if not isinstance(parsed, dict): + return [SyncResult("*", False, f"{config_path} is not a TOML table")] + doc = parsed + + mcp_servers = doc.get("mcp_servers") + if mcp_servers is None: + # A super table writes only [mcp_servers.] headers, not an + # empty [mcp_servers] above them. + mcp_servers = tomlkit.table(is_super_table=True) + doc["mcp_servers"] = mcp_servers + elif isinstance(mcp_servers, tomlkit.items.InlineTable): + return [ + SyncResult( + "*", + False, + f"{config_path} defines mcp_servers as an inline table; rewrite it as " + "[mcp_servers.] tables and run sync again", + ) + ] + elif not isinstance(mcp_servers, dict): + return [SyncResult("*", False, f"{config_path} has a non-table mcp_servers entry")] + + results = [] + newly_added: list[str] = [] + for server in servers: + if server.name in mcp_servers: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + + 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[server.name] = server_tbl + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {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[server.name] = server_tbl + newly_added.append(server.name) + results.append(SyncResult(server.name, True, f"added to {config_path}")) + else: + results.append(SyncResult(server.name, False, "server must define either 'command' or 'url'")) + + if newly_added: + write_private_text(config_path, tomlkit.dumps(doc)) + elif os.name == "posix" and config_path.exists(): + try: + config_path.resolve().chmod(0o600) + except OSError as exc: # e.g. not our file; the sync itself still succeeded + logger.debug("could not tighten permissions on %s: %s", config_path, exc) + 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) 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..91035c0 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -208,8 +208,11 @@ 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 for agent_id in ["claude", "agent", "agy", "gemini", "codex"]: assert agent_id in result.stdout + assert "per-run" in result.stdout + assert "sync" in result.stdout class _FakeRepoEmpty: @@ -611,14 +614,48 @@ def test_mcp_sync_unsupported_agent_exits_nonzero(monkeypatch): assert result.exit_code == 1 -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) ) + dispatched = [] + monkeypatch.setattr( + mcp_module, + "sync", + lambda agent_id, servers: dispatched.append(agent_id) or [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 dispatched == ["codex"] + + +def test_mcp_sync_without_agent_syncs_available_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 aid, srvs: synced.append(aid) or [mcp_module.SyncResult("s", True, "added")], + ) + + class FakeAdapter: + def __init__(self, avail): + self._avail = avail + + def is_available(self): + return self._avail + + monkeypatch.setattr( + "secfoo.cli.get_adapter", + lambda aid: FakeAdapter(True) if aid == "codex" else FakeAdapter(False), + ) + result = runner.invoke(app, ["mcp", "sync"]) + assert result.exit_code == 0 + assert synced == ["codex"] @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 1f279b5..52d4057 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -4,8 +4,10 @@ import stat import subprocess import sys +from pathlib import Path import pytest +import tomlkit from secfoo import mcp from secfoo.settings import MCPServerConfig @@ -236,14 +238,201 @@ def test_sync_cursor_tightens_an_existing_file_even_when_nothing_is_added(tmp_pa assert stat.S_IMODE(cursor_path.stat().st_mode) == 0o600 +# ---------- 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_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + assert f"added to {codex_path}" in results[0].message + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + assert doc["mcp_servers"]["Atlassian-Rovo-MCP"]["command"] == "npx" + assert doc["mcp_servers"]["Atlassian-Rovo-MCP"]["args"] == [ + "-y", + "mcp-remote@latest", + "https://mcp.atlassian.com/v1/mcp/authv2", + ] + + +def test_sync_codex_stdio_with_env(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + server = MCPServerConfig(name="env-server", command="run", env={"MY_KEY": "val"}) + results = mcp.sync_codex([server]) + assert results[0].ok is True + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + assert doc["mcp_servers"]["env-server"]["env"]["MY_KEY"] == "val" + + +def test_sync_codex_remote_streamable_http(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([REMOTE_SERVER]) + assert results[0].ok is True + doc = tomlkit.parse(codex_path.read_text(encoding="utf-8")) + assert doc["mcp_servers"]["example"]["url"] == "https://example.com/mcp" + headers = doc["mcp_servers"]["example"]["http_headers"] + assert headers["Authorization"] == "Bearer abc" + + +def test_sync_codex_rejects_sse(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + sse_server = MCPServerConfig( + name="sse-srv", url="https://example.com/sse", transport="sse" + ) + results = mcp.sync_codex([sse_server]) + assert results[0].ok is False + assert "SSE transport" in results[0].message + + +def test_sync_codex_preserves_existing_config_and_comments(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + initial_content = ( + '# Global configuration\nmodel = "gpt-5.6-terra"\n\n[features]\nmulti_agent = true # needed\n' + ) + codex_path.write_text(initial_content, encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + content = codex_path.read_text(encoding="utf-8") + assert "# Global configuration" in content + assert 'model = "gpt-5.6-terra"' in content + assert "multi_agent = true # needed" in content + doc = tomlkit.parse(content) + assert "Atlassian-Rovo-MCP" in doc["mcp_servers"] + + +def test_sync_codex_skips_already_configured(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + codex_path.write_text( + '[mcp_servers.example]\nurl = "https://example.com/mcp"\n', + encoding="utf-8", + ) + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([REMOTE_SERVER]) + assert results == [mcp.SyncResult("example", True, "already configured, skipped")] + + +def test_sync_codex_reports_missing_cli(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + monkeypatch.setattr(mcp.shutil, "which", lambda name: None) + + results = mcp.sync_codex([STDIO_SERVER]) + assert len(results) == 1 + assert results[0].ok is False + assert "codex" in results[0].message + assert not codex_path.exists() + + +def test_sync_codex_rejects_invalid_toml(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + 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 str(codex_path) in results[0].message + + +def test_sync_codex_rejects_non_table_mcp_servers(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + codex_path.write_text('mcp_servers = "not a table"\n', encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is False + assert str(codex_path) in results[0].message + + +def test_sync_codex_rejects_non_table_root_doc(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + codex_path.write_text("a = 1", encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + monkeypatch.setattr(mcp.tomlkit, "parse", lambda text: "not a table") + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is False + assert "not a TOML table" in results[0].message + + +def test_sync_codex_rejects_server_without_command_or_url(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + mock_server = type("MockServer", (), {"name": "empty", "command": None, "url": None})() + results = mcp.sync_codex([mock_server]) + assert results[0].ok is False + assert "must define either 'command' or 'url'" in results[0].message + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits") +def test_sync_codex_writes_config_owner_only(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([REMOTE_SERVER]) + assert results[0].ok is True + assert stat.S_IMODE(codex_path.stat().st_mode) == 0o600 + + +def test_codex_config_path_honours_codex_home(tmp_path, monkeypatch): + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", None) + monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) + assert mcp.codex_config_path() == tmp_path / "codex-home" / "config.toml" + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is True + assert (tmp_path / "codex-home" / "config.toml").exists() + + +def test_codex_config_path_defaults_to_home_dot_codex(monkeypatch): + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", None) + monkeypatch.delenv("CODEX_HOME", raising=False) + assert mcp.codex_config_path() == Path.home() / ".codex" / "config.toml" + + +def test_sync_codex_new_file_has_no_empty_mcp_servers_header(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + mcp.sync_codex([REMOTE_SERVER]) + text = codex_path.read_text(encoding="utf-8") + assert "[mcp_servers]\n" not in text + assert "[mcp_servers.example]" in text + + +def test_sync_codex_reports_inline_mcp_servers_table(tmp_path, monkeypatch): + codex_path = tmp_path / "config.toml" + original = 'mcp_servers = { other = { command = "x" } }\n' + codex_path.write_text(original, encoding="utf-8") + monkeypatch.setattr(mcp, "CODEX_CONFIG_PATH", codex_path) + + results = mcp.sync_codex([STDIO_SERVER]) + assert results[0].ok is False + assert "inline table" in results[0].message + assert codex_path.read_text(encoding="utf-8") == original + + # ---------- 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") assert mcp.sync("gemini", []) == "gemini-result" assert mcp.sync("agent", []) == "cursor-result" + assert mcp.sync("codex", []) == "codex-result" def test_sync_unsupported_agent_raises(): @@ -253,6 +442,19 @@ def test_sync_unsupported_agent_raises(): mcp.sync("claude", []) +def test_canonical_mcp_support_covers_all_adapters(): + from secfoo.agents.registry import ADAPTERS + + assert set(mcp.CANONICAL_MCP_SUPPORT.keys()) == set(ADAPTERS.keys()) + assert mcp.CANONICAL_MCP_SUPPORT["claude"].mechanism == "per-run" + assert mcp.CANONICAL_MCP_SUPPORT["codex"].mechanism == "sync" + assert mcp.CANONICAL_MCP_SUPPORT["gemini"].mechanism == "sync" + assert mcp.CANONICAL_MCP_SUPPORT["agent"].mechanism == "sync" + text = mcp.format_mcp_support_text() + for agent_id in ADAPTERS: + assert agent_id in text + + def test_sync_gemini_reports_missing_cli_instead_of_crashing(monkeypatch): monkeypatch.setattr(mcp.shutil, "which", lambda name: None) diff --git a/tests/test_store_privacy.py b/tests/test_store_privacy.py index fa0abe2..1657739 100644 --- a/tests/test_store_privacy.py +++ b/tests/test_store_privacy.py @@ -60,6 +60,34 @@ def test_write_private_text_creates_0600_and_tightens_an_existing_file(tmp_path) assert _mode(old) == 0o600 and old.read_text() == "api_key = 'new'\n" +def test_write_private_text_atomic_no_temp_residue(tmp_path): + dest = tmp_path / "secret.toml" + config.write_private_text(dest, "hello = 'world'\n") + assert dest.read_text() == "hello = 'world'\n" + # Ensure no lingering .tmp files exist in dest.parent + tmp_files = list(tmp_path.glob(".*tmp*")) + assert tmp_files == [] + + +@posix_only +def test_write_private_text_preserves_symlink(tmp_path): + target = tmp_path / "dotfiles" / "config.toml" + target.parent.mkdir(parents=True) + target.write_text("initial = true\n") + target.chmod(0o644) + + symlink_path = tmp_path / "agent" / "config.toml" + symlink_path.parent.mkdir(parents=True) + symlink_path.symlink_to(target) + + config.write_private_text(symlink_path, "updated = true\n") + + assert symlink_path.is_symlink() + assert symlink_path.resolve() == target.resolve() + assert target.read_text() == "updated = true\n" + assert _mode(target) == 0o600 + + @posix_only def test_credential_files_are_0600_even_when_a_readable_one_existed(tmp_path, monkeypatch): cloud_path, memory_path = tmp_path / "cloud.toml", tmp_path / "memory.toml"