claude-code-router
Routes and translates Anthropic Messages API requests to a local Ollama server via OpenAI-compatible chat completions, with health checks and circuit-breaker failover between local and cloud backends.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
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 msbased on prompt length, conversation depth, tool-call weight (Edit/BashvsRead/Grep), extended thinking, and architectural/security signals.AST-Aware Code & Log Compactor — Uses Python's
astmodule 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/Bashturns and identical prompts using deterministic SHA-256 keys,PRAGMA journal_mode=WAL, and configurable TTLs (~0.015 mscache hits).Bidirectional Wire Translator — Translates Anthropic
/v1/messages(includingtool_use,tool_result, and SSE streams) <-> OpenAI/v1/chat/completionsfor localbenni-inference-engine(BIE) orOllamaservers, plus/v1/messages/count_tokens.Automatic
429/529Circuit 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-statsslash 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 4100Key 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% |
|
|
|
|
8 | 3,235 | 665 | 79.4% |
|
|
|
|
24 | 9,617 | 1,927 | 80.0% |
|
|
|
|
🌐 Drop-In Anthropic Proxy & MCP Server
REST Endpoints
Method | Endpoint | Purpose |
|
| Complexity routing, AST compaction, semantic cache, and local/cloud dispatch |
|
| Fast deterministic token estimation for Claude Code |
|
| Proxy, SQLite3 WAL cache, circuit breaker, and local BIE/Ollama health |
|
| 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 intotrivial/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 |
High-Throughput Sovereign Local Inference for 8GB–16GB Consumer GPUs | ||
Hybrid Local-Cloud Model Router, AST Context Compactor & Semantic Cache | ||
Zero-Dependency Spec-Driven Development, Static AST Drift Detector & MCP Guardrail | ||
Deterministic Zero-Cloud Agent Evaluation, Red-Teaming & Benchmark Harness |
🏛️ Commercial & Sovereign Architecture
Need autonomous multi-agent swarm orchestration, private datacenter infrastructure, or enterprise governance?
Official Website: https://benni-os.net
Operator Mode Playbook: https://benni-os.net/blog/academy.html
GitHub Organization: https://github.com/Benni-OS
Maintainer: Benni Alencar
📄 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…
This server cannot be deployed
Maintenance
Related MCP Connectors
Exact Claude API cost calc with real cache economics, plus a tiktoken-misuse scanner.
Count tokens (o200k/cl100k), truncate to a budget, chunk text for RAG and estimate LLM cost.
Token counting, RAG chunking, truncation, HTML to Markdown and JSON repair
BYOK AI router & FinOps control plane: audit token waste, check tool safety, and rank models.
Related MCP Servers
AlicenseNot gradedqualityDmaintenanceEnables intelligent LLM optimization and routing for Claude Desktop and HTTP clients, reducing token usage and automatically selecting the best model for each query.4MIT- AlicenseNot gradedqualityCmaintenanceEnables 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.1MIT
- AlicenseNot gradedqualityCmaintenanceEnables Claude to route sub-tasks to the cheapest suitable model tier based on semantic rules, with tools for dispatching and previewing routing decisions.MIT
- AlicenseNot gradedqualityDmaintenanceEnables 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