WORKFLOW · cost-engineering
Workflow: weekly usage and cost report
A scheduled GitHub Actions workflow that pulls the week's token usage and spend from the Usage and Cost Admin API, grouped by model and workspace, and files the digest where the team will read it.
✓ verified 2026-07-18 · stack: github-actions, github · source
Cost observability dies in dashboards nobody opens. The Usage and Cost
Admin API serves the same data programmatically
(/v1/organizations/usage_report/messages and
/v1/organizations/cost_report, Admin API key required), which means the
weekly numbers can arrive as a commit the team actually sees
(usage-cost API).
This workflow files a Monday digest: tokens by model, spend by workspace,
week on week.
name: cost-report
# Mondays 07:00 UTC: last week's API usage and spend as a committed# markdown digest. Requires ANTHROPIC_ADMIN_KEY (an Admin API key,# sk-ant-admin01-...; a standard API key will 401).on: schedule: - cron: "0 7 * * 1" workflow_dispatch:
permissions: contents: write
jobs: report: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - name: Build the digest env: ANTHROPIC_ADMIN_KEY: ${{ secrets.ANTHROPIC_ADMIN_KEY }} run: node scripts/cost-report.mjs > reports/cost/latest.md - name: Commit the digest run: | git config user.name "cost-report" git config user.email "actions@users.noreply.github.com" git add reports/cost/latest.md git diff --cached --quiet || git commit -m "reports: weekly usage and cost digest" git push#!/usr/bin/env node// Weekly digest from the Usage & Cost Admin API. Costs arrive in cents// as decimal strings; usage buckets are daily. Both endpoints paginate// via has_more/next_page.const BASE = 'https://api.anthropic.com/v1/organizations';const HEADERS = { 'anthropic-version': '2023-06-01', 'x-api-key': process.env.ANTHROPIC_ADMIN_KEY,};
const end = new Date();const start = new Date(end.getTime() - 7 * 86_400_000);const iso = (d) => d.toISOString().replace(/\.\d{3}Z$/, 'Z');
async function fetchAll(path, params) { const rows = []; let page; do { const url = new URL(`${BASE}/${path}`); for (const [k, v] of Object.entries(params)) url.searchParams.append(k, v); if (page) url.searchParams.set('page', page); const res = await fetch(url, { headers: HEADERS }); if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`); const body = await res.json(); rows.push(...body.data); page = body.has_more ? body.next_page : undefined; } while (page); return rows;}
const usage = await fetchAll('usage_report/messages', { starting_at: iso(start), ending_at: iso(end), 'group_by[]': 'model', bucket_width: '1d',});const cost = await fetchAll('cost_report', { starting_at: iso(start), ending_at: iso(end), 'group_by[]': 'workspace_id',});
const tokensByModel = new Map();for (const bucket of usage) { for (const r of bucket.results ?? []) { const key = r.model ?? 'unknown'; const t = tokensByModel.get(key) ?? { in: 0, out: 0 }; t.in += (r.uncached_input_tokens ?? 0) + (r.cache_read_input_tokens ?? 0); t.out += r.output_tokens ?? 0; tokensByModel.set(key, t); }}const centsByWorkspace = new Map();for (const bucket of cost) { for (const r of bucket.results ?? []) { const key = r.workspace_id ?? 'default'; centsByWorkspace.set(key, (centsByWorkspace.get(key) ?? 0) + Number(r.amount ?? 0)); }}
console.log(`# Usage and cost: week to ${iso(end).slice(0, 10)}\n`);console.log(`## Tokens by model\n`);for (const [m, t] of tokensByModel) console.log(`- ${m}: ${t.in.toLocaleString()} in / ${t.out.toLocaleString()} out`);console.log(`\n## Spend by workspace (USD)\n`);for (const [w, c] of centsByWorkspace) console.log(`- ${w}: $${(c / 100).toFixed(2)}`);What it does
- Pulls daily usage buckets grouped by model and the cost report grouped
by workspace for the trailing seven days, paginating both endpoints
(
has_more/next_page) so large orgs are not silently truncated. - Commits the digest into the repo, where a diff in the weekly number is a reviewable event: the same delivery mechanism this site uses for its own agent-produced reports, and the metric feed the cost-per-merged-PR pattern needs a numerator for.
- Costs arrive as decimal strings in cents; the script converts once, at the edge, so the report reads in dollars.
Failure modes
- Wrong key class. These are Admin API endpoints: a standard
sk-ant-api...key 401s, and individual (non-organisation) accounts have no Admin API at all. Claude Enterprise organisations use the separate Analytics API instead, and Claude Platform on AWS does not serve these endpoints currently. - Per-user Claude Code costs need the other API. This report is organisation and workspace level; per-user Claude Code breakdowns come from the Claude Code Analytics API, and mixing the two double-counts.
- Data freshness is minutes, not instant. Usage typically lands within five minutes; a report run at 00:01 for a week ending 00:00 is safe, but do not tighten the window to hours and expect completeness.
- Priority Tier costs are absent from the cost endpoint by design;
if you use it, track it via the usage endpoint’s
service_tierdimension or the bill will not reconcile.
Verified against the endpoint paths, Admin-key requirement, bucket and group_by dimensions, pagination contract, cents-as-strings convention, and the freshness and Priority Tier caveats at platform.claude.com/docs/en/api/usage-cost-api, 2026-07-18.