Back to Browse

Tokensafe MCP Server

Developer Tools4.3Elevated riskMCP RegistryLocalRemote
Free

Server data from the Official MCP Registry

Context, runtime and review for AI coding agents. One local install.

About

Context, runtime and review for AI coding agents. One local install.

Remote endpoints: streamable-http: https://api.tokensafe.dev/mcp

At a glance

Runs
On your computer, from the npm package tokensafe, which we verified belongs to this listing, or on a server the publisher hosts. You connect to its URL, nothing to install.
Works with
Claude Desktop, Claude Code, Grok Build (formerly Cursor), Windsurf, VS Code, Codex, Antigravity CLI, Gemini CLI, ChatGPT.
Tools (13)
get_public_statscheck_latest_versionget_license_statusget_team_metricsdistill_promptteam_cache_lookupteam_cache_storelist_invoicesget_setup_instructionssearch_docsgenerate_team_seatrevoke_team_seatpreview_weekly_digest

Security report

How we score
4.3out of 10Elevated riskMCP Marketplace security score

Serious: Uses an outdated component (cryptography) with a known security hole

TokenSafe is a local developer-tool MCP server whose core features (AST-based file reading, SQLite indexing, token optimization) match its purpose, and the code shown has no hardcoded secrets or obvious exfiltration. The main concerns are that the compress_prompt tool appears to send developer prompts to an external LLM (DeepSeek-V3) and that optional cloud features send a license bearer token to a remote endpoint; neither could be fully verified because the source was truncated. Both should be confirmed as opt-in and clearly disclosed before the server is trusted with sensitive code. Supply chain analysis found 10 known vulnerabilities in dependencies (0 critical, 7 high severity). Package verification found 2 issues.

Claude reviewed an earlier version of this code on Dec 5, 2026. The code has changed since then.

13 tools verified Β· Open access Β· 17 issues found

Security scores are indicators to help you make informed decisions, not guarantees. Always review permissions before connecting any MCP server.

How to Install & Connect

Available as Local & Remote

This plugin can run on your machine or connect to a hosted endpoint. during install.

Documentation

View on GitHub

From the project's GitHub README.


What's New in 5.x

TokenSafe 4.0 is a major architecture release designed for Zero Mid-Day Lockouts, 3-Second Turn Latency, Exact Code Context (Zero Loss), and Developer Flow:

  • ⚑ SQLite FTS5 BM25 Code Indexer & Search (scoped_search, tokensafe search): Native SQLite full-text search with trigram tokenization and BM25 relevance ranking (<1ms) across the repository. Replaces raw terminal grep entirely with zero-token-waste search.
  • πŸ”— SQLite Graph Cache & Cross-Boundary Route Linking: Persistent SQLite caching (.tokensafe/cache/graph.db) with bidirectional semantic linking between frontend client endpoints (fetch, axios, apiClient) and backend HTTP routes (FastAPI, Express, Flask, Next.js).
  • πŸ–ΌοΈ Vision Image Downscaler (optimize_image, tokensafe optimize-image): Automatically scales down oversized screenshots, architecture diagrams, and mockups (>1024px) via Pillow or macOS sips, saving 50–75% vision tokens while keeping original files intact.
  • 🧠 Anti-Stuck Dead-Ends Ledger (get_mistakes, tokensafe mistakes): Persistent project memory tracking failed hypotheses, loop guard trips, and git reverts to prevent agents from cycling through already-failed solutions.
  • 🧹 Transcript Superseded Output Pruning (prune_superseded, tokensafe prune-superseded): Prunes obsolete intermediate tool reads that were superseded by subsequent edits or re-reads in long agent transcripts (-30-40% context).
  • 🧼 ANSI Escape Sequence Stripper: Cleans all ANSI/VT100 escape codes from tool outputs, test runners, and proxy streams before they enter model context.
  • πŸ‘» Ghost Tokens Auditor (tokensafe doctor): Detects and cleans redundant multi-IDE configuration files (.cursorrules, CLAUDE.md, .windsurfrules, .clinerules) and oversized rule files, saving 2,000–5,000 wasted ghost tokens on every turn.
  • πŸ–₯️ Local Control Panel (tokensafe panel): Loopback-only browser panel over the same local store β€” measured savings and versions, one card per discovered project with OUMV adapter readiness, live runtimes, observe/mutate permissions, reversible wiring, and a curated command runner. No extra dependencies.
  • πŸ›‘οΈ Exact Code Context & Reversible Stash (expand_ref): 100% byte-exact target symbol preservation with reversible 8-char hash anchors (#a1b2c3d4) to instantly recover any folded block.
  • 🌲 C# Tree-sitter Support: Native AST slicing and God Nodes detection for C# (tree-sitter-c-sharp) alongside TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, and PHP.

Install & Agents

Connect TokenSafe to the AI coding agents on your workstation in one command:

# Option 1: Zero-Install via npx (recommended)
npx tokensafe

# Option 2: Python / PyPI
pip install tokensafe && tokensafe

# Option 3: Direct shell script (macOS / Linux)
curl -fsSL https://tokensafe.dev/install.sh | bash

The installer detects which agents live on your machine, registers the TokenSafe MCP server, injects project rules, and wires lifecycle hooks where the agent supports them.

Runtime requirements

  • CPython 3.10+ (3.11+ recommended). If no suitable interpreter is found, the npm launcher provisions a pinned, SHA-256-verified CPython 3.12 build into ~/.tokensafe/runtime and installs the dependencies there, so TokenSafe works on a machine without Python. One-time download: 25 MB on macOS, 47 MB on Windows, 53-68 MB on Linux. Opt out with TOKENSAFE_NO_DOWNLOAD=1, force a specific interpreter with TOKENSAFE_PYTHON=/path/to/python3, relocate the whole tree with TOKENSAFE_HOME.
  • cryptography>=42.0 is the only required Python dependency (Ed25519 license checks, under 1 ms per validation).
  • Optional accelerators, installed by default but not required: tree-sitter plus grammar wheels for AST-accurate slicing across 13 languages (without them the slicer falls back to stdlib heuristics; disable with TOKENSAFE_TREESITTER=off), and Pillow for cross-platform image downscaling (macOS falls back to sips).
  • The managed runtime is pinned in bin/python-runtime.json: CPython 3.12.16 from astral-sh/python-build-standalone, five platform builds, every archive verified against a hardcoded SHA-256 before extraction.
AgentIntegration
Google AntigravityPlugin symlink + hooks + skills + MCP (loaded automatically on startup)
Claude Code CLIMCP + SessionStart / UserPromptSubmit / PreToolUse hooks
CursorMCP + beforeShellExecution / beforeReadFile hooks
Claude DesktopMCP registration (claude_desktop_config.json)
WindsurfMCP registration + global rules
OpenAI CodexMCP in ~/.codex/config.toml (stdio + cloud HTTP natively)
Cline / Roo CodeMCP registration (VS Code)
GitHub CopilotMCP registration
Z.ai CodeMCP registration
Kimi CodeNative Plugin (kimi.plugin.json) + MCP + PreToolUse / SessionStart hooks
ChatGPTCloud connector, nothing to install

Claude Desktop / Cursor MCP config:

{
  "mcpServers": {
    "tokensafe": { "command": "npx", "args": ["-y", "tokensafe", "mcp"] }
  }
}

Cloud features (team metrics, opt-in cloud distillation, shared team cache, billing) run on the remote endpoint https://api.tokensafe.dev/mcp with Authorization: Bearer <TS2. license key>. Four public tools work without a key, so ChatGPT connects with authentication set to None.

Full per-agent configuration, hook details, and the Codex/ChatGPT setup live in docs/AGENT_SETUP.md.

CLI Quickstart

# View live savings dashboard in your terminal
tokensafe stats
⚑ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD
Total Tokens Saved:   4,524,156 tokens
Efficiency Gain:      [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘] 92.5%
Context Traffic:      4,889,255 raw β†’ 370,574 optimized (2,132 events)

β€’ Command Sanitizer (CLI)        :   727,300 tokens saved (263 events)
β€’ Architecture Graph             :   758,256 tokens saved (13 events)
β€’ Multi-turn History Fold        : 2,897,897 tokens saved (471 events)
β€’ Prompt Compactor (local+cache) :    43,502 tokens saved (1,255 events)
# Control panel in the browser: savings, versions, OUMV per project, commands
tokensafe panel

The panel is served from 127.0.0.1 only, needs no extra dependencies, and shows the measured savings figure (estimated/legacy mass is reported separately), the engine + OUMV wire versions, and one card per discovered project with adapter readiness, live runtimes, observe/mutate permissions, reversible wiring, and a curated command runner. The drawer's Repositories block binds the project to one GitHub or GitLab repository (platforms in .tokensafe/review.json) with a live Test against the platform API, and a Next steps block suggests at most three concrete moves from what the panel can actually measure. The What the numbers mean legend (or ?) defines every figure β€” measured vs estimated, context tax, headroom, team-cache hit rate, Sextant adoption. --no-open prints the URL; --port 0 picks a free port. --strict-port (the default) exits with code 3 and names the owning pid when the port is taken, instead of silently moving to the next one; --port-fallback restores probing. --status [--json] prints the running instance (URL, pid, assets dir) and --stop shuts it down. Edited assets are re-read on mtime, so a panel restart is no longer needed after a CSS/JS tweak.

# Audit your environment: MCP tool overhead, skills tax, risky settings
tokensafe doctor

# Recursive security & hygiene audit of a repository
tokensafe guard audit

# Preview prompt compaction on custom input
tokensafe test "fix the validate_token method in src/auth.py to check jwt expiration"

# Map architectural hotspots before multi-file changes
tokensafe graph

# Disable a heavy MCP server without editing JSON
tokensafe mcp disable <server>

# Compile and preview the Friday team ROI digest
tokensafe digest

# Scaffold a new token-optimized project for AI agents
tokensafe create my-app --template fullstack  # tokensafe-ui + tokensafe-python
tokensafe create my-service --template go     # tokensafe-backend (Go)

# Retrofit existing apps for AI agents (out-of-the-box stack detection)
tokensafe integrate          # Generates .tokensafe/oumv.json with safe defaults
tokensafe adapters           # Catalog of frontend & backend OUMV adapters
tokensafe oumv doctor        # Verify live dev-server & static AST capabilities

# Activate a Team or Solo license key
tokensafe activate TS2.eyJlbWFpbCI6...

The full command reference lives in tokensafe help (generated from the registry); Reference shows the task-level map.

Why TokenSafe

Giving coding agents raw access to entire repositories creates three daily costs:

  1. Senior hours burned on AI PRs: reading 2,000-line modules for a 10-line fix makes models forget imports, invent methods, and regress adjacent code.
  2. Secret leaks and unsafe shortcuts: static prompt rules in .cursorrules wear off mid-session. Agents hardcode fallback credentials, disable TLS checks, or stage .env files with git add ..
  3. Mid-sprint quota stops and blind spend: bloated diffs, lockfiles, and verbose MCP schemas burn 5-hour limits while engineering leads lack per-seat ROI visibility.
OutcomeWhat changes for your teamHow it is enforced
Clean code on the first passAgents read only target functions, design tokens, and 1-hop dependencies instead of 2,000 lines of noise.Sub-30ms local AST skeletonizer, architecture graph, predictive signature prefetch, lockfile-stripping diff slicer, loop guard.
Zero leaked secrets in gitHardcoded password fallbacks, TLS bypasses, raw SQL interpolation, and .env commits are stopped before reaching disk or staging.Deterministic TokenSafe Guard on every tool call, output guard on large writes, local PII/key redaction.
Predictable sprint velocity & ROITeammates get warm cache hits, and CTOs receive a Friday ROI digest separating measured and estimated savings.Shared team cache, live context budget HUD, per-seat dashboard.

A $29 seat pays for itself by saving one hour of senior code review or preventing one leaked key. Typical payback: 1 to 3 days of team usage.

Before and After

One contrast: an agent asked to change one helper in a 1,420-line file receives 94 lines of target logic and type contracts instead of the whole module. The same principle applies to terminal output, diffs, and session history.

What breaks coding agentsHow TokenSafe fixes itThe outcome
"Lost in the Middle" context fade: an agent reads a 2,000-line file to change one 10-line helper, forgets imports, and invents methods.AST skeletonizer folds inert bodies into typed signatures while keeping the target symbol and 1-hop callees intact.Focused signal: the model keeps full type contracts without drowning in unrelated logic.
Terminal log flooding: npm test or pytest fails and dumps 4,000 lines of stack traces and lockfile diffs into context.Command sanitizer strips lockfile noise and trims output to the failing assertion and stack frame.Root-cause fixes instead of unrelated rewrites.
Infinite wait on background tests: yarn test hangs in watch mode, or jest finishes but unclosed handles keep the process alive.Test-runner guard forces run-once mode (CI=true, --watch=false, --forceExit) and peeks at <cwd>/package.json to identify the runner behind opaque scripts.The test run terminates with an exit code and the agent moves on.
5-attempt retry loops: an agent repeats the same broken edit until the context budget runs dry.Loop guard detects repeated identical tool calls and halts the cycle.Stuck loops stop before damaging working modules.
Unsafe edits & secret leaks: fallback keys, verify=False, SQL string interpolation, or git add . with .env present.TokenSafe Guard audits writes and shell commands locally before execution.Credentials, SQLi patterns, and destructive commands are blocked locally.

When an operation is blocked, the agent sees an explicit, constructive message:

πŸ›‘οΈ TokenSafe Guard: Blocked a hardcoded secret fallback in config.py.
   Leave the default empty or read from os.environ at runtime.

10 Core Engine Capabilities

Why TokenSafe agents ship working code on the first pass without burning quotas or leaking keys:

CapabilityWhat it solvesHow it worksImpact
1. Architecture Graphget_architecture_graphAgents open an unfamiliar repo and burn 45k tokens blindly crawling files.Analyzes dependency centrality, import hubs, and critical call paths in memory.< 250 tokens to map God Nodes (vs ~45k blind crawl)
2. Smart Code Slicingsmart_read_fileFeeding 3,000 lines into context causes models to hallucinate fake methods.Preserves target method logic while folding uncalled helpers into typed contracts.-95.0% tokens (192 vs 3,840) across 11 languages
3. Pre-Git Security Guardguard_inspectAutonomous agents read .env secrets or hardcode fallback keys in edits.Sub-millisecond pre-flight interception blocks secrets, TLS bypasses, and dangerous commands.0 leaked keys in LLM logs or git history
4. Lockfile & Noise Shieldschema_slicerReading package-lock.json or uv.lock dumps 360k+ tokens in one turn.Intercepts lockfiles and massive schemas, returning a queryable dependency summary.-99.8% tokens (855 vs 367,410 tokens)
5. Monorepo API Surface Mapget_api_surfaceAgents guess interfaces or crawl dozens of modules to find exported types.Extracts all exported types, interfaces, and contracts across the repo in one pass.1 tool call vs 50 separate file reads
6. Subagent Pointer CacheSUBAGENT_DEDUPMulti-turn chats and swarms pay full price to re-read the same shared utilities.In-memory content hashes return 1-line pointer hits for unchanged files.0 tokens wasted on repeat file reads
7. Shared Team Cacheteam_cache10 to 50 engineers repeatedly parse the same core libraries from scratch.L3 monorepo pool shares stripped signatures and package contracts across teammates.72% team hits with 0ms turnaround
8. KV-Cache Prefix Lockingcache_normalizerShifting timestamps and reordered tools break provider prompt cache hits.Locks prefix order, sorts schemas, and injects breakpoints for Anthropic, DeepSeek, and OpenAI.92% cache hit rate at 0.10x provider rates
9. Compact Test Runnersanitize_commandTest suites spew 1,000 lines of passing dots that crowd out instructions.Forces run-once mode (CI=true) and collapses passing runs to a single line.1 line vs 1,200 lines (traces kept on failure)
10. Context Governor & Ledgercompact_conversationModels suffer needle-in-a-haystack amnesia after 70% context saturation.Monitors context thresholds and compacts chat sprawl into an actionable State Ledger.50+ turns without regression or amnesia

Deeper mechanics (language matrix, AST syntax trees, cache tiers, governor) live in docs/ARCHITECTURE.md.

Review Gatekeeper (Team)

tokensafe review turns the same graph and guard layers into a pre-PR pipeline: a deterministic Risk Router classifies a diff into Tier 0 (auto-merge eligible), Tier 1 (fast-track) or Tier 2 (deep review); a local gate runs the security/secret/syntax checks plus your test command; the pre-PR hook blocks git push / gh pr create with a compact fix list in enforce mode; and the GitHub App publishes one Check Run plus a sticky 1-screen brief per PR.

Defaults are fail-safe: dry_run and a report rollout stage. Policy is read from the base branch, CI/infra and policy edits are never Tier 0, and deletions or renames of hubs escalate instead of disappearing from a post-change graph.

Auto-merge is earned, not switched on: report β†’ approval β†’ full is promoted manually after clean Tier 0 merges, approval requires a CODEOWNER, and a per-repo freeze is always one command away. Every decision is hash-chained; outcomes (revert/hotfix/incident) produce Tier 0 precision with a Wilson interval and a ROI marked measured only when the sample supports it. Shipped since: ownership routing (tokensafe review owners), rule packs + review explain, mechanical review fix, and a self-hosted GitLab path with merge-when-pipeline-succeeds. Setup, config and threat model: docs/REVIEW_GATEKEEPER.md; audit contract: docs/REVIEW_AUDIT.md; public numbers: docs/REVIEW_BENCHMARK_PROTOCOL.md.

Reads, ingress, recovery, and host coverage

Compaction is the most expensive event in a long session, and a full re-read after every edit is the most common one. TokenSafe now handles both explicitly.

FeatureSurfaceWhat it does
Diff-on-change readssmart_read_file(path, diff_since=<mtime|sha256>)A changed file returns only bounded unified-diff hunks (≀5 hunks, ≀40% of the file); a rewrite falls back to a normal read. A session-scoped raw baseline makes the diff possible.
Post-compaction recoveryClaude Code PreCompact / PostCompact; fallback detector on every host with a transcriptReinjects a small digest: goal, last state, next focus, and up to five ranked pointers to the turns the compaction dropped. Each pointer expands with tokensafe recall --id <session>:<index>.
Transcript recallCLI tokensafe recall '<query>' [--sessions this|project|all], MCP session_context(action='recall_transcript')BM25F search over prior Claude/Codex/Kimi/ZCode/Cursor/Antigravity transcripts. No index copy; snippets are secret-redacted and output is budget-capped.
Cross-session handoffsStop / PreCompact hooks; MCP session_context(action='recall_transcript') to expand a pointerWrites a bounded, redacted handoffs.json per project under ~/.tokensafe/data (goal, edited files with mtimes, decisions, TODOs), never inside the repo. The next session's brief carries one line, and the guard marks it stale after 7 days or when a tracked file changed.
First-prompt recallClaude Code, ZCode, Kimi, Antigravity user-prompt hooksOne-shot per session: the project's prior transcripts are BM25-ranked against the first prompt and up to two pointers (≀450 chars) are added as context. Disabled when no prior transcript belongs to this workspace; Cursor has no injection channel and skips it.
Project memoryMCP session_context(action='remember'|'recall'|'forget')Machine-local decisions/notes/preferences with dedupe. Manual entries outrank auto-extracted ones (capped 100 vs 30), entries whose files changed are flagged stale, and the brief shows the newest manual decision.
Lossless ingress stagingTOKENSAFE_INGRESS_THRESHOLD (default 8000 tokens), MCP session_context(action='ingress_show'), CLI tokensafe ingress showA long prompt is stored redacted with a recovery handle; the model gets a TOCP summary plus a section index and reads exact sections on demand. tokensafe ingress stats reports the fetch rate.
Blast-radius hintapply_edits resultAfter a successful edit on a warm graph, one advisory line names direct importers and static callers; no crawl, no mandatory follow-up call.
Out-of-context computerun_helper(action='compute')A restricted Python program runs over repository files (AST import/name allowlist, repo path jail, rlimits, 5 s budget) and returns only its JSON result. Inputs never enter the context.
Image peeksmart_read_file(path='shot.png', include_image=true)Returns a downscaled (≀1024 px, ≀512 KiB base64) MCP image block plus one metadata line; hosts without vision keep the text.
Zero-token statuslineClaude Codetokensafe statusline renders today's measured savings in the host status bar. The line never enters the conversation.
Claude Code plugin/plugin marketplace add <owner>/tokensafe then /plugin install tokensafe@tokensafeMarketplace manifest, nine lifecycle hooks (including compact events), and an MCP entry. The plugin fails open if the Python engine is absent.
Host capability matrixtokensafe doctorStates exactly which host supports hooks, compact events, context injection, statusline, and transcript parsing, so partial coverage is never sold as full.

Only hosts with a context-injection surface receive hook-injected digests (Claude Code, ZCode, Kimi Code, Antigravity). Cursor, Codex, Claude Desktop, Windsurf, Cline/Roo, and Copilot get the MCP tools, rules, transcript recall, and the fallback compaction detector; their host contracts expose no equivalent injection point today. Cursor still writes cross-session handoffs on stop; it only skips the push-recall line.

What happens on the first prompt

You install TokenSafe, open a project in your agent, and the first turn does the wiring:

  1. Detect the stack (React/Vue/Solid/Angular + Vite, FastAPI, Flask, Django, Go/Gin|Chi, Node/Express|Fastify, Next.js, Elysia on Bun, ASP.NET Core, Spring, Laravel/Symfony, or nothing supported) β€” every supported app in a monorepo, not just the first.
  2. Activate the adapters:
    • frontend β€” tokensafe dev serves OUMV from an inline Vite config; no file in the repository changes;
    • FastAPI β€” a global ~/.tokensafe/pyhooks/sitecustomize.py mounts mount_tokensafe(app) when the server runs through tokensafe run-backend uvicorn ...;
    • Go β€” one AutoMount() line between tokensafe:oumv markers, byte-exact backup in ~/.tokensafe/inject/, go build validated; --revert restores the entrypoint and go.mod/go.sum when they were not edited after inject (net/http gets a printed manual recipe instead, and Echo is reported as planned);
    • Node (Express/Fastify) β€” one mountTokensafe(app) / registerTokensafe(app) line, same markers and byte-exact revert; ASP.NET Core β€” one AddTokensafe()/UseTokensafe() pair;
    • Next.js (App Router) β€” three generated files: app/api/tokensafe/route.ts (createNextRouteHandlers, bridge on), app/api/tokensafe/bridge/route.ts (the browser bridge) and instrumentation-client.ts (installNextBridge, Next β‰₯ 15.3); older Next gets the two route files plus a manual snippet. --revert deletes exactly the files it created and restores a pre-existing v1 route it upgraded;
    • Elysia (Bun) β€” one app.use(oumv()) line before app.listen() (tokensafe-backend-node/elysia), same markers and byte-exact revert;
    • Flask / Django β€” certified WSGI adapters mounted explicitly: mount_tokensafe(app) in the app factory (wraps app.wsgi_app) or mount_tokensafe(application) in wsgi.py; tokensafe inject --status prints the recipe and writes nothing, because the WSGI application is yours to wrap.
  3. Brief the agent β€” a short routing block (hook context and MCP instructions) says which stack is worked through OUMV and which through the TokenSafe tools. Nothing is written into the repository by the brief.

Without a live runtime oumv stays useful and says what it did: observe/understand/index answer from the static graph, verify answers a labelled static subset (OFFLINE_STATIC_VERIFY: file exists, syntax, OCC version, symbol/route presence) instead of failing, and observe on a file at L1+ returns the same skeleton a read would and seeds the read cache β€” a later smart_read_file on that file returns a pointer instead of the body again.

tokensafe inject --status     # what would be wired, and where
tokensafe inject --dry-run    # same, but explicit
tokensafe inject              # apply every detected app (config + Python autoload + adapter lines)
tokensafe inject --revert     # undo every patch: Go entrypoint/modules, .NET csproj, Next files, Python hook, config
tokensafe create shop --template react-fastapi   # greenfield with everything pre-wired
tokensafe oumv doctor         # readiness: adapter installed? runtime live? blocking reasons

Full matrix and details: docs/OUMV.md.

Benchmarks

Measured agent matrix v7 (Go + React, DeepSeek β€” 3 tasks Γ— 5 runs Γ— 3 arms)

Real 12-assertion oracle re-run after every step; tokens and cost from the provider's usage payload. baseline = file/search/command tools, tokensafe = this product's MCP server (smart_read_file(endpoint="POST /api/…") in one call β†’ apply_edits with the hunk and inline verify="auto"), oumv = the OUMV runtime measured in November 2026 (observe L3 returns the handler, its version and the same-package callees; applyEdit mode=patch carries an inline verify probe and an actionable -32009). The Go sandbox is the benchmark module plus 200 generated service files; the React sandbox is a TaskManager store + component whose declared npm test is the oracle.

ArmSolvedMean stepsMean inputMean outputCost/run
baseline β€” Go15/155.932,2311,712$0.0051
tokensafe β€” Go15/153.18,240401$0.0012
oumv β€” Go15/152.76,712433$0.0011
baseline β€” React15/154.918,3961,591$0.0033
tokensafe β€” React15/154.311,971507$0.0017
oumv β€” React15/154.29,814642$0.0016

vs baseline β€” Go: oumv -79.2% input, -77.8% cost, -55.1% steps; tokensafe -74.4%, -76.4%, -48.3%. React: oumv -46.7% input, -52.7% cost, -14.9% steps; tokensafe -34.9%, -50.4%, -12.2%. Every session in both matrices solved β€” the v6 max-steps flounder on product-validation is gone. On Go the protocol arm creates the fix in 2.0 calls against the product arm's 3.2 and ties it on the other two tasks; on React a component has no endpoint for a route slice, so the protocol arm's getSource β†’ patch path wins there as well.

Full method, per-task tables, both targets, the min–max spread and the limits (one model, alias drift between dates, cache-hit share): OUMV_AGENT_MATRIX_V7.md in the backend repo, generated from the run JSON by go/benchmark/render_agent_matrix.py. The previous measured run is OUMV_AGENT_MATRIX_V5.md.

--- | :--- | :--- | :---: | :---: | :---: | :---: | | Frontend (UI) | tokensafe-ui | React 18/19 vs. TokenSafe UI | 21.0x | -95% (1.5k vs 32.5k) | 1 vs 6 turns | Zero reactive stale closures | | Backend (Python) | tokensafe-python | Vanilla FastAPI vs. TokenSafe UARP | 23.5x | -96% (1.4k vs 33.3k) | 1 vs 6 turns | 0 DB pollution (automatic rollback) | | Backend (Go) | tokensafe-backend | Vanilla Gin vs. TokenSafe Backend | 24.6x | -96% (1.3k vs 33.9k) | 1 vs 6 turns | 0 DB pollution + in-memory compiler guard |


Core SWE Benchmarks

Reference run across 10 production engineering scenarios (169,761 baseline tokens down to 8,173 tokens, -95.2% net context reduction, -99.4% peak single-scenario reduction, +30.6% turn latency speedup with 100% accuracy retention):

Prompt compaction, graph topology (SWE-06), dep_mode="signature" slicing (SWE-07), repeat-read pointer dedup (SWE-09), and parametric slot cache hits (SWE-10) are measured live (1,368 optimized tokens) while baselines (169,761), turn counts, and output estimates (6,805 tokens) are modeled constants. See METRICS.md and BENCHMARK_REPORT.md.

Benchmark ScenarioTask ComplexityBaseline TokensTokenSafe TokensReductionTurn SpeedupAccuracy
SWE-06: Zero-Token Architecture DiscoveryGod Node indexing vs. crawl49,716312-99.4%6 β†’ 1 turns (+83%)100% Pass
SWE-09: Repeat-Read Pointer DedupAgentFirewall unchanged pointer17,388208-98.8%2 β†’ 1 turns (+50%)100% Pass
SWE-03: Monorepo Lockfile Git DiffMonorepo branch diff18,911761-96.0%2 turns100% Pass
SWE-07: Graph-Guided AST Symbol Slicingdep_mode="signature" + collapsed imports26,0231,194-95.4%4 β†’ 2 turns (+50%)100% Pass
SWE-10: Parametric Distillation Slot CacheSlot template hit (0 LLM tokens)2,814133-95.3%2 β†’ 1 turns (+50%)100% Pass
SWE-08: Monorepo Lockfile Grep Leakgit grep across lockfiles10,111491-95.1%2 turns100% Pass
SWE-01: Race Condition / Distributed LockAST query & Redis redlock5,046414-91.8%4 β†’ 3 turns (+25%)100% Pass
SWE-05: Multi-Turn History Compaction8-turn session history fold31,0103,130-89.9%8 turns100% Pass
SWE-02: OAuth JWT Expiration TriageController bug investigation3,733403-89.2%3 β†’ 2 turns (+33%)100% Pass
SWE-04: CI Test Failure ExtractionFull test log & stack trace5,0091,127-77.5%3 turns100% Pass

Why "Up to 99%" (Multiplicative Math & Honest Boundaries)

TokenSafe combines two multiplicative savings layers rather than relying on AST compression alone:

  1. Context Token Reduction (-85% to -99.4%): Graph-guided dep_mode="signature" keeps only the edited symbol body intact while collapsing imports and 1-hop dependency implementations into signatures (-95.4% in SWE-07), Architecture Discovery maps repos in < 350 tokens vs. full crawls (-99.4% in SWE-06), and repeat reads resolve to ~75-token integrity pointers (-98.8% in SWE-09, or -99.56% on raw file re-reads).
  2. KV-Cache Prefix Locking (90.8% hit rate at 0.10x cached-read rate): The Append-Only Epoch Governor (ContextGovernor) freezes history prefixes monotonically up to 80% of the model context window while PromptCacheNormalizer strips volatile metadata, sorts tool schemas, and injects provider cache_control breakpoints / prompt_cache_key. In a live 20-turn replay over src/*.py (BENCHMARK_REPORT.md):
Multi-Turn 20-Turn Replay MetricValueComparison
Byte-Identical KV-Cache Prefix Hit Rate90.8%535,491 / 589,846 input tokens
20-Turn Context Input Tokens-84.6%3,837,648 βž” 589,846
Claude Sonnet 4.5 Input Bill (vs. Uncached)-96.8%Cached input reads @ $0.30/M (0.10x)
Claude Sonnet 4.5 Total Bill (vs. Uncached)-96.6%$11.6779 βž” $0.4005 (includes uncached $15/M outputs)
Claude Sonnet 4.5 Total Bill (vs. Naive Mid-Trim Cache)-84.6%$2.5984 βž” $0.4005
DeepSeek V3 Total Bill (vs. Uncached)-96.9%Cached reads $0.028/M (0.10x), outputs $1.10/M

Honest bounds: When ~85–95% fewer context tokens combine with a 90%+ KV-cache hit rate billed at 0.10x, cached input spend approaches 1–2% of uncached cost (up to ~99% savings) on graph-first, repeat-read, and cache-warm workflows. Total session invoices typically fall 80–97% because newly generated output tokens and first-turn cache writes are never discounted by KV-caching.

How to read these numbers: this benchmark is a simulated harness. Compression ratios and 20-turn KV-prefix byte matches are computed live from real files, while baselines and turn speedups are modeled. Production events in TokenSafe are explicitly labeled measured or estimated (see METRICS.md).

Real-Repository Benchmark (measured on live clones)

No modeling: fifteen popular repositories across 10 languages (Python, TypeScript, JavaScript, Go, Rust, Java, Ruby, PHP, C#, Swift, C) cloned at HEAD, scenarios pre-registered before measurement (tokensafe/bench_scenarios.json), every token counted on real bytes, and deterministic zero-loss gates that disqualify any scenario they fail. Curated rows (all rows in docs/BENCHMARK_REAL.md):

Repo (language)ScenarioBaseline tokTokenSafe tokReductionGates
lodash (JS)Symbol read (AST skeleton)515,843855-99.8%PASS
lodash (JS)Multi-turn + repeat reads1,640,6744,233-99.7%PASS
lodash (JS)Architecture discovery802,825178-99.98%PASS
lodash (JS)Junk-read guard87,4751,745-98.0%PASS
lodash (JS)KV-cache 10-turn bill7,390,3471,567,062-78.8%PASS
fastapi (Py)Junk-read guard (uv.lock cap)367,129855-99.8%PASS
flask (Py)Architecture discovery53,237176-99.7%PASS
sinatra (Ruby)Architecture discovery28,165199-99.3%PASS
composer (PHP)Junk-read guard (composer.lock)33,1031,645-95.0%PASS
flask (Py)Write egress (output axis, $15/M)7,10644-99.4%PASS
flask (Py)Multi-turn + repeat reads45,3365,304-88.3%PASS
curl (C)Symbol read (AST skeleton)125,16831,174-75.1%PASS
rich (Py)Multi-turn + repeat reads80,03612,329-84.6%PASS
requests (Py)Multi-turn + repeat reads59,3809,561-83.9%PASS
flask (Py)Symbol read (AST skeleton)18,8643,784-79.9%PASS
rich (Py)Symbol read (AST skeleton)28,6757,710-73.1%PASS
requests (Py)Symbol read (AST skeleton)9,7432,849-70.8%PASS
sinatra (Ruby)KV-cache 10-turn bill303,85063,393-79.1%PASS
retrofit (Java)KV-cache 10-turn bill3,312,375673,361-79.7%PASS
gin (Go)KV-cache 10-turn bill317,63865,036-79.5%PASS
zod (TS)KV-cache 10-turn bill1,905,787431,857-77.3%PASS
serde (Rust)KV-cache 10-turn bill1,307,460300,472-77.0%PASS
curl (C)KV-cache 10-turn bill1,586,875423,360-73.3%PASS
newtonsoft (C#)Symbol read (AST skeleton)56,07617,871-68.1%PASS
alamofire (Swift)Symbol read (AST skeleton)13,9098,100-41.8%PASS
serde (Rust)Symbol read (AST skeleton)69,61042,671-38.7%PASS
gin (Go)Symbol read (AST skeleton)23,56714,938-36.6%PASS
flask (Py)Secret guard (cat .env -> deny, 0 leak)15382-46.4%PASS
flask (Py)Tree-sitter AST (13 langs)18,8642,410-87.2%PASS
fastapi (Py)Reversible Hash Stashing (#hash)7,60537-99.5%PASS
rich (Py)Context Tax & Ghost Token Audit13,425699-94.8%PASS
rich (Py)Verbose test output (noise strip)746385-48.4%PASS
composer (PHP)Prompt compaction (TOCP)13846-66.7%FAIL
flask (Py)Full-suite pytest output6,4026,191-3.3%PASS
fastapi (Py)Git diff churn -> slice416393-5.5%PASS

Aggregate: ~25.7M measured tokens saved per traced pass over all 15 repositories in 10 languages (186 gated-OK rows; input at $3/M, output axis at $15/M, KV-cache hits billed at $0.30/M). Clean pytest suites honestly score ~0-3% β€” savings are never invented. 17 gate-FAILs and 21 skips are published with reasons on the live page (e.g. fastapi's test-output: strict warning filters escalate a pytest-asyncio deprecation into a pytest INTERNALERROR; whole-repo API surfaces bigger than hub crawls for fastapi/httpie; httpie's core.py refuses skeletonization β€” one function is most of the file). Full table + raw JSON: docs/BENCHMARK_REAL.md Β· live page: https://tokensafe.dev/bench Β· methodology post: https://tokensafe.dev/blog/real-repo-benchmark-5-repos. Reproduce:

tokensafe bench --real                        # all 15 pre-registered repos
tokensafe bench --real --repo=pallets/flask   # one repo
tokensafe bench --real --here                 # your current repository

Head-to-Head Competitor Benchmark (Measured on Real Repositories)

We cloned 8 popular open-source repositories across Python, Go, C, and Java, and tested JayPokale/Chisle, alexgreensh/token-optimizer, and TokenSafe (v4.1.2) on the exact same hub files and target functions. Every token was counted with a calibrated BPE tokenizer on real bytes.

Deterministic zero-loss gates disqualify any output where the code fails to compile/parse, or where the targeted function is missing. Savings without code correctness are just destructive truncation.

Documentation truncated β€” see the full README on GitHub.

Reviews

No reviews yet

Be the first to review this server!