Skip to main content
Glama

Tests Python Dependencies Anthropic Proxy MCP License: MIT Benni OS

Zero-Dependency Hybrid Local-Cloud Model Router, AST Context Compactor & Semantic Prefix Cache for Claude Code.
Cut Claude Code API spend by routing trivial turns to local GPUs (BIE / Ollama), compacting bloated code & logs via Python AST, and deduplicating repeated tool payloads in SQLite3 WAL — with zero runtime dependencies.


⚡ Why claude-code-router?

Running every Claude Code turn — typo fixes, file reads, log inspection, and boilerplate edits — through frontier cloud models burns tokens and budget unnecessarily.

claude-code-router sits transparently between Claude Code (ANTHROPIC_BASE_URL) and your inference backends using pure Python stdlib (http.server, sqlite3, ast, json):

  • Sub-Millisecond Complexity Scorer — Deterministically classifies every turn (trivial, standard, frontier) in < 0.5 ms based on prompt length, conversation depth, tool-call weight (Edit/Bash vs Read/Grep), extended thinking, and architectural/security signals.

  • AST-Aware Code & Log Compactor — Uses Python's ast module to collapse long function bodies while preserving imports, signatures, decorators, and line anchors (# [L...-L...]), and strips ANSI/repeated log noise while keeping every traceback frame.

  • SQLite3 WAL Semantic Prefix Cache — Deduplicates repeated Read/Grep/Bash turns and identical prompts using deterministic SHA-256 keys, PRAGMA journal_mode=WAL, and configurable TTLs (~0.015 ms cache hits).

  • Bidirectional Wire Translator — Translates Anthropic /v1/messages (including tool_use, tool_result, and SSE streams) <-> OpenAI /v1/chat/completions for local benni-inference-engine (BIE) or Ollama servers, plus /v1/messages/count_tokens.

  • Automatic 429/529 Circuit Breaker — Smoothly fails over between local GPU (127.0.0.1:8080 / 11434) and Anthropic Cloud on rate limits or connection errors.

  • One-Command Claude Code Injection (claude-router init) — Idempotently configures .claude/settings.json, .mcp.json, and /router-status + /router-stats slash commands without clobbering existing settings.


Related MCP server: tierline

🏗️ Architecture

  Claude Code CLI / IDE / MCP Clients
         │
         ├──► HTTP  POST /v1/messages, /v1/messages/count_tokens
         └──► STDIO JSON-RPC 2.0 (claude-router mcp)
                       │
                       ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │                         claude-code-router                          │
  │                                                                     │
  │  ┌───────────────────┐  ┌───────────────────┐  ┌─────────────────┐  │
  │  │ Complexity Scorer │  │ AST & Log         │  │ SQLite3 WAL     │  │
  │  │ • Trivial (<0.32) │─►│ Compactor         │─►│ Semantic Cache  │  │
  │  │ • Standard        │  │ • Keep signatures │  │ • SHA-256 keys  │  │
  │  │ • Frontier (>=.68)│  │ • Keep tracebacks │  │ • TTL + hits    │  │
  │  └───────────────────┘  └───────────────────┘  └─────────────────┘  │
  │                                                         │           │
  │  ┌───────────────────┐  ┌───────────────────┐           ▼           │
  │  │ Rolling Telemetry │  │ Wire Translator   │  ┌─────────────────┐  │
  │  │ • P50/P90/P99 ms  │◄─│ • Anthropic<->OAI │◄─│ Circuit Breaker │  │
  │  │ • USD Saved       │  │ • SSE Stream      │  │ • 429/529 Trip  │  │
  │  └───────────────────┘  └───────────────────┘  └─────────────────┘  │
  └─────────────────────────────────────────────────────────────────────┘
         │                                         │
         ▼                                         ▼
   Local GPU (BIE / Ollama)                 Anthropic Cloud API
   127.0.0.1:8080 / :11434                  Haiku / Sonnet / Opus

🚀 60-Second Quickstart

# 1. Clone and install (zero runtime dependencies)
git clone https://github.com/Benni-OS/claude-code-router
cd claude-code-router
pip install -e .

# 2. Verify environment, SQLite3 WAL, and routing pipeline
claude-router doctor

# 3. Run the multi-scale complexity, AST compaction & cache matrix
claude-router matrix

# 4. Inject .claude/settings.json, .mcp.json, and slash commands
claude-router init --project-dir .

# 5. Start the Anthropic-compatible proxy server
claude-router serve --port 4100

Key CLI Commands

claude-router doctor                         # Full environment, SQLite WAL & backend probe
claude-router matrix                         # Multi-scale scorer, AST compaction & cache benchmark
claude-router init --project-dir .           # Idempotent .claude/settings.json & .mcp.json setup
claude-router serve --port 4100              # Start threaded HTTP /v1/messages proxy
claude-router serve --port 4100 --dry-run    # Offline deterministic dry-run proxy mode
claude-router route "Fix typo in README"     # Inspect routing tier, model & USD saved
claude-router compact src/my_module.py       # Preview AST-aware compaction savings
claude-router cache --stats                  # Inspect SQLite3 WAL cache entries & hits
claude-router mcp                            # Launch native JSON-RPC 2.0 stdio MCP server

📊 Benchmarks & AST Compaction Matrix

Measured with claude-router matrix (Python 3.11.0, Windows, 5 repetitions per scale):

Functions

Orig Chars

Compact Chars

Context Savings

Assigned Tier

Score Latency

Compact Latency

Cache Hit Latency

2

847

202

76.1%

trivial

0.1197 ms

0.1801 ms

0.0176 ms

8

3,235

665

79.4%

trivial

0.3853 ms

0.6463 ms

0.0150 ms

24

9,617

1,927

80.0%

standard

1.1139 ms

1.9881 ms

0.0128 ms


🌐 Drop-In Anthropic Proxy & MCP Server

REST Endpoints

Method

Endpoint

Purpose

POST

/v1/messages

Complexity routing, AST compaction, semantic cache, and local/cloud dispatch

POST

/v1/messages/count_tokens

Fast deterministic token estimation for Claude Code

GET

/health

Proxy, SQLite3 WAL cache, circuit breaker, and local BIE/Ollama health

GET

/v1/router/metrics

Rolling P50/P90/P99 latency, local offload ratio, cache hit rate, and USD saved

Native MCP Tools (claude-router mcp)

  • router_classify_turn — Classify a prompt + tool list into trivial / standard / frontier.

  • router_compact_context — Compact Python code blocks and log/traceback outputs via AST.

  • router_cache_stats — Query SQLite3 WAL semantic cache hits and tokens saved.

  • router_estimate_savings — Compute USD saved vs Claude Opus baseline.


🗂️ Project Structure

claude-code-router/
├── src/
│   └── claude_code_router/
│       ├── cli.py                    # CLI entrypoint (init, serve, route, compact, cache, mcp, doctor, matrix)
│       ├── core/
│       │   ├── circuit_breaker.py    # Automatic 429/529 & connection-error failover breaker
│       │   ├── complexity_scorer.py  # Sub-ms prompt & tool-context complexity classifier
│       │   ├── context_compactor.py  # AST-aware Python code & log/traceback compactor
│       │   ├── injector.py           # Idempotent .claude/settings.json, .mcp.json & slash command injector
│       │   ├── semantic_cache.py     # Thread-safe SQLite3 WAL prefix & tool-result cache
│       │   └── wire_translator.py    # Bidirectional Anthropic <-> OpenAI payload & SSE translator
│       ├── serve/
│       │   ├── health_monitor.py     # Local BIE/Ollama reachability & WAL cache monitor
│       │   ├── mcp_server.py         # Zero-dependency JSON-RPC 2.0 stdio MCP server
│       │   ├── proxy_server.py       # Threaded HTTP proxy (/v1/messages, /health, /v1/router/metrics)
│       │   └── telemetry.py          # Rolling P50/P90/P99 latency & FinOps USD saved telemetry
│       └── tools/
│           ├── bench_matrix.py       # Multi-scale complexity, AST compaction & cache benchmark matrix
│           └── doctor.py             # Environment & routing pipeline diagnostic (claude-router doctor)
├── examples/
│   ├── quickstart_anthropic_proxy.py # Dry-run /v1/messages proxy quickstart
│   └── quickstart_context_compaction.py # AST code & log compaction example
├── scripts/
│   ├── benchmark_router_latency.py   # Latency & compaction benchmark runner
│   └── gate_router_integrity.py      # End-to-end zero-dependency integrity gate
├── docs/
│   └── ARCHITECTURE.md               # Detailed request pipeline architecture
└── tests/                            # Full pytest suite (33 tests)

🌍 Part of the Benni OS Ecosystem

claude-code-router is part of the coordinated Benni Master OS v9.4 open-source infrastructure suite:

Repository

Focus & Architecture

Stars

benni-inference-engine

High-Throughput Sovereign Local Inference for 8GB–16GB Consumer GPUs

GitHub Stars

claude-code-router

Hybrid Local-Cloud Model Router, AST Context Compactor & Semantic Cache

GitHub Stars

conductor-sdd

Zero-Dependency Spec-Driven Development, Static AST Drift Detector & MCP Guardrail

GitHub Stars

agent-eval-harness

Deterministic Zero-Cloud Agent Evaluation, Red-Teaming & Benchmark Harness

GitHub Stars


🏛️ Commercial & Sovereign Architecture

Need autonomous multi-agent swarm orchestration, private datacenter infrastructure, or enterprise governance?


📄 License & Provenance

  • License: MIT License

  • Author: Benni Alencar (bennialencar@benni-os.net)

  • Architecture: Benni Master OS v9.4 Tier-0 Governance Standard

claude-code-router — Hybrid Local-Cloud Model Router & AST Context Compactor for Claude Code • benni-os.net • MIT License

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables intelligent LLM optimization and routing for Claude Desktop and HTTP clients, reducing token usage and automatically selecting the best model for each query.
      4
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables LLM clients and coding agents to analyze prompts and recommend the cheapest AI model that meets the task requirements across text, voice, video, and other modalities, projecting monthly cost savings against a flagship baseline.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables exact Claude API cost estimation from token counts with correct prompt-cache economics, plus cache break-even analysis showing whether and at which TTL reusing a prefix pays off. It also scans source code for tiktoken-based token counting used alongside Claude models and points to the correct fix.
      MIT