/cstats

Portable Rust Hook to display Claude Code statistics directly in your terminal.

Primary LanguageRustMIT LicenseMIT

cstats

CI Release License Rust Version

Claude Code Usage Statistics Tracker

Lightweight CLI tool that fetches and displays your Claude Code usage statistics from the Anthropic API. Track tokens, costs, and API calls with beautiful terminal output.

Installation

curl -fsSL https://cstats.refcell.org/install | bash

Setup

Quick Setup

Initialize cstats and configure your Anthropic API key:

cstats init

This will create a configuration file at ~/.cstats/config.json and guide you through setting up your API key.

Manual Setup

Alternatively, you can set your Anthropic API key as an environment variable:

export ANTHROPIC_API_KEY="sk-ant-..."

Configuration Priority

cstats follows this priority order for configuration:

  1. Environment variables (highest priority)
  2. Configuration file (~/.cstats/config.json)
  3. Default values (lowest priority)

This means environment variables will always override config file settings.

Usage

Quick Start

# Initialize configuration (first time setup)
cstats init                       # Create config file and set API key

# Display usage statistics
cstats stats                      # Daily stats (default)
cstats stats --period summary     # All-in-one summary view

Example Output

Daily Stats (Default)

📊 Daily Usage (Last 24 hours)
Tokens: 1,234,567 (823,456↓ 411,111↑) | Cost: $12.3456
Calls: 142 (140 ok, 2 fail) | 98.6% success | 250ms avg

Summary View

📊 Usage Summary
Daily:   1,234,567 tokens | 142 calls | $12.3456
Weekly:  8,901,234 tokens | 987 calls | $89.0123
Monthly: 45,678,901 tokens | 4,321 calls | $456.7890 (est: $468.1234/mo)

All Commands

# Display usage statistics
cstats stats                      # Daily stats (default)
cstats stats --period weekly      # Weekly stats
cstats stats --period monthly     # Monthly stats
cstats stats --period summary     # Complete summary

# Additional options
cstats stats --detailed           # Show model breakdown
cstats stats --billing            # Include billing info
cstats stats --rate-limit         # Show rate limits

# Configuration management
cstats config show                # View current configuration
cstats config validate            # Validate configuration
cstats config set-api-key         # Update Anthropic API key

# Install Claude Code hook (choose your shell)
cstats hook bash >> ~/.bashrc     # For bash
cstats hook zsh >> ~/.zshrc       # For zsh  
cstats hook fish >> ~/.config/fish/config.fish  # For fish

# View help
cstats --help

Features

  • 📊 Real-time usage statistics from Anthropic API
  • 💰 Token and cost tracking (daily/weekly/monthly)
  • 🤖 Claude Code session integration
  • ⚡ Smart caching for fast responses
  • 🎨 Beautiful terminal output
  • 🌍 Cross-platform (macOS, Linux, Windows)

Claude Code Integration

cstats automatically integrates with Claude Code to display your usage statistics at the start of each session. When you launch Claude Code, you'll see a compact summary of your API usage:

What You'll See

When starting a Claude Code session, cstats displays:

📊 Daily Usage (Last 24 hours)
Tokens: 1,234,567 (823,456↓ 411,111↑) | Cost: $12.3456
Calls: 142 (140 ok, 2 fail) | 98.6% success | 250ms avg

This compact format shows:

  • Tokens: Total usage with input (↓) and output (↑) breakdown
  • Cost: Total cost in USD for the period
  • Calls: API call statistics with success rate and average response time

Installation

The installation script automatically configures Claude Code hooks for you. If you need to manually install or reinstall the hooks:

# Automatic hook installation (recommended)
curl -fsSL https://cstats.refcell.org/install-hook | bash

# Or manually add hooks to ~/.claude/settings.json
cstats hook install

How It Works

cstats adds hooks to your ~/.claude/settings.json file that run when:

  • Starting a new Claude Code session (startup matcher)
  • Resuming an existing session (resume matcher)

The hooks run cstats stats --period daily to show your most recent usage. The integration is non-intrusive and won't affect Claude Code's performance.

Development

# Clone the repository
git clone https://github.com/refcell/cstats.git
cd cstats

# Build
just build

# Run tests
just test

# Install locally
just install

Project Structure

cstats/
├── crates/
│   ├── cstats-core/    # Core library with API client
│   ├── cstats-cli/     # CLI binary
│   └── cstats-hook/    # Shell hook generator
├── api/                # Vercel API endpoints
├── public/             # Static web assets
└── scripts/            # Installation scripts

Configuration

Configuration File

The configuration file is stored at ~/.cstats/config.json. Create it using:

cstats init

Example configuration with all available options:

{
  "database": {
    "url": "sqlite:./cstats.db",
    "max_connections": 10,
    "timeout_seconds": 30
  },
  "api": {
    "base_url": null,
    "timeout_seconds": 30,
    "retry_attempts": 3,
    "anthropic": {
      "api_key": "sk-ant-...",
      "base_url": "https://api.anthropic.com",
      "timeout_seconds": 30,
      "max_retries": 3,
      "initial_retry_delay_ms": 1000,
      "max_retry_delay_ms": 30000,
      "rate_limit_buffer": 10
    }
  },
  "cache": {
    "cache_dir": "/path/to/cache/cstats",
    "max_size_bytes": 104857600,
    "ttl_seconds": 3600
  },
  "stats": {
    "default_metrics": ["execution_time", "memory_usage", "cpu_usage"],
    "sampling_rate": 1.0,
    "aggregation_window_seconds": 300
  }
}

Configuration Fields

  • database: Reserved for future use (local usage tracking)
  • api.anthropic: Anthropic API settings
    • api_key: Your Anthropic API key (required)
    • base_url: API endpoint (default: "https://api.anthropic.com")
    • max_retries: Number of retry attempts for failed requests
    • rate_limit_buffer: Request buffer before rate limits
  • cache: Local caching for faster responses
    • cache_dir: Directory for cache files (auto-detected by OS)
    • max_size_bytes: Maximum cache size (default: 100MB)
    • ttl_seconds: Cache expiration time (default: 1 hour)
  • stats: Statistics collection settings (future use)

Note: Since the Anthropic API doesn't provide public usage endpoints, cstats currently uses local mock data for demonstration purposes.

Environment Variables

Environment variables take precedence over config file settings:

  • ANTHROPIC_API_KEY - Your Anthropic API key
  • CSTATS_DATABASE_URL - Override database URL
  • CSTATS_API_BASE_URL - Override API base URL

Configuration Commands

# View current configuration and sources
cstats config show

# Validate configuration
cstats config validate

# View default configuration
cstats config default

# Set or update API key
cstats config set-api-key

License

MIT - See LICENSE

Links