Every agent developer has asked it. Now there's a tool that answers it.


You just burned $47 on a single Claude Code session. The API dashboard says you used 2.3 million tokens. Your agent ran for 45 minutes, made 38 tool calls, and somewhere in that sprawling context window, a 12,000-token system prompt got re-sent on every single turn. A tool definition for send_email — which the model never once invoked — sat there, bloating every request, costing you money for absolutely nothing.

Standard observability tells you the total. It never tells you what's in there.

That's the problem Context Lens was built to solve. And after hitting 326 GitHub stars, shipping npm v0.8.0, and getting a DEV.to feature on June 8, it's rapidly becoming the go-to profiler for anyone running LLM agents in production.

What Context Lens Does

Context Lens is a local HTTP proxy that sits between your coding agent and the LLM API, intercepting every request and response to build a real-time breakdown of what's actually filling your context window. Think of it as py-spy or pprof — but instead of profiling CPU cycles or memory allocations, it profiles token allocations.

It decomposes your context into regions:

  • System prompts — the instructions your agent framework injects every turn
  • Tool schemas — JSON definitions for every tool the model could call
  • Tool results — output from previous tool calls, re-sent verbatim on every subsequent turn
  • Conversation history — user messages and assistant responses
  • Thinking blocks — internal reasoning tokens
  • Retrieved content — RAG chunks, file contents, search results

Then it tracks which blocks get re-billed across turns using SHA-256 content hashing. That tool result from turn 3? It gets billed again at turns 4, 5, 6, 7... forever. Most of it is never read again. Context Lens makes this invisible waste visible — and quantifies it in dollars.

The Waste Problem Is Bigger Than You Think

Here's the math that should make every agent developer uncomfortable. In a multi-turn agent loop, the entire context window re-sends on every API call. Anthropic's prompt caching helps (and Context Lens tracks cache read/write tokens separately in its usage_ext namespace), but caching is opt-in, model-specific, and doesn't eliminate the fundamental problem: you're paying to re-transmit data the model has already seen.

The DEV.to feature that published on June 8 laid this out with clarity that resonated with the community:

In multi-turn agent loops, the full context re-sends on every API call. A tool result added at turn 3 gets billed again at turns 4, 5, 6, 7... forever. Most of it is never read again.

Context Lens runs five waste detectors and ranks findings by dollar cost:

Detector What it finds
Duplicate Same block re-sent verbatim across multiple turns
Near-Duplicate >85% Jaccard similarity between distinct blocks
Stale Tool Result Tool output never referenced by a later assistant message
Unused Tool Schema Tool defined every turn but never called
Redundant Retrieval Retrieved chunk with <15% overlap with model output

Each finding comes with a concrete one-line fix. Not "optimize your prompts" — actual, actionable suggestions like "remove send_email from tool definitions" or "cache this block instead of re-transmitting."

How It Works: Zero-Config Proxy

The beauty of Context Lens is that it requires no code changes. You don't modify your agent, you don't add instrumentation, you don't refactor anything. You just prefix your command:

# Claude Code
context-lens claude

# OpenAI Codex
context-lens codex

# Gemini CLI
context-lens gemini

# Cline (VS Code extension)
context-lens cline

# Aider
context-lens aider --model claude-sonnet-4

# Pi Coding Agent
context-lens pi

# Anything else
context-lens -- python my_agent.py

This starts the proxy on port 4040, opens the web UI on port 4041, sets the right environment variables (ANTHROPICBASEURL, OPENAIBASEURL, etc.), and runs your command. Multiple tools can share one proxy — just open more terminals.

How the Proxy Actually Works

Under the hood, Context Lens uses two interception strategies depending on the tool:

Reverse Proxy (Anthropic, OpenAI, Gemini): The proxy intercepts BASE_URL environment variables and forwards requests to the real API endpoints. This is the cleanest approach — no certificate shenanigans, no MITM. Works for Claude Code, Codex, Gemini CLI, Aider, and Pi.

MITM Proxy (ChatGPT, Cline): For tools that don't expose base URL configuration, Context Lens uses httpsproxy with a local CA certificate. It generates a trust-on-first-use cert and sets NODEEXTRACACERTS automatically. This is how it captures ChatGPT subscription traffic and Cline's VS Code extension.

Both strategies are transparent to the LLM — the model has no idea it's being profiled.

The Web UI: A Profiler for Your Tokens

The web UI at http://localhost:4041 is where Context Lens really shines. It provides:

  • Composition treemap — a D3-powered visual breakdown showing exactly what percentage of your context is system prompts vs. tool schemas vs. tool results vs. actual conversation. You can immediately see if your system prompt is eating 40% of your budget.
  • Cost tracking — per-turn and per-session cost estimates across models, based on published pricing. No more guessing whether that 12K-token system prompt is actually costing you real money. (It is.)
  • Conversation threading — groups API calls by session, distinguishing main agent turns from subagent turns. Essential for understanding multi-agent architectures.
  • Agent breakdown — token usage and cost per agent within a session. See which subagent is burning through your budget.
  • Timeline — bar chart of context size over time, filterable by main/all/cost. Watch your context window grow turn by turn and identify the moment it spirals.
  • Context diff — turn-to-turn delta showing what grew, shrank, or appeared. Pinpoint exactly which tool call added 15K tokens that never got used again.
  • Findings — flags large tool results, unused tool definitions, context overflow risk, and compaction events. The five waste detectors in visual form.

The UI auto-detects your tool — it recognizes Claude Code, Codex, Aider, Pi, and others by source tag or system prompt. No configuration needed.

LHAR: The HAR File for LLM Traffic

One of Context Lens's most thoughtful design decisions is LHAR (LLM HTTP Archive) — a structured format for recording, analyzing, and sharing context window interactions. Think of it as HAR for web traffic, but purpose-built for LLM API calls.

LHAR files use JSON Lines format (newline-delimited JSON), making them streamable and append-friendly:

{"type":"session","trace_id":"abc123","started_at":"2026-02-10T12:00:00.000Z","tool":"claude","model":"claude-sonnet-4-20250514"}
{"type":"entry","trace_id":"abc123","id":"4bac36b9-...","source":{...},"gen_ai":{...},"usage_ext":{...}}

Each entry includes seven namespaces: source (which tool, which agent role), genai (OpenTelemetry GenAI semantic conventions for request/response metadata), usageext (provider-specific extensions like cache tokens and cost), http (transport metadata), timings, transfer, and context_lens (composition analysis).

This matters because it makes sessions shareable and comparable. You can export a session as LHAR, send it to a teammate, and they can load it into their own Context Lens instance. Team dashboards are on the roadmap, but LHAR gives you the interoperability today.

Privacy Modes: Profiles Without Leaking Secrets

Running a proxy that sees every LLM request is inherently sensitive. Context Lens offers three privacy levels:

  • --privacy=minimal — captures everything including full message content. Use for local development only.
  • --privacy=standard (default) — captures composition analysis but redacts sensitive content.
  • --privacy=full — captures only aggregate token counts and composition percentages, no message content at all.

For team deployments, --redact strips secrets before capture, and --redact=pii broadens redaction to personally identifiable information. The --rehydrate flag restores original values in responses, so you can debug with real data while storing safe archives.

# Minimal privacy for deep debugging
context-lens --privacy=minimal claude

# Standard privacy with PII redaction for team sharing
context-lens --privacy=standard --redact=pii codex

# Full privacy — composition analysis only
context-lens --privacy=full gemini

Running in Production: Docker and Background Mode

For team use or persistent monitoring, Context Lens runs as a Docker container:

docker run -d \
  -p 4040:4040 \
  -p 4041:4041 \
  -e CONTEXT_LENS_BIND_HOST=0.0.0.0 \
  -v ~/.context-lens:/root/.context-lens \
  ghcr.io/larsderidder/context-lens:latest

There's also a background mode for running the proxy as a detached service:

context-lens background start   # start detached proxy + UI
context-lens background status  # check status
context-lens background stop    # stop

For split deployments (proxy in one container, analysis server in another), set CONTEXTLENSINGEST_URL so the proxy POSTs captures directly to the analysis server over the Docker network. No shared filesystem needed.

The Composition Math: A Real Example

Let's make this concrete. Context Lens's built-in demo simulates a 30-turn agent loop — no API key needed:

Context Composition by Region

Region                  Tokens    Cost (USD)   Share
──────────────────────────────────────────────────
assistant_message       11,490    $0.0345      25.5%
tool_result             10,333    $0.0310      22.9%
tool_schema              9,450    $0.0284      21.0%
retrieved_content        5,805    $0.0174      12.9%
user_message             4,740    $0.0142      10.5%
system                   3,240    $0.0097       7.2%
──────────────────────────────────────────────────
TOTAL                   45,058    $0.1352

Re-billing: 43,185 tokens (95.8%) → $0.1296 recoverable

Top Waste Findings

#  Type              Sev.   Wasted Tokens   Cost     Fix
1  duplicate         medium        7,084   $0.0213   Cache or externalize...
2  redundant_ret     medium        5,805   $0.0174   Use a re-ranker...
3  unused_schema     low           3,150   $0.0095   Remove send_email...

95.8% of tokens in that session were re-billed waste. That's the difference between a $0.14 session and a $0.01 session. Scale that across a team of 20 developers running agents all day, and you're looking at $200/day in pure waste — tokens that contribute nothing to the model's output.

The unused tool schema finding is particularly telling. That send_email tool definition — probably 500+ tokens of JSON schema — was transmitted on every turn and never called once. Remove it from the context, and you've saved 3,150 tokens for zero accuracy loss.

Why This Matters Now

The timing for Context Lens isn't accidental. Three trends are converging:

  1. Agent frameworks are exploding. Claude Code, Codex, Gemini CLI, Cline, Aider, Pi — every major AI company and half the open-source community is building coding agents. Each one stuffs context windows with system prompts, tool definitions, and accumulated conversation history. Nobody is measuring the waste.
  1. Token costs are compounding. When every developer on your team runs an agent for 8 hours, and each session re-transmits a 15K-token context window on every turn, the math gets brutal fast. Context Lens gives you per-session visibility into where the budget actually goes.
  1. Prompt engineering is becoming a discipline. The Semantic Density Effect paper showed that condensing prompts to maximize information per token improves accuracy by +8.4 percentage points across five frontier models. Context Lens gives you the profiler to know what to condense.

Framework Support

Context Lens is deliberately framework-agnostic. It doesn't care what agent framework you're using — it intercepts at the HTTP level:

Provider Method Status
Anthropic Reverse Proxy ✅ Stable
OpenAI Reverse Proxy ✅ Stable
Google Gemini Reverse Proxy 🧪 Experimental
ChatGPT (Subscription) MITM Proxy ✅ Stable
Cline MITM Proxy ✅ Stable
Pi Coding Agent Reverse Proxy ✅ Stable
OpenAI-Compatible (Ollama, vLLM, OpenRouter) Reverse Proxy ✅ Stable
Aider / Generic Reverse Proxy ✅ Stable

For OpenAI-compatible endpoints, set UPSTREAMOPENAIURL so the proxy knows where to forward:

context-lens --upstream-openai-url=https://openrouter.ai/api/v1 aider

Comparison: Context Lens vs. Other Approaches

vs. LangSmith / Helicone / Arize: These are observability platforms that tell you how many tokens you used. Context Lens tells you what those tokens contained. They're complementary — use both. But if you can only afford one question, "why is this session so expensive?" beats "how much did this session cost?"

vs. manual prompt inspection: You could dump your API requests and read them. Some developers do. But in a 30-turn agent session, you're looking at 30+ API calls, each with a full context window. That's not inspection — that's archaeology. Context Lens automates the decomposition and surfaces the waste patterns.

vs. ContextLens (Python profiler): There's a separate Python package called contextlens-profiler by a different author (Harshal Sant) that takes a programmatic approach — you import it as a library, wrap your API client, and run analysis in Python. It's useful for offline trace analysis and has the same five waste detectors. Context Lens (the npm package by Lars de Ridder) takes the zero-config proxy approach — no code changes, no imports, just prefix your command. Different tradeoffs for different workflows.

Getting Started

npm install -g context-lens

# Profile your next Claude Code session
context-lens claude

# Or use npx for one-off runs
npx context-lens codex

Configuration lives in ~/.context-lens/config.toml. CLI flags always override config file values.

# ~/.context-lens/config.toml
[proxy]
# port = 4040
# redact = "secrets"  # secrets | pii | strict

[ui]
# port = 4041
# no_open = false

[privacy]
# level = "standard"  # minimal | standard | full

Run context-lens doctor to check ports, certs, config, and background state.

The Bottom Line

Context Lens answers the question every agent developer eventually asks: "why is this session so expensive?" Not with vague hand-waving about "token costs are high," but with a precise, visual, dollar-quantified breakdown of exactly which parts of your context window are waste.

It's MIT-licensed, framework-agnostic, requires no code changes, and runs locally. The proxy approach means it works with any tool that talks to OpenAI, Anthropic, or Google APIs. The LHAR export format means you can share sessions with teammates and build your own analysis tooling on top.

If you're running agent workflows and not using Context Lens, you're flying blind on costs. Install it, prefix your next session, and see what's actually filling your context. The results will probably surprise you.


Context Lens is open source (MIT) at github.com/larsderidder/context-lens. Install via npm install -g context-lens. Current version: v0.8.0. 326 GitHub stars and growing.