Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents
pip install tokensafe==1.3.12 Copy PIP instructions
Install • MCP Setup • How It Works • Pricing • Official Website & Docs
Connect TokenSafe to all detected AI coding agents on your machine in seconds:
# Option 1: Zero-Install via npx (Recommended for Cursor & Claude Desktop) 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 🔌 Universal MCP Server Configuration Connect TokenSafe directly to Claude Desktop (claude_desktop_config.json) or Cursor MCP Settings:
{ "mcpServers": { "tokensafe": { "command": "npx", "args": ["-y", "tokensafe", "mcp"] } } } 🚀 The Breakthrough: How It Saves 60%–90% Tokens Traditional AI code interactions suffer from massive context bloat:
We originally built TokenSafe for a purely selfish reason: to stop getting $400 monthly LLM API bills from running autonomous coding agents.
Then something unexpected happened during real-world dogfooding.
Our agents didn't just get cheaper — they wrote noticeably better code, stopped inventing imaginary methods, and eliminated cyclic regression bugs.
Transformer models don't write bad code because they're stupid. They write bad code because we drown them in 15,000 lines of garbage.
Why do AI coding agent quotas (like Antigravity's 5-Hour Limit or Claude/OpenAI monthly token budgets) evaporate after just a few prompts?
Whenever an MCP server is configured in your editor (Cursor, Claude Desktop, Antigravity, Windsurf), the complete JSON schema for every single tool is injected into the LLM's system prompt on EVERY API TURN — even if you never use that tool!
┌────────────────────────────────────────────────────────────────────────┐ │ SYSTEM PROMPT ANATOMY (EVERY SINGLE TURN) │ ├────────────────────────────────────────────────────────────────────────┤ │ Base System Instructions ~1,500 tokens │ │ Active Workspace Skills & Prompts ~8,000 tokens │ │ Regular MCP Tools (context7, prisma, etc.) ~800 tokens │ │ 🚨 Heavy MCP Tools (200+ schemas from cloud/re tools) ~6,000 tokens │ ├────────────────────────────────────────────────────────────────────────┤ │ TOTAL HIDDEN BASE TAX BEFORE YOU TYPE A SINGLE CHARACTER: │ │ 🔥 ~16,300 tokens PER TURN × 15 turns = 244,500 tokens burned! │ └────────────────────────────────────────────────────────────────────────┘ 1 Server with 50 tools = ~1,500 – 2,500 tokens of static tax on every turn. 1 Server with 200+ tools = ~5,000 – 10,000 tokens per turn! In a 15-turn coding task, 75,000 to 150,000 tokens are burned on tool schemas alone. How TokenSafe Eliminates MCP Bloat: tokensafe doctor (Context Tax Auditor): Scans all configured MCP servers and active skills, measures the exact token overhead per turn, and flags servers with $\ge 40$ tools as CRITICAL BLOAT. 1-Click MCP Management: Instantly toggle heavy servers without editing JSON files manually: tokensafe mcp disable rea # Prunes 208 schemas from system prompt tokensafe mcp enable rea # Re-enables when actively needed PreInvocation Bloat Alerts: Live in-chat warning badges in the IDE when critical MCP bloat is detected on session start. Data Retention & Compact Rollups: Automatic rolling-window event cleanup (tokensafe prune and tokensafe vacuum) prevents SQLite telemetry from ballooning on disk. ⚡ TokenSafe vs. Graphify: Dynamic In-Flight Defense vs. Static Reports How TokenSafe complements or supersedes static graph tools like Graphify (graphify-labs/graphify):
Complements & Replaces: If you already use Graphify for repository mapping, TokenSafe works alongside it by compressing real-time agent tool reads on the wire. Or use TokenSafe standalone for a zero-configuration, zero-cost, sub-30ms architecture engine out of the box.
TokenSafe features an intelligent prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (-40% to -70% tokens).
Zero Configuration for Solo & Team: You do not need to register for Google AI Studio, OpenAI, or DeepSeek API accounts. TokenSafe Cloud handles high-throughput neural distillation automatically with enterprise-grade sub-second turnaround.
To prevent compiler cost overhead from exceeding token savings, TokenSafe applies a 3-stage defense:
Check your license status, active distillation mode, and cache stats anytime:
tokensafe providers For custom self-hosted environments (TOKENSAFE_SELF_HOSTED=1), configure your preferred provider in data/config.json:
{ "preferred_provider": "gemini", "gemini_api_key": "YOUR_GEMINI_API_KEY", "gemini_model": "gemini-flash-lite-latest", "llm_distill_min_tokens": 100, "distill_max_tokens": 60 } Check active providers and cache stats anytime:
tokensafe providers 📊 Zero-Loss SWE-bench Benchmark Results Verified across 8 real-world production software engineering scenarios (131,604 baseline tokens down to 7,251 tokens, -94.5% net token reduction, +28.1% turn latency speedup with 100% Zero-Loss accuracy retention):
👉 Start your 7-Day Free Trial on our website
# View live savings dashboard in your terminal tokensafe stats ┌────────────────────────────────────────────────────────────────────────┐ │ ⚡ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD ⚡ │ └────────────────────────────────────────────────────────────────────────┘ Total Tokens Saved: 4,524,156 tokens Efficiency Gain: [████████████████████████████░░] 92.5% Estimated Savings: $6.7865 USD Context Traffic: 4,889,255 raw ➔ 370,574 optimized (2132 events) ── Breakdown by Source ────────────────────────────────────────────────── • AST Skeletonizer (Signatures) : 3,509 tokens saved (2 events) • Command Sanitizer (CLI) : 727,300 tokens saved (263 events) • Context Governor : 5,800 tokens saved (29 events) • Graph-Guided Slicer (Call-Graph) : 42,420 tokens saved (14 events) • Architecture Graph (God Nodes) : 758,256 tokens saved (13 events) • Multi-turn History Fold : 2,897,897 tokens saved (471 events) • Output Token Guard (write_file) : 42,466 tokens saved (84 events) • Prompt Compactor (TOCP + Cache) : 43,502 tokens saved (1255 events) • File Line Slicer (AST) : 3,006 tokens saved (1 events) Run `tokensafe test " "` to test compression on custom input. Run `tokensafe html` to view interactive browser dashboard. # Open interactive local Apple dark-mode browser dashboard tokensafe html # Test prompt compression on custom input in real time tokensafe test "please fix the validate_token method in src/auth.py so that it checks jwt expiration and returns boolean" # Audit environment and context token tax (MCP & skills) tokensafe doctor # List configured LLM distillation providers and models tokensafe providers # Analyze repository God Nodes and dependency topology tokensafe graph # Generate compact tokensafe-out/API_SURFACE.md interface snapshot tokensafe map # Manage or disable high-overhead MCP tools tokensafe mcp list tokensafe mcp disable tokensafe mcp enable # Optimize SQLite metrics storage tokensafe vacuum tokensafe prune # Generate or preview Friday team ROI digest email tokensafe digest # Run the SWE-bench zero-loss verification suite tokensafe benchmark # Run the local transparent AI proxy (0.0.0.0:8765/v1) tokensafe proxy # Activate your Pro License key (TS2 Asymmetric Ed25519 Key) tokensafe activate TS2.eyJlbWFpbCI6... 🐳 Docker Deployment (Multi-Provider Support) TokenSafe is fully containerized with a hardened multi-stage production Docker image, non-root security (uid: 1000), and native multi-provider LLM routing.
You can configure any or all of your preferred LLM provider keys:
Run TokenSafe as a centralized microservice or team gateway:
version: '3.8' services: tokensafe: build: context: . dockerfile: Dockerfile container_name: tokensafe restart: unless-stopped ports: - "8765:8765" environment: - TOKENSAFE_HOST=0.0.0.0 - TOKENSAFE_PORT=8765 - TOKENSAFE_DATA_DIR=/app/data # Choose your provider(s): - DEEPSEEK_API_KEY=${DEEPSEEK_API_KEY:-} - OPENAI_API_KEY=${OPENAI_API_KEY:-} - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-} - GEMINI_API_KEY=${GEMINI_API_KEY:-} - TOKENSAFE_LICENSE_KEY=${TOKENSAFE_LICENSE_KEY:-} volumes: - ./data:/app/data healthcheck: test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8765/api/health')"] interval: 30s timeout: 5s retries: 3 Start the container in detached mode:
docker compose up -d 3. Verification & Live SSE Streaming Health check: curl http://localhost:8765/api/health Live SSE Event Stream: curl -N http://localhost:8765/api/events Point your AI Agents: Configure your IDE or Agent to use http://localhost:8765/v1 as the upstream base URL. 🔒 Security Architecture & Cloud API Endpoints TokenSafe Cloud Backend enforces enterprise zero-trust security across all communications:
python3 -m unittest discover tests Zero external runtime dependencies — runs on standard Python 3.10+.
TokenSafe is built on an Open-Core model designed to give every developer immediate zero-friction value while offering unlimited throughput and centralized governance for professionals and teams:
MIT License. Commercial enterprise licenses available for on-premise B2B deployments.
tokensafe markdown 📂 Project Structure agy-token-optimizer/ ├── plugin.json # Antigravity plugin manifest ├── hooks.json # Lifecycle hook declarations (PreInvocation, PreToolUse, PostToolUse) ├── Dockerfile # Hardened multi-stage container deployment ├── docker-compose.yml # Production Docker compose with multi-provider routing ├── rules/ │ └── AGENTS.md # TOCP Protocol directives for LLM (prompt-cached) ├── skills/ │ └── token-optimizer/ │ └── SKILL.md # On-demand Antigravity skill ├── proto/ │ └── tocp.proto # Protocol Buffers contract ├── src/ │ ├── cli.py # Unified CLI dispatcher (npm, pip, standalone) │ ├── cache_normalizer.py # Prompt Cache Prefix Normalizer (Anthropic & DeepSeek) │ ├── governor.py # Context Window Governor & Token Ceiling (Cascading reduction) │ ├── agent_firewall.py # Cross-Agent Deduplication Cache (Subagent Firewall) │ ├── diff_slicer.py # AST Diff Slicer & Lockfile Stripper (`git diff -U2`) │ ├── weekly_digest.py # Friday Team ROI Digest & Engineer Leaderboard │ ├── environment_auditor.py # MCP Server & Skill context token tax auditor │ ├── command_sanitizer.py # High-output terminal command sanitizer │ ├── proxy.py # Multi-provider transparent AI proxy & SSE broadcaster │ ├── graph_engine.py # Sub-30ms AST parser, call graphs & God Node centrality │ ├── tokenizer.py # Zero-dependency calibrated BPE token counter │ ├── compactor.py # Enhanced semantic compactor (Local Regex + Distillation -> TOCP S-Expr) │ ├── distiller.py # Multi-provider LLM distillation engine (Gemini, DeepSeek, OpenAI) │ ├── distiller_cache.py # Two-tier LRU + SQLite prompt distillation cache │ ├── deepseek_distiller.py # DeepSeek-Flash semantic compiler with token arbitrage guard │ ├── slicer.py # AST & Line windowing tool optimizer │ ├── metrics.py # Persistent SQLite metrics engine │ ├── dashboard.py # Visual ANSI terminal, Markdown & reactive SSE web dashboard │ ├── license_manager.py # Ed25519 cryptographic license verification │ ├── mailer.py # Transactional email & Friday ROI digest dispatcher │ ├── mcp_server.py # Native Model Context Protocol (MCP) server │ ├── installer.py # Multi-IDE agent auto-installer & config wizard │ └── cloud_backend.py # Cloud REST backend, telemetry sync & Stripe webhooks ├── hooks/ │ ├── pre_invocation.py # PreInvocation hook entry point │ ├── pre_tool_use.py # PreToolUse hook entry point │ └── post_tool_use.py # PostToolUse hook entry point ├── frontend/ # Modern React / Vite / Tailwind Web App & Dashboard ├── bin/ │ ├── tokensafe.js # Node.js npm launcher (npx tokensafe) │ └── tokensafe # Python CLI launcher (pip / standalone) ├── tests/ # Unit test suite (100% passing) ├── install.sh # One-click installer for Antigravity └── README.md 🛠️ Installation & Antigravity Setup Run the installer:
./install.sh This symlinks the plugin directly into ~/.gemini/config/plugins/agy-token-optimizer. Antigravity automatically loads it on startup.
python3 -m unittest discover tests No external packages required — runs on standard Python 3.10+.
ai llm tokens token-optimization context-window cursor claude antigravity codex mcp mcp-server ast proxy jwt ed25519 zero-trust
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
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.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




