import { run } from "../db";
import { randomId } from "../crypto";
import { enforceRateLimit } from "../limits";
import type { McpCaller } from "./protocol";
const MAX_AUDIT_STRING = 200;
const MAX_AUDIT_JSON = 4000;
const MAX_AUDIT_DEPTH = 4;
const REDACTED_KEYS = new Set(["content", "token", "resolutions", "body"]);
function redact(value: unknown, depth = 0): unknown {
if (depth > MAX_AUDIT_DEPTH) return "…";
if (typeof value === "string") return value.length > MAX_AUDIT_STRING ? `<${value.length} chars>` : value;
if (Array.isArray(value)) return value.slice(0, 20).map((item) => redact(item, depth + 1));
if (typeof value !== "object" || value === null) return value;
const out: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value)) {
out[key] = REDACTED_KEYS.has(key) && typeof item === "string" ? `<${item.length} chars>` : redact(item, depth + 1);
}
return out;
}
/** One row per write tool call, successful or not, naming the agent and the human behind it. */
export async function auditToolCall(input: {
caller: McpCaller;
tool: string;
args: unknown;
repoId: string | null;
outcome: "ok" | "denied" | "error";
detail: string | null;
}): Promise<void> {
try {
await run(
`INSERT INTO mcp_audit (id, user_id, token_id, agent_name, repo_id, tool, arguments, outcome, detail, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
randomId(),
input.caller.viewer.id,
input.caller.tokenId,
input.caller.agent.name,
input.repoId,