Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

feat(mcp): per-tenant tool grants, call approvals and the generated tool catalogue

Beenu Arora75293b1e13d7
diff --git a/scripts/check_mcp_over_http.py b/scripts/check_mcp_over_http.py
index 782e099b2..384928f99 100644
--- a/scripts/check_mcp_over_http.py
+++ b/scripts/check_mcp_over_http.py
@@ -62,8 +62,15 @@ hold for that to be safe, each one a thing that was wrong before:
Usage:
python3 scripts/check_mcp_over_http.py
+ python3 scripts/check_mcp_over_http.py --write-catalogue
python3 scripts/check_mcp_over_http.py --self-test
+``--write-catalogue`` regenerates the API's copy from the registry. It lives
+here, in the gate, rather than in a sibling generator so that the thing which
+*writes* the catalogue and the thing which *checks* it parse the registry with
+one reader. Two readers of one file is how a parity gate ends up agreeing with
+itself and not with the tree.
+
Exit codes: 0 clean, 1 findings.
"""
@@ -254,6 +261,39 @@ def violations(root: Path) -> list[str]:
return found
+def write_catalogue(root: Path) -> int:
+ """Regenerate ``mcp_tool_catalog.json`` from the TypeScript registry.
+
+ ``default_enabled`` is derived, never authored: a read-only tool is on
+ out of the box and anything that writes is off until a tenant says
+ otherwise. Deriving it means a new write tool cannot arrive switched on
+ because somebody copied the entry above it.
+ """
+ registry = _read_only_flags(_registry_sources(root))
+ exported = _tool_names_from_registry(_read(root, REGISTRY_MODULE) or "")
+ if exported:
+ registry = {k: v for k, v in registry.items() if k in exported}
+ if not registry:
+ print("check_mcp_over_http: no tools found in the registry — refusing to write an empty catalogue", file=sys.stderr)
+ return 1
+ payload = {
+ "_comment": (
+ "Generated by scripts/check_mcp_over_http.py --write-catalogue from "
+ "services/mcp/src/tools/. Do not hand-edit: the same script fails CI "
+ "when this file and the registry disagree."
+ ),
+ "tools": [
+ {"name": name, "read_only": registry[name], "default_enabled": registry[name]}
+ for name in sorted(registry)
+ ],
+ }
+ path = root / CATALOGUE
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ print(f"check_mcp_over_http: wrote {len(registry)} tool(s) to {CATALOGUE}")
+ return 0
+
+
def main() -> int:
root = repo_root()
if not (root / MCP_SRC).is_dir():
@@ -384,4 +424,6 @@ def _rule_self_test() -> list[tuple[str, bool]]:
if __name__ == "__main__":
if SELF_TEST_FLAG in sys.argv[1:]:
sys.exit(self_test_main(Path(__file__).name, extra=_rule_self_test()))
+ if "--write-catalogue" in sys.argv[1:]:
+ sys.exit(write_catalogue(repo_root()))
sys.exit(main())
diff --git a/services/api/app/data/mcp_tool_catalog.json b/services/api/app/data/mcp_tool_catalog.json
new file mode 100644
index 000000000..bb696638c
--- /dev/null
+++ b/services/api/app/data/mcp_tool_catalog.json
@@ -0,0 +1,100 @@
+{
+ "_comment": "Generated by scripts/check_mcp_over_http.py --write-catalogue from services/mcp/src/tools/. Do not hand-edit: the same script fails CI when this file and the registry disagree.",
+ "tools": [
+ {
+ "name": "aisoc_explain_step",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_get_alert",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_get_case",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_get_detection_rule",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_get_investigation",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_get_replay_report",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_get_triage_verdict",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_lake_query",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_lake_schema",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_list_actions",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_list_alerts",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_list_cases",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_list_investigations",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_list_replay_reports",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_preview_action",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_query_detections",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_replay_decision",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_run_hunt",
+ "read_only": true,
+ "default_enabled": true
+ },
+ {
+ "name": "aisoc_run_investigation",
+ "read_only": false,
+ "default_enabled": false
+ }
+ ]
+}
diff --git a/services/api/app/models/mcp_access.py b/services/api/app/models/mcp_access.py
new file mode 100644
index 000000000..8a5c2aeee
--- /dev/null
+++ b/services/api/app/models/mcp_access.py
@@ -0,0 +1,82 @@
+"""ORM models for the inbound MCP surface — tool grants and call approvals.
+
+Depth plan 9.1 (parity 6.6); migration ``104_mcp_access.sql`` carries the
+reasoning for each column.
+
+Not to be confused with :mod:`app.models.mcp_server`, which is the *outbound*
+registry: third-party MCP servers a tenant has told the agent it may call.
+These two tables are the inbound side — AiSOC's own MCP server, and who may
+reach into this deployment through it.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Text, UniqueConstraint
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+#: States an approval row can hold. ``consumed`` exists so an approval is
+#: spent by the call it authorised rather than standing open until it
+#: expires: a one-shot grant is what an approver believes they are giving.
+APPROVAL_STATES: tuple[str, ...] = ("pending", "approved", "denied", "consumed", "expired")
+
+
+class McpToolGrant(Base):
+ """One tenant's deliberate decision about one MCP tool.
+
+ Absence of a row is not a denial — it means the tool's catalogue default
+ applies. See the migration header.
+ """
+
+ __tablename__ = "aisoc_mcp_tool_grants"
+ __table_args__ = (UniqueConstraint("tenant_id", "tool_name", name="aisoc_mcp_tool_grants_unique"),)
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True
+ )
+ tool_name: Mapped[str] = mapped_column(Text, nullable=False)
+ enabled: Mapped[bool] = mapped_column(Boolean, nullable=False)
+ decided_by: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC)
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC)
+ )
+
+
+class McpToolApproval(Base):
+ """One non-read-only MCP tool call waiting on, or carrying, a human decision."""
+
+ __tablename__ = "aisoc_mcp_tool_approvals"
+ __table_args__ = (
+ CheckConstraint(
+ "state IN ('pending', 'approved', 'denied', 'consumed', 'expired')",
+ name="aisoc_mcp_tool_approvals_state_check",
+ ),
+ )
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True
+ )
+ tool_name: Mapped[str] = mapped_column(Text, nullable=False)
+ #: SHA-256 hex over the canonicalised arguments. A digest rather than the
+ #: arguments because those carry hostnames and queries and this row is
+ #: rendered in the console.
+ argument_fingerprint: Mapped[str] = mapped_column(Text, nullable=False)
+ requested_by: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ state: Mapped[str] = mapped_column(Text, nullable=False, default="pending")
+ decided_by: Mapped[str | None] = mapped_column(Text, nullable=True)
+ decided_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ decision_note: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC)
+ )
diff --git a/services/api/app/services/mcp_access.py b/services/api/app/services/mcp_access.py
new file mode 100644
index 000000000..090740955
--- /dev/null
+++ b/services/api/app/services/mcp_access.py
@@ -0,0 +1,301 @@
+"""Decide whether one MCP tool call may run, for one tenant, right now.
+
+Depth plan 9.1 (parity 6.6). ``services/mcp`` used to be a stdio child
+process holding one operator's API key. Over HTTP it is a shared process that
+several tenants reach with credentials of their own, so three questions have
+to be answered before a tool runs, and this module is the only place that
+answers them:
+
+1. **Does the credential carry the scope the tool needs?** The MCP process is
+ not the authority on that. It asks here, and here asks the same
+ ``require_permission`` path every console route uses.
+2. **Has the tenant turned this tool on?** A separate decision from (1),
+ owned by a different person: a key's scopes are what a credential may do,
+ a grant is what the estate has agreed an assistant reaches at all.
+3. **Is this a read?** Anything that is not gets a human in front of it.
+
+The tenant is never a parameter here. It is taken from the authenticated
+principal by the route and passed in as a resolved ``uuid.UUID``, which is
+the lesson from the outbound MCP surface: a tool that *declares* a
+``tenant_id`` and forwards it is a cross-tenant read waiting for a schema to
+stop being strict by accident.
+
+Catalogue, not a hand-written table
+-----------------------------------
+What a tool is called and whether it writes come from
+``app/data/mcp_tool_catalog.json``, generated from the TypeScript registry
+and held in parity with it by ``scripts/check_mcp_over_http.py``. Hand-keying
+that list here would let the authority and the thing it authorises drift, and
+the quiet direction of that drift -- this file not knowing a tool writes --
+is the one that costs something.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import json
+import uuid
+from collections.abc import Mapping
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.mcp_access import McpToolApproval, McpToolGrant
+
+CATALOGUE_PATH = Path(__file__).resolve().parent.parent / "data" / "mcp_tool_catalog.json"
+
+#: How long an approval stays usable once granted. Short on purpose: an
+#: approval is a decision about a call somebody is making now, not a standing
+#: permission, and an unbounded one would quietly become the latter.
+APPROVAL_TTL = timedelta(minutes=30)
+
+#: Which permission each tool needs. Keyed by tool, because the scope a tool
+#: needs is a property of what it reaches rather than of its name -- and a
+#: default of "any authenticated caller" would make the whole surface
+#: reachable with a key minted for one narrow job.
+TOOL_PERMISSIONS: dict[str, str] = {
+ "aisoc_list_alerts": "alerts:read",
+ "aisoc_get_alert": "alerts:read",
+ "aisoc_get_triage_verdict": "alerts:read",
+ "aisoc_list_cases": "cases:read",
+ "aisoc_get_case": "cases:read",
+ "aisoc_run_investigation": "cases:write",
+ "aisoc_query_detections": "rules:read",
+ "aisoc_get_detection_rule": "rules:read",
+ "aisoc_list_investigations": "cases:read",
+ "aisoc_get_investigation": "cases:read",
+ "aisoc_replay_decision": "cases:read",
+ "aisoc_explain_step": "cases:read",
+ "aisoc_list_replay_reports": "reports:read",
+ "aisoc_get_replay_report": "reports:read",
+ "aisoc_list_actions": "actions:read",
+ "aisoc_preview_action": "actions:execute",
+ "aisoc_lake_schema": "lake:read_schema",
+ "aisoc_lake_query": "lake:query",
+ "aisoc_run_hunt": "hunts:read",
+}
+
+
+@dataclass(frozen=True)
+class ToolSpec:
+ """One row of the generated catalogue."""
+
+ name: str
+ read_only: bool
+ default_enabled: bool
+
+ @property
+ def required_permission(self) -> str:
+ # A tool with no entry above is refused rather than defaulted: an
+ # unmapped tool is one nobody decided the authority for, and
+ # inventing one here is how a narrow key reaches a wide surface.
+ return TOOL_PERMISSIONS.get(self.name, "")
+
+
[email protected]_cache(maxsize=1)
+def tool_catalogue() -> dict[str, ToolSpec]:
+ """The generated catalogue, parsed once.
+
+ Cached because it is a committed file that cannot change inside a
+ process. Tests that need a different catalogue call ``.cache_clear()``.
+ """
+ raw = json.loads(CATALOGUE_PATH.read_text(encoding="utf-8"))
+ return {
+ entry["name"]: ToolSpec(
+ name=entry["name"],
+ read_only=bool(entry.get("read_only")),
+ default_enabled=bool(entry.get("default_enabled")),
+ )
+ for entry in raw.get("tools", [])
+ }
+
+
+def argument_fingerprint(arguments: Mapping[str, Any] | None) -> str:
+ """A stable digest of the arguments a call was made with.
+
+ An approval has to be for a call, not for a verb: approving "investigate
+ case A" must not authorise "investigate case B". Canonical JSON with
+ sorted keys so two clients that serialise in different orders produce the
+ same fingerprint for the same call.
+ """
+ payload = json.dumps(arguments or {}, sort_keys=True, separators=(",", ":"), default=str)
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
+
+
+@dataclass(frozen=True)
+class Decision:
+ """What the authorize route answers with."""
+
+ #: ``allow`` | ``deny`` | ``approval_required``
+ outcome: str
+ reason: str
+ #: Set when ``outcome`` is ``approval_required`` -- the row a human decides.
+ approval_id: uuid.UUID | None = None
+ required_permission: str = ""
+
+ @property
+ def allowed(self) -> bool:
+ return self.outcome == "allow"
+
+
+async def effective_tools(db: AsyncSession, tenant_id: uuid.UUID) -> list[dict[str, Any]]:
+ """Every catalogued tool with this tenant's effective enablement.
+
+ ``source`` says which decision produced the answer, because "on because
+ nobody has thought about it" and "on because somebody turned it on" are
+ different states and a console that renders them identically invites the
+ operator to assume the second.
+ """
+ rows = (await db.execute(select(McpToolGrant).where(McpToolGrant.tenant_id == tenant_id))).scalars().all()
+ grants = {row.tool_name: row for row in rows}
+ out: list[dict[str, Any]] = []
+ for spec in sorted(tool_catalogue().values(), key=lambda s: s.name):
+ grant = grants.get(spec.name)
+ out.append(
+ {
+ "name": spec.name,
+ "read_only": spec.read_only,
+ "enabled": grant.enabled if grant is not None else spec.default_enabled,
+ "source": "tenant" if grant is not None else "default",
+ "required_permission": spec.required_permission,
+ "requires_approval": not spec.read_only,
+ "decided_by": grant.decided_by if grant is not None else "",
+ }
+ )
+ return out
+
+
+async def _live_approval(
+ db: AsyncSession, tenant_id: uuid.UUID, tool_name: str, fingerprint: str
+) -> McpToolApproval | None:
+ """An approved, unexpired, unspent approval for exactly this call."""
+ now = datetime.now(UTC)
+ stmt = (
+ select(McpToolApproval)
+ .where(
+ McpToolApproval.tenant_id == tenant_id,
+ McpToolApproval.tool_name == tool_name,
+ McpToolApproval.argument_fingerprint == fingerprint,
+ McpToolApproval.state == "approved",
+ McpToolApproval.expires_at > now,
+ )
+ .order_by(McpToolApproval.created_at.desc())
+ .limit(1)
+ )
+ return (await db.execute(stmt)).scalar_one_or_none()
+
+
+async def authorize(
+ *,
+ db: AsyncSession,
+ tenant_id: uuid.UUID,
+ tool_name: str,
+ arguments: Mapping[str, Any] | None,
+ has_permission: Any,
+ requested_by: str,
+) -> Decision:
+ """Answer the three questions in the module docstring, in that order.
+
+ ``has_permission`` is a callable taking a permission string -- the
+ principal's own check, passed in rather than reached for, so this module
+ stays testable without a request and cannot accidentally consult a
+ different authorization path than the routes do.
+ """
+ spec = tool_catalogue().get(tool_name)
+ if spec is None:
+ # Not a refusal to be fixed by granting something. The catalogue is
+ # generated from the registry, so an unknown name means the caller is
+ # asking for a tool this deployment does not serve.
+ return Decision(outcome="deny", reason=f"Unknown tool: {tool_name}")
+
+ permission = spec.required_permission
+ if not permission:
+ return Decision(
+ outcome="deny",
+ reason=(
+ f"{tool_name} has no permission mapped in TOOL_PERMISSIONS, so nothing "
+ "decides what a key must hold to call it. Refusing rather than defaulting."
+ ),
+ )
+ if not has_permission(permission):
+ return Decision(
+ outcome="deny",
+ reason=f"The presented credential does not carry {permission}.",
+ required_permission=permission,
+ )
+
+ grant = (
+ await db.execute(
+ select(McpToolGrant).where(
+ McpToolGrant.tenant_id == tenant_id,
+ McpToolGrant.tool_name == tool_name,
+ )
+ )
+ ).scalar_one_or_none()
+ enabled = grant.enabled if grant is not None else spec.default_enabled
+ if not enabled:
+ where = "disabled for this tenant" if grant is not None else "off by default because it is not read-only"
+ return Decision(
+ outcome="deny",
+ reason=f"{tool_name} is {where}. A tenant administrator enables it at /api/v1/mcp/tools.",
+ required_permission=permission,
+ )
+
+ if spec.read_only:
+ return Decision(outcome="allow", reason="read-only tool", required_permission=permission)
+
+ fingerprint = argument_fingerprint(arguments)
+ approval = await _live_approval(db, tenant_id, tool_name, fingerprint)
+ if approval is not None:
+ # Spent here rather than left standing: an approver is deciding about
+ # a call, and a grant that outlives the call it was given for is a
+ # permission nobody agreed to.
+ approval.state = "consumed"
+ await db.flush()
+ return Decision(
+ outcome="allow",
+ reason=f"approved by {approval.decided_by or 'an approver'}",
+ approval_id=approval.id,
+ required_permission=permission,
+ )
+
+ pending = (
+ await db.execute(
+ select(McpToolApproval)
+ .where(
+ McpToolApproval.tenant_id == tenant_id,
+ McpToolApproval.tool_name == tool_name,
+ McpToolApproval.argument_fingerprint == fingerprint,
+ McpToolApproval.state == "pending",
+ McpToolApproval.expires_at > datetime.now(UTC),
+ )
+ .order_by(McpToolApproval.created_at.desc())
+ .limit(1)
+ )
+ ).scalar_one_or_none()
+ if pending is None:
+ pending = McpToolApproval(
+ tenant_id=tenant_id,
+ tool_name=tool_name,
+ argument_fingerprint=fingerprint,
+ requested_by=requested_by,
+ state="pending",
+ expires_at=datetime.now(UTC) + APPROVAL_TTL,
+ )
+ db.add(pending)
+ await db.flush()
+
+ return Decision(
+ outcome="approval_required",
+ reason=(
+ f"{tool_name} is not read-only, so a bearer credential is not enough. "
+ f"Approval {pending.id} is waiting at /api/v1/mcp/approvals."
+ ),
+ approval_id=pending.id,
+ required_permission=permission,
+ )
diff --git a/services/api/migrations/104_mcp_access.sql b/services/api/migrations/104_mcp_access.sql
new file mode 100644
index 000000000..75f5f4b7c
--- /dev/null
+++ b/services/api/migrations/104_mcp_access.sql
@@ -0,0 +1,147 @@
+-- 104_mcp_access.sql — who may call which MCP tool, and the queue that holds
+-- the ones a key alone is not enough for.
+--
+-- Depth plan 9.1 (parity 6.6). `services/mcp` was stdio-only: an MCP host
+-- started it as a child process with one operator's API key in the host's
+-- config file. Nothing in this repository deployed it, and nothing recorded
+-- what it read. Moving it onto HTTP is what makes these two tables
+-- necessary, because the transport change is also a threat-model change:
+-- several tenants now share one process, and the credential arrives in the
+-- request rather than in the environment.
+--
+-- aisoc_mcp_tool_grants — the tenant-level switch
+-- -----------------------------------------------
+-- A key's scopes say what a *credential* may do. This says what a *tenant*
+-- has turned on, which is a different decision and belongs to a different
+-- person: a tenant administrator who has decided their estate's event lake
+-- is not something an assistant reaches, whatever key somebody mints.
+--
+-- Absence of a row is not "denied". It means "the tool's own default
+-- applies", and the default is declared per tool in
+-- `app/data/mcp_tool_catalog.json`: read-only tools default on, anything
+-- that writes defaults off. Storing only the deliberate decisions keeps the
+-- table small and, more usefully, keeps "nobody has thought about this tool"
+-- distinguishable from "somebody turned it off" — which a NOT NULL boolean
+-- seeded for every tool would have destroyed.
+--
+-- aisoc_mcp_tool_approvals — the queue for everything that is not a read
+-- ---------------------------------------------------------------------
+-- A tool whose registry entry says `readOnlyHint: false` cannot run on the
+-- strength of a bearer token. The authorize path creates a row here instead
+-- and answers the caller with its id, so the refusal is actionable rather
+-- than a dead end: a human approves it in the console and the same call
+-- succeeds on retry.
+--
+-- `argument_fingerprint` is a SHA-256 over the canonical argument *names and
+-- values* the caller supplied. An approval has to be for a specific call,
+-- not for a verb: approving "run an investigation on case A" must not
+-- authorise "run an investigation on case B". It is a hash rather than the
+-- arguments themselves because those arguments routinely carry hostnames
+-- and queries, and this table is read by the console.
+--
+-- `expires_at` is NOT NULL for the reason every standing grant in this tree
+-- is time-boxed: an approval that never expires is a permission, and nobody
+-- decided to grant a permission.
+--
+-- Reversible: DROP TABLE IF EXISTS, either order (no FK between them).
+
+CREATE TABLE IF NOT EXISTS aisoc_mcp_tool_grants (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+
+ -- Matches `name` in app/data/mcp_tool_catalog.json. Not an FK: the
+ -- catalogue is a generated file held in parity with the TypeScript
+ -- registry by scripts/check_mcp_tool_catalog.py, and a row for a tool
+ -- that has since been removed should survive as history rather than
+ -- block the removal.
+ tool_name TEXT NOT NULL,
+
+ enabled BOOLEAN NOT NULL,
+
+ -- Who flipped it. Free text because the actor may be a user email or an
+ -- API key prefix, and an auditor reading this wants whichever it was.
+ decided_by TEXT NOT NULL DEFAULT '',
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT aisoc_mcp_tool_grants_unique UNIQUE (tenant_id, tool_name)
+);
+
+CREATE INDEX IF NOT EXISTS aisoc_mcp_tool_grants_tenant
+ ON aisoc_mcp_tool_grants (tenant_id);
+
+CREATE TABLE IF NOT EXISTS aisoc_mcp_tool_approvals (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+
+ tool_name TEXT NOT NULL,
+ -- SHA-256 hex over the canonicalised arguments. See the header for why
+ -- this is a digest and not the arguments.
+ argument_fingerprint CHAR(64) NOT NULL,
+
+ -- The key prefix (never the key) or user email that asked.
+ requested_by TEXT NOT NULL DEFAULT '',
+
+ state TEXT NOT NULL DEFAULT 'pending'
+ CHECK (state IN ('pending', 'approved', 'denied', 'consumed', 'expired')),
+
+ decided_by TEXT,
+ decided_at TIMESTAMPTZ,
+ -- Why it was denied, or any note the approver left. Shown to the caller.
+ decision_note TEXT NOT NULL DEFAULT '',
+
+ expires_at TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+-- The authorize path's lookup: "is there a live approval for exactly this
+-- call?". Partial on `approved` because pending and consumed rows accumulate
+-- and the hot query only ever wants the one state.
+CREATE INDEX IF NOT EXISTS aisoc_mcp_tool_approvals_live_idx
+ ON aisoc_mcp_tool_approvals (tenant_id, tool_name, argument_fingerprint)
+ WHERE state = 'approved';
+
+-- The console's queue.
+CREATE INDEX IF NOT EXISTS aisoc_mcp_tool_approvals_pending_idx
+ ON aisoc_mcp_tool_approvals (tenant_id, created_at DESC)
+ WHERE state = 'pending';
+
+COMMENT ON TABLE aisoc_mcp_tool_grants IS
+ 'Per-tenant MCP tool switch. An absent row means the tool default in '
+ 'app/data/mcp_tool_catalog.json applies, which keeps "nobody decided" '
+ 'distinguishable from "somebody turned it off".';
+
+COMMENT ON TABLE aisoc_mcp_tool_approvals IS
+ 'One row per non-read-only MCP tool call that needed a human. The '
+ 'fingerprint binds an approval to a specific call, so approving an '
+ 'investigation on one case does not authorise one on another.';
+
+-- Written out per table rather than looped with format(): a loop is shorter
+-- and makes the policy invisible to grep and to
+-- scripts/check_tenant_query_predicates.py, which reads migrations to learn
+-- which tables carry one.
+DO $$
+BEGIN
+ EXECUTE 'ALTER TABLE aisoc_mcp_tool_grants ENABLE ROW LEVEL SECURITY';
+ EXECUTE 'ALTER TABLE aisoc_mcp_tool_grants FORCE ROW LEVEL SECURITY';
+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON aisoc_mcp_tool_grants';
+ EXECUTE
+ 'CREATE POLICY tenant_isolation ON aisoc_mcp_tool_grants '
+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '
+ 'WITH CHECK (tenant_id = current_tenant_id())';
+
+ EXECUTE 'ALTER TABLE aisoc_mcp_tool_approvals ENABLE ROW LEVEL SECURITY';
+ EXECUTE 'ALTER TABLE aisoc_mcp_tool_approvals FORCE ROW LEVEL SECURITY';
+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON aisoc_mcp_tool_approvals';
+ EXECUTE
+ 'CREATE POLICY tenant_isolation ON aisoc_mcp_tool_approvals '
+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '
+ 'WITH CHECK (tenant_id = current_tenant_id())';
+
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_mcp_tool_grants TO aisoc_app';
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_mcp_tool_approvals TO aisoc_app';
+ END IF;
+END
+$$;