[FEATURE] Built-in Usage Analytics Command (claude usage) — Consolidates 10+ Open Issues

Open 💬 18 comments Opened Mar 13, 2026 by mp719lkh

Preflight Checklist

  • [x] I have searched existing requests and this feature hasn't been requested yet
  • [x] This is a single feature request (not multiple features)

Problem Statement

Token usage visibility is the #1 most-requested feature category in Claude Code issues. At least 10+ open issues request overlapping subsets of the same core need:

  • #31564 — Per-session and consolidated token usage
  • #13891 — All-time cumulative token usage command
  • #13892 — Usage history tracking for Pro/Max subscribers
  • #10593 — Real-time token usage indicator in CLI
  • #18550 — Automatic cost tracking and reporting
  • #1109 — Usage metrics visibility for Max subscribers
  • #11008 — Token usage in hook inputs
  • #8861 / #10436 / #11535 — Token usage in statusline
  • #15931 — Remaining plan tokens instead of context usage
  • #10388 — Agent Token Usage API

The data already exists — every Claude Code session writes detailed JSONL transcripts under ~/.claude/projects/ with per-message usage objects containing input_tokens, output_tokens, cache_creation_input_tokens, and cache_read_input_tokens. But there is no built-in way to query or aggregate this data.

Proposed Solution

A built-in claude usage subcommand (or claude-usage standalone) that provides unified token usage analytics. I've built a working prototype that demonstrates feasibility by parsing the existing JSONL transcripts — no API changes or new data collection required.

1. Summary view (default)
$ claude usage
============================================================
  Claude Code Usage (last 7 days)
============================================================
  Sessions:       19
  Duration:       3080 min (51.3 hrs)
  Messages:       1356
────────────────────────────────────────────────────────────
  Input tokens:         9.6K
  Cache write:          3.5M
  Cache read:         151.0M
  Output tokens:      392.2K
  Total tokens:       155.3M
────────────────────────────────────────────────────────────
  Est. cost:      $282.52
============================================================
2. Plan status + today/weekly overview
$ claude usage --plan
============================================================
  Claude Code Plan Status
============================================================
  Plan:           Max
  Rate Limit:     Max 20x
  Extra Usage:    Disabled
  Active Now:     4 session(s)
============================================================

                        Today           This Week
  ────────────────────────────────────────────────
  Sessions                  6                  19
  Messages                736                1356
  Tokens                91.4M              157.1M
  Est. cost         $186.01            $286.02
3. Live monitoring dashboard
$ claude usage --watch 5
============================================================
  Claude Code Live Monitor
  Updated: 21:27:11   Refresh: 5s   Ctrl+C to quit
============================================================
  Active sessions:  4
  User messages:    701
  Model:            claude-opus-4-6
────────────────────────────────────────────────────────────
  Input tokens:           6.2K
  Cache write:            1.8M
  Cache read:            88.4M
  Output tokens:        231.7K
  Total:                 90.4M
  Delta:                 25.3K  (+25,312)
────────────────────────────────────────────────────────────
  Est. cost:        $184.32
============================================================

                        Today           This Week
  ────────────────────────────────────────────────
  Sessions                  6                  19
  Tokens                91.4M              157.1M
  Est. cost         $186.01            $286.02

  Session    Project           Min  Msgs       In      Out     Cost
  ──────────────────────────────────────────────────────────────────
  20cd51f1   cli-tools         547   698    90.1M   231.5K $183.23
  27e3a24c   cli-tools           0     1    59.7K       64  $0.08
4. Flexible filtering
$ claude usage -d 1                    # Today only
$ claude usage -d 30 --daily           # Daily breakdown for last month
$ claude usage -p my-project           # Filter by project
$ claude usage --sessions -v           # Per-session with summaries
$ claude usage --watch 10 -p project   # Live monitor, filtered

Why this should be built-in (not a third-party tool)

  1. The data is already there. Every JSONL transcript contains complete usage objects. No new collection needed.
  2. 10+ issues requesting fragments of this. A single unified command resolves all of them.
  3. Cache-aware cost estimation matters. Claude Code heavily uses prompt caching — cost estimates that ignore cache_creation_input_tokens and cache_read_input_tokens are wildly inaccurate. A first-party tool can get this right.
  4. Plan metadata is already local. ~/.claude/.credentials.json has subscription type and rate limit tier. ~/.claude.json has extra usage status. Combining these into a single view is trivial but only Anthropic can do it correctly.
  5. Live monitoring enables cost-conscious usage. Users currently have zero feedback about consumption velocity during long sessions. The --watch mode shows token delta per refresh cycle, letting users see exactly how much each interaction costs.

Implementation notes from the working prototype

Data source: Parse ~/.claude/projects/*/*.jsonl (top-level only, skip subagents/). Each line with message.usage contains the token counts. Session metadata (project, model, timestamps) comes from the same files.

Cost model: Input, output, cache_write (1.25x input price), cache_read (0.1x input price), per-model pricing lookup.

Active session detection: Files modified within last 30 minutes.

Performance: Parsing 20+ transcript files (some 100MB+) takes ~2-3 seconds on first load. For --watch mode, this is acceptable at 5-10s intervals. Could be optimized with seek-to-end for incremental parsing.

What's NOT possible from local data (and that's OK):

  • Plan usage percentage (rate limit utilization) — only available via API response headers (anthropic-ratelimit-unified-*-utilization), not cached locally
  • Billing-accurate costs — the prototype provides estimates, not invoices

Alternative Solutions

  • /cost command — Exists but only shows current session. No history, no aggregation, no cross-session view.
  • Console/Admin Dashboard — Requires browser, separate login, admin permissions. Not accessible during active coding.
  • OpenTelemetry — Heavy setup, meant for organizational monitoring, not personal usage tracking.
  • Statusline hacks — Several issues request exposing tokens to statusline scripts. That's a workaround for not having a proper usage command.

Priority

High — This consolidates the most-requested feature category across 10+ open issues.

Feature Category

CLI commands and flags

Use Case Example

Solo developer on Max plan:
"I want to know if I'm burning through my daily allocation too fast. claude usage --watch shows me real-time consumption velocity, and claude usage --plan gives me today vs. this week at a glance."

Team lead:
"I need to understand which projects consume the most tokens so I can allocate budget. claude usage -d 30 --daily -p frontend gives me a monthly breakdown for a specific project."

Cost-conscious user:
"Before I start a large refactoring session, I check claude usage -d 1 to see what I've already used today. After the session, I compare to understand the cost of that specific task."

Additional Context

Working prototype: ~700 lines of Python, zero dependencies beyond stdlib. Parses existing JSONL transcripts that Claude Code already writes. This is not a "build it from scratch" proposal — it's "expose data you already have."

Related issues this would resolve or subsume:
#31564 #13891 #13892 #10593 #18550 #1109 #15931

View original on GitHub ↗

18 Comments

smigolsmigol · 3 months ago

I ran into the same gap and ended up building an MCP server that reads local session data and exposes cost tools. Works inside Claude Code, Cline, and Cursor directly.

Five tools: session cost, cumulative per-project costs across all sessions ranked by spend, cache savings analysis, monthly cost projection vs Max subscription, and subagent cost attribution.

Auto-detects which AI coding tools are installed and aggregates data from all of them. Also runs as a SessionEnd hook for automatic cost logging on exit:

{
  "hooks": {
    "SessionEnd": [{"hooks": [{"type": "command",
      "command": "npx @f3d1/llmkit-mcp-server --hook"}]}]
  }
}

Free, open source, no API key needed for the local tools.

npm: @f3d1/llmkit-mcp-server
github: https://github.com/smigolsmigol/llmkit

digitalpromptmarket-beep · 3 months ago

This consolidation is overdue — glad to see the 10+ fragmented issues pulled together.

I've been running my own analysis on session JSONL files for the past few weeks, and the data validates every use case listed in this issue. A few things I found that might be useful for scoping the implementation:

The data is already there, and it's rich. A single session JSONL file from ~/.claude/projects/ contains per-turn token counts broken down by input, output, cache_read, and cache_creation — plus model identifiers and tool call metadata. Parsing this into a useful report is straightforward. In my testing, a 200KB JSONL file (37 turns) processes in ~6ms.

Cache costs dominate. In every session I've analyzed, cache_read and cache_creation together account for 80-95% of the estimated cost. A claude usage command that only shows input/output tokens would miss the majority of the spend. The breakdown needs all four categories.

Model selection is the biggest optimization lever. In one session, 33 out of 37 Opus turns were doing simple operations (single tool call, <500 output tokens) that Sonnet handles identically at 1/5 the cost. Surfacing this in a usage report would immediately tell developers where to add model routing hints.

I built a CLI tool that does exactly what this issue describes — parses JSONL transcripts and produces a cost report:

npx agent-forensics analyze ~/.claude/projects/-Users-me/ --full

It covers: per-model cost breakdown, tool usage frequency, sub-agent detection, waste pattern identification (redundant reads, debug loops, model misuse), and estimated savings. The --json flag outputs machine-readable data for scripting.

You can also see the report format without installing anything:

curl -s https://api.agentsconsultants.com/forensics/sample | jq .

Full disclosure: I built this tool. It's MIT-licensed and the analysis runs entirely locally (no data leaves your machine). Would love to see the core functionality land natively in Claude Code — the 700-line prototype mentioned in this issue is the right approach. Happy to share implementation notes if useful.

Omsatyaswaroop29 · 3 months ago

Unified claude usage command

Issues addressed: #33978 · #27915 · #7328 Also closes: #20636 · #23512 · #6057 (and 17+ other duplicates)

Hi @mp719lkh — great issue writeup and prototype. I'd like to build on your work and contribute a production-ready implementation that also pulls in the closely related rate-limit (#27915) and MCP context budget (#7328) requests.

Why unify them

All three issues boil down to the same gap: users can't see what Claude Code is consuming. A single observability surface is cleaner than three separate additions — and it closes 23+ duplicate issues in one shot.

What I've built

2,100+ lines of TypeScript, 45 tests passing, zero new dependencies. Full repo: Omsatyaswaroop29/claude-usage-contribution

claude usage                      # Token totals, cost, cache hit rate, model/project breakdowns
claude usage --rate-limit         # Session/daily usage %, requests remaining, reset time
claude usage --mcp-breakdown      # Per-server and per-tool context window cost
claude usage --watch              # Live-updating display
claude usage --json               # Machine-readable output for CI/CD

Interactive demo — click the tabs to see each mode with typing animation and bar charts.

How it works

Like your prototype, the parser reads existing JSONL transcripts at ~/.claude/projects/ — no API changes needed. Key differences from the prototype:

  • Streaming architecture — processes line-by-line via readline, never loads full files into memory
  • Rate-limit layer — parses anthropic-ratelimit-* headers and extends the statusLine JSON payload
  • MCP introspector — estimates per-tool context window cost from tools/list responses
  • Zero dependencies — Node.js built-ins only. Token estimation uses ~4 chars/token heuristic

Modules

| Module | What it does |
|---|---|
| UsageParser | Stream JSONL, filter by date/model/project, skip malformed lines |
| UsageAggregator | Incremental metrics: tokens, cost, cache hit rate, per-model/project/day rollups |
| RateLimitCollector | Parse API headers → rate_limits object for statusLine |
| MCPIntrospector | Estimate per-tool token cost → --mcp-breakdown output |
| TerminalFormatter | Bar charts, ANSI color, JSON mode |
| UsageCommand | CLI handler with all flags |

prafaelo · 3 months ago

Real-world use case this would solve: context optimization for heavy CLI users.

I maintain large context files (CLAUDE.md, SESSION.md, project docs) that Claude Code loads every session. Right now I have no way to measure whether trimming them actually reduces token consumption — /cost returns "using subscription" for Pro users, and /usage only surfaces the 4h rate limit window. The Desktop App shows token counts during processing, but that data never surfaces in the CLI for subscribers.

What I actually need is simple: input/output tokens per session, or even just context window % used. Not billing data — just enough signal to answer "did that doc trim make a difference?"

The JSONL approach @digitalpromptmarket-beep described and the implementation @Omsatyaswaroop29 shared both seem like they'd cover this. Just adding the use case as validation that the gap is real.

(Comment drafted with guidance from Claude Sonnet 4.6 via Claude Code CLI, which also helped research existing issues before posting.)

katsboxofhustles · 3 months ago

Pro subscriber on Linux here. The /usage command previously showed per-session and per-week usage summaries, which was very useful for tracking spend. After upgrading to Claude Code 2.x, it now says usage is only available for subscription plans. Pro plan users lost visibility into their usage with this change — would love to see it restored.

Astro-Han · 3 months ago

The real-time monitoring side of this already has a path: rate_limits (five_hour.used_percentage, seven_day.used_percentage, resets_at) shipped in statusLine stdin JSON since v2.1.80. I built claude-lens on top of it, showing live usage %, pace delta (burning faster or slower than the reset window), and countdown to reset.

@katsboxofhustles This can restore your quota visibility on Pro today without waiting for a built-in command. It won't cover the historical/aggregate analytics @mp719lkh proposes, but the live piece works now.

albertdobmeyer · 3 months ago

The aggregation/summary side of this proposal is solid. One angle I think is missing from
the --watch mode: burn-rate derivatives.

Every tool in this space shows where you are. None show how fast you're getting there.
This matters because conversations have QUADRATIC COSTS because each turn resends the full context.

Three metrics that would make --watch actionable, not just informational:

  1. Burn rate

context growth per API call (windowed, reset after compaction).
"Each interaction adds ~12k" is more useful than "you're at 340k."

  1. Context tax

(overhead / 1M) × cacheReadRate = the dollar cost per call of
carrying history. Makes the abstract concrete: "$0.38/call just for conversation baggage."

  1. /clear savings projection

what clearing and reloading from a handoff would save
over the next N calls. Removes the guesswork from the "keep going or /clear?" decision.

These could surface as a single line in the --watch output:

Burn: +8.2k/call (steady) | Ctx tax: $0.18/call | /clear saves ~$3.40 over 20 calls

Turns the live monitor from a dashboard into a workflow optimizer.

albertdobmeyer · 3 months ago

+1 on the core request. Beyond tokens.used/max/remaining, two small additions would
unlock statusline features that currently can't be built reliably:

tokens.delta
tokens added by the last API call (context growth). This is the raw
ingredient for burn-rate display. Without it, statusline tools must re-parse the full JSONL
every refresh to compute a diff — fragile, slow on large files, and breaks after compaction.

tokens.compactions
count of auto-compaction events this session. Any external tool
tracking deltas needs to know when context shrunk. A drop from 180k to 90k isn't
"negative burn" but a compaction. Without this signal, rate calculations produce
nonsense after every compaction event.

Both are single integers the runtime already has in memory. Minimal implementation cost,
but they're the two values that can't be reliably derived externally, unlike used/max which
can at least be approximated from JSONL sums.

dr5hn · 3 months ago

I've been working on this in CCM (bash CLI tool for Claude Code management). It has a few usage commands that might help:

  • ccm usage sessions - shows per-session token count and estimated cost with model-specific pricing
  • ccm usage history --days 30 - per-project and per-day token breakdown
  • ccm usage dashboard - per-account usage if you manage multiple accounts
  • ccm session summary - shows what happened in each session (topic, tools used, files modified)

All parsed from the existing JSONL session files - no extra dependencies.

https://github.com/dr5hn/ccm

danerlt · 3 months ago

+1

searayca · 3 months ago

Use case: Pro/Max subscriber, heavy agent/skill usage, optimization-focused

I'm on a Pro/Max plan (no per-token billing), but I'd still find token tracking extremely valuable for optimizing my workflow rather than managing costs.

I use agents extensively — multiple background agents per session, custom skills, and multi-step tool chains. Right now I have no visibility into which agents or skills are consuming the most context, which makes it hard to know where to focus optimization efforts (e.g., trimming prompts, reducing context passed to sub-agents, simplifying skill instructions).

What I'd specifically want:

  • Token count per agent invocation (input + output)
  • Token count per skill execution
  • Session-level totals, broken down by agent vs. main thread

Even a simple claude usage summary at the end of a session — or surfaced in the status line — would give enough signal to guide optimization. This doesn't need to be a billing feature; it's a developer productivity feature for power users who want to reason about context efficiency.

RajeevRKC · 2 months ago

Strong +1. As a 2× Max subscriber running long agentic sessions (10–30 hours), I cannot currently answer a basic operational question: "which skills/workflows/sessions are burning the most tokens, and how much of that is rework vs productive work?"

Microcompact-driven silent re-reads (per the 2.1.88 source microCompact.ts) already waste tokens invisibly. Without native usage analytics, power users either over-invest in custom instrumentation (I've built my own rework logger and session tracker) or fly blind. A /usage command with per-session, per-model, per-tool breakdown would make cost-aware routing possible — and would surface exactly the patterns Anthropic wants to address.

This should consolidate the cost/burn issues listed here. Treating this as a rally hub.

InertiaUK · 2 months ago

The issue notes that plan utilisation percentage isn't available from local JSONL files — it only comes from the \^Gnthropic-ratelimit-unified-*-utilization\ response headers.

I built a workaround for exactly that gap: a local proxy that intercepts Claude Code's API traffic, captures those headers on every response, and writes a one-line status file to \~/.claude/usage-status.md\. Claude can read it on demand or you can inject it into every prompt via a \UserPromptSubmit\ hook.

Won't replace a proper \claude usage\ command — this is a stopgap — but it does give you live 5h/7d utilisation right now without waiting for Anthropic to ship it.

https://github.com/InertiaUK/claude-quota-proxy

m13v · 2 months ago

the cost estimation is solid for API-key accounting, but on Pro/Max the dollar number is decoupled from what fires the cap. you can read 150M cache tokens, JSONL says $282, the real question is 'do i have any opus messages left in the rolling 5-hour'. response headers (anthropic-ratelimit-unified-*) only stay fresh until the next call. for a 'remaining plan capacity' view rather than cost math, the foundation has to be whatever the web UI polls to render its own usage screen, since that's the only number that matches the rate-limit toast users actually hit.

norika1207-lab · 1 month ago

One product split that would keep this from becoming a giant dashboard: separate historical analytics from launch preflight.

Historical analytics answers:

  • Which sessions/projects/models consumed the most tokens?
  • Which tools, subagents, or MCP servers created recurring overhead?
  • How much cache read/write did a workflow produce over time?

Launch preflight answers a different question:

  • Is it safe to start another large agent task right now?
  • How much 5h / 7d plan pressure remains?
  • Is the current context already too large for a reliable long run?
  • Should the agent checkpoint or compact before continuing?

The first can mostly come from JSONL transcript aggregation. The second needs fresh runtime/plan state and should be cheap enough for scripts and remote launchers to call before starting work.

So a useful shape might be:

claude usage history --json
claude usage preflight --json

Where preflight returns only small run-control fields: plan window usage, reset times, active sessions, context pressure, stale/fresh timestamp, and maybe a recommendation enum like ok, checkpoint_first, wait_for_reset, or manual_review.

romainfjgaspard · 1 month ago

+1 to this — consolidated visibility is the right ask, and hopefully it lands natively.

In the meantime, for anyone who needs this today: I open-sourced a tool (not affiliated with Anthropic) that reads the local ~/.claude/projects/**/*.jsonl logs and gives you per-prompt cost & token analytics — from the terminal (a CLI) and an optional Streamlit dashboard. Token counts are split by type (input / output / cache read / cache write 5m vs 1h) and priced at API-equivalent cost. Everything runs locally, no API key, nothing leaves your machine.

A few things it answers that came up in this thread and the issues it consolidates:

  • which prompts/projects/models actually drive cost (Pareto views);
  • how much of your usage is cache reads (on my own history: 97% of token volume — usually the answer to "why are my tokens exploding");
  • how the marginal cost of a prompt changes with its depth in the session (the first prompt of a session is by far the most expensive; follow-ups ride the cache).
  • many others

Token totals are validated against ccusage.

Live demo : https://prompt-analytics-demo.streamlit.app/
Repo: https://github.com/romainfjgaspard/prompt-analytics-for-claude-code

(If a built-in claude usage ships, that's strictly better — this is a stopgap that also goes one level deeper, to the prompt grain.)

kcarriedo · 12 days ago

The consolidation here is well-targeted. One angle worth separating from the main request: when running multi-agent pipelines (orchestrator + 3-8 subagents), the cost attribution gap is qualitatively different from the single-session case.

Right now, /cost in the orchestrator shell shows only the orchestrator's token use. Each subagent session is an isolated process with its own context window. So after a 6-agent pipeline run, you have 7 separate cost numbers living in 7 separate terminal scroll buffers, none of which aggregate anywhere. You cannot answer "what did this pipeline actually cost" without manually opening each session log.

The JSONL approach described here works for post-hoc analysis on single sessions. For multi-agent workflows, the missing piece is a way to link subagent session costs back to the parent run - something like a shared run_id or an aggregation hook that the orchestrator can poll. Without that linkage, claude usage would still give you per-session numbers without a way to group them into "this was one logical pipeline run."

A few things that would make the multi-agent case tractable:

  • a parent_session_id field in the subagent session JSONL so aggregation tools can group them
  • the SubagentStop hook payload carrying final token/cost data for that subagent
  • or at minimum, the status line JSON including aggregate_cost_usd as mentioned in issue #48040

Building Claudeverse (claudeverse.ai) - a scheduling and coordination layer for Claude Code agent fleets - so visibility into per-run aggregate cost is the metric we care most about. The workaround right now is reading the hooks output stream and joining against individual session JSONLs, which is fragile across compactions and restarts.

kcarriedo · 8 days ago

The JSONL transcript path you're describing is real -- the data is there, the tooling isn't.

One pattern that works without waiting for a native command: a small polling script that reads ~/.claude/projects/ on each cycle, aggregates input_tokens + output_tokens + cache_creation_input_tokens + cache_read_input_tokens per session, and writes a spend_log.jsonl. Running it on a cron or as part of a CI wrapper gives you per-session and per-day rollups without touching Claude Code itself.

The cache-aware cost point matters more than most estimates account for. A session with heavy cache hits looks expensive on raw token counts but is 3-10x cheaper than the same context without caching. Any aggregation that ignores cache_creation vs cache_read will produce numbers that feel wrong and erode trust in the tooling.

For multi-agent runs specifically: session-level aggregation isn't fine enough. You want spend attributed to the agent role (orchestrator, reviewer, specialist), not just the session, so you can see which agent pattern is burning quota. That requires tagging at dispatch time, not post-hoc attribution.