Skip to main content
logo

PyPI PyPI - Downloads license issue resolution open issues


Quick start | Motivation | What's new | Install guide | Coding agent setup | FAQ | Supported agents

ContextSpy is a context window profiler for large language models and common agentic AI coding tools. It is used to intercept requests to an LLM API, analyze and visualize prompt composition, and track context changes between multiple requests in the same session. Modern AI coding agents (GitHub Copilot, Claude Code, opencode, etc.) pack a lot into each LLM request: system prompts, tool definitions and results, file contents, conversation history. It's often unclear why a session is slow, expensive, or hitting the context limit. ContextSpy makes the invisible visible - you see a live breakdown of every token category for every request, across sessions, over time.

Example dashboard view
Dashboard view

Think of your favorite CPU or memory profiler, just applied to the contents of the context of an AI agent. While you can optimize performance just by reviewing code, having a profiler to capture and visualise snapshot data helps a lot. Same with LLM context optimisation.

Quick start

Quick setup for macOS (Apple Silicon) — see install guide for Linux, Windows, and PyPI options:

# install latest binary release with Homebrew
brew tap RimantasZ/contextspy
brew install contextspy

# Install CA certificate into system trust store (one-time, cloud mode only)
sudo contextspy install-cert

# Start the proxy (keep this terminal open)
contextspy start

# In a new terminal: launch your coding agent through the proxy
# contextspy run sets required environment variables, so LLM requests are routed through the proxy
contextspy run opencode <path to your project>
# contextspy run code <path to your project>
# contextspy run claude # run in the drectory of your project
# contextspy run codex  # run in the directory of your project (Codex CLI, not the desktop app)

Open http://127.0.0.1:5173 in your browser for the ContextSpy dashboard.

If something doesn't work, see the troubleshooting section in the install guide.

Alternatively, refer to configure your agent on how to route LLM traffic through the proxy at http://127.0.0.1:8888

Context profiling? Why should I care?

Token costs are rising. With AI agents embracing more and more complex workflows and use cases, token consumption and subsequent cloud API bills are growing larger and larger. This is also applicable for AI coding agents and tools, where providers are gradually switching from subsidized subscription mode and are either reducing token limits or switching to token usage based billing (e.g. GitHub Copilot).

Input tokens are major part. When discussing AI model pricing, most people bring up token generation cost - that's where the numbers look most dramatic ($25 per million tokens for Opus 4.8 output vs $0.40 for gpt-5-nano). But in agentic workloads, input tokens outnumber output by 20-50x, or even more. So most of your API bill is influenced by input context, not the output the model generates.

AI coding agents = lots of input. The expensive part is the quick accumulation of context - with every turn it fills up with additional tokens - system prompt, skills, tool definitions, tool results, file contents, conversation history. You start with 5000 - 10000 tokens in a fresh session, but by turn 25 it might be 30 to 50 thousand, spend some more time and it might be hitting the context window limit and compacting. Every API call to the model sends the full context as part of the prompt - and here is where the token consumption and costs skyrocket quickly.

Why large context is bad

We all have been told that the more information we will give to the model, the more capable it will be. And there are models with 1M token (or even bigger) context windows.

There are three ways you pay for extra (and sometimes unnecessary) information in your context:

  1. API Costs - even with near perfect cache hits, input token costs outweigh output, often by order of magnitude or more.
  2. Compute and latency - larger contexts take considerably longer to process - especially in locally hosted models
  3. Context rot - with larger contexts, LLMs start to lose precision rapidly, with 100k being the limit where rapid degradation starts. So you are paying for more expensive model, but getting performance of cheaper one - or even worse.

ContextSpy makes these costs visible so you can act on them. The responsive light/dark dashboard includes session and provider summaries, model and latency breakdowns, tool-use treemaps, and a request workbench with compact, relative-size, and raw payload views. Filters, linked-block navigation, metadata inspection, and in-content search help trace exactly where the context went. Session detail also reconstructs conversations: unrelated roots, exact or inferred continuations, forks, parallel timing, and the blocks/tokens that persisted, were promoted from a parent response, added, removed, or replaced. Forked conversations can share earlier requests.

How does it work

ContextSpy starts an HTTPS proxy (or reverse proxy for locally hosted models) that captures supported LLM invocation endpoints, analyzes them, and stores the results in a local SQLite database. A local web server serves the dashboard used to explore the captured data.

Some screenshots

Request view
Request view

Context breakdown
Context breakdown

Session view
Session view

Is it safe to use? Does it send my data to the cloud?

No, it does not send any data to the cloud. All data is stored locally on your machine.

But users must be aware, that it will be running proxy, and capturing all traffic from agent to LLM provider - and storing it locally to be displayed and analysed in the UI. The proxy and dashboard server are bound to localhost, and not exposed to external access, but still could be accessed locally.

The intended use case is to run ContextSpy as a profiler tool on dedicated profiling and optimisation sessions, rather than keeping it permanently as a monitoring tool.

The contents of requests (observed payloads, canonical request/response JSON, stream event logs, and block contents) become eligible for purging after 7 days by default — configurable via [retention] in ~/.contextspy/config.toml. Aggregated token counts and classifications are retained indefinitely. Purging only runs at server startup, not on a background timer, so a contextspy process left running for many days in a row won't purge again until it's restarted.

The contents of database can be cleared manually by running contextspy reset-db. In practice, it is recommended to do it from time to time.

Upgrades and migration

The new version can be installed with homebrew:

## optional - sometimes brew "forgets" custom tap, add it again if just update fails
brew tap RimantasZ/contextspy 
## update homebrew and upgrade contextspy
brew update
brew upgrade contextspy

At this stage, the database schema is subject to change. Structural changes (new tables/columns) are applied automatically on next startup. If a data migration is needed (e.g. backfilling new derived data for existing requests), contextspy start will print a warning — run contextspy db-upgrade to backfill, or contextspy reset-db to start fresh. Before an upgrade makes any database changes, it copies the SQLite file to a backup beside it named <db_name>_backup_v<version_from>_to_v<version_to>_<YYYY-MM-DD-HHMM>.back (UTC). If that name already exists, -1, -2, and so on is added before .back.

Tech stack

Layer Technology
Backend Python 3.11+, FastAPI + uvicorn, WebSocket for live push
Frontend React + Vite, TanStack Query, Recharts, Tailwind CSS
CLI Typer
Proxy mitmproxy — TLS-terminating forward proxy (cloud) and reverse proxy (local)
Storage SQLite via SQLAlchemy — all data local in ~/.contextspy/
Tokenizer tiktoken (o200k_base) for token estimation
Packaging uv, Homebrew tap, .deb, standalone binary

Features

  • Two proxy modes — forward proxy for supported cloud APIs (OpenAI, Anthropic, Azure OpenAI, Copilot, opencode's gateway, and Codex's ChatGPT backend); reverse proxy for local LLM servers (Ollama, llama.cpp, vLLM)
  • Context breakdown — input tokens split into 8 categories: system prompt, tool definitions, tool results, file contents, conversation history, current user message, assistant prefill, uncategorised
  • Live dashboard — responsive light/dark charts, tool-use treemaps, and a request workbench with compact, relative-size, and raw payload views plus block search and inspection
  • Session tracking — name time windows, keep stable per-session request numbers, and compare usage across runs
  • Conversations — visualize independent and forked request paths without assuming session request order is conversation order; inspect exact/inferred evidence and parent-relative context changes
  • SQLite storage — all data stored locally in ~/.contextspy/; no data leaves your machine
  • Agent detection — Copilot, Claude Code/SDK, Codex CLI, opencode, Cursor, OpenAI SDK, and generic clients

License

Apache 2.0 — see LICENSE and NOTICE.

Metadata

Release files for contextspy 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for contextspy 0.5.0
File Size Uploaded
contextspy-0.5.0.tar.gz 932.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for contextspy 0.5.0
File Interpreter ABI Platform
contextspy-0.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 1.8 MB

Release files / contextspy-0.5.0.tar.gz

Download URL contextspy-0.5.0.tar.gz
Size 932.1 kB
Tags Source
SHA-256 checksum
How to use checksums
0af5d44559e3d5202b330990a5fa895e754ccc72aacb3efcefb46d836027fafa
BLAKE2b-256 checksum
How to use checksums
56b836429e6ee8ef7408be00019d39497b135fcc97fec36d33c5ea8da27b697c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.

Transparency log

Release files / contextspy-0.5.0-py3-none-any.whl

Download URL contextspy-0.5.0-py3-none-any.whl
Size 915.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bad3703d147819e12962617749b0377b506635565d72a00bc9d000c051580044
BLAKE2b-256 checksum
How to use checksums
2af5b0b9636b6d0d18e24f9ec34cc88117d4f02cf134c711c0844de2759017e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.

Transparency log

Release history Release notifications | RSS feed

0.6.0

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

This release

0.5.0 This release

2 release files

0.4.1

2 release files

0.3.6

2 release files

0.3.5

2 release files

0.3.4

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.11

2 release files

0.1.10

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.3

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page