diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-19 16:39:54 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-19 16:39:54 +0000 |
| commit | 0b0a62192591f8c01097c51f591bab11ec8627f0 (patch) | |
| tree | 665608f8384a17e3c75ae4f71cb8709ebbed6405 /plugins | |
| parent | ea10b213686c90bb1984b2016937310e05336cf3 (diff) | |
security-guidance: run reviews on machines with a managed MCP configmhegazy/sg-reviewer-managed-mcp
Since 2.0.14 the plugin starts the reviewing Claude Code with
--strict-mcp-config. Claude Code exits at startup with that flag on a
machine whose administrator delivers the MCP servers (managed-mcp.json),
so the agentic commit review always fell back to the single-shot review,
and reviews that only run through Claude Code (Bedrock, Vertex) failed.
When the inner CLI refuses the flag, the plugin now starts it once more
without it, and leaves it out for the rest of the hook process. Those
starts deny every MCP tool (--disallowedTools "mcp__*") instead, so the
reviewer still gets only its read tools. Review rows from such a process
carry strict_mcp_off: 1.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 55 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 4 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_reviewer_tools.py | 123 |
3 files changed, 178 insertions, 4 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 9fe8640c..aaf785fb 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -30,7 +30,7 @@ import time import traceback import urllib.parse import urllib.request -from typing import Optional, Tuple, Dict, Any, List +from typing import Optional, Tuple, Dict, Any, List, Callable import extensibility import review_api @@ -679,7 +679,9 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) # comes). Bound the wait so a misconfigured 3P session doesn't stall the # whole hook. try: - result = _asyncio.run(_asyncio.wait_for(_arun(), timeout=60)) + result = _run_inner_cli( + lambda: _asyncio.run(_asyncio.wait_for(_arun(), timeout=60)), + _captured_stderr) if _captured_stderr: debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):") for _l in _captured_stderr[:20]: @@ -1419,7 +1421,42 @@ def _only_tools_args(tools: Tuple[str, ...] = ()) -> Dict[str, Optional[str]]: the permission mode that CLI starts in. Passed as CLI flags because not every Agent SDK build that can run a review has a `tools` option. """ - return {"tools": ",".join(tools), "strict-mcp-config": None} + args: Dict[str, Optional[str]] = {"tools": ",".join(tools)} + if _send_strict_mcp: + args["strict-mcp-config"] = None + else: + # The servers an administrator delivers still start; their tools are + # kept from the reviewer. + args["disallowedTools"] = "mcp__*" + return args + + +# Claude Code exits at startup when given --strict-mcp-config on a machine +# whose administrator delivers the MCP servers (managed-mcp.json). The flag +# is sent until an inner CLI refuses it. +_send_strict_mcp = True + + +def _names_strict_mcp_flag(stderr_line: Any) -> bool: + return "--strict-mcp-config" in str(stderr_line) + + +def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any: + """start() runs one inner CLI to its result; stderr_lines receives what + that CLI writes to stderr. A start the CLI refused over + --strict-mcp-config is made once more without the flag, and the flag is + left out for the rest of this process.""" + global _send_strict_mcp + del stderr_lines[:] + try: + return start() + except Exception: + if not any(_names_strict_mcp_flag(l) for l in stderr_lines): + raise + _send_strict_mcp = False + debug_log("inner CLI refused --strict-mcp-config; starting it again without the flag") + del stderr_lines[:] + return start() def _agentic_spawn_env() -> Dict[str, str]: @@ -1641,11 +1678,19 @@ def _agentic_review( # Without a callback the inner CLI writes to this hook's stderr, which # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] + # Lines of the current start that name --strict-mcp-config (_run_inner_cli). + flag_refusals: List[str] = [] def _child_stderr_metric() -> Dict[str, int]: return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} def _on_child_stderr(line: str) -> None: + if _names_strict_mcp_flag(line): + # Not counted: where the flag is refused, every review gets this + # line once, from the start that is then made again. + flag_refusals.append(str(line)) + debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") + return child_stderr_lines[0] += 1 metrics["child_stderr"] = child_stderr_lines[0] if child_stderr_lines[0] <= 20: @@ -1756,7 +1801,9 @@ def _agentic_review( def _run(system: str, prompt: str, *, schema: Dict[str, Any] ) -> Tuple[Optional[Dict[str, Any]], int, Optional[str]]: - return _asyncio.run(_arun(system, prompt, schema=schema)) + return _run_inner_cli( + lambda: _asyncio.run(_arun(system, prompt, schema=schema)), + flag_refusals) # Stage 1: investigate — SDK enforces _FINDINGS_SCHEMA and retries the # agent on mismatch, so `inv` is either a validated dict or None. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index ea5bab18..60f72ee3 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -297,6 +297,10 @@ def emit_metrics( cfg = llm.gateway_cfg() if cfg: tail["gateway_cfg"] = cfg + if not llm._send_strict_mcp: + # An inner CLI refused --strict-mcp-config (a machine with a + # managed-mcp.json) and the review was started again without it. + tail["strict_mcp_off"] = 1 tail.update(_TAIL_METRICS) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py index 3e2aa86c..3b9521ff 100644 --- a/plugins/security-guidance/tests/test_reviewer_tools.py +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -1,6 +1,8 @@ """The inner Claude Code the plugin starts for a review gets only the tools the review needs.""" +import json import sys +import threading import types import pytest @@ -9,11 +11,22 @@ import llm READ_ONLY = {"tools": "Read,Grep,Glob", "strict-mcp-config": None} NO_TOOLS = {"tools": "", "strict-mcp-config": None} +# Once an inner CLI has refused --strict-mcp-config. +READ_ONLY_NO_MCP = {"tools": "Read,Grep,Glob", "disallowedTools": "mcp__*"} +NO_TOOLS_NO_MCP = {"tools": "", "disallowedTools": "mcp__*"} + + +@pytest.fixture(autouse=True) +def strict_mcp_flag_sent(monkeypatch): + monkeypatch.setattr(llm, "_send_strict_mcp", True) def test_tool_flags(): assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY assert llm._only_tools_args() == NO_TOOLS + llm._send_strict_mcp = False + assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY_NO_MCP + assert llm._only_tools_args() == NO_TOOLS_NO_MCP def test_flags_reach_the_command_line_of_the_installed_sdk(): @@ -26,6 +39,16 @@ def test_flags_reach_the_command_line_of_the_installed_sdk(): cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command() assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob" assert cmd.count("--tools") == 1 and "--strict-mcp-config" in cmd + assert "--disallowedTools" not in cmd + + llm._send_strict_mcp = False + opts = sdk.ClaudeAgentOptions( + cli_path="claude", allowed_tools=["Read", "Grep", "Glob"], + extra_args=llm._only_tools_args(llm._REVIEWER_TOOLS)) + cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command() + assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob" + assert cmd[cmd.index("--disallowedTools") + 1] == "mcp__*" + assert cmd.count("--disallowedTools") == 1 and "--strict-mcp-config" not in cmd @pytest.fixture @@ -82,3 +105,103 @@ def test_single_turn_sdk_review_gets_no_tools(sdk): assert llm._call_claude_via_sdk("review this", schema) is not None assert len(sdk) == 1 assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == [] + + +# What Claude Code prints, before exiting 1, on a machine whose administrator +# delivers the MCP servers. +REFUSAL = "You cannot use --strict-mcp-config when an enterprise MCP config is present" + + +@pytest.fixture +def managed_mcp(sdk, monkeypatch): + """The stand-in SDK's inner CLI now refuses --strict-mcp-config. Gives + the options of the refused starts and of the ones that ran.""" + answer = sys.modules["claude_agent_sdk"].query + refused = [] + + async def query(prompt, options): + if "strict-mcp-config" in options.kwargs["extra_args"]: + refused.append(options.kwargs) + options.kwargs["stderr"](REFUSAL) + raise RuntimeError("Command failed with exit code 1") + async for msg in answer(prompt, options): + yield msg + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + return refused, sdk + + +def test_agentic_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp, tmp_path): + _, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert len(vulns) == 1 + # The refused start's line is not what child_stderr is there to count. + assert "agentic_fallback" not in metrics and "child_stderr" not in metrics + refused, ran = managed_mcp + assert [o["extra_args"] for o in refused] == [READ_ONLY] + # investigate, second investigate pass, refute + assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3 + for opts in ran: + assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] + + +def test_single_turn_sdk_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp): + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema) is not None + refused, ran = managed_mcp + assert [o["extra_args"] for o in refused] == [NO_TOOLS] + assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] + # The refusal is remembered for the rest of the hook process. + assert llm._call_claude_via_sdk("review this", schema) is not None + assert len(refused) == 1 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP + + +def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path): + async def query(prompt, options): + sdk.append(options.kwargs) + options.kwargs["stderr"]("Fallback model cannot be the same as the main model") + raise RuntimeError("Command failed with exit code 1") + yield + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + guidance, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert guidance is None and vulns == [] + assert metrics["agentic_fallback"] == "investigate:RuntimeError" + assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None + assert [o["extra_args"] for o in sdk] == [READ_ONLY, NO_TOOLS] + + +def test_reviews_started_together_are_each_started_again(managed_mcp): + refused, ran = managed_mcp + both_refused = threading.Barrier(2, timeout=10) + refuse = sys.modules["claude_agent_sdk"].query + + async def query(prompt, options): + if "strict-mcp-config" in options.kwargs["extra_args"]: + both_refused.wait() + async for msg in refuse(prompt, options): + yield msg + + sys.modules["claude_agent_sdk"].query = query + schema = {"type": "object", "properties": {}} + results = [] + threads = [threading.Thread( + target=lambda: results.append(llm._call_claude_via_sdk("review this", schema))) + for _ in range(2)] + for t in threads: + t.start() + for t in threads: + t.join(20) + assert len(results) == 2 and None not in results + assert len(refused) == 2 and [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] * 2 + + +def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys): + import security_reminder_hook as hook + + def row(): + hook.emit_metrics({"vulns_found": 0, "review_ms": 10}) + return json.loads(capsys.readouterr().out)["metrics"] + + assert "strict_mcp_off" not in row() + assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is not None + assert row()["strict_mcp_off"] == 1 |
