Skip to main content
Glama

                                 ┌────────────────────────────────────────────────────────┐
                                 │                   Autonomous Agents                    │
                                 │  Claude Code • Cursor • Antigravity • Cline • Windsurf │
                                 └───────────────────────────┬────────────────────────────┘
                                                             │
                                                             ▼ (HTTP / SSE Outbound Prompts)
   ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
   │                                 ⚡ TOKENECTOMY AI GATEWAY (127.0.0.1:8080)                                       │
   │                                                                                                                  │
   │  ┌─────────────────────────┐   ┌───────────────────────────┐   ┌──────────────────────────────────────────────┐  │
   │  │   Zero-Cost Prompt      │   │   Zero-Leak Credential    │   │         Polyglot Trace Surgery               │  │
   │  │         Cache           │   │         Redaction         │   │            (9 Languages)                     │  │
   │  │  <1ms Hit • 100% Free   │   │  API Keys • JWTs • DB URIs│   │  node_modules • site-packages • .cargo       │  │
   │  └───────────┬─────────────┘   └─────────────┬─────────────┘   └──────────────────────┬───────────────────────┘  │
   │              │                               │                                        │                          │
   │              └───────────────────────────────┼────────────────────────────────────────┘                          │
   │                                              ▼                                                                   │
   │                                 Smart Upstream Auto-Router                                                       │
   │                         (Anthropic • OpenAI • Groq • Ollama Local)                                               │
   └──────────────────────────────────────────────┬───────────────────────────────────────────────────────────────────┘
                                                  │
                 ┌────────────────────────────────┼────────────────────────────────┐
                 ▼                                ▼                                ▼
       api.anthropic.com                  api.openai.com                   localhost:11434
    (Claude 3.5 / 3.7 Sonnet)         (GPT-4o / o1 / o3-mini)              (DeepSeek / Llama)

⚡ Quick Start (10s)

0. Zero-Config One-Liner Wrapper (wrap)

Run any coding agent or test suite directly behind Tokenectomy's privacy & caching gateway with zero manual environment variable setup:

# Wrap Claude Code CLI
razor wrap -- claude

# Wrap Aider with DeepSeek or Ollama (Auto-Transpiled on the fly!)
razor wrap -- aider --model deepseek/deepseek-chat

# Wrap test runs to scrub logs and prevent accidental credential leakage
razor wrap npm test

1. Launch the Standalone AI Gateway (Manual Mode)

npx -y tokenectomy-razor --proxy

💡 Smart Multi-Provider Auto-Routing & Universal LLM Transpiler ON by default! Tokenectomy automatically analyzes request paths and headers. Need to run Claude Code against DeepSeek or Ollama? Tokenectomy transparently transpiles Anthropic /v1/messages format into OpenAI /v1/chat/completions on-the-fly and vice-versa.

2. Connect Your Favorite Agent

Point your coding agent or CLI to the local gateway on 127.0.0.1:8080:

Agent / Environment

Setup Command or Configuration

Auto-Routed Upstream

Claude Code

export ANTHROPIC_BASE_URL="http://127.0.0.1:8080"

https://api.anthropic.com

Cursor

Models &gt; OpenAI Base URL: http://127.0.0.1:8080/v1

https://api.openai.com

Google Antigravity / Gemini

export OPENAI_BASE_URL="http://127.0.0.1:8080/v1"

https://api.openai.com

Cline / Roo Code

Provider: OpenAI Compatible &bull; Base URL: http://127.0.0.1:8080/v1

https://api.openai.com

Ollama / Local LLMs

Base URL: http://127.0.0.1:8080

http://localhost:11434

3. Real-Time FinOps & Security Dashboard

Open http://127.0.0.1:8080/dashboard in your browser to observe live token reductions, prompt cache hits, dollar savings, and redacted credentials in real time.


4. Companion MCP Server Setup (Sub-Cortex)

For agents calling deep diagnostic tools (get_error_context, analyze_code, apply_code_patch):

Claude Code CLI

claude mcp add tokenectomy npx -y tokenectomy-razor --mcp

Google Antigravity / Gemini CLI

agy mcp add tokenectomy-razor -- npx -y tokenectomy-razor --mcp

Cursor Composer (.cursor/mcp.json)

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

Claude Desktop (claude_desktop_config.json)

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

5. Terminal Piping & CLI Scrubbing

npm test 2>&1 | npx tokenectomy-razor

Related MCP server: uacos

🛑 The Problem: Why Your AI Hits Rate Limits & Hallucinates

When your app crashes during development (Next.js, Express, FastAPI, Tokio), the runtime dumps hundreds of lines of third-party plumbing from node_modules or site-packages.

When you paste that raw crash dump into Cursor or Claude:

  1. Eats Your 5-Hour Rate Limit: A single Express/Prisma error can dump 5,000 to 45,000 tokens of third-party library code you never wrote. A few crash loops easily burn your session limit.

  2. Triggers AI Hallucinations: Claude gets lost in framework internals (node_modules/express/lib/router/layer.js or starlette/routing.py) and tries to edit library files instead of your actual application code.

  3. Leaks Secrets & Credentials: Connection strings with raw database passwords, JWT bearer tokens, and cloud keys embedded in error traces get forwarded to external model servers.

Raw Terminal Crash (45,820 tokens + Leaked Secrets)
     │
     ▼  <0.2ms Local Rust DFA Engine
[Redact Passwords & Keys] ──► [Strip Third-Party Framework Frames] ──► [Isolate Root Cause]
     │
     ▼
Clean Context (118 tokens • Zero Secrets • Sub-millisecond)

🔍 Before & After Comparison

❌ Without Tokenectomy: AI Hallucinates & Burns Context

TypeError: Cannot read properties of undefined (reading 'token')
    at loadComponents (/app/node_modules/next/dist/server/load-components.js:14:2)
    at renderToHTML (/app/node_modules/next/dist/server/render.js:50:5)
    at nextServer (/app/node_modules/next/dist/server/next-server.js:80:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runMicrotasks (node:internal/process/task_queues:120:3)
    at checkoutHandler (/app/pages/api/checkout.ts:42:15)
Database connection failed: postgresql://admin:super_secret_password@db.prod.internal:5432/primary
API key leaked: sk-ant-api03-abcdef1234567890abcdef1234567890

What Claude does: Analyzes load-components.js and next-server.js, speculates on Webpack / Next.js internals, and leaks connection credentials to remote inference logs.

✅ With Tokenectomy: Clean Context & Instant Fix

// [Tokenectomy Surgery: 5 internal framework frames pruned (83.3%)]
// Source: /app/pages/api/checkout.ts:42:15
42 |   const sessionToken = req.headers.authorization.token;
   |                                                  ^ TypeError: Cannot read properties of undefined (reading 'token')
🛡️ [CONNECTION_STRING_REDACTED]
🛡️ [ANTHROPIC_KEY_REDACTED]

What Claude does: Instantly identifies that line 42 in checkout.ts attempted to access .token on undefined headers. Suggests optional chaining req.headers.authorization?.token immediately. Credentials redacted before transmission.


🔬 Verifiable Benchmarks

All performance claims are hardware-grounded and independently reproducible on physical hardware (measured on 10-Core Intel Core i5-1235U @ 15W running Arch Linux, Kernel 6.13):

Hardware Dependency Notice: Performance is hardware-dependent; reported throughput represents measured results on the specified test hardware (10-Core Intel Core i5-1235U @ 15W TDP). Throughput scales with higher TDP desktop/server CPUs and faster memory buses. Developers are encouraged to independently audit performance using the reproduction command below.

$ cargo test --release --test stress_benchmark -- --nocapture

=====================================================================================
🧪 TOKENECTOMY OSS VERIFIABLE HEAVY STRESS BENCHMARK (100% REPRODUCIBLE IN OSS)
   Hardware: 10-Core / 12-Thread Intel Core i5-1235U | OS: Arch Linux | Kernel Telemetry Active
   Initial Baseline Process Memory (VmRSS): 3.45 MB
=====================================================================================

🔥 [TEST 1/3] QUARTER-MILLION LINES LOG REDACTION TORTURE (250,000 LINES / 25MB+ BUFFER)
  ├── Buffer Size: 24.44 MB (250000 lines)
  ├── Redaction Latency: 471.05ms (51.9 MB/sec)
  ├── Line Throughput: 530,735 lines/sec
  ├── Peak Memory (VmRSS): 76.05 MB (Delta: +72.60 MB)
  └── Status: ✅ PASSED (100% of 250,000 lines sanitized, zero memory balloon)

🔥 [TEST 2/3] REDOS CATASTROPHIC BACKTRACKING TORTURE (50,000 CHARS PAYLOAD)
  ├── Attack Payload Size: 50,082 characters
  ├── Execution Latency: 1.165 ms
  └── Status: ✅ PASSED (Linear O(N) evaluation, ReDoS-resistant on tested payloads)

🔥 [TEST 3/3] HIGH-CONCURRENCY TORTURE (100 PARALLEL OS THREADS)
  ├── Thread Concurrency: 100 concurrent OS threads
  ├── Successful Operations: 100/100 (100.0%)
  ├── Total Elapsed: 11.31ms
  ├── Concurrency Throughput: 17,688 ops/sec
  ├── Final VmRSS: 78.99 MB
  └── Status: ✅ PASSED (Zero race condition, zero deadlock)

=====================================================================================
🏆 TOKENECTOMY OSS STRESS BENCHMARK: 3/3 PASSED (100% GREEN)
   Total Suite Duration: 580.83ms
   Bounded Final VmRSS: 78.99 MB
=====================================================================================
test test_oss_heavy_stress_benchmark ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.58s

Benchmark Target

Workload Under Test

Verified Measurement

Result

Log Redaction Throughput

250,000 lines (24.44 MB) enterprise dump with API keys & connection URIs

530,735 lines/sec (471.0 ms, 51.9 MB/s)

Pass

ReDoS Resilience

50,000-character pathological backtracking regex payload

1.16 ms (Deterministic Linear $O(N)$ DFA Evaluation)

Pass

Thread Concurrency

100 concurrent OS threads executing simultaneous redaction

17,688 ops/sec (100/100 completed in 11.31 ms)

Pass

Memory Footprint

Peak Resident Memory during 250k-line continuous stress test

76.05 MB VmRSS via /proc/self/status (~3× input buffer size)

Pass

Release Test Suite

Full integration test matrix across extractors, filters, and analyzers

90 / 90 Verified Green (Zero panics, zero leaks)

Pass

🛡️ Automated Redaction & Secret Sanitization Benchmark

Evaluated across an internal benchmark test fixture (tests/fixtures/) of 12 polyglot crash traces (Rust, Python, TypeScript, Go, YAML) containing 22 ground-truth credentials and clean negative controls. Evaluated head-to-head against Gitleaks v8.30.1 (default ruleset).

Architectural Note: Gitleaks is designed primarily as a repository commit/diff scanner, not an in-memory runtime trace redactor. Tokenectomy Razor is engineered specifically for runtime stream sanitization and stack trace surgery.

1. Per-Category Precision, Recall & F1-Score

Secret Category

Ground Truth

Razor Recall

Razor F1

Gitleaks Recall

Gitleaks F1

Sanitization Advantage

Anthropic Claude API Key (sk-ant-...)

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

AWS Access Key ID (AKIA...)

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

AWS Secret Access Key

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

Database URI (PostgreSQL, MySQL, Redis, Mongo)

4

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

Generic Passwords / Auth Secrets (YAML/JSON)

3

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

GitHub Personal Access Token (ghp_...)

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

GitLab Personal Access Token (glpat-...)

1

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

HuggingFace API Token (hf_...)

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

JSON Web Token (RFC 7519 / Truncated)

2

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

npm Registry Access Token (npm_...)

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

OpenAI API Key (sk-..., sk-proj-...)

1

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

PEM Private RSA Key Block

1

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

PyPI Package Upload Token (pypi-AgEI...)

1

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

SendGrid API Key (SG...)

1

100.0%

100.0%

0.0%

0.0%

+100% Recall (M2M zero-leak)

Slack Bot/User Token (xoxb-...)

1

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

Stripe Live/Test Secret Key (sk_live_...)

1

100.0%

100.0%

100.0%

100.0%

Parity (100% caught)

2. Head-to-Head Performance & Architectural Summary

Dimension

Tokenectomy Razor (--scrub)

Gitleaks v8.30.1

Architectural Rationale

Overall Secret Recall

100.0% (22/22)

36.4% (8/22)

Razor captures unquoted URIs, DB ports & AI keys missed by diff rules

Overall Precision

100.0% (0 False Positives)

88.9%

Zero false triggers on compiler errors & minified traces

Overall F1-Score

100.0% (internal fixture)

51.6%

Comprehensive coverage engineered specifically for crash context

Execution Engine

High-throughput Rust DFA ($O(N)$)

Go regex scanner + Git tree crawler

Sub-millisecond latency for agent streaming backtraces

ReDoS Resilience

Deterministic Linear Time ($O(N)$)

Engine dependent

Non-backtracking DFA regex prevents catastrophic backtracking on tested dumps

Sanitization Action

Inline token redaction ([KEY_REDACTED])

Warning log only (No scrub)

Directly sanitizes text before ingestion by LLM cortex

3. Token Reduction & LLM Context Savings (tiktoken cl100k_base)

Metric

Measured Value

Operational Impact for AI Coding Agents

Mean Token Reduction

41.67%

Consistently shrinks raw crash trace token footprint

Median Reduction (P50)

42.95%

Typical credential and connection dump reduction

90th Percentile (P90)

61.42%

Eliminates long multi-line keys and credentials

Min / Max Spread

0.00% — 81.36%

0% on clean negative controls (zero distortion), up to 81.4% on leaks

Total Tokens Preserved / Saved

920 tokens (44.02% net)

Prevents context window saturation and reduces LLM billing


🔌 Advanced Agent & Gateway Configuration

1. Multi-Provider AI Gateway Options (--proxy)

Tokenectomy's gateway runs locally on 127.0.0.1:8080 with zero manual configuration. In complex development environments or containerized agent topologies, you can customize binding and routing:

# Default Smart Auto-Routing (routes Anthropic, OpenAI, and Ollama requests dynamically):
razor --proxy

# Safety Circuit Breaker: Prevent runaway agent loops from burning your hourly budget or 5-hour window:
razor --proxy --max-hourly-tokens 200000

# Resilient 429 Auto-Retry: Automatically pause and retry when hitting upstream rate limits (default: on):
razor --proxy --max-retries 5

# Explicit upstream override (e.g. Groq, vLLM, or OpenRouter):
razor --proxy --upstream-url https://api.groq.com/openai/v1

# Secure remote container binding with mandatory bearer token:
razor --proxy --proxy-bind 0.0.0.0:8080 --allow-remote --proxy-token "$MY_GATEWAY_TOKEN"

Real-Time Metrics & Prometheus Export

Tokenectomy exposes live FinOps and token economics data via JSON:

curl http://127.0.0.1:8080/v1/metrics

Returns instant telemetry for rate_limits_mitigated, circuit_breaker_trips, last_latency_ms, current_hourly_tokens, cache_hits, cache_tokens_saved, and estimated_cost_saved_usd.


2. Standalone CLI & Terminal Scrubbing

When debugging or piping terminal test output directly:

# Pipe terminal test failures through the surgical redactor:
npm test 2>&1 | razor --scrub

# Sanitize a specific raw log file:
razor --scrub --file /var/log/app/error.log > sanitized.log

# Offline local air-gapped mode (zero external network calls):
cat failure.log | razor --scrub --local-only

🛠️ Exposed MCP Tools

Tokenectomy Razor complies with Glama Grade A Tool Definition Quality Score (TDQS) with explicit parameter boundaries:

Tool Name

Capability Description

get_error_context

Performs trace surgery on error dumps, removes framework noise, redacts credentials, and extracts relevant local source context bounded to the workspace.

analyze_code

Performs static AST code analysis to detect resource leaks, unclosed handles, and syntax vulnerabilities with bounded execution limits and precise LSP UTF-16 coordinates.

apply_code_patch

Applies atomic file modifications with post-write language syntax verification (cargo check, py_compile, node --check) and automated rollback on failure.

search_stack_overflow

Queries Stack Exchange API for relevant error signatures using sanitized, redacted search terms.

audit_context_health

Audits raw logs, traces, or prompt payloads for token bloat, framework noise, and credentials. Returns M2M telemetry, savings metrics, and context health grades.


🌐 Supported Polyglot Ecosystems

Language

Frameworks Supported

Excluded Framework Internals

Rust

Tokio, Actix-web, Axum

.cargo/registry, .rustup, target/debug/build

TypeScript / JS

Next.js, Express, NestJS, Vite

node_modules, .next, dist, webpack internals

Python

Django, FastAPI, Flask, PyTorch

site-packages, dist-packages, venv, __pycache__

Golang

Gin, Fiber, Stdlib Panics

go/src (stdlib), go/pkg/mod, vendor

Java / Kotlin

Spring Boot 3, Tomcat, Netty

.m2/repository, .gradle/caches, internal bytecode

C / C++

AddressSanitizer, GDB / LLDB

/usr/include, /usr/lib, vcpkg_installed

C# (.NET)

ASP.NET Core, .NET Runtime

System.Private.CoreLib, Microsoft.AspNetCore

Ruby on Rails

Rails, Sinatra, Bundler

/gems/, ruby/gems, internal rack handlers

PHP

Laravel, Symfony

vendor/composer, vendor/symfony


📦 Installation Options

Method 1: Instant via npx (Zero Toolchain Setup)

npx -y tokenectomy-razor --mcp

Method 2: Cargo (crates.io)

cargo install tokenectomy

Method 3: Precompiled Standalone Binaries

Zero-dependency, standalone release binaries available on GitHub Releases:

  • Linux: x86_64-unknown-linux-gnu, x86_64-unknown-linux-musl, aarch64-unknown-linux-gnu

  • macOS: aarch64-apple-darwin (Apple Silicon M1/M2/M3/M4), x86_64-apple-darwin (Intel)

  • Windows: x86_64-pc-windows-msvc.exe

Method 4: Multi-Arch Docker Container (GHCR)

docker pull ghcr.io/tokenectomy-labs/razor:latest
docker run -i ghcr.io/tokenectomy-labs/razor:latest --mcp

⚖️ Edition Comparison

Capability

Razor (Community OSS)

Sentinel (Commercial Tier)

Polyglot Stack Trace Surgery

Yes (9 Runtime Languages)

Yes (All 9 Languages + Deep AST Semantic Healing)

O(N) ReDoS-Safe Secret Redaction

Yes

Yes

JSON-RPC 2.0 MCP Server

Yes

Yes

AI Gateway Reverse Proxy (--proxy)

Yes

Yes

SHA-256 Idempotency Cache (24h TTL)

Yes

Yes

FinOps Metrics Dashboard

Yes

Yes

Syntax Validation Rollback (Compilers / Linters)

Yes

Yes

Automated Test Suite Rollback (0 Dirty Diff)

—

Yes

Tree-sitter AST Syntax Healing

—

Yes

Anti-Hallucination Scope Guard

—

Yes

Multi-File Atomic Transactions

—

Yes

Time Machine Undo Engine (--undo)

—

Yes

Autonomous Healing State Machine

—

Yes

Need Enterprise AST Self-Healing? Explore the Sentinel Tier


🗺️ Roadmap & Milestones

Milestone / Capability

Status

Target

Core Polyglot Log Surgery & $O(N)$ ReDoS Redaction

✅ Complete

v1.0.0

AI Gateway Reverse Proxy (--proxy) & Idempotency Cache

✅ Complete

v1.1.0

Multi-arch Docker & GitHub Actions Marketplace Action

✅ Complete

v1.1.3

Static AST Analysis Engine (analyze_code) & UTF-16 LSP

✅ Complete

v1.1.5

Glama.ai Tool Definition Quality Score (TDQS Grade A)

✅ Complete

v1.1.5

Precompiled Standalone Binaries (Linux, macOS, Windows)

✅ Complete

v1.1.6

Official MCP Registry Listing (io.github.Tokenectomy-Labs/razor)

✅ Complete

v1.1.7

mcpservers.org Directory Listing

✅ Complete

v1.1.7

Java/Kotlin (Spring Boot 3) & C/C++ (ASan) Extractors

✅ Complete

v1.2.0

C# (.NET) & Ruby on Rails Deep Stack Surgery

✅ Complete

v1.2.2

User-defined custom redaction & noise rules (~/.tokenectomy.toml)

✅ Complete

v1.2.2

Autonomous Context Health Audit (audit_context_health) & M2M Advisory

✅ Complete

v1.2.2

Automated Redaction Benchmark & CI Gate

✅ Complete

v1.2.2

Declarative Advisory M2M Control Plane ([:TOKENECTOMY:M2M_CONTROL_PLANE:v1.3.0])

✅ Complete

v1.3.0

Interactive Multi-Strategy Budgeting (aggressive, conservative, lossless_compact)

✅ Complete

v1.2.3

GitHub Actions OIDC Official Registry Publishing Gate

✅ Complete

v1.2.3

awesome-mcp-servers Community Catalog Listing

✅ Complete

v1.2.4

Inline Dropped Frame Identities ([DROPPED_FRAMES: ...]) & Anti-Silent Truncation Audit

✅ Complete

v1.3.1

Content-Addressable Raw Log Cache & Verification Hash (--diff-verify)

✅ Complete

v1.3.1

Smart Multi-Provider Auto-Routing (Anthropic, OpenAI, Ollama) & Zero-Cost Prompt Caching

✅ Complete

v1.3.3

Agent Safety Circuit Breaker (--max-hourly-tokens), 429 Auto-Retry Mitigator & CORS Preflight

✅ Complete

v1.3.3

Universal LLM Format Transpiler (OpenAI /v1/chat/completions ⇄ Anthropic /v1/messages)

✅ Complete

v1.3.4

Zero-Config Agent Command Wrapper (razor wrap -- <cmd>) & Git Pre-commit Hook

✅ Complete

v1.3.4

Multi-Provider High-Availability & Automatic Outage Fallback

📋 Planned

v1.4.0

Declarative AI Gateway Configuration (gateway.toml / tokenectomy.yaml)

📋 Planned

v1.4.0

Full SSE Streaming Token Caching Engine

📋 Planned

v1.4.0

Native VS Code & JetBrains companion extensions

📋 Planned

v1.4.0

Server-Sent Events (SSE) remote MCP transport

📋 Planned

v1.4.0


🔒 Security & Invariants

  • Local Execution by Default: All stack trace parsing, frame pruning, and secret redaction execute locally on physical hardware.

  • Documented Network Egress: In MCP server mode, search_stack_overflow is the sole tool with outbound network egress (HTTPS to api.stackexchange.com). The payload is strictly limited to sanitized, redacted error signature text (no code lines, no local paths, zero credentials). In air-gapped environments, use --local-only to disable network search entirely.

  • Deterministic Linear-Time Pattern Matching: All pattern matchers utilize non-backtracking DFA regex engines ($O(N)$ linear time) and Aho-Corasick automaton evaluation.

  • Path Traversal Boundary Isolation: File operations are strictly locked within the active workspace root (CWD). Path traversals (../) and unauthorized symlinks are blocked.

  • Safe Rust Implementation: Core execution paths enforce safe Rust memory guarantees with bounded stream readers (.take()) preventing resource exhaustion.

For vulnerability disclosures, please review our Security Policy.


Tokenectomy Razor is provided strictly for lawful developer productivity, observability, log surgery, and defensive credential redaction. Any downstream forks, clones, redistributions, or private deployments operate completely independently of the original authors. Tokenectomy Labs and its maintainers assume zero liability for unlawful, malicious, or unauthorized actions committed by third parties using this codebase or derivatives thereof. All downstream operators bear 100% individual responsibility for compliance with local and international cybersecurity laws. See DISCLAIMER.md for full legal terms.

❓ Frequently Asked Questions (FAQ)

How does Tokenectomy Razor prevent Claude Code & Cursor from hitting rate limits?

When tests or terminal builds crash, frameworks like Next.js, Express, Jest, and Django dump thousands of internal stack frames (node_modules, site-packages). Sending raw 5,000-line crash logs consumes 15,000 to 45,000 tokens per prompt, draining your 5-hour session limit in minutes. Tokenectomy Razor intercepts logs and strips 95% of non-actionable framework plumbing, reducing a 40,000-character crash log to under 200 essential tokens in <0.2ms.

How do I stop Cursor from sending node_modules error logs to LLMs?

Run Tokenectomy Razor as a local AI Gateway reverse proxy (npx -y tokenectomy-razor --proxy). In Cursor settings, point your OpenAI Base URL to http://127.0.0.1:8080/v1. Any terminal error output pasted or referenced by Composer will be automatically sanitized, scrubbed, and cached on the fly before reaching model servers.

How does Tokenectomy prevent credential leakage in error logs?

All log surgery and secret redaction execute 100% locally on your machine in memory before outbound transmission. Razor uses deterministic linear-time regex and Aho-Corasick automata to detect and redact PostgreSQL/MongoDB connection URIs, JWT bearer tokens, and cloud API keys with [REDACTED] tokens. Zero cloud egress is required for scrubbing.


🤝 Community & Resources


Available Tools

5 tools
analyze_codeA

Performs static AST code analysis using Tree-sitter to detect resource leaks (such as unclosed file handles), security vulnerabilities, and logic flaws with bounded execution limits and precise LSP UTF-16 coordinates.

• Side Effects: None. Strictly read-only analysis of in-memory code; does not execute code, spawn subprocesses, or write to disk. • Auth & Permissions: None required. Fully offline, in-memory parser. • Rate Limits: None. Bounded to 1MB max source size, 128 max AST depth, and 50,000 max node visits per call. • Return Shape: Returns a JSON object containing 'language', 'findings_count', 'duration_ms' (latency metric), and 'findings' (array of objects with rule_id, message, severity, line [1-indexed], column [1-indexed UTF-16 code units], and remediation). • Failure Modes: Returns findings: [] if the code contains no detected defects. Returns an error message if the language is unsupported or if source code exceeds the 1MB or 128 AST depth limits. • When to use: Use proactively before committing or running code, or when reviewing Python files for unclosed file handles, resource leaks, or AST defects. • When NOT to use: Do NOT use when you have an active runtime crash log (use get_error_context instead), and do NOT use to apply fixes automatically (use apply_code_patch instead). • Prerequisites: Supported languages currently include Python ('python', 'py').

Inputs: code (required), language (required).

apply_code_patchA

Applies an atomic, verified code edit to a specific file by substituting original_code with new_code, with automatic syntax validation and instant rollback on failure.

• Side Effects: Modifies the target file on the local filesystem. If syntax checks pass, the file is overwritten with patched contents; if syntax validation fails, the file is immediately restored to its exact original state (zero dirty diff). • Auth & Permissions: Requires write permissions for the target file on the host filesystem within the workspace boundary. Path traversal outside workspace root is blocked. • Rate Limits: None. Local disk I/O. • Return Shape: Returns a JSON object with 'status' ('success' or 'error'), 'file_path', 'lines_changed', 'verification' ('passed' or 'reverted'), and 'message'. • Failure Modes: Fails and aborts without touching the file if file_path is not found, if original_code does not match the file content uniquely, or if the compiler/linter check fails after patch application. • When to use: Use when you have finalized a bug fix or refactoring snippet and need safe, transactional application with zero risk of syntax corruption. • When NOT to use: Do NOT use for speculative edits without prior diagnosis (use get_error_context first), and do NOT use for whole-file generation when only a small block changes. • Prerequisites: Target file must exist and be within the current workspace directory.

Inputs: new_code (required), file_path (required), original_code (required), dry_run.

audit_context_healthA

Audits a raw error log, code snippet, or prompt payload for token bloat, framework noise, and credential leaks. Returns actionable M2M telemetry and savings recommendations without mutating workspace state.

• Side Effects: None. Read-only in-memory evaluation. • Auth & Permissions: None. • Rate Limits: None. • Return Shape: Returns JSON with 'raw_characters', 'estimated_raw_tokens', 'clean_characters', 'estimated_clean_tokens', 'tokens_saved', 'noise_reduction_pct', 'secrets_detected', 'health_grade' ('OPTIMAL', 'MODERATE_BLOAT', 'CRITICAL_BLOAT'), and 'recommendation'. • When to use: Call proactively when dealing with large terminal dumps or before sending long logs to the LLM to verify context efficiency. • When NOT to use: Do NOT use to apply file edits (use apply_code_patch) or query stack overflow.

Inputs: payload (required).

get_error_contextA

Extracts focused source code snippets and git diffs from a raw error log or stack trace, stripping framework noise (node_modules, site-packages) and redacting credentials.

• Side Effects: None. Strictly read-only; does not modify workspace files, git state, or environment variables. • Auth & Permissions: None required. Reads local filesystem within the current workspace boundary. • Rate Limits: None. Runs entirely locally on native machine code. • Return Shape: Returns a JSON object with 'sanitized_trace' (string without secrets/noise), 'source_frames' (array of objects with file, line, code_snippet), and 'git_diff' (string or null). • Failure Modes: If source files referenced in the trace do not exist locally, omits code snippets for those frames while still returning the sanitized trace. Returns an error JSON on unreadable input. • When to use: Call immediately when receiving a runtime exception, test failure, or compiler error to isolate the root cause before planning code fixes. • When NOT to use: Do NOT use to search web solutions (use search_stack_overflow), do NOT use to modify files (use apply_code_patch), and do NOT use to statically lint clean code without an error log (use analyze_code). • Prerequisites: Workspace directory must be accessible locally; git repository recommended for diff extraction.

Inputs: log (required), strategy, context_lines.

search_stack_overflowA

Queries the public Stack Overflow / Stack Exchange API for verified programming solutions and discussions matching an error signature.

• Side Effects: None. Strictly read-only network search; does not mutate local files or repository state. • Auth & Permissions: No API key required for standard rate-limited anonymous queries. • Rate Limits: Subject to public Stack Exchange API rate limits (~300 requests/day per IP). Results are cached locally when possible. • Return Shape: Returns a JSON object containing 'query', 'total_results', and 'results' (array of objects with title, url, score, is_answered, answer_count, and answer excerpt). • Failure Modes: Returns empty results array if no matching questions exist. Returns an error message if network connectivity fails or API quota is exhausted. • When to use: Use when local code context from get_error_context is insufficient and external community patterns, known library bugs, or API migration examples are needed. • When NOT to use: Do NOT use with raw un-sanitized logs containing private tokens or file paths, do NOT use for local codebase inspection (use get_error_context), and do NOT use to edit code (use apply_code_patch). • Prerequisites: Outbound HTTP internet access to api.stackexchange.com.

Inputs: query (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 5 tools

    Disambiguation2/5

    get_error_context and audit_context_health overlap heavily: both consume raw error logs, strip framework noise, and detect credentials, differing mainly in output metrics vs. source extraction. The other tools are distinct, but these two create real ambiguity about which to call for a given error log.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun snake_case pattern: get_error_context, search_stack_overflow, apply_code_patch, analyze_code, audit_context_health. The verbs clearly describe the action and the nouns identify the target.

    Tool Count5/5

    Five tools is well-scoped for an error-diagnosis-and-patching workflow. Each tool serves a distinct stage (extract context, search external knowledge, analyze statically, apply patch, audit token health) without redundant or excessive surface area.

    Completeness3/5

    The core flow from error context to search to analysis to patching is present, but there is no tool to verify behavior after a patch or revert a syntactically valid but logically incorrect change. Additionally, audit_context_health reports token savings but does not return a cleaned/trimmed payload, leaving a notable gap for a context-optimization-focused server.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      A lightning-fast, language-agnostic code analysis MCP (Model Context Protocol) server built in Rust
      9
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Local-first code intelligence and safety layer for AI coding agents. MCP server exposes dependency graph, impact analysis, and AST-compressed repo context, backed by typed local memory, patch-scope safety gates, and git-independent transaction rollback.
      1
      MIT
    • F
      license
      Not graded
      quality
      A
      maintenance
      Local MCP server that lets your AI coding agent query its own cross-tool project history - file/command freshness, past test failures, cost & token spend, cache status, and session handoff - over stdio, 100% local, no telemetry.
      58
      -