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 = {}; 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 { 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, input.tool, JSON.stringify(redact(input.args)).slice(0, MAX_AUDIT_JSON), input.outcome, input.detail?.slice(0, 500) ?? null, Date.now(), ); } catch (error) { console.error("MCP audit write failed", error); } } /** * Per-token and per-session budgets on top of the per-user limits the shared server modules enforce, * so one runaway agent cannot exhaust its human's whole allowance. */ export async function limitToolCall(caller: McpCaller, write: boolean): Promise { const token = caller.tokenId ?? caller.viewer.id; await enforceRateLimit("GIT_LIMITER", `mcp:token:${token}`); if (caller.sessionId) await enforceRateLimit("GIT_LIMITER", `mcp:session:${caller.sessionId}`); if (!write) return; await enforceRateLimit("WRITE_LIMITER", `mcp:token:${token}`); if (caller.sessionId) await enforceRateLimit("WRITE_LIMITER", `mcp:session:${caller.sessionId}`); }