Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(cli): add aisoc serve / db upgrade / mcp serve|install (#110)
Beenu Arora8e1649232f66
diff --git a/packages/aisoc-cli/src/aisoc_cli/main.py b/packages/aisoc-cli/src/aisoc_cli/main.pyindex ddbfb8c24..0bf1a0ada 100644--- a/packages/aisoc-cli/src/aisoc_cli/main.py+++ b/packages/aisoc-cli/src/aisoc_cli/main.py@@ -1,5 +1,5 @@"""-AiSOC CLI — scaffold, validate, and publish plugins and detections.+AiSOC CLI — scaffold, validate, publish, and operate.Commands:aisoc plugin new <name> Scaffold a typed plugin from disk templates@@ -8,11 +8,18 @@ Commands:aisoc plugin publish [path] Sign with Ed25519 key + POST to AiSOC APIaisoc detection validate <file> Validate Sigma rule syntaxaisoc keygen Generate an Ed25519 signing key pair+ aisoc serve [--detach] Start the dev stack via docker compose+ aisoc db upgrade Run database migrations against the dev stack+ aisoc mcp serve [--transport] Launch the MCP server for IDE assistants+ aisoc mcp install --host <h> Wire AiSOC into Claude / Cursor / Continue"""from __future__ import annotationsimport base64import json+import os+import shutil+import subprocessimport sysfrom importlib import resourcesfrom pathlib import Path@@ -456,5 +463,245 @@ def _basic_sigma_validate(rule_path: Path) -> None:console.print("[yellow]Install sigma-cli for full validation: pip install sigma-cli[/yellow]")+# ── Repo / compose helpers ────────────────────────────────────────────────────++def _find_repo_root(start: Path | None = None) -> Path:+ """Walk up from ``start`` (default: cwd) looking for a docker-compose root.++ A repo root here is any directory containing either ``docker-compose.yml``+ or ``docker-compose.dev.yml``. Falls back to the current working directory+ if no match is found, so the underlying ``docker compose`` invocation can+ still produce a sensible error message.+ """+ current = (start or Path.cwd()).resolve()+ for candidate in [current, *current.parents]:+ if (candidate / "docker-compose.yml").exists() or (+ candidate / "docker-compose.dev.yml"+ ).exists():+ return candidate+ return current+++def _compose_file_arg(repo_root: Path) -> list[str]:+ """Pick the right ``-f`` arg for docker compose.++ Prefers ``docker-compose.dev.yml`` (the dev-aliased entry point) when+ present, otherwise falls back to the base ``docker-compose.yml``.+ """+ dev = repo_root / "docker-compose.dev.yml"+ if dev.exists():+ return ["-f", str(dev)]+ return ["-f", str(repo_root / "docker-compose.yml")]+++def _require_docker() -> None:+ """Hard-fail with a friendly message if docker is not on PATH."""+ if shutil.which("docker") is None:+ console.print(+ "[red bold]docker not found on PATH[/red bold]\n\n"+ "Install Docker Desktop or Docker Engine, then retry. See:\n"+ " https://docs.docker.com/engine/install/"+ )+ sys.exit(1)+++# ── serve command ─────────────────────────────────────────────────────────────++ "--detach/--no-detach",+ "detach",+ default=True,+ show_default=True,+ help="Run docker compose up in detached mode (default: detached).",+)+ "--build/--no-build",+ "build",+ default=False,+ show_default=True,+ help="Force a rebuild of changed images before starting.",+)+def serve(detach: bool, build: bool) -> None:+ """Start the AiSOC dev stack via docker compose.++ Resolves the closest docker-compose root walking up from the cwd, prefers+ ``docker-compose.dev.yml`` if it exists, and shells out to+ ``docker compose -f <file> up``. Treat this as the founder-style+ one-liner equivalent of the documented ``docker compose up -d``.+ """+ _require_docker()+ repo_root = _find_repo_root()+ cmd = ["docker", "compose", *_compose_file_arg(repo_root), "up"]+ if detach:+ cmd.append("-d")+ if build:+ cmd.append("--build")++ console.print(+ Panel(+ f"[bold]cwd:[/bold] {repo_root}\n"+ f"[bold]cmd:[/bold] {' '.join(cmd)}",+ title="[bold green]aisoc serve[/bold green]",+ )+ )+ result = subprocess.run(cmd, cwd=str(repo_root))+ if result.returncode != 0:+ sys.exit(result.returncode)+++# ── db group ──────────────────────────────────────────────────────────────────++def db() -> None:+ """Database lifecycle commands."""++[email protected]("upgrade")+ "--service",+ default="api",+ show_default=True,+ help="docker compose service that owns the migrations.",+)+def db_upgrade(service: str) -> None:+ """Apply pending SQL migrations against the running dev stack.++ Delegates to ``docker compose exec <service> python -m+ app.scripts.run_migrations``, which is the custom forward-only migration+ runner under ``services/api``. Requires the stack to already be up+ (``aisoc serve``).+ """+ _require_docker()+ repo_root = _find_repo_root()+ cmd = [+ "docker",+ "compose",+ *_compose_file_arg(repo_root),+ "exec",+ "-T",+ service,+ "python",+ "-m",+ "app.scripts.run_migrations",+ ]+ console.print(+ Panel(+ f"[bold]cwd:[/bold] {repo_root}\n"+ f"[bold]cmd:[/bold] {' '.join(cmd)}",+ title="[bold green]aisoc db upgrade[/bold green]",+ )+ )+ result = subprocess.run(cmd, cwd=str(repo_root))+ if result.returncode != 0:+ console.print(+ "[yellow]If the stack is not up yet, run [bold]aisoc serve[/bold] "+ "first, then re-run this command.[/yellow]"+ )+ sys.exit(result.returncode)+++# ── mcp group ─────────────────────────────────────────────────────────────────++def mcp() -> None:+ """Model Context Protocol (MCP) commands."""+++def _resolve_mcp_entry(repo_root: Path) -> tuple[list[str], str] | None:+ """Return (argv, label) for invoking the local MCP build, or None.++ Looks for a built ``services/mcp/dist/index.js`` next to ``package.json``.+ Returns None if the build artifact is missing, so callers can fall back to+ ``npx @aisoc/mcp``.+ """+ dist = repo_root / "services" / "mcp" / "dist" / "index.js"+ if dist.exists():+ node = shutil.which("node") or "node"+ return [node, str(dist)], f"node {dist.relative_to(repo_root)}"+ return None+++def _mcp_argv(repo_root: Path, subcommand: str, extra: list[str]) -> tuple[list[str], str]:+ """Build the argv for an MCP subcommand, preferring local dist over npx."""+ local = _resolve_mcp_entry(repo_root)+ if local is not None:+ argv, label = local+ return [*argv, subcommand, *extra], f"{label} {subcommand} {' '.join(extra)}".strip()++ npx = shutil.which("npx") or "npx"+ return (+ [npx, "@aisoc/mcp", subcommand, *extra],+ f"npx @aisoc/mcp {subcommand} {' '.join(extra)}".strip(),+ )++[email protected]("serve")+ "--transport",+ type=click.Choice(["stdio", "http"]),+ default="stdio",+ show_default=True,+ help="MCP transport (stdio for IDE assistants, http for remote agents).",+)+ "--port",+ type=int,+ default=None,+ help="Port for the http transport (ignored when --transport=stdio).",+)+def mcp_serve(transport: str, port: int | None) -> None:+ """Launch the MCP server that exposes AiSOC to IDE assistants.++ Prefers the locally built ``services/mcp/dist/index.js`` (from+ ``pnpm --filter @aisoc/mcp build``). Falls back to ``npx @aisoc/mcp``+ when no local build is available.+ """+ repo_root = _find_repo_root()+ extra: list[str] = ["--transport", transport]+ if transport == "http" and port is not None:+ extra.extend(["--port", str(port)])++ argv, label = _mcp_argv(repo_root, "serve", extra)+ console.print(+ Panel(+ f"[bold]cwd:[/bold] {repo_root}\n"+ f"[bold]cmd:[/bold] {label}",+ title="[bold green]aisoc mcp serve[/bold green]",+ )+ )+ # Replace this process with node so stdio is fully transparent — required+ # for IDE assistants that pipe MCP frames over stdin/stdout.+ os.execvp(argv[0], argv)++[email protected]("install")+ "--host",+ type=click.Choice(["claude", "cursor", "continue", "cody"]),+ required=True,+ help="IDE assistant to wire AiSOC into.",+)+def mcp_install(host: str) -> None:+ """Register the AiSOC MCP server with the given IDE assistant.++ Thin wrapper over ``aisoc-mcp install --host <host>`` that picks the local+ dist build when available and falls back to ``npx @aisoc/mcp`` otherwise.+ """+ repo_root = _find_repo_root()+ argv, label = _mcp_argv(repo_root, "install", ["--host", host])++ console.print(+ Panel(+ f"[bold]cwd:[/bold] {repo_root}\n"+ f"[bold]cmd:[/bold] {label}",+ title="[bold green]aisoc mcp install[/bold green]",+ )+ )+ result = subprocess.run(argv, cwd=str(repo_root))+ if result.returncode != 0:+ sys.exit(result.returncode)++if __name__ == "__main__":cli()diff --git a/packages/aisoc-cli/tests/test_ops_commands.py b/packages/aisoc-cli/tests/test_ops_commands.pynew file mode 100644index 000000000..9fa91fbbd--- /dev/null+++ b/packages/aisoc-cli/tests/test_ops_commands.py@@ -0,0 +1,276 @@+"""CLI surface tests for the operator subcommands (serve, db, mcp).++These commands shell out to long-running processes (``docker compose``,+``node services/mcp/dist/index.js``) so we don't actually execute them.+Instead we verify:++* The new subcommands are registered on the ``cli`` group and discoverable+ via ``--help``.+* They construct the right argv before delegating to ``subprocess.run`` or+ ``os.execvp``, so the demo script stays a thin shell over docker compose+ and the MCP node binary.++If these tests break, the founder-style quickstart in the video script will+desync from the CLI — that's exactly the regression we want to catch.+"""+from __future__ import annotations++from pathlib import Path++import pytest+from click.testing import CliRunner++from aisoc_cli import main as cli_main+from aisoc_cli.main import cli+++def runner() -> CliRunner:+ return CliRunner()+++def fake_repo(tmp_path: Path) -> Path:+ """A minimal repo root with both compose files and a built MCP dist."""+ (tmp_path / "docker-compose.yml").write_text("services: {}\n")+ (tmp_path / "docker-compose.dev.yml").write_text(+ "include:\n - path: docker-compose.yml\n"+ )+ mcp_dist = tmp_path / "services" / "mcp" / "dist"+ mcp_dist.mkdir(parents=True)+ (mcp_dist / "index.js").write_text("#!/usr/bin/env node\n")+ return tmp_path+++# ── help / discovery ──────────────────────────────────────────────────────────++def test_top_level_help_lists_new_groups(runner: CliRunner) -> None:+ result = runner.invoke(cli, ["--help"])+ assert result.exit_code == 0, result.output+ # All four entrypoints must surface under `aisoc --help`.+ assert "serve" in result.output+ assert "db" in result.output+ assert "mcp" in result.output+++def test_db_group_lists_upgrade(runner: CliRunner) -> None:+ result = runner.invoke(cli, ["db", "--help"])+ assert result.exit_code == 0, result.output+ assert "upgrade" in result.output+++def test_mcp_group_lists_serve_and_install(runner: CliRunner) -> None:+ result = runner.invoke(cli, ["mcp", "--help"])+ assert result.exit_code == 0, result.output+ assert "serve" in result.output+ assert "install" in result.output+++# ── serve ─────────────────────────────────────────────────────────────────────++def test_serve_invokes_docker_compose_up(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, fake_repo: Path+) -> None:+ """``aisoc serve`` shells out to ``docker compose -f <file> up -d``."""+ captured: dict[str, object] = {}++ def fake_run(cmd: list[str], cwd: str | None = None, **_: object):+ captured["cmd"] = cmd+ captured["cwd"] = cwd++ class _Result:+ returncode = 0++ return _Result()++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: "/usr/bin/docker")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: fake_repo)+ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)++ result = runner.invoke(cli, ["serve"])+ assert result.exit_code == 0, result.output++ cmd = captured["cmd"]+ assert cmd[:2] == ["docker", "compose"]+ assert "-f" in cmd+ assert "docker-compose.dev.yml" in " ".join(cmd)+ assert cmd[-2:] == ["up", "-d"]+ assert captured["cwd"] == str(fake_repo)+++def test_serve_no_detach_drops_minus_d(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, fake_repo: Path+) -> None:+ captured: dict[str, object] = {}++ def fake_run(cmd: list[str], cwd: str | None = None, **_: object):+ captured["cmd"] = cmd++ class _Result:+ returncode = 0++ return _Result()++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: "/usr/bin/docker")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: fake_repo)+ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)++ result = runner.invoke(cli, ["serve", "--no-detach"])+ assert result.exit_code == 0, result.output+ cmd = captured["cmd"]+ assert cmd[-1] == "up"+ assert "-d" not in cmd+++def test_serve_fails_without_docker(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner+) -> None:+ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: None)+ result = runner.invoke(cli, ["serve"])+ assert result.exit_code != 0+ assert "docker not found" in result.output.lower()+++# ── db upgrade ────────────────────────────────────────────────────────────────++def test_db_upgrade_invokes_run_migrations(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, fake_repo: Path+) -> None:+ """``aisoc db upgrade`` execs the custom forward-only migration runner."""+ captured: dict[str, object] = {}++ def fake_run(cmd: list[str], cwd: str | None = None, **_: object):+ captured["cmd"] = cmd++ class _Result:+ returncode = 0++ return _Result()++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: "/usr/bin/docker")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: fake_repo)+ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)++ result = runner.invoke(cli, ["db", "upgrade"])+ assert result.exit_code == 0, result.output++ cmd = captured["cmd"]+ # docker compose -f <file> exec -T api python -m app.scripts.run_migrations+ assert cmd[:2] == ["docker", "compose"]+ assert "exec" in cmd+ assert "-T" in cmd+ assert "api" in cmd+ assert cmd[-3:] == ["-m", "app.scripts.run_migrations"][-3:] or cmd[-2:] == [+ "-m",+ "app.scripts.run_migrations",+ ]+ # Final form: python -m app.scripts.run_migrations+ assert "python" in cmd+ assert "app.scripts.run_migrations" in cmd+++def test_db_upgrade_non_zero_exits_with_hint(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, fake_repo: Path+) -> None:+ def fake_run(cmd: list[str], cwd: str | None = None, **_: object):+ class _Result:+ returncode = 1++ return _Result()++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: "/usr/bin/docker")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: fake_repo)+ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)++ result = runner.invoke(cli, ["db", "upgrade"])+ assert result.exit_code == 1+ assert "aisoc serve" in result.output+++# ── mcp serve ─────────────────────────────────────────────────────────────────++def test_mcp_serve_uses_local_dist(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, fake_repo: Path+) -> None:+ """When ``services/mcp/dist/index.js`` exists, we exec node on it."""+ captured: dict[str, object] = {}++ def fake_execvp(file: str, args: list[str]) -> None:+ captured["file"] = file+ captured["args"] = args+ # os.execvp would replace the process; in tests we just need to stop.+ raise SystemExit(0)++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: "/usr/bin/node")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: fake_repo)+ monkeypatch.setattr(cli_main.os, "execvp", fake_execvp)++ result = runner.invoke(cli, ["mcp", "serve", "--transport", "stdio"])+ assert result.exit_code == 0, result.output++ args = captured["args"]+ assert args[0] == "/usr/bin/node"+ assert str(fake_repo / "services" / "mcp" / "dist" / "index.js") in args+ assert "serve" in args+ assert "--transport" in args+ assert "stdio" in args+++def test_mcp_serve_falls_back_to_npx(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path+) -> None:+ """When no dist build exists, the CLI uses ``npx @aisoc/mcp``."""+ # Build a repo root that has compose but no MCP dist.+ (tmp_path / "docker-compose.yml").write_text("services: {}\n")+ captured: dict[str, object] = {}++ def fake_execvp(file: str, args: list[str]) -> None:+ captured["args"] = args+ raise SystemExit(0)++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: f"/usr/bin/{_name}")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: tmp_path)+ monkeypatch.setattr(cli_main.os, "execvp", fake_execvp)++ result = runner.invoke(cli, ["mcp", "serve"])+ assert result.exit_code == 0, result.output++ args = captured["args"]+ assert args[0] == "/usr/bin/npx"+ assert "@aisoc/mcp" in args+ assert "serve" in args+++# ── mcp install ───────────────────────────────────────────────────────────────++def test_mcp_install_invokes_host(+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, fake_repo: Path+) -> None:+ captured: dict[str, object] = {}++ def fake_run(cmd: list[str], cwd: str | None = None, **_: object):+ captured["cmd"] = cmd++ class _Result:+ returncode = 0++ return _Result()++ monkeypatch.setattr(cli_main.shutil, "which", lambda _name: f"/usr/bin/{_name}")+ monkeypatch.setattr(cli_main, "_find_repo_root", lambda start=None: fake_repo)+ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)++ result = runner.invoke(cli, ["mcp", "install", "--host", "claude"])+ assert result.exit_code == 0, result.output++ cmd = captured["cmd"]+ assert "install" in cmd+ assert "--host" in cmd+ assert "claude" in cmd+++def test_mcp_install_rejects_unknown_host(runner: CliRunner) -> None:+ result = runner.invoke(cli, ["mcp", "install", "--host", "notahost"])+ assert result.exit_code != 0+ # Click writes invalid-choice errors to stderr/stdout.+ assert "notahost" in result.output or "Invalid value" in result.output