import { all, run } from "../db"; const DAY_CHARS = 10; const MAX_REPORT_DAYS = 90; /** One upsert per tool call; errors are counted too, since they still consume capacity. */ export async function recordToolUsage(accountId: string, tool: string, failed: boolean): Promise { try { await run( `INSERT INTO mcp_usage_daily (account_id, day, tool, calls, errors) VALUES (?, ?, ?, 1, ?) ON CONFLICT (account_id, day, tool) DO UPDATE SET calls = calls + 1, errors = errors + excluded.errors`, accountId, new Date().toISOString().slice(0, DAY_CHARS), tool, failed ? 1 : 0, ); } catch (error) { console.error("MCP usage metering failed", error); } } export type UsageRow = { day: string; tool: string; calls: number; errors: number }; export async function usageForAccount(accountId: string, days: number): Promise { const since = new Date(Date.now() - Math.min(days, MAX_REPORT_DAYS) * 86_400_000).toISOString().slice(0, DAY_CHARS); return all( "SELECT day, tool, calls, errors FROM mcp_usage_daily WHERE account_id = ? AND day >= ? ORDER BY day DESC, tool", accountId, since, ); }