28 lines · 1.1 KB
import { addCounter } from "../counters";
import { usageKey } from "../counter-keys";
import { accountDb } from "../scoped-db";

const DAY_CHARS = 10;
const MAX_REPORT_DAYS = 90;

/** Counted in the account's Counters object and flushed to mcp_usage_daily; errors still consume capacity. */
export async function recordToolUsage(accountId: string, tool: string, failed: boolean): Promise<void> {
  try {
    const day = new Date().toISOString().slice(0, DAY_CHARS);
    await addCounter("mcp-usage", accountId, usageKey(day, tool), [1, failed ? 1 : 0, 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<UsageRow[]> {
  const since = new Date(Date.now() - Math.min(days, MAX_REPORT_DAYS) * 86_400_000).toISOString().slice(0, DAY_CHARS);
  return accountDb(accountId).all<UsageRow>(
    "SELECT day, tool, calls, errors FROM mcp_usage_daily WHERE account_id = ? AND day >= ? ORDER BY day DESC, tool",
    accountId,
    since,
  );
}