From 68c1aad8103dc8b531f34907bc033f2900cafe1e Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Thu, 3 Dec 2026 13:26:33 +0530 Subject: [PATCH] feat(mcp): add opencode MCP sync verified against opencode v2.2.5 (#124) --- docs/REFERENCE.md | 6 +-- docs/agents.md | 2 +- src/secfoo/cli.py | 2 +- src/secfoo/mcp.py | 96 +++++++++++++++++++++++++++++++++++++++-- tests/test_cli.py | 5 +++ tests/test_mcp.py | 107 ++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 210 insertions(+), 8 deletions(-) diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 9ff4cff..7a1e01c 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -1067,9 +1067,9 @@ 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), `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 | +| `gemini`, `agent` (Cursor), `codex`, `opencode` | 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) | +| `copilot`, `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. @@ -1096,7 +1096,7 @@ 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`, Cursor -(`agent`) or `codex`, run `secfoo mcp sync --agent ` (or `secfoo mcp sync`) +(`agent`), `codex`, or `opencode`, 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 9345822..d6b313b 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -18,7 +18,7 @@ brackets indicate optional arguments. All CLI processes run in `WORKDIR`. | `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). | -| `opencode` | Install via `npm install -g opencode-ai` or `curl -fsSL https://opencode.ai/install \| bash`. Non-interactive `opencode run --pure --format json --dir WORKDIR [-m MODEL]` (prompt on stdin). Read-only permissions set via `OPENCODE_CONFIG_CONTENT` / `OPENCODE_PERMISSION`. | `secfoo models --agent opencode`. Examples: `anthropic/claude-sonnet-4-5`, `openai/gpt-5`. Live via `opencode models`, else curated. | +| `opencode` | Install via `npm install -g opencode-ai` or `curl -fsSL https://opencode.ai/install \| bash`. Non-interactive `opencode run --pure --format json --dir WORKDIR [-m MODEL]` (prompt on stdin). Read-only permissions set via `OPENCODE_CONFIG_CONTENT` / `OPENCODE_PERMISSION`. MCP servers are registered into `$OPENCODE_CONFIG` (default `~/.config/opencode/opencode.json`) via `secfoo mcp sync --agent opencode` (or `secfoo mcp sync`; schema verified against `opencode v2.2.5` on 2026-12-03). | `secfoo models --agent opencode`. Examples: `anthropic/claude-sonnet-4-5`, `openai/gpt-5`. Live via `opencode models`, else curated. | | `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`. MCP servers from `[[mcp_servers]]` (and `secfoo-memory`) are connected by secfoo itself. Only their read-only tools are offered to the model (`readOnlyHint: true`, or the server's `tools = [...]` list), with at most 20 tool calls per run (`[agents.api].tool_call_budget`, `0` turns tools off). The tool phase also stops once the input tokens sent reach 4× the first call's. Each call, the number of rounds and the total input tokens are logged to `stderr.log`. | `secfoo models --agent api`. Examples: `openai/gpt-4.1-mini`, `anthropic/claude-sonnet-4-5`. Live from LiteLLM filtered by env API keys. | `agy` and `devin` do not support adapter model selection; passing an explicit diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 5640cc5..7fd2228 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -3069,7 +3069,7 @@ def mcp_sync( help="Which agent's MCP config to update. If omitted, syncs all installed sync-supported agents.", ), ) -> None: - """Register configured MCP servers persistently into gemini, Cursor or Codex config. + """Register configured MCP servers persistently into gemini, Cursor, Codex, or OpenCode 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. diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index d2c861e..d0fa61f 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -15,6 +15,10 @@ 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. +- opencode: reads `$OPENCODE_CONFIG` or `~/.config/opencode/opencode.json` + (`mcp.servers.`, verified against `opencode v2.2.5`). `secfoo mcp sync` + merges local (`type: "local"`, `command: [...]`, `environment`) and remote + (`type: "remote"`, `url`, `headers`) entries 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. @@ -44,6 +48,9 @@ # 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 +# None = resolve at call time from $OPENCODE_CONFIG / $XDG_CONFIG_HOME, falling +# back to ~/.config/opencode/opencode.json. Tests set this to a fixed path. +OPENCODE_CONFIG_PATH: Path | None = None def codex_config_path() -> Path: @@ -53,7 +60,20 @@ def codex_config_path() -> 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"} + +def opencode_config_path() -> Path: + """The opencode.json OpenCode reads: $OPENCODE_CONFIG, then $XDG_CONFIG_HOME/opencode/opencode.json.""" + if OPENCODE_CONFIG_PATH is not None: + return OPENCODE_CONFIG_PATH + explicit = os.environ.get("OPENCODE_CONFIG") + if explicit: + return Path(explicit).expanduser() + xdg = os.environ.get("XDG_CONFIG_HOME") + base = Path(xdg).expanduser() if xdg else Path.home() / ".config" + return base / "opencode" / "opencode.json" + + +SYNC_SUPPORTED_AGENTS = {"gemini", "agent", "codex", "opencode"} @dataclass @@ -98,8 +118,8 @@ class AgentMCPSupport: ), "opencode": AgentMCPSupport( agent_id="opencode", - mechanism="none", - guidance="Not yet automated in secfoo mcp sync (planned for follow-up)", + mechanism="sync", + guidance="Run `secfoo mcp sync --agent opencode` once to register persistently in ~/.config/opencode/opencode.json", ), "droid": AgentMCPSupport( agent_id="droid", @@ -376,6 +396,74 @@ def sync_codex(servers: list[MCPServerConfig]) -> list[SyncResult]: return results +# ---------- opencode: persistent, via opencode.json merge ---------- + + +def _server_to_opencode_shape(server: MCPServerConfig) -> dict: + """OpenCode `mcp.servers.` entry shape (verified against opencode v2.2.5).""" + if server.command: + entry: dict = {"type": "local", "command": [server.command, *server.args]} + if server.env: + entry["environment"] = dict(server.env) + return entry + entry = {"type": "remote", "url": server.url} + if server.headers: + entry["headers"] = dict(server.headers) + return entry + + +def sync_opencode(servers: list[MCPServerConfig]) -> list[SyncResult]: + if shutil.which("opencode") is None: + return [SyncResult("*", False, "opencode isn't installed (not found on PATH)")] + + config_path = opencode_config_path() + root: dict = {} + if config_path.exists(): + try: + parsed = json.loads(config_path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError) as exc: + return [SyncResult("*", False, f"{config_path} is not valid JSON: {exc}")] + if not isinstance(parsed, dict): + return [SyncResult("*", False, f"{config_path} is not a JSON object")] + root = parsed + + mcp_section = root.get("mcp") + if mcp_section is None: + mcp_section = {} + root["mcp"] = mcp_section + elif not isinstance(mcp_section, dict): + return [SyncResult("*", False, f"{config_path} has a non-object mcp entry")] + + existing = mcp_section.get("servers") + if existing is None: + existing = {} + mcp_section["servers"] = existing + elif not isinstance(existing, dict): + return [SyncResult("*", False, f"{config_path} has a non-object mcp.servers entry")] + + results = [] + newly_added = False + for server in servers: + if server.name in existing: + results.append(SyncResult(server.name, True, "already configured, skipped")) + continue + if not server.command and not server.url: + results.append(SyncResult(server.name, False, "server must define either 'command' or 'url'")) + continue + existing[server.name] = _server_to_opencode_shape(server) + newly_added = True + results.append(SyncResult(server.name, True, f"added to {config_path}")) + + if newly_added: + write_private_text(config_path, json.dumps(root, indent=2)) + elif os.name == "posix" and config_path.exists(): + try: + config_path.resolve().chmod(0o600) + except OSError as exc: + 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) @@ -383,6 +471,8 @@ def sync(agent_id: str, servers: list[MCPServerConfig]) -> list[SyncResult]: return sync_cursor(servers) if agent_id == "codex": return sync_codex(servers) + if agent_id == "opencode": + return sync_opencode(servers) raise ValueError( f"secfoo mcp sync isn't supported for {agent_id!r}.\n\n" f"Agent MCP support:\n\n" diff --git a/tests/test_cli.py b/tests/test_cli.py index 91035c0..939914c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -629,6 +629,11 @@ def test_mcp_sync_codex_is_supported(monkeypatch): assert result.exit_code == 0 assert dispatched == ["codex"] + dispatched.clear() + result_oc = runner.invoke(app, ["mcp", "sync", "--agent", "opencode"]) + assert result_oc.exit_code == 0 + assert dispatched == ["opencode"] + def test_mcp_sync_without_agent_syncs_available_agents(monkeypatch): servers = [MCPServerConfig(name="s", command="npx")] diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 52d4057..ea7ff19 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -423,6 +423,110 @@ def test_sync_codex_reports_inline_mcp_servers_table(tmp_path, monkeypatch): assert codex_path.read_text(encoding="utf-8") == original +# ---------- opencode: persistent via opencode.json merge ---------- + + +def test_sync_opencode_creates_new_config_file(tmp_path, monkeypatch): + oc_path = tmp_path / "opencode" / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_CONFIG_PATH", oc_path) + + results = mcp.sync_opencode([STDIO_SERVER]) + assert results == [mcp.SyncResult("Atlassian-Rovo-MCP", True, f"added to {oc_path}")] + payload = json.loads(oc_path.read_text(encoding="utf-8")) + assert payload == { + "mcp": { + "servers": { + "Atlassian-Rovo-MCP": { + "type": "local", + "command": ["npx", "-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"], + } + } + } + } + + +def test_sync_opencode_stdio_with_env_and_remote_with_headers(tmp_path, monkeypatch): + oc_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_CONFIG_PATH", oc_path) + stdio_with_env = MCPServerConfig(name="mem", command="uvx", args=["secfoo-memory"], env={"TOKEN": "s3cr3t"}) + + results = mcp.sync_opencode([stdio_with_env, REMOTE_SERVER]) + assert all(r.ok for r in results) + servers = json.loads(oc_path.read_text(encoding="utf-8"))["mcp"]["servers"] + assert servers["mem"] == { + "type": "local", + "command": ["uvx", "secfoo-memory"], + "environment": {"TOKEN": "s3cr3t"}, + } + assert servers["example"] == { + "type": "remote", + "url": "https://example.com/mcp", + "headers": {"Authorization": "Bearer abc"}, + } + + +def test_sync_opencode_preserves_existing_keys_and_skips_configured(tmp_path, monkeypatch): + oc_path = tmp_path / "opencode.json" + oc_path.write_text( + json.dumps( + { + "model": "openai/gpt-5", + "mcp": {"servers": {"existing": {"type": "local", "command": ["echo"]}}}, + } + ), + encoding="utf-8", + ) + monkeypatch.setattr(mcp, "OPENCODE_CONFIG_PATH", oc_path) + + results = mcp.sync_opencode( + [MCPServerConfig(name="existing", command="npx"), REMOTE_SERVER] + ) + assert results[0] == mcp.SyncResult("existing", True, "already configured, skipped") + assert results[1].ok is True + parsed = json.loads(oc_path.read_text(encoding="utf-8")) + assert parsed["model"] == "openai/gpt-5" + assert "existing" in parsed["mcp"]["servers"] + assert "example" in parsed["mcp"]["servers"] + + +def test_sync_opencode_reports_missing_cli_and_invalid_json(tmp_path, monkeypatch): + oc_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_CONFIG_PATH", oc_path) + monkeypatch.setattr(mcp.shutil, "which", lambda name: None) + results = mcp.sync_opencode([STDIO_SERVER]) + assert results[0].ok is False + assert "opencode" in results[0].message + + monkeypatch.setattr(mcp.shutil, "which", lambda name: "/usr/bin/opencode") + oc_path.write_text("{bad json", encoding="utf-8") + results = mcp.sync_opencode([STDIO_SERVER]) + assert results[0].ok is False + assert "not valid JSON" in results[0].message + + +def test_sync_opencode_rejects_invalid_shapes_and_owner_only_permissions(tmp_path, monkeypatch): + oc_path = tmp_path / "opencode.json" + monkeypatch.setattr(mcp, "OPENCODE_CONFIG_PATH", oc_path) + oc_path.write_text(json.dumps({"mcp": "not-an-object"}), encoding="utf-8") + assert mcp.sync_opencode([STDIO_SERVER])[0].ok is False + + oc_path.unlink() + mcp.sync_opencode([REMOTE_SERVER]) + if mcp.os.name == "posix": + assert stat.S_IMODE(oc_path.stat().st_mode) == 0o600 + + +def test_opencode_config_path_respects_env_overrides(tmp_path, monkeypatch): + monkeypatch.setattr(mcp, "OPENCODE_CONFIG_PATH", None) + explicit = tmp_path / "custom.json" + monkeypatch.setenv("OPENCODE_CONFIG", str(explicit)) + assert mcp.opencode_config_path() == explicit + + monkeypatch.delenv("OPENCODE_CONFIG", raising=False) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg")) + assert mcp.opencode_config_path() == tmp_path / "xdg" / "opencode" / "opencode.json" + + # ---------- dispatch ---------- @@ -430,9 +534,11 @@ def test_sync_dispatches_by_agent_id(monkeypatch): monkeypatch.setattr(mcp, "sync_gemini", lambda servers: "gemini-result") monkeypatch.setattr(mcp, "sync_cursor", lambda servers: "cursor-result") monkeypatch.setattr(mcp, "sync_codex", lambda servers: "codex-result") + monkeypatch.setattr(mcp, "sync_opencode", lambda servers: "opencode-result") assert mcp.sync("gemini", []) == "gemini-result" assert mcp.sync("agent", []) == "cursor-result" assert mcp.sync("codex", []) == "codex-result" + assert mcp.sync("opencode", []) == "opencode-result" def test_sync_unsupported_agent_raises(): @@ -450,6 +556,7 @@ def test_canonical_mcp_support_covers_all_adapters(): assert mcp.CANONICAL_MCP_SUPPORT["codex"].mechanism == "sync" assert mcp.CANONICAL_MCP_SUPPORT["gemini"].mechanism == "sync" assert mcp.CANONICAL_MCP_SUPPORT["agent"].mechanism == "sync" + assert mcp.CANONICAL_MCP_SUPPORT["opencode"].mechanism == "sync" text = mcp.format_mcp_support_text() for agent_id in ADAPTERS: assert agent_id in text