Skip to main content
Glama
README.md
<div align="center">

<img src="docs/assets/logo.jpg" alt="ReToken logo" width="120">

# ReToken

**Cut the token bill of Claude Code and other coding agents, without hiding anything from the model.**

A local Rust proxy that sits between your coding agent and the model provider. It trims noisy tool output, keeps prompt caches warm and lets the model recover anything it shortened.

[![CI](https://github.com/AshleyImmanuel/ReToken/actions/workflows/ci.yml/badge.svg)](https://github.com/AshleyImmanuel/ReToken/actions/workflows/ci.yml)
[![AshleyImmanuel/ReToken MCP server](https://glama.ai/mcp/servers/AshleyImmanuel/ReToken/badges/score.svg)](https://glama.ai/mcp/servers/AshleyImmanuel/ReToken)
[![Release](https://img.shields.io/github/v/release/AshleyImmanuel/ReToken)](https://github.com/AshleyImmanuel/ReToken/releases)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
![Built with Rust](https://img.shields.io/badge/built%20with-Rust-orange.svg)
![Platforms](https://img.shields.io/badge/platforms-Linux%20%7C%20macOS%20%7C%20Windows-lightgrey.svg)

[Quick start](#quick-start) · [Results](#results) · [How it works](#how-it-works) · [Configuration](#configuration) · [Architecture](#architecture)

</div>

---

## Why ReToken

Coding agents re-send the whole conversation on every turn: build logs, test output, JSON responses and file reads. That repeated input is most of an agent's API bill. ReToken removes the noise from it on the wire, so the same agent finishes the same task for less, with no change to the agent.

- **Built for coding agents.** Used day to day with Claude Code. It forwards both API keys and Claude Code subscription (OAuth) logins unchanged. Any client that lets you set an Anthropic, OpenAI or Gemini base URL can point at it.
- **Speaks three wire formats.** Anthropic Messages, OpenAI Chat Completions and Responses, and the Gemini API (`generateContent`) used by Gemini 4 Hydrogen, Neon and other Gemini models.
- **Helps where a proxy can't reach.** `retoken exec` shortens command output before an agent sees it, for apps like Google Antigravity whose model traffic cannot be redirected.
- **Stays on your machine.** Listens on `127.0.0.1` only and forwards each request to the provider your agent already uses, with the agent's own credentials.
- **Every lossy change can be undone.** The model can fetch the original of anything ReToken shortened through the `retoken_retrieve` MCP tool.

## Results

Headless Claude Code benchmark (Claude Sonnet, Claude Code 2.1, November 2026). Each setup ran three tasks (explain code, fix a failing test, summarize a module) three times from a clean checkout. All 36 runs produced a correct answer.

| Setup | Cost per task | Turns | Seconds | Output tokens |
| :--- | ---: | ---: | ---: | ---: |
| Direct to the API | $0.0425 | 4.78 | 12.7 | 859 |
| caveman proxy | $0.0330 | 4.33 | 13.4 | 870 |
| ReToken | $0.0329 | 4.33 | 12.8 | 826 |
| **ReToken + terse mode** | **$0.0302 (−29%)** | **3.78** | **11.4** | **719** |

This is a small sample of short tasks, so treat the numbers as indicative. The harness is in [`benchmarks/`](benchmarks/README.md) so you can re-run it yourself.

**Long, log-heavy sessions.** A second benchmark (Claude Sonnet, November 2026) gave headless Claude Code four tasks on a Python project with noisy test runs and a 23,000-character request log, three runs each. To measure ReToken itself rather than the detour through a proxy, it is compared with the same proxy and retrieval tool with every optimization switched off. All 48 runs produced a correct fix.

| Task | Proxy, optimizations off | ReToken | ReToken + terse mode |
| :--- | ---: | ---: | ---: |
| Fix three bugs, re-running the test suite after each fix | $0.223 | $0.151 (−32%) | $0.154 (−31%) |
| Find a crash in a 23,000-character log | $0.113 | $0.113 (0%) | $0.103 (−9%) |
| Read every module and write docs | $0.150 | $0.149 (0%) | $0.149 (0%) |
| All three in one session | $0.295 | $0.269 (−9%) | $0.241 (−18%) |
| **Average per run** | **$0.195** | **$0.170 (−13%)** | **$0.162 (−17%)** |

These savings come on top of Claude Code's own prompt caching. The biggest change is in cache writes (−21%, against −6% for cache reads), because trimmed output never enters the cache in the first place. Where the agent already filters output itself (`| tail -50`) or reads files it has not seen yet, ReToken leaves the text alone and saves nothing. Three runs per task is a small sample, and this harness is not in the repository yet.

## Quick start

**1. Install**

Download the archive for your platform from the [latest release](https://github.com/AshleyImmanuel/ReToken/releases/latest) (Linux x86_64, macOS Intel and Apple Silicon, Windows x86_64; checksums in `checksums.txt`) and put `retoken` on your `PATH`.

Or build from source with a recent stable Rust toolchain:

```bash
git clone https://github.com/AshleyImmanuel/ReToken.git
cd ReToken
cargo install --path cli        # installs `retoken` into ~/.cargo/bin
```

**2. Connect your agent**

<details open>
<summary><b>Claude Code</b></summary>

```bash
claude mcp add retoken -- retoken mcp   # lets the model recover shortened output
retoken wrap claude                     # starts the proxy and runs Claude Code through it
```

</details>

<details>
<summary><b>Codex CLI</b></summary>

```bash
retoken wrap codex          # works with a ChatGPT plan or an API key, for every agent Codex starts
```

`wrap` adds a `retoken` model provider on Codex's command line: `http://127.0.0.1:8888/chatgpt` when Codex is signed in with ChatGPT (forwarded to the ChatGPT Codex backend), `http://127.0.0.1:8888/v1` with an API key. To make it permanent, put the same provider in `~/.codex/config.toml`:

```toml
model_provider = "retoken"

[model_providers.retoken]
name = "ReToken"
base_url = "http://127.0.0.1:8888/chatgpt"   # or http://127.0.0.1:8888/v1 with an API key
wire_api = "responses"
requires_openai_auth = true
```

Codex already caps each command's output (about 350 tokens per call, middle cut) before it reaches ReToken, and OpenAI caches its long fixed prefix automatically, so there is little left for a proxy to trim: ReToken currently forwards Codex's Responses requests unchanged. Tested with Codex CLI 0.169 on a ChatGPT plan.

Where Codex's tokens go, measured through the proxy (GPT-6.2 Astra, ChatGPT plan). Codex's own "tokens used" figure is exactly uncached input plus output, so cached tokens barely count. Every new session and sub-agent starts with a fixed prefix of about 21k tokens (tool definitions, base instructions, skill list) that the ChatGPT backend caches per session only, so in a short session that prefix is most of the metered total. Shortening old tool outputs in the history was tried and dropped: it cut total input by 21% but raised the metered number, because the rewrite costs a one-time cache miss and the outputs were already cached. A shared `prompt_cache_key` across sessions made no difference either.

What does cut Codex's metered tokens:

- `omit_skill_descriptions = true` under `[features]` in `~/.codex/config.toml`: skill names stay listed and descriptions are read from each `SKILL.md` on demand. Measured: 20.4k → 16.2k tokens at the start of every session and sub-agent, and Codex still found the right skill. The flag is marked "under development" in `codex features list`.
- Fewer fresh starts: continuing a session is far cheaper than starting a new one or another sub-agent.
- A lower `model_reasoning_effort` for routine work.

Uninstalling skills barely helps: Codex fills a fixed budget for the skill list (about 27 KB), so the remaining skills just get longer descriptions. `retoken stats` and the proxy log (`Stream usage:` lines) show input, cached and output tokens per request.

</details>

<details>
<summary><b>opencode</b></summary>

Point the provider's base URL at `http://127.0.0.1:8888/v1`, then register the retrieval server in `opencode.jsonc`:

```jsonc
"mcp": { "retoken": { "type": "local", "command": ["retoken", "mcp"] } }
```

</details>

<details>
<summary><b>Cursor, Windsurf and other IDEs</b></summary>

Start the proxy with `retoken run`, then set the IDE's custom provider or OpenAI base URL to `http://127.0.0.1:8888/v1`. Keep your API key as it is; ReToken forwards it unchanged.

IDE setups are not covered by the test suite. Some IDEs send custom-base-URL requests from their own servers instead of your machine, and those requests cannot reach a proxy on `127.0.0.1`.

</details>

<details>
<summary><b>Gemini CLI and Antigravity CLI (Gemini API key)</b></summary>

These clients must use a Gemini API key (`GEMINI_API_KEY`). Google sign-in traffic is a different API, which ReToken rejects. Register the retrieval server in the client's MCP settings (`~/.gemini/config/mcp_config.json` for the Antigravity CLI):

```json
{ "mcpServers": { "retoken": { "command": "retoken", "args": ["mcp"] } } }
```

Then run the client through the proxy. With `GEMINI_API_KEY` set, `wrap` points `GOOGLE_GEMINI_BASE_URL` at `http://127.0.0.1:8888` (no `/v1`):

```bash
retoken wrap agy
```

The Antigravity CLI also needs `"modelProvider": "gemini"` in `~/.gemini/antigravity-cli/settings.json` to use an API key. Gemini support is tested against a mock Gemini server, not yet against the live API.

</details>

<details>
<summary><b>Google Antigravity app</b></summary>

The app's model traffic goes through Google's own service and cannot be redirected, so the proxy cannot help there. `retoken exec` and a workspace rule keep noisy command output out of the conversation instead:

```bash
retoken init --antigravity
```

See [`docs/antigravity.md`](docs/antigravity.md) for the MCP setup and what `retoken exec` keeps.

</details>

<details>
<summary><b>Aider and other CLI agents</b></summary>

```bash
retoken wrap aider
```

`wrap` starts the proxy if it is not running and sets the base-URL environment variables for the wrapped command only.

</details>

**3. Check it works**

```bash
retoken doctor   # proxy status, config, storage and provider connectivity
retoken stats    # tokens saved, cache hit ratio, bytes transferred
```

**4. Stay up to date**

```bash
retoken update --check   # is there a newer release?
retoken update           # install it and restart the running proxy onto it
```

The running proxy also checks GitHub once a day and installs new releases by itself; see [Updates](#updates).

Prefer to let an agent set it up? Ask it: *"Read AI_INSTALL.md in https://github.com/AshleyImmanuel/ReToken and integrate ReToken after showing me what will change."* [`AI_INSTALL.md`](AI_INSTALL.md) also covers verification and rollback.

## How it works

```mermaid
flowchart LR
    A["Coding agent<br/>(Claude Code, Cursor, ...)"] -->|request| R["ReToken<br/>127.0.0.1:8888"]
    R -->|"trimmed request<br/>+ cache breakpoints"| P["Model provider<br/>(Anthropic, OpenAI, Gemini)"]
    P -->|response| R
    R -->|response| A
    R -.->|"originals"| S[("Local store<br/>&lt;data dir&gt;/ccr")]
    M["retoken mcp<br/>retoken_retrieve"] -.->|reads| S
    A -.->|"tool call"| M
```

1. **The model always sees what it is reading.** A file read reaches the model in full on the turn it is read. Only after the model has moved on does a large file shrink to an outline (signatures, types, exact line numbers) with a handle to the original.
2. **Noise goes, failures stay.** Large build, test and log output is shortened, but errors, assertion details and test summaries are always kept, along with the unusual line a few lines above a crash that often explains it (an untagged "falling back to…" or "timed out"). Large uniform JSON arrays keep their first and last items, any error items and statistical outliers. Exact repeats of earlier tool output become a reference to the first copy.
3. **Lossy only when reversible.** Lossy changes are applied only when the agent exposes the `retoken_retrieve` tool. Without it, ReToken makes lossless changes only. User prompts, system instructions, assistant history, tool definitions and code comments are never altered.
4. **Prompt caches stay warm.** Each tool result changes at most once, so history stays byte-stable. ReToken places Anthropic cache breakpoints (following the client's TTL, including a rolling breakpoint on the conversation tail) and orders OpenAI tools deterministically, so repeated history is billed at the cached rate. For Gemini, ReToken adds no cache markers; Gemini's own implicit prefix caching, where the model supports it, benefits from the same byte-stable history.
5. **Optional terse mode.** Asks the model for short prose replies while keeping code, commands and tool inputs unchanged.

## Configuration

ReToken reads `retoken.json`, `.retoken.json` or `.retoken/config.json` from the working directory, then applies `RETOKEN_*` environment variables on top. Partial files are fine; anything omitted keeps its default. A malformed file stops startup with an error.

```json
{ "port": 8888, "terse_mode": true }
```

| Setting | Env variable | Default | What it does |
| :--- | :--- | :--- | :--- |
| `compression_enabled` | `RETOKEN_COMPRESSION_ENABLED` | `true` | Tool-output compression (lossless unless the retrieval tool is present) |
| `prompt_caching_enabled` | `RETOKEN_PROMPT_CACHING_ENABLED` | `true` | Anthropic cache breakpoints and OpenAI prefix canonicalization |
| `terse_mode` | `RETOKEN_TERSE_MODE` | `false` | Ask the model for terse prose replies |
| `subagent_context_lift` | `RETOKEN_SUBAGENT_CONTEXT_LIFT` | `true` | Multi-agent: move each Claude Code subagent's shared opening context into the cached system prompt so sibling agents read it instead of writing it (see [Multi-agent runs](#multi-agent-runs)) |
| `shared_preamble_breakpoint` | `RETOKEN_SHARED_PREAMBLE_BREAKPOINT` | `true` | Cache breakpoint after the reminders a conversation starts with, when the client has not placed one (Claude Code does for the main agent, not for subagents); only cache markers change |
| `subagent_terse_mode` | `RETOKEN_SUBAGENT_TERSE_MODE` | `false` | Terse replies for Claude Code subagents only (their replies are read by the main agent, not by you) |
| `ccr_enabled` | `RETOKEN_CCR_ENABLED` | `false` | Proxy-side replay of `retoken_retrieve` calls (experimental) |
| `cache_enabled` | `RETOKEN_CACHE_ENABLED` | `true` | Exact-match response cache for deterministic requests |
| `cache_ttl_secs` | `RETOKEN_CACHE_TTL_SECS` | `300` | Response cache entry lifetime |
| `port` | `RETOKEN_PORT` | `8888` | Loopback port to listen on |
| `upstream_timeout_secs` | `RETOKEN_UPSTREAM_TIMEOUT_SECS` | `60` | Connect and idle-read timeout to the provider |
| `allowed_upstream_hosts` | `RETOKEN_ALLOWED_UPSTREAM_HOSTS` | any public host | Allowlist for custom upstreams |
| `gemini_base_url` | `RETOKEN_GEMINI_BASE_URL` | `https://generativelanguage.googleapis.com` | Upstream for Gemini API requests |
| `chatgpt_base_url` | `RETOKEN_CHATGPT_BASE_URL` | `https://chatgpt.com/backend-api/codex` | Upstream for `/chatgpt/...` requests (Codex on a ChatGPT plan) |
| `auto_update` | `RETOKEN_AUTO_UPDATE` | `install` | Daily update check: `install` (download, verify, restart; release binaries only), `notify` (log only) or `off` |

Set `compression_enabled` and `prompt_caching_enabled` to `false` for a byte-for-byte pass-through. The full list, including memory limits, is in [`AI_INSTALL.md`](AI_INSTALL.md#step-4-choose-settings-optional).

## CLI

| Command | Purpose |
| :--- | :--- |
| `retoken run` | Start the proxy on `127.0.0.1:8888` (the default when no command is given) |
| `retoken wrap <cmd>` | Run an agent through the proxy, starting it if needed |
| `retoken exec -- <cmd>` | Run a command and print its output with noise removed (errors and summaries kept, exit code preserved) |
| `retoken mcp` | Serve the `retoken_retrieve` tool over MCP (stdio) |
| `retoken doctor` | Diagnose proxy status, latency, config, storage and connectivity |
| `retoken stats` | Show live token savings, cache hit ratio and data transferred |
| `retoken cache [status\|clear\|invalidate <key>]` | Inspect or clear the response cache |
| `retoken analyze [path]` | Symbol scan and dependency graph for Rust, Python and TypeScript/JavaScript |
| `retoken update [--check] [--from <path>]` | Install the latest release (or a local build) and restart the running proxy onto it |
| `retoken init [--antigravity]` | Add a Claude Code project skill (`.claude/skills/retoken/SKILL.md`); with `--antigravity`, also an Antigravity rule (`.agents/rules/retoken.md`) |

## Multi-agent runs

When Claude Code fans out to subagents (the Agent tool, workflows, high-effort modes), every agent sends the same tool list, system prompt, reminders and opening context (deferred tools, environment, skills), and only its own task differs. Claude Code puts that opening context after the task text, so each sibling writes it to the prompt cache again at the cache-write price. ReToken moves it into the system prompt, before the task, and adds a breakpoint after the shared reminders, so the first agent writes the shared prefix once and every sibling reads it at the cache-read price. No text is changed or dropped. The move is decided on a conversation's first turn and kept for all its turns (pins in `<data dir>/lift-pins.txt`), so thinking-block signatures and cache entries stay valid, and turning it off affects only new conversations.

Measured on a two-subagent Claude Code task (Haiku, 2 runs each): the second subagent's first turn went from writing 4.2k tokens to writing none and reading 32k, cache writes per run fell from 32-63k to 28k tokens, and cost per run fell about 24% ($0.0117 to $0.0089 on average). Answers were unchanged, no request failed, and a subagent still found and loaded a deferred tool through ToolSearch. The saving grows with the number of sibling agents. A single main agent needs none of this: Claude Code already marks its reminders for caching, so a new session reuses tools, system prompt and reminders from the cache (measured: 32.7k tokens read, 5.6k written on a new session's first request), and its opening context carries a per-session scratchpad path, so it cannot be shared across sessions. Tool output inside subagents is trimmed as for the main agent, and `subagent_terse_mode` shortens subagent replies (3-5% in the same test, within noise, so it stays off).

## Updates

`retoken update` installs the newest release over the installed binary and moves the running proxy onto it. `retoken update --check` only reports, `--from <path>` installs a binary you built yourself, `--no-restart` leaves the running proxy alone, and `--force` reinstalls the current release (or replaces a development build).

The proxy checks by itself too: about two minutes after it starts, then once a day by the wall clock (a laptop that slept through the day checks soon after waking), retrying after an hour when GitHub cannot be reached. With the default `auto_update: install`, official release binaries install a newer release and restart; `notify` only logs that one is available; `off` stops the check. Binaries built from source (`cargo install`, forks, local patches) never replace themselves with an upstream release: for them `install` behaves like `notify`.

What an update does:

1. Downloads this platform's archive and `checksums.txt` from the repository's GitHub release over HTTPS, and refuses the archive if its SHA-256 does not match. Pre-releases and drafts are never installed.
2. Runs the new binary's `--version` and refuses it unless it reports the release's version.
3. Renames the current binary to `retoken.old` (`retoken.old.exe` on Windows) next to it and puts the new one in its place. Programs already running from the old file, such as `retoken mcp`, keep running.
4. Starts the new proxy from the same folder and with the same settings. Only once it has loaded its configuration does the old proxy stop accepting connections; it finishes the requests it is serving (for up to 10 minutes), then exits. Agents see at most a moment of refused connections.
5. If the new proxy exits or is not ready within 30 seconds, the old proxy keeps serving and the previous binary is put back. A release that failed this way is never installed automatically again.

Automatic updates only ever move to a newer version, and builds inside a Cargo `target/` directory never update themselves. After `retoken update --from`, automatic installs pause until `retoken update` installs a release again. To go back by hand, stop the proxy, rename `retoken.old` to `retoken`, and set `auto_update` to `off` or `notify` so the next check does not reinstall the newer release. `RETOKEN_UPDATE_API` points the check at a mirror of the GitHub releases API. If the binary sits in a directory you cannot write to without `sudo`, the update fails and logs why; install there by hand or set `auto_update` to `notify`. Update state (paused, skipped version, next check) is kept in `<data dir>/update-state.json`.

## Security and privacy

- **Loopback only.** The proxy binds to `127.0.0.1` and rejects requests whose `Host` header is not a loopback name, which blocks DNS-rebinding attacks from web pages.
- **SSRF protection for custom upstreams.** Loopback, private, link-local, carrier-grade NAT, reserved and cloud-metadata ranges are blocked unless you opt in, and the verified address is pinned at connect time to close the DNS-rebinding window.
- **Credential-aware caching.** Cache keys include a SHA-256 fingerprint of the credentials and client headers, so one key's responses are never served to another. Requests that sample (temperature omitted or above zero without a seed, or `n > 1`) are not cached unless you send `x-retoken-cache-stochastic: true`.
- **Bounded memory.** Request and buffered response bodies are capped at 10 MB, and the response cache at 1,024 entries and 256 MB by default.
- **Keys stay out of logs.** Gemini API keys sent as a `?key=` URL parameter are redacted from log lines and error messages.
- **Verified updates.** Updates come only from this repository's GitHub releases, must match the SHA-256 in the release's `checksums.txt`, and never downgrade on their own. The restart endpoint used by `retoken update` requires a custom header that web pages cannot send, so a site you visit cannot restart the proxy.
- **Local retention.** Originals of shortened output are stored under `<data dir>/ccr` and deleted after 7 days unused.

To report a vulnerability, see [`SECURITY.md`](SECURITY.md).

## Architecture

ReToken is a Cargo workspace. The request path runs through `gateway`, `compressors` and `core`.

| Crate | Status | Role |
| :--- | :--- | :--- |
| [`gateway`](gateway) | Implemented | `axum` proxy: provider routing, request rewriting, streaming, caching, admin routes |
| [`compressors`](compressors) | Implemented | Tool-output classification and compression, log slicing, JSON collapsing, the CCR store |
| [`core`](core) | Implemented | Configuration, response cache, session state, telemetry |
| [`cli`](cli) | Implemented | The `retoken` binary and its MCP server |
| [`mcp`](mcp) | Implemented | Standalone `retoken-mcp` server exposing proxy status, doctor and cache tools to agents |
| [`analyzers`](analyzers) | Implemented | Comment-aware symbol extraction and dependency graphs |
| [`retrieval`](retrieval) | Experimental | Context budgeting and prefix canonicalization helpers |
| [`scheduler`](scheduler) | Experimental | Tool-call DAG scheduling and prefetch prototypes (not on the request path) |

See [`ARCHITECTURE.md`](ARCHITECTURE.md) for the request data flow.

## Project status

ReToken is in active development and its author uses it daily with Claude Code. The default configuration is conservative: lossless rewriting plus cache breakpoints. Lossy elision, terse mode and proxy-side CCR replay change what the model sees, so they are opt-in or gated on the retrieval tool. CCR replay in particular has not been tested against high-volume production traffic.

Planned: `retoken trace` for per-request payload inspection, and `retoken benchmark` for one-command cost measurement.

## Contributing

Bug reports, benchmark results and new compression strategies are welcome. Read [`CONTRIBUTING.md`](CONTRIBUTING.md) to set up and open a pull request; issues labelled `good first issue` are a good place to start.

## License

[MIT](LICENSE) © Immanuel Ashley

TDQS

A4.7/5.0

Scored across 1 tool

Disambiguation5/5

There is only one tool, so there is no possibility of misselection between competing tools. Its purpose—retrieving elided content via a ReToken handle—is stated unambiguously, including the guidance to skip it when visible output suffices.

Naming Consistency4/5

The single name `retoken_retrieve` follows a clean snake_case, server-prefixed verb pattern. There is no inconsistency to speak of, though a one-tool set gives no opportunity to demonstrate a repeatable convention.

Tool Count4/5

The server's scope is deliberately narrow—recovering content hidden behind a marker—and one tool covers that job without redundancy. It is on the thin side, but no additional tool would obviously earn its place.

Completeness4/5

The tool supports the three plausible access modes (whole original, search, line range) plus truncation handling, which covers the retrieval lifecycle well. Minor gaps exist around discovering handles or inspecting size/metadata without fetching content.

Maintenance

ActivityActive
ResponsivenessNo recent community issues