mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
By the maintainer's decision of 2026-11-25, recorded in the handover: "McpServer.handle catches Exception only, so a missing scan path raises SystemExit through it and ends the stdio loop; openultrasast.scan and openultrasast.benchmark both take that path. One bad call would become an error result for that call and the server would stay up." `McpServer.handle` in src/openultrasast/mcp.py catches `SystemExit` beside `Exception` and answers with the error it already builds for any exception a tool raises: `-32603` with `SystemExit: scan path is not a directory: <path>`. The stdio loop reads on, answers the next request and exits 0 at EOF; before, the process exited 1 with that message on stderr and nothing on stdout. `openultrasast.benchmark` takes the same clause when the manifest names a source path that does not exist. No other path changes: the notification return comes before the `try`, a line that does not parse is answered in `serve`, and `cli.py:588` is the only `SystemExit` a tool handler can reach (the independent reviewer's trace), raised before the configuration is loaded and before a run directory is created. "Error result" is read as that JSON-RPC error: the decision names `handle`, and the handover keeps this channel apart from `isError: true`, which `_call_tool` builds for `McpToolError`. A missing path therefore travels a different channel from a missing `path` argument or an unsupported mode; that is left for the maintainer's menu, with one pre-existing gap the reviewer found: a line that is valid JSON but not an object still ends the loop. Tests: through `serve`, a tools/call for `openultrasast.scan` with a missing path followed by a ping gives the error object and then the ping result, and `serve` returns 0; through `handle`, the same call gives that error object. Both failed on the code as it was, each with the `SystemExit` raised through the function it calls (the first in my run, the second in the reviewer's, on a copy of the code before the change); the second pins that the catch sits in `handle`, the public dispatch, where a catch in `serve` alone passes the first. The 23 test files around the scan path and the MCP server pass (242 passed before the second test was added, and `tests/test_mcp.py` 18 passed after); ruff, mypy, the three gates and compileall pass, and the gates print what they printed before the change. The real `ousast mcp` process, fed the same two lines, answered both and exited 0 with an empty stderr. An independent reviewer approved the change in one round and proposed the second test.
267 lines
11 KiB
Python
267 lines
11 KiB
Python
"""Narrow MCP server: tool listing, scan→status flow, and surface safety (Phase 12)."""
|
|
|
|
import errno
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from test_run_pruning import _default_cache, _earlier_run, _refuse_removal
|
|
|
|
from openultrasast.mcp import McpServer, serve
|
|
|
|
EXPECTED_TOOLS = {
|
|
"openultrasast.scan",
|
|
"openultrasast.status",
|
|
"openultrasast.findings",
|
|
"openultrasast.get_finding",
|
|
"openultrasast.evidence",
|
|
"openultrasast.artifacts",
|
|
"openultrasast.benchmark",
|
|
"openultrasast.explain",
|
|
"openultrasast.propose_patch",
|
|
"openultrasast.export_report",
|
|
}
|
|
|
|
|
|
def _call(server: McpServer, name: str, arguments: dict) -> dict:
|
|
response = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
|
|
assert response is not None
|
|
result = response["result"]
|
|
payload = json.loads(result["content"][0]["text"]) if not result["isError"] else {"error": result["content"][0]["text"]}
|
|
return {"isError": result["isError"], **payload}
|
|
|
|
|
|
# ---- protocol + tool listing ------------------------------------------------
|
|
|
|
|
|
def test_initialize_returns_server_info() -> None:
|
|
server = McpServer()
|
|
response = server.handle({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {}})
|
|
assert response is not None
|
|
assert response["result"]["serverInfo"]["name"] == "openultrasast"
|
|
assert "protocolVersion" in response["result"]
|
|
|
|
|
|
def test_tools_list_is_exactly_the_narrow_surface() -> None:
|
|
server = McpServer()
|
|
response = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}})
|
|
assert response is not None
|
|
names = {tool["name"] for tool in response["result"]["tools"]}
|
|
assert names == EXPECTED_TOOLS
|
|
|
|
|
|
def test_surface_exposes_no_shell_or_exec_tool() -> None:
|
|
# The narrow surface must never expose arbitrary shell/exec/docker tools.
|
|
server = McpServer()
|
|
forbidden = ("shell", "exec", "command", "docker", "run_command", "bash")
|
|
for name in server.tool_names:
|
|
assert not any(token in name.lower() for token in forbidden), name
|
|
for tool in McpServer()._tools.values(): # no tool accepts a free-form command argument
|
|
properties = tool.input_schema.get("properties", {})
|
|
assert "command" not in properties
|
|
assert "shell" not in properties
|
|
assert "docker" not in properties
|
|
|
|
|
|
def test_scan_rejects_deep_and_keeps_cli_only_modes() -> None:
|
|
server = McpServer()
|
|
listed = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}})
|
|
assert listed is not None
|
|
scan_tool = next(tool for tool in listed["result"]["tools"] if tool["name"] == "openultrasast.scan")
|
|
mode_enum = scan_tool["inputSchema"]["properties"]["mode"]["enum"]
|
|
assert mode_enum == ["quick", "standard"]
|
|
assert "deep" not in mode_enum
|
|
|
|
result = _call(server, "openultrasast.scan", {"path": ".", "mode": "deep"})
|
|
assert result["isError"]
|
|
assert "deep" in result["error"]
|
|
|
|
|
|
def test_notifications_get_no_response() -> None:
|
|
server = McpServer()
|
|
assert server.handle({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None
|
|
|
|
|
|
def test_unknown_method_returns_jsonrpc_error() -> None:
|
|
server = McpServer()
|
|
response = server.handle({"jsonrpc": "2.0", "id": 9, "method": "does/not/exist"})
|
|
assert response is not None and response["error"]["code"] == -32602
|
|
|
|
|
|
# ---- scan -> status -> findings -> explain flow -----------------------------
|
|
|
|
|
|
def _repo(tmp_path: Path) -> Path:
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
|
|
return repo
|
|
|
|
|
|
def test_scan_then_status_and_findings(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
|
|
server = McpServer()
|
|
|
|
scan = _call(server, "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
|
assert not scan["isError"] and scan["scan_id"]
|
|
assert scan["notices"] == [] # a run root of its own is never pruned, so the scan has nothing to say
|
|
run_dir = scan["run_dir"]
|
|
|
|
status = _call(server, "openultrasast.status", {"run_dir": run_dir})
|
|
assert status["finding_count"] == scan["finding_count"]
|
|
|
|
findings = _call(server, "openultrasast.findings", {"run_dir": run_dir})
|
|
assert findings["count"] == scan["finding_count"]
|
|
finding_id = findings["findings"][0]["finding_id"]
|
|
|
|
explain = _call(server, "openultrasast.explain", {"run_dir": run_dir, "finding_id": finding_id})
|
|
assert explain["finding_id"] == finding_id and explain["severity"]
|
|
|
|
evidence = _call(server, "openultrasast.evidence", {"run_dir": run_dir, "finding_id": finding_id})
|
|
assert "reachability_status" in evidence
|
|
|
|
|
|
def test_propose_patch_degrades_visibly(tmp_path: Path) -> None:
|
|
server = McpServer()
|
|
result = _call(server, "openultrasast.propose_patch", {"run_dir": str(tmp_path), "finding_id": "x"})
|
|
assert result["status"] == "not_implemented"
|
|
|
|
|
|
def test_missing_required_argument_is_a_tool_error() -> None:
|
|
server = McpServer()
|
|
result = _call(server, "openultrasast.status", {})
|
|
assert result["isError"] and "run_dir" in result["error"]
|
|
|
|
|
|
def test_export_report_returns_markdown(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
|
|
server = McpServer()
|
|
scan = _call(server, "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
|
report = _call(server, "openultrasast.export_report", {"run_dir": scan["run_dir"], "format": "markdown"})
|
|
assert report["format"] == "markdown" and report["content"]
|
|
|
|
|
|
def test_scan_result_carries_the_notice_of_the_runs_the_scan_removed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
runs = _default_cache(tmp_path, monkeypatch)
|
|
expired = _earlier_run(runs, 40)
|
|
|
|
result = _call(McpServer(), "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
|
|
|
assert not result["isError"]
|
|
assert result["notices"] == [f"removed 1 run older than 30 days from {runs}"]
|
|
assert not expired.exists()
|
|
|
|
|
|
def test_scan_result_carries_the_notice_of_a_removal_that_was_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
runs = _default_cache(tmp_path, monkeypatch)
|
|
expired = _earlier_run(runs, 40)
|
|
refusal = PermissionError(errno.EACCES, "Permission denied", str(expired))
|
|
_refuse_removal(monkeypatch, expired, refusal)
|
|
|
|
result = _call(McpServer(), "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
|
|
|
assert result["exit_code"] == 0
|
|
assert result["notices"] == [f"old runs could not be removed from {runs}: {refusal}"]
|
|
|
|
|
|
def test_benchmark_result_carries_the_notice_of_the_runs_the_scan_removed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
runs = _default_cache(tmp_path, monkeypatch)
|
|
_repo(tmp_path)
|
|
_earlier_run(runs, 40)
|
|
manifest = tmp_path / "benchmark.toml"
|
|
manifest.write_text('name = "py-smoke"\nlanguage = "python"\n\n[source]\npath = "repo"\n')
|
|
|
|
result = _call(McpServer(), "openultrasast.benchmark", {"manifest": str(manifest), "mode": "quick"})
|
|
|
|
assert not result["isError"]
|
|
assert result["notices"] == [f"removed 1 run older than 30 days from {runs}"]
|
|
|
|
|
|
def test_a_benchmark_run_sits_beside_the_scan_runs_not_in_the_scanned_tree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
runs = _default_cache(tmp_path, monkeypatch)
|
|
repo = _repo(tmp_path)
|
|
manifest = tmp_path / "benchmark.toml"
|
|
manifest.write_text('name = "py-smoke"\nlanguage = "python"\n\n[source]\npath = "repo"\n')
|
|
|
|
result = _call(McpServer(), "openultrasast.benchmark", {"manifest": str(manifest), "mode": "quick"})
|
|
|
|
assert not result["isError"]
|
|
benchmark_run = runs / result["benchmark_run_id"]
|
|
assert benchmark_run.is_dir()
|
|
assert any((path / "manifest.json").is_file() for path in runs.iterdir() if path != benchmark_run)
|
|
assert not (repo / ".openultrasast" / "benchmarks").exists()
|
|
|
|
|
|
# ---- stdio loop -------------------------------------------------------------
|
|
|
|
|
|
def test_serve_stdio_loop_handles_tools_list() -> None:
|
|
stdin = io.StringIO(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + "\n")
|
|
stdout = io.StringIO()
|
|
assert serve(stdin, stdout) == 0
|
|
response = json.loads(stdout.getvalue().strip())
|
|
assert {tool["name"] for tool in response["result"]["tools"]} == EXPECTED_TOOLS
|
|
|
|
|
|
def test_serve_stdio_loop_survives_a_tool_that_stops_the_cli(tmp_path: Path) -> None:
|
|
"""A tool can stop the CLI (`_run_scan` on a missing scan path); the loop answers that call and reads on."""
|
|
scan = {"name": "openultrasast.scan", "arguments": {"path": str(tmp_path / "missing")}}
|
|
requests = [
|
|
{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": scan},
|
|
{"jsonrpc": "2.0", "id": 2, "method": "ping"},
|
|
]
|
|
stdin = io.StringIO("".join(json.dumps(request) + "\n" for request in requests))
|
|
stdout = io.StringIO()
|
|
|
|
assert serve(stdin, stdout) == 0
|
|
|
|
failed, pong = (json.loads(line) for line in stdout.getvalue().splitlines())
|
|
assert failed == {
|
|
"jsonrpc": "2.0",
|
|
"id": 1,
|
|
"error": {"code": -32603, "message": f"SystemExit: scan path is not a directory: {tmp_path / 'missing'}"},
|
|
}
|
|
assert pong == {"jsonrpc": "2.0", "id": 2, "result": {}}
|
|
|
|
|
|
def test_handle_answers_a_tool_that_stops_the_cli_with_an_error(tmp_path: Path) -> None:
|
|
"""The catch lives in `handle`, the public dispatch; `serve` is not its only possible caller."""
|
|
scan = {"name": "openultrasast.scan", "arguments": {"path": str(tmp_path / "missing")}}
|
|
server = McpServer()
|
|
|
|
response = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": scan})
|
|
|
|
assert response == {
|
|
"jsonrpc": "2.0",
|
|
"id": 1,
|
|
"error": {"code": -32603, "message": f"SystemExit: scan path is not a directory: {tmp_path / 'missing'}"},
|
|
}
|
|
|
|
|
|
def test_the_findings_list_carries_the_rung_and_leads_with_what_was_decided(tmp_path: Path) -> None:
|
|
"""The final objective is an LLM diving in without re-deriving the reasoning.
|
|
|
|
Without the rung a caller cannot tell the finding the graph DECIDED from the ones an enumerator merely
|
|
proposed: libpng returned 198 rows of which one was entailed, and finding it would have meant fetching
|
|
all 198 individually. The evidence itself stays on `get_finding`; what the list owes is triage.
|
|
"""
|
|
run = tmp_path / "run"
|
|
run.mkdir()
|
|
(run / "findings.json").write_text(
|
|
json.dumps(
|
|
{
|
|
"findings": [
|
|
{"finding_id": "b", "path": "z.c", "line": 9, "severity": "low", "title": "noise", "rung": "suspicion"},
|
|
{"finding_id": "a", "path": "a.py", "line": 73, "severity": "high", "title": "sqli", "rung": "model_entailed"},
|
|
]
|
|
}
|
|
)
|
|
)
|
|
|
|
result = _call(McpServer(), "openultrasast.findings", {"run_dir": str(run)})
|
|
|
|
assert [item["finding_id"] for item in result["findings"]] == ["a", "b"], "decided first"
|
|
assert result["findings"][0]["rung"] == "model_entailed"
|
|
assert result["by_rung"] == {"model_entailed": 1, "suspicion": 1}
|