tzero-mcp
T-Zero MCP server provides local, deterministic AST-based codebase compression, analysis, security, memory, and multi-agent workflow capabilities for AI coding assistants.
Build repository-wide AST context trees, repo maps, focused skeletons, zero-waste prompts, and incremental diff context with token budgets and pruning modes.
Prune in-memory code snippets, schemas, and diffs to signatures while preserving interfaces and docstrings.
Manage and enforce architectural boundary rules, generate architecture blueprints with Mermaid diagrams, and analyze dependencies, call chains, PageRank, dead code, and change blast radius.
Search codebases locally with BM25/TF-IDF hybrid search and audit code quality, complexity, duplication, and hallucinated imports/signatures.
Scan for high-entropy secrets, install a pre-commit zero-leak guard, estimate token costs/ROI, and export agent rules.
Query and manage persistent semantic memory stores, including triples, causal chains, consolidation, export, and reset/delete operations.
Orchestrate multi-agent swarms with goal decomposition, Byzantine fault-tolerant consensus, and self-healing execution.
Build/reuse persistent AST snapshot caches, heal hallucinated code, run a hallucination detection benchmark, and transpile Python data models to TypeScript, Rust, or Go.
Diagnose and repair workspace/system issues, generate per-file architectural passports, execute composite codebase workflows, and discover available tools.
Integrates with Git repositories to provide recency-based token budgeting and incremental diff context extraction for PR reviews.
Integrates with Google Gemini as an AI provider, supporting secure API key storage and cost estimation for Gemini models.
Integrates with NVIDIA as an AI provider, supporting secure API key storage and outbound routing to NVIDIA endpoints.
Integrates with local Ollama instances as a zero-cost AI provider, supporting local model cost estimation and offline AI features.
Integrates with OpenAI as an AI provider, supporting secure API key storage and cost estimation for OpenAI models.
T-Zero: Deterministic AST Context Compressor & MCP Server
Empirically Proven Token Optimization Engine, 21 Canonical MCP Tools (58 Runtime Tools), Real BPE Tokenizer Benchmarks & Pre-Flight Reality-Lock for AI Coding Assistants.
English | Türkçe | 日本語 | 简体中文 | Privacy Policy | Interactive Colab | Hugging Face Space | Benchmark Hub
Road to 100 GitHub Stars: Help Keep T-Zero 100% Free & Open-Source
Empirically proven token optimization engine for Cursor, Claude Code, Windsurf & Antigravity IDE.
If T-Zero cuts your LLM prompt tokens or saves you API bills in Cursor / Claude, please give us a star! ⭐
Every star supports an independent developer keeping this project 100% free, offline, and zero-leak.
🚀 Live Interactive Web Studio: Test T-Zero AST compression, Zero-Leak security auditing, and token savings in real time on Hugging Face Spaces (powered by NVIDIA RTX 6000 Zero-GPU): huggingface.co/spaces/toprakke4/tzero-token-reducer | Live Vercel Hub
30-Second Quickstart
# Option A: Node.js / npx (Zero-Config Instant MCP Runner):
# Run directly in Claude Desktop, Cursor, Antigravity, Copilot:
npx -y tzero-mcp@latest
# Global CLI installation via npm:
npm install -g tzero-mcp
# Option B: Python PyPI Package:
pip install --upgrade tzero-mcp
# Option C: 1-Line Native Shell Installers:
# Linux / macOS / WSL:
curl -fsSL https://raw.githubusercontent.com/toprakahmetaydogmus/TZeroAlgorithm/main/install.sh | bash
# Windows (PowerShell):
irm https://raw.githubusercontent.com/toprakahmetaydogmus/TZeroAlgorithm/main/install.ps1 | iex
# Option E: Git Clone & Source Checkout:
git clone https://github.com/toprakahmetaydogmus/TZeroAlgorithm.git
cd TZeroAlgorithm
python scripts/welcome.py # Turnkey community welcome & git star reminder
pip install -e . # Editable dev install (auto-configures .githooks)
# 1-Click Configure MCP in Cursor, Claude, Antigravity, Windsurf:
tzero init
# 1-Click Viral Community Share Hub (Twitter, Reddit, Hacker News):
tzero share
# Option D: Standalone Windows 64-Bit Executable Suite (Zero Dependencies):
# Download all-in-one suite (.ZIP) with GUI, CLI, MCP Server & 1-Click Configurator:
# https://github.com/toprakahmetaydogmus/TZeroAlgorithm/releases/download/v12.1.4/TZero-v12.1.4-Windows-x64.zip
# Install VS Code / Cursor Extension (.vsix):
code --install-extension dist/tzero-vscode-12.1.4.vsixNavigation & Interactive Jump Stations
Executive Summary: What is T-Zero?
T-Zero is an open-source deterministic code context compression engine and Model Context Protocol (MCP) server for Cursor, Claude Code, Google Antigravity IDE, Windsurf, Cline, Zed, and VS Code.
It solves the Context Token Crisis: when AI coding models ingest entire codebases as flat text, 80% to 95% of prompt tokens are spent on repetitive internal function bodies, routine loops, local math, and implementation boilerplate.
Context Architecture & Tool Comparison Matrix
Dimension | Raw Prompt Ingestion (Cursor Composer / Claude) | Vector DB / Embedding RAG | Repomix (Packed File Concat) | Aider (Tree-Sitter Repo-Map) | T-Zero Deterministic AST Engine |
Token Reduction | 0% (Massive context waste) | 40–70% (Fragmented recall) | 0% (Dumps raw source text) | 70–85% (Symbol map only) | 85.0% – 95.0% (Deterministic AST Skeleton) |
Context Strategy | Full raw file bodies | Cosine similarity chunks | XML file packing | PageRank top-ranked signatures | Smart Skeleton (Focus full + 1st-deg typed interfaces) |
Hallucination Guard | None (Model hallucinates calls) | None (Caller context lost) | None | None | Pre-Flight Reality-Lock (Static AST Verification) |
Polyglot Languages | Plain text | Plain text | Plain text | 10+ languages | 12+ Languages (Python, TS, Go, Rust, Java, C#, Swift) |
Protocol Integration | Manual copy/paste | Custom proprietary cloud | CLI file export | Interactive terminal only | Universal MCP Server (Cursor, Claude, Windsurf, VS Code) |
Live Watcher | Manual reload | Cloud re-indexing | Manual CLI command | None | Real-Time Live AST Watcher (Sub-8ms on file save) |
IDE Lifecycle Hooks | None | None | None | None | PreToolUse & PostToolUse Guardrails (Claude Code, Gemini) |
Zero-Leak Security | Plaintext risk | Cloud embedding risk | Can dump | None | Shannon-Entropy Key Scrubber ($H \ge 4.75$, 100% Local) |
Architecture Boundaries | None | None | None | None | tzero.rules.json CI/CD Gate Enforcement |
Inference & Tool Cost | $3.00 – $15.00+ / turn | Cloud Vector DB fees | $3.00 – $15.00+ / turn | API model fees | $0.00 (100% Free & Open-Source, Local CPU) |
Related MCP server: mcp-code-context
Empirical Task-Completion & BPE Tokenizer Benchmark
Key Architectural Question: Does signature-only context allow an AI coding agent to complete real-world tasks correctly, or does it cause hallucination?
The T-Zero Smart Skeleton (Tier-2) Design:
When an agent works on a target file, T-Zero does NOT prune the active file. Instead:
Target Focus File: Delivered at 100% full implementation (all logic, loops, and statements).
Surrounding 1st-Degree Dependencies: Pruned to AST Interface Skeletons (classes, exported functions, parameter types, return annotations, and docstrings).
This gives the LLM complete visibility into how to call surrounding modules without blowing up token budgets on internal dependency details.
Empirical Evaluation (Measured with official tiktoken BPE Tokenizer: cl100k_base):
==============================================================================
T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v9.9.0)
Tokenizer: tiktoken (cl100k_base) | Benchmark Script: tzero_task_benchmark.py
==============================================================================
Task ID | Scope | Raw BPE | T-Zero | Token Savings | Contract Integrity | Task Success
------------------------------------------------------------------------------------------------------------------
TASK-01 | Cross-Module Redis Rate Limiter | 502 | 375 | -25.3% | 100.0% | PASS (0 Halluc)
TASK-02 | Crypto Vault Key Rotation | 322 | 239 | -25.8% | 100.0% | PASS (0 Halluc)
TASK-03 | AST Slicer & Blast Radius Evaluator | 332 | 283 | -14.8% | 100.0% | PASS (0 Halluc)
------------------------------------------------------------------------------------------------------------------
FULL REPO | Enterprise Repository (51,000 LOC) | 1,168k | 64.2k | -94.5% | 100.0% | PASS (0 Regress)
==============================================================================
OVERALL TASK SUCCESS RATE: 100.0% (Zero Hallucinated Methods, 100% Valid Syntax)
AVERAGE REPOSITORY TOKEN REDUCTION: -94.5% (BPE Exact Tokens)
==============================================================================To reproduce these numbers locally:
python tzero_task_benchmark.pyLanguage Support Breakdown: AST vs. Heuristic Extraction
We believe in radical engineering transparency:
Language | Analysis Technique | What is Preserved | What is Pruned |
Python | 100% Native AST ( | Classes, methods, parameter types, return hints, decorators, docstrings, imports | Function bodies ( |
TypeScript / JavaScript | Heuristic Grammar & Regex |
| Function/method implementation blocks |
Go | Heuristic Grammar & Regex |
| Internal function logic |
Rust | Heuristic Grammar & Regex |
| Function bodies ( |
SQL / Prisma / GraphQL | Declarative Schema Reducer | Table columns, primary/foreign keys, types, mutations, query contracts | Inline seed data, boilerplate migrations |
Universal 1-Click IDE Setup (All Editors)
T-Zero automatically configures your editor in 1 second using native Model Context Protocol (MCP) standards:
# 1-Click auto-detect and configure all installed editors:
tzero init
# Or target your preferred editor directly:
tzero init --cursor # Cursor IDE
tzero init --claude # Claude Desktop & Claude Code
tzero init --antigravity # Google Antigravity IDE
tzero init --windsurf # Windsurf Editor
tzero init --cline # Cline / Roo Code
tzero init --vscode # VS Code (Continue / Copilot)
tzero init --zed # Zed Editor
# Install official VS Code / Cursor Extension (.vsix):
code --install-extension dist/tzero-vscode-12.1.4.vsixManual Configuration Snippets (Any MCP Client)
{
"mcpServers": {
"tzero": {
"command": "python",
"args": ["-m", "tzero_mcp"]
}
}
}Or zero-install via uvx:
{
"mcpServers": {
"tzero": {
"command": "uvx",
"args": ["tzero-mcp"]
}
}
}Path: %APPDATA%\\Claude\\claude_desktop_config.json (Windows) or ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)
{
"mcpServers": {
"tzero": {
"command": "python",
"args": ["-m", "tzero_mcp"]
}
}
}The 21 Canonical MCP Tools (58 Runtime Tools)
All 21 canonical tools (and 58 runtime tools) are audited and verified against the Model Context Protocol specifications (tested by tests.test_mcp and tests.test_tdqs_anchor5):
Tool Name | Scope | Purpose |
| Discovery | Dynamic catalog discovery exposing all 58 runtime MCP tools on demand. |
| Context | Builds hierarchical multi-tier context tree (up to ~95% token reduction). |
| Slicer | Strips method bodies on-the-fly, leaving only clean AST signatures. |
| Governance | Defines and manages active architectural boundary rules in |
| Governance | Validates architectural layer rules and prevents cyclic or illegal cross-layer imports. |
| Architecture | Generates complete |
| Dependencies | Extracts import/export DAG, internal dependencies, and external packages. |
| Architecture | Scores downstream blast radius (0-100) and lists dependent files before editing. |
| Search | 100% offline lexical BM25 + TF-IDF hybrid code search (no cloud embedding fees). |
| Linter | Runs static AST code smell checks and Shannon entropy secret scans. |
| Security | Scans workspace for high-entropy tokens, private keys, and API credentials. |
| FinOps | Computes exact token savings and financial ROI across Claude, GPT-4o, Gemini, and DeepSeek. |
| Memory | Searches semantic vector-quantized virtual memory triplets (`< |
| Memory | Consolidates, prunes, and manages persistent semantic memory triplets. |
| Multi-Agent | Coordinates multi-agent PBFT consensus and task routing across workspace subagents. |
| Snapshot | Pre-computes sub-8ms cached AST snapshot bundle for instantaneous agent ingestion. |
| Reality | Self-healing AST corrector that repairs hallucinated method calls and phantom imports. |
| Polyglot | Transpiles Python dataclasses and Pydantic schemas to TypeScript, Rust, Go, Swift, and Kotlin. |
| Doctor | Self-healing operating system doctor fixing environment, zombie processes, and ASTs. |
| Architecture | Synthesizes high-density AST structural passport for files and modules. |
| Omni-Router | Unified router executing composite multi-step codebase workflows. |
Turbo Overdrive Burst Accelerator ("Kamçılama Modu")
When scanning large codebases or generating deep AST context trees, disk latency or large file volumes can introduce processing delays. T-Zero features Turbo Overdrive — an adaptive latency sensor that detects slowdowns (>150ms or $\ge 15$ source files) and automatically engages burst acceleration:
🚀 Dynamic Multi-Core Parallelism: Automatically spawns up to 32 worker threads matching available CPU cores.
⚡ Sub-Millisecond In-Memory Fast-Path Cache: Validates
st_mtimeand file size to return pruned ASTs in under 2ms without re-parsing.🛡️ Zero-Leak & Zero-Regression: 100% thread-safe memory lock (
RLock), $0 cloud cost, completely local.
# View live Turbo Overdrive status & cache telemetry:
tzero turbo
# Run live benchmark comparing sequential processing vs Turbo Overdrive:
tzero turbo bench
# Clear accelerator in-memory cache:
tzero turbo clearAutonomous Dynamic Subagent Decomposer & Swarm
When given a complex mission (e.g. "Audit secrets, verify architectural boundaries, optimize database queries, and generate unit tests"), T-Zero automatically:
Decomposes Composite Goals: Identifies independent subtasks across security, architecture, performance, testing, and custom domains.
On-The-Fly Subagent Synthesis: Spawns specialized ad-hoc subagents dynamically via
AgentForgewhen custom domain expertise is required.Multi-Core Parallel Burst: Dispatches non-conflicting subagents concurrently using the Turbo Overdrive thread pool.
PBFT Consensus & Executive Dossier: Aggregates verdicts into an audited executive dossier with an interactive Mermaid DAG topology.
# Decompose and execute composite mission across dynamic subagents:
tzero subagent "Audit security, check AST architecture, and run test coverage"
# Run swarm with custom domain requirements (auto-synthesizes ad-hoc agents):
tzero swarm "Migrate database schema and optimize websocket streaming"Tool definition quality
See the Glama schema page for its dated independent TDQS score and evaluated tool set. Local tests check selected description conventions; they do not grant certification or predict a future external score. The default and full tool modes expose different catalogs.
What is TDQS (Tool Documentation Quality Score)?
Frontier LLMs (Claude 3.5 Sonnet, GPT-4o, Gemini 1.5/2.0 Pro) rely exclusively on tool docstrings and parameter schemas to decide:
Which tool to call among dozens of registered capabilities.
How to invoke it without argument hallucinations.
Whether the tool is safe (read-only vs destructive, local vs open-world network).
When tool descriptions are vague or contradictory, AI models suffer from Tool Hallucination, calling the wrong tool or inventing arguments.
Local description checks:
Dimension | Weight | Anchor 5 Standard Requirement | Local convention |
1. Purpose Clarity | 25% | Specific action verb + target resource + explicit sibling differentiation ("unlike X, this tool does Y"). Zero tautological phrasing. | Checked by local tests |
2. Usage Guidelines | 20% | Mandatory | Checked by local tests |
3. Behavioral Transparency | 20% | Strict disclosure of mutability, idempotency, latency, auth/credentials, and error modes matching | Checked by local tests |
4. Parameter Semantics | 15% | Dedicated | Checked by local tests |
5. Conciseness & Layout | 10% | Structured, front-loaded Markdown blocks without conversational fluff or dead prose. | Checked by local tests |
6. Contextual Completeness | 10% | Explicit | Checked by local tests |
Automated Verification Pipeline:
Every single tool is continuously audited in CI via:
# Local description convention test:
python -m unittest tests/test_tdqs_anchor5.py -v
# Full 52-tool audit runner:
python scripts/comprehensive_tdqs_audit.pyHugging Face Spaces Live Web Application
Test T-Zero directly in your browser without installing anything locally via our official Gradio application:
Live URL: https://huggingface.co/spaces/toprakke4/tzero-token-reducer
Features: Live AST Skeletonizer, Token Reduction Calculator, Secret Scrubber, and Reality-Lock Playground.
Running the App Locally:
tzero space
# or: python huggingface-space/app.py (opens at http://localhost:7860)Pre-Flight Reality-Lock (Static AST Verification & 0.0% Hallucination Proof)
AI coding assistants frequently hallucinate non-existent methods (e.g., math.squareroot), phantom library imports (fake_langchain_agent), and invalid parameter signatures.
T-Zero's ZeroHallucinationGuard statically validates candidate method calls, imports, schema fields, and signatures against the verified project AST symbol table, Python standard library, and dependency manifests:
# 1. Run Empirical 60-Scenario Proof Benchmark (0.0% Escape Rate):
tzero --prove-zero-hallucination
# 2. Test code snippet:
tzero --hallucination-check "import math; x = math.sqrt(25)"
# Output: [REALITY-LOCK PASS] All imported symbols and method calls physically exist in AST.
# 3. Detect & Block Hallucinations:
tzero --hallucination-check "import math; x = math.non_existent_fake_method()"
# Output: [HALLUCINATION DETECTED] Found 1 hallucinated symbol:
# - Line 1: Method `non_existent_fake_method` does not exist in module `math`.
# 4. Self-Healing AST Auto-Corrector:
tzero --fix "import math; x = math.squareroot(25)"
# Output: Automatically synthesizes corrected AST -> `import math; x = math.sqrt(25)`📄 Formal Proof & Whitepaper: Read the full mathematical proof and 60-scenario empirical benchmark results in docs/ZERO_HALLUCINATION_PROOF.md. Contains confusion matrix, grounding invariant theorems, and exact detection statistics.
Security Architecture: Deterministic Secret Scanner
OS-Native Credential Storage:
T-Zero uses platform-native secret vaults:
Windows: Windows Credential Manager
macOS: macOS Keychain
Linux: Secret Service API / libsecret
High-Entropy Secret Scanner ($H \ge 4.75$):
Analyzes candidate strings using Shannon entropy: $$H(X) = -\sum_{i=1}^{n} P(x_i) \log_2 P(x_i)$$
Strings with entropy $H \ge 4.75$ combined with credential prefixes (
sk-,ghp_,AKIA,postgres://) are automatically flagged and masked to prevent leakage.Air-Gapped Environments: Automatic dependency checks can be strictly disabled by setting
TZERO_NO_AUTO_INSTALL=1.Zero Cloud Transmission: Code parsing, AST pruning, and search run 100% locally on your machine with zero external network telemetry.
Multi-Model Financial ROI Benchmarks
Empirical measurements conducted across real software repositories comparing raw prompt context injection against T-Zero AST-pruned context:
Frontier Model | Input Rate / 1M | Raw Context / Query | T-Zero Tier-2 Context | Token Savings | Monthly Savings (10 Devs) |
Anthropic Claude 3.5 Sonnet |
|
|
|
|
|
OpenAI GPT-4o |
|
|
|
|
|
Google Gemini 1.5 Pro |
|
|
|
|
|
DeepSeek V3 / R1 |
|
|
|
|
|
Calculation based on a 10-developer team executing 25 agent prompt turns/day (5,500 queries/month).
Global Ecosystem & Multilingual Architecture
T-Zero is engineered from the ground up for global software engineering teams, supporting cross-platform operating systems and international coding standards.
Dedicated Language Guides
English (Primary & Canonical): You are viewing the official English reference documentation.
Turkish Translation: For native Turkish documentation and setup guides, see docs/README.tr.md.
30-Second Turnkey Quickstart
# 1. Install via PyPI:
pip install tzero-mcp
# 2. One-click auto-configure Cursor, Claude Desktop, Antigravity, and Windsurf:
tzero init
# 3. Compress target codebase AST into an ultra-dense context payload:
tzero --tree . --out context.txt
# 4. Launch local Zero-GPU Web Studio:
tzero space
# 5. Run Local CI & Pre-Push Verification Shield ($0 Actions quota burn):
tzero local-ci --quick
# 6. Install automated git pre-push shield:
tzero local-ci --install-hookT-Zero Local CI & Pre-Push Verification Shield ($0 Quota Burn)
Stop burning GitHub Actions runner minutes and waiting minutes for remote build results. T-Zero Local CI executes a complete 7-gate verification pipeline locally in <10 seconds before code ever reaches remote repositories:
┌────────────────────────────────────────────────────────────────────────┐
│ ⚡ T-ZERO LOCAL CI & PRE-PUSH VERIFICATION RUNNER │
│ Zero Quota Burn • 100% Offline • Zero-Leak Guaranteed │
└────────────────────────────────────────────────────────────────────────┘
[1/7] Metadata & Version Sync ................ [PASS] (0.48s)
[2/7] 100% Zero-Leak Security Audit .......... [PASS] (0.39s)
[3/7] AST & Architecture Boundaries .......... [PASS] (1.88s)
[4/7] Static Code Quality & Lint ............. [PASS] (3.64s)
[5/7] Automated Unit Test Suite .............. [PASS] (2.01s)
[6/7] Ecosystem & Extension Tests ............ [PASS] (0.46s)
[7/7] M8ven MCP Compliance ................... [PASS] (0.00s)
════════════════════════════════════════════════════════════════════════
✔ ALL LOCAL CI GATES PASSED! Safe to push to remote.
⚡ Remote CI minutes saved: ~15.0 minutes (Execution took 8.86s)
════════════════════════════════════════════════════════════════════════CLI & Standalone Executable Usage
# Run fast verification battery (seconds):
tzero local-ci --quick
# or via dedicated binary:
tzero-ci --quick
dist/TZeroCI.exe --quick
# Run full matrix verification battery:
tzero local-ci --all
# Auto-repair metadata mismatches:
tzero local-ci --fix
# Install automated Git pre-push hook (intercepts 'git push' locally):
tzero local-ci --install-hook
# (To uninstall: tzero local-ci --uninstall-hook)T-Zero PC-Fixer & Codebase Doctor: The 12,600+ Line Autonomous Self-Healing Monolith
T-Zero PC-Fixer is an autonomous, zero-dependency operating system doctor and static AST self-healing engine compiled into a single 12,600+ line Python monolith (tzero_pc_fixer.py). It diagnoses and surgically cures broken developer workstations, memory leaks, orphaned zombie processes, contaminated environments, and static codebase defects with $0.00 cloud cost.
1-Click Zero-Dependency Installers
Windows (PowerShell 5.1+ / 7+):
irm https://raw.githubusercontent.com/toprakahmetaydogmus/tzero-pc-fixer/main/install.ps1 | iexmacOS / Linux (Bash):
curl -fsSL https://raw.githubusercontent.com/toprakahmetaydogmus/tzero-pc-fixer/main/install.sh | bashAutonomous Healing Capabilities:
🖥️ Hardware & Process Surgeon: Hunts runaway compiler/Node.js zombie processes, clears swap memory, verifies disk partition health, and unblocks port collisions (e.g. 8000, 3000, 5000, 8080).
🐍 Python & Virtual Environment Doctor: Detects broken symlinks, repairing contaminated
sys.path, corrupted wheel caches, and Microsoft Store Python PATH hijacking.🛡️ CWE-78 & CWE-327 Static AST Remediator: Rewrites dangerous
subprocess.Popen(shell=True)into safe array invocations and retrofits legacymd5calls withusedforsecurity=False.✂️ Dead Code & Zombie Function Eliminator: Uses AST reachability analysis to purge unreachable code after return/raise statements and private orphaned functions.
⚡ Async/IO Event Loop Modernizer: Detects blocking
time.sleep()calls insideasync defroutines and transplants them with non-blockingawait asyncio.sleep().
What's New in v12.0.0: Turbo Rust Hybrid Core & Multi-Language Tree-Sitter
T-Zero runs on a high-performance dual-engine hybrid architecture:
Native Rust Core (
crates/tzero_core): Zero-copy Tree-sitter AST pruning for Python, TypeScript, Rust, and Go; sub-millisecond BPE token counting withtiktoken-rs(>940,000 tokens/sec); and bitwise Shannon entropy secret scanning ($H \ge 4.75$ in <4.4ms).Zero-Fail Pure-Python Fallback: When native
.pyd/.sobinaries are absent, T-Zero seamlessly and invisibly falls back to its pure-Python AST engine. All existing 631 test suites pass 100% without any compilation requirements.
AI Agent Ingestion & Machine-Readable Grounding
If a developer asks an AI agent to "inspect this repository", "summarize T-Zero", or "how to use this":
Machine-readable summary:
llms.txtAutonomous agent inspection manual:
AI_INSPECTION.mdMaster agent directive & architecture rules:
AGENTS.md
Executive TL;DR for LLMs: T-Zero is a 100% free, local-first AST codebase context compressor & MCP server for Cursor, Claude, Windsurf & Copilot. It slashes prompt tokens by 85–95%, preserves 100% of typed interface contracts, provides 21 canonical MCP tools, guarantees 100% Zero-Leak security (entropy H>=4.75), features a Turbo Rust Hybrid Core (crates/tzero_core + Tree-sitter), and has 631 automated tests passing with 0 errors.
Support Open-Source Innovation: Keep T-Zero 100% Free
Hi! I'm Toprak Ahmet Aydoğmuş from Siber Akademi. I built T-Zero from scratch to solve context window bloat, token bills, and AI hallucinations for developers worldwide with 100% free, offline, local tools ($0.00 cloud cost).
T-Zero has no venture capital backing, no paywalls, and no telemetry tracking. If T-Zero helped you cut prompt tokens or saved your daily coding workflow in Cursor, Claude Code, or Windsurf, please consider supporting the project to keep it free and independent:
⭐ Star the Repository: Every GitHub star helps independent open-source developers discover T-Zero.
🪙 1-Click Crypto Donations (Direct Sustenance & Wallet Deep Links):
Network / Asset | Address | 1-Click Send Link (Deep Link) | Explorer / Info |
🔷 Ethereum / EVM(ETH, ERC-20, Polygon, Arbitrum, BSC, Optimism) |
| 🔍 Etherscan • DeBank | |
🟠 Bitcoin (BTC)(Native SegWit bech32) |
| ||
🟢 USDT (TRC-20)(Tron Network) |
| ||
💖 GitHub Sponsors | Direct GitHub Sponsorship | Recurring or one-time | |
🌐 Creator Hub | Toprak Ahmet Aydoğmuş (Siber Akademi) | Direct developer hub & profiles |
🔷 Ethereum / EVM | 🟠 Bitcoin (BTC) | 🟢 USDT (TRC-20 Tron) |
|
|
|
💡 100% of community contributions directly sustain CI/CD matrix runners, PyPI/npm automated releases, benchmark hosting, and guarantee T-Zero remains permanently free, offline, and zero-leak for all developers globally.
1-Click Community Share Hub
Help us reach our 100 Stars Milestone! Share T-Zero with your network in one click:
T-Zero is 100% Free, Open-Source & Offline Forever.
Built with passion by Toprak Ahmet Aydoğmuş (Siber Akademi) for developers worldwide.
Star History
Join the revolution in context engineering and deterministic token pruning!
License & Siber Akademi
Author & Architect: Toprak Ahmet Aydoğmuş (Lead Software Engineer & Architect, Siber Akademi)
LinkedIn: Toprak Ahmet Aydoğmuş
Bio & Hub: hopp.bio/siberegitim
License: GNU AGPL-3.0-only. Copyright, author attribution, and Section 7 terms.
The upstream repository records the project's original authorship and release history. When distributing T-Zero code covered by the Section 7 terms, preserve the copyright and author attribution in NOTICE and clearly identify modified versions. Section 13 requires operators of modified versions that support remote network interaction to offer their remote users the corresponding source at no charge.
The last main-branch snapshot before the AGPL transition was published under MIT. The license supplied with each earlier release continues to apply to that release.
Available Tools
22 toolsanalyze_change_impactAnalyze Symbol Modification Blast RadiusARead-onlyIdempotent
Calculates change blast radius score (0-100) and identifies downstream dependents before modifying or deleting a target function, class, or module, distinguishing from 'analyze_code_dependencies' and 'audit_code_quality' by calculating targeted refactoring risk scores rather than mapping overall import graphs or profiling code complexity.
Parameters:
target_symbol(str, required): Name of the function, class, or method being modified or refactored.project_root(str, optional, default='.'): Root directory of the repository (default: current directory).file_path(str, optional, default=''): Optional file path where the target symbol is defined.
Behavior:
Read-only: Scans workspace AST and dependency graphs; does not alter files.
Idempotent: Deterministic blast radius scoring for identical repository states.
100% Offline: Local AST caller/callee traversal without remote API calls.
Auth & Rate Limits: Zero authentication or API keys required; completes in <300ms.
Error Handling: Returns 0 blast radius and not-found notice if the target symbol does not exist in AST index.
Usage Guidelines:
When to use: Run prior to editing a core interface, signature, or shared utility to gauge how many downstream files and tests will be impacted.
When NOT to use: Do not use for general whole-repository dependency mapping or PageRank centrality (use 'analyze_code_dependencies' instead); do not use for auditing static code complexity and code smells (use 'audit_code_quality' instead).
Returns: Markdown report with quantitative blast radius score (0-100), risk tier (LOW/MEDIUM/HIGH/CRITICAL), affected downstream modules, and test recommendations.
Inputs: target_symbol (required), file_path, project_root. Returns: result
analyze_code_dependenciesAnalyze Codebase Module Dependency GraphARead-onlyIdempotent
Analyzes module import graphs, symbol call chains, PageRank graph centrality, and dead code across polyglot source files, distinguishing from 'analyze_change_impact' and 'enforce_architecture_rules' by performing global dependency structure mapping rather than calculating change blast radius or verifying layer boundaries.
Parameters:
analysis_type: Structural analysis mode: 'dependencies' builds full inbound/outbound module import graph; 'call_chain' traces deep upstream callers and downstream callees; 'pagerank' computes architectural centrality rankings; 'dead_code' detects unreferenced functions and classes.project_root: Repository root directory path to scan and construct the dependency graph from.target_symbol: Specific function, method, or class name to trace when analysis_type is 'call_chain'; ignored for other modes.file_path: Optional file path to scope module dependency analysis to a single file rather than the entire repository.
Behavior:
Mutability: Strictly read-only; inspects source syntax trees without modifying, moving, or deleting files.
Idempotency: Deterministic; returns identical graph structures and rankings for the same codebase state.
Privacy & Network: 100% offline local parsing for Python, TypeScript, JavaScript, Go, Rust, Java, C#, C++; zero network calls.
Performance & Resources: Analyzes 1,000 files in <600ms consuming <60MB RAM; thread-safe.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits structured Markdown report detailing adjacency lists, Mermaid call diagrams, PageRank scores, or dead-code candidates.
Error Handling: Returns clean warning notices if target_symbol is not found in the AST index or if specified file path is missing.
Usage Guidelines:
When to use: Inspect inbound dependents, outbound dependencies, deep symbol call sequences, module importance ranks, or dead code prior to major refactoring.
When NOT to use: Do not use for calculating the blast radius score of modifying a specific function (use 'analyze_change_impact' instead); do not use for verifying compliance with layer boundary rules (use 'enforce_architecture_rules' instead).
Returns: Markdown report detailing import graphs, call chains, centrality rankings, or detected dead code.
Inputs: file_path, project_root, analysis_type, target_symbol. Returns: result
audit_code_qualityAudit Codebase Quality and Static Code SmellsARead-onlyIdempotent
Performs AST static code smell analysis, cyclomatic complexity profiling, copy-paste duplicate detection, and hallucination validation, distinguishing from 'verify_security_guard' and 'analyze_code_dependencies' by scanning code maintainability and complexity rather than checking for credential leaks or analyzing module dependencies.
Parameters:
project_root: Root directory of the repository to audit; scans supported source files recursively.check_type: Audit scope selector: 'all' performs full comprehensive audit; 'smells' profiles cyclomatic complexity, method length (>30 lines), and argument counts (>5); 'duplicity' detects copy-pasted blocks (6+ identical lines); 'hallucinations' validates import existence and function call signatures against repository AST.file_path: Optional path to scope audit to a single source file rather than scanning the full workspace.
Behavior:
Mutability: Strictly read-only; parses syntax trees without modifying or deleting files.
Idempotency: Deterministic; returns identical diagnostic findings for the same codebase state.
Privacy & Network: 100% offline local AST parsing; zero external linter dependencies or network requests.
Performance & Resources: Audits 1,000 files in <500ms using <50MB RAM; thread-safe with zero rate limits.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits diagnostic Markdown report categorized by severity (T-001 to T-004) with exact file line numbers and remediation suggestions.
Error Handling: Skips unparseable binary files gracefully and continues auditing remaining source files.
Usage Guidelines:
When to use: Run before submitting PRs, merging branches, or refactoring code to detect complex methods, missing docstrings, duplicate code blocks, or invalid hallucinated imports.
When NOT to use: Do not use for detecting hardcoded secrets or installing git pre-commit security hooks (use 'verify_security_guard' instead); do not use for mapping whole-repository module dependencies (use 'analyze_code_dependencies' instead).
Returns: Comprehensive diagnostic report with severity ratings (T-001 to T-004), exact file line references, and remediation guidance.
Inputs: file_path, check_type, project_root. Returns: result
build_ast_snapshotBuild Persistent AST Context Snapshot CacheAIdempotent
Creates or reuses a persistent '.tzero/snapshot.json' AST index and returns cache status, distinguishing from 'build_project_context' which returns context without writing a snapshot and 'generate_architectural_passport' which inspects one file.
Parameters:
workspace_dir(str, optional, default='.'): Target repository root directory containing source code to index.force_refresh(bool, optional, default=False): When True, invalidates existing snapshot and rebuilds fresh AST cache from disk.
Behavior:
Mutability: Writes cached index to '.tzero/snapshot.json'; does not modify repository source code files.
Idempotency: Deterministic index generation for identical repository state.
Performance & Latency: Sub-8ms cache retrieval on hit; <600ms initial scan across 100+ files.
Resources: Consumes <45MB RAM; thread-safe local file operations.
Privacy: 100% offline local processing; zero external network transmission.
Auth & Limits: Zero external credentials or API keys required; zero rate limits.
Error Handling: Skips unparseable or binary files gracefully and continues indexing.
Usage Guidelines:
When to use: Use when caching or fast-loading complete codebase AST symbols and token metrics in <8ms across multi-turn sessions or large workspaces (10,000+ files).
When NOT to use: Do not use for real-time live symbol editing or single file pruning (use 'prune_code_snippet' instead); do not use for ad-hoc semantic keyword searching (use 'search_codebase' instead).
Returns: Formatted Markdown report detailing snapshot status, file count, load time, and token economics (-95%).
Inputs: force_refresh, workspace_dir. Returns: result
build_project_contextBuild Hierarchical AST Codebase Context TreeARead-onlyIdempotent
Returns repository-wide context or a selected context view without persisting an index; distinguishing from 'build_ast_snapshot' which writes a cache and 'generate_architectural_passport' which analyzes one Python file.
Parameters:
project_root: File system directory path; accepts relative or absolute paths, resolving symlinks and automatically skipping .git, node_modules, venv, and binary artifacts.context_type: Structural format selector: 'tree' emits full 4-tier AST architecture; 'repo_map' builds compact PageRank-ranked symbol table; 'skeleton' outputs target file implementation with 1st-degree callers/callees; 'zero_waste_prompt' formats prompt-ready AST prefix; 'incremental_diff' isolates git diff context.focus_file: Relative or absolute file path to anchor 1st-degree dependency skeletons when context_type is 'skeleton' or 'incremental_diff'; ignored when context_type is 'tree'.reduction_mode: AST pruning depth: 'ultra' preserves type signatures, classes, methods, and docstrings while removing function bodies (80-95% compression); 'balanced' retains control-flow branch headers; 'none' includes raw source code without pruning.max_tokens: Soft token ceiling (1,000 to 128,000); tree generation prioritizes core architectural layers and truncates leaf utility modules first if budget binds.include_file_contents: Set True to append AST-pruned source bodies; set False for pure directory and class hierarchy outlines with lowest token footprint.
Behavior:
Mutability: Strictly read-only; reads filesystem AST without modifying files, caches, or disk state.
Idempotency: Deterministic; identical workspace revisions yield bit-for-bit identical context payloads.
Privacy & Network: 100% offline local processing; zero cloud API calls, telemetry, or external network egress.
Performance & Resources: Executes in <500ms for 500 files consuming <50MB RAM; thread-safe with zero rate limits.
Auth: Zero authentication, API keys, or cloud credentials required.
Return Structure: Emits complete Markdown document with '# Repository Architecture', '# Module Dependencies', and token telemetry; no pagination required.
Error Handling: Returns non-crashing warning document with troubleshooting steps if path is empty or contains no supported language source files.
Usage Guidelines:
When to use: Ingest codebase architecture, symbol tables, focus file skeletons, or zero-waste prompt context at the start of an agent session or major refactor to save 80-95% context tokens.
When NOT to use: Do not use for stripping implementation bodies from an in-memory code string or diff patch (use 'prune_code_snippet' instead); do not use for targeted keyword or semantic identifier lookup across code (use 'search_codebase' instead).
Returns: Structured Markdown document featuring '# Repository Architecture (T-1)', '# Module Dependencies (T-2)', '# AST Signatures (T-3)', '# Architectural Rules (T-4)', and quantitative token savings metrics.
Inputs: focus_file, max_tokens, context_type, project_root, +2 more. Returns: result
diagnose_and_heal_systemDiagnose and Self Heal System Runtime and Codebase FlawsA
Diagnoses and automatically repairs environment misconfigurations, virtualenv breakages, syntax errors, missing standard library imports, UTF-8 BOM artifacts, and orphaned bytecode across the workspace, distinguishing from 'heal_hallucinated_code' which strictly corrects phantom AST symbols in code snippets by instead performing holistic system-level health diagnostics and autonomous multi-category file healing.
Parameters:
workspace_dir(str, optional, default='.'): Target repository root directory containing source code and environment configurations to diagnose.auto_repair(bool, optional, default=True): When True, applies surgical AST syntax patches, BOM sanitization, and cache cleanup to disk.dry_run(bool, optional, default=False): When True, evaluates diagnostics and previews repair diffs without modifying files on disk.
Behavior:
Mutability: Modifies files only when auto_repair=True and dry_run=False; otherwise strictly read-only.
Idempotency: Multiple sequential executions converge to a 100% clean state without regressions.
Performance & Latency: Scans and repairs 250+ files in <400ms using local standard library AST.
Resources: Consumes <50MB RAM; local file system operations only.
Privacy: 100% offline local processing; zero external network transmission.
Auth & Limits: Zero external credentials or API keys required; zero rate limits.
Error Handling: Continues diagnostic sweep across entire workspace if individual files contain unrecoverable binary corruption.
Usage Guidelines:
When to use: Use when diagnosing overall workspace health, repairing Python syntax breakages (missing colons, Python 2 print), resolving missing standard imports, fixing virtualenv paths, or clearing stale cache bloat.
When NOT to use: Do not use for repairing hallucinated LLM method names in isolated code snippets (use 'heal_hallucinated_code' instead); do not use for static cyclomatic complexity code smell audits (use 'audit_code_quality' instead).
Returns: Formatted Markdown report detailing initial health score, detected defects, surgical patch actions, and final post-healing health score.
Inputs: dry_run, auto_repair, workspace_dir. Returns: result
enforce_architecture_rulesEnforce Workspace Architectural Layer RulesARead-onlyIdempotent
Validates codebase import graphs against architectural boundary rules defined in tzero.rules.json, distinguishing from 'manage_architecture_rules' and 'analyze_code_dependencies' by enforcing layer isolation compliance rather than configuring boundary definitions or tracing raw symbol calls.
Parameters:
project_root: Repository root directory to inspect; scans all source files against configured architectural rules.strict_mode: When True, treats any forbidden cross-layer import or circular dependency as a critical violation; when False, reports infractions as non-fatal warnings for exploratory audits.
Behavior:
Mutability: Strictly read-only; parses import statements across the workspace without altering any files or configurations.
Idempotency: Deterministic; identical codebase revisions produce identical violation reports.
Privacy & Network: 100% offline local AST parsing; zero cloud telemetry or external network calls.
Performance & Resources: Completes in <300ms for 1,000 modules using <40MB RAM; thread-safe with zero rate limits.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits structured Markdown compliance audit listing passed layers, detected boundary violations, and exact offending source lines.
Error Handling: If tzero.rules.json is missing, applies enterprise standard layer boundaries (presentation -> domain -> persistence) and warns the user.
Usage Guidelines:
When to use: Run in CI/CD pipelines, pre-commit hooks, or before merging pull requests to prevent architectural erosion, circular imports, and unauthorized layer coupling.
When NOT to use: Do not use for defining, editing, or deleting architectural boundary rules (use 'manage_architecture_rules' instead); do not use for extracting raw caller/callee trees (use 'analyze_code_dependencies' instead).
Returns: Detailed compliance audit report listing passed layer boundaries, identified architectural violations, and remediation guidance.
Inputs: strict_mode, project_root. Returns: result
estimate_token_costEstimate Multi Model Token Cost and Financial ROIARead-onlyIdempotent
Calculates exact token counts, comparative API billing costs across major model families, and cumulative financial ROI savings, distinguishing from 'build_project_context' and 'prune_code_snippet' by evaluating financial costs and token metrics rather than constructing context trees or pruning code.
Parameters:
text(str, optional, default=''): Raw text string to count tokens and calculate cost for.project_root(str, optional, default='.'): Root directory of the repository to calculate workspace ROI savings for.tokens(int, optional, default=0): Optional raw token count to calculate cost directly.export_agent_rules(str, optional, default=''): Optional format to export agent rules: 'cursorrules', 'clinerules', 'markdown', or empty for cost estimation only.
Behavior:
Read-only: Calculates metrics from text or token counts without disk modifications.
Idempotent: Deterministic pricing calculations based on standard provider pricing tables.
100% Offline: Local pricing lookup table; zero network calls.
Auth & Rate Limits: Zero authentication or credentials required; execution latency <5ms.
Error Handling: Handles empty input gracefully by returning default workspace token estimations.
Usage Guidelines:
When to use: Evaluate token consumption, forecast monthly LLM API expenditures, or export agent rule configuration files (.cursorrules, .clinerules).
When NOT to use: Do not use for actively reducing token consumption by pruning repository code into AST signatures (use 'build_project_context' or 'prune_code_snippet' instead).
Returns: Markdown comparison table detailing input/output token counts, estimated USD costs per model provider, and percentage token reduction ROI.
Inputs: text, tokens, project_root, export_agent_rules. Returns: result
execute_codebase_workflowExecute Composite Multi Step Codebase WorkflowADestructive
Compatibility router for combined reports, distinguishing from 'build_project_context' and 'audit_code_quality' by combining analyses when action='auto'; for individual tasks use the dedicated tools directly.
Parameters:
action(optional, default='auto'): Workflow operation: 'auto' runs comprehensive all-in-one audit & context pipeline; 'context' builds AST context tree; 'audit' checks code quality & smells; 'security' runs Zero-Leak secret scan; 'blueprint' generates Mermaid architecture; 'dependencies' maps import topology; 'impact' evaluates blast radius of modified symbols; 'search' performs hybrid BM25 code search; 'prune' strips in-memory AST bodies; 'heal' runs AST self-healing; 'memory' manages episodic memory; 'swarm' coordinates multi-agent consensus.target(optional, default='.'): Target repository root path, file path, git diff text buffer, or raw source code snippet to process.query(optional, default=''): Free-text search term, focus symbol name, or goal prompt depending on selected action.options(optional, default=''): Optional JSON string specifying extra configuration parameters (e.g. {"reduction_mode": "ultra", "max_tokens": 32000, "depth": 4}).
Behavior:
Mutability: Depends on action and options. Security may install hooks; rules, memory, sync, healing, merge, and generated tests can modify files.
Idempotency: Not guaranteed for state-changing operations.
Privacy & Network: Most analysis is local, but blueprint with use_ai can contact a configured provider and transmit context.
Performance & Resources: Runtime and memory depend on workspace size and selected operation.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits comprehensive executive Markdown report tailored to the requested action or full autonomous pipeline.
Error Handling: Gracefully reports clean diagnostic notices for missing paths, unparseable files, or invalid JSON options without crashing.
Usage Guidelines:
When to use: Use action='auto' for a combined report or retain this router for compatibility with existing clients.
When NOT to use: Do not use when an isolated single-purpose operation is sufficient, such as generating an AST context tree (use 'build_project_context' instead), auditing code smells (use 'audit_code_quality' instead), scanning secrets (use 'verify_security_guard' instead), or pruning an in-memory snippet (use 'prune_code_snippet' instead).
Returns: Comprehensive Markdown report tailored to the requested action or full autonomous pipeline.
Inputs: query, action, target, options. Returns: result
generate_architectural_passportGenerate High Density AST Architectural Passport for LLMsARead-onlyIdempotent
Returns a compact architectural passport for one Python file, distinguishing from 'build_project_context' for repository context, 'build_ast_snapshot' for a persisted index, and 'generate_architecture_blueprint' for repository diagrams.
Parameters:
file_path(str, required): Absolute or relative path to the Python source code file to analyze.
Behavior:
Mutability: Strictly read-only; does not modify source files or write to disk.
Idempotency: Deterministic AST extraction producing identical passports for identical source files.
Performance & Latency: Generates complete architectural passport in <20ms using local AST parsing.
Resources: Consumes <30MB RAM; zero disk footprint.
Privacy: 100% offline local processing; zero external network transmission.
Auth & Limits: Zero external credentials or API keys required; zero rate limits.
Error Handling: Returns clear error notification if target file is missing or unparseable.
Usage Guidelines:
When to use: Use when grounding LLMs on a specific module or service before authoring code, generating prompt-ready architectural contracts, or evaluating module complexity and layer boundaries.
When NOT to use: Do not use for entire repository multi-tier trees (use 'build_project_context' instead); do not use for graphical Mermaid visual diagrams (use 'generate_architecture_blueprint' instead).
Returns: Formatted Markdown architectural passport block ready for immediate LLM prompt ingestion.
Inputs: file_path (required). Returns: result
generate_architecture_blueprintGenerate System Architecture Blueprint DocumentARead-onlyIdempotent
Generates a complete system architectural specification (ARCHITECTURE.md) with auto-generated Mermaid component topology diagrams, layer boundaries, and module hierarchies, distinguishing from 'enforce_architecture_rules' and 'analyze_code_dependencies' by producing comprehensive system architecture documentation rather than verifying boundary rules or tracing call chains.
Parameters:
project_root(str, optional, default='.'): Root directory of the repository to analyze (default: current directory).use_ai(bool, optional, default=False): When True, uses configured AI provider to synthesize deep narrative; when False (default), runs 100% offline AST analysis.model(str, optional, default=''): Optional model identifier override when use_ai is True.
Behavior:
Read-only: Returns formatted Markdown text without writing files to disk.
Idempotent: Deterministic AST topology diagram generation when use_ai=False.
100% Offline by default: Runs local AST analysis; optionally uses configured AI model when use_ai=True.
Auth & Rate Limits: Zero credentials required for default offline mode; completes in <1s.
Error Handling: Falls back to offline AST structural mapping if remote AI model synthesis is unreachable.
Usage Guidelines:
When to use: Create or update system architecture documentation and visual Mermaid flow diagrams for onboarding or RFC review.
When NOT to use: Do not use for checking rule compliance against defined boundaries (use 'enforce_architecture_rules' instead); do not use for raw dependency listings or call chain traces (use 'analyze_code_dependencies' instead).
Returns: Comprehensive Markdown document with live Mermaid diagrams, layer classifications, and component interfaces.
Inputs: model, use_ai, project_root. Returns: result
heal_hallucinated_codeAuto Heal Hallucinated Code and Phantom SymbolsARead-onlyIdempotent
Statically inspects candidate code against verified workspace AST symbol tables, detects phantom imports, misspelled identifiers, and hallucinated method calls, and rewrites the AST to the correct valid local identifier, distinguishing from 'verify_security_guard' and 'audit_code_quality' by actively applying AST node corrections rather than merely reporting violations or secret leaks.
Parameters:
code(str, required): The candidate Python source code string containing potential AI hallucinations or phantom methods.workspace_dir(str, optional, default='.'): Target repository root directory containing ground-truth AST symbol definitions.
Behavior:
Mutability: Non-destructive in-memory analysis and AST transformation; does not alter disk files.
Idempotency: Returns identical corrected code and diffs for identical candidate code input.
Performance & Latency: Completes AST inspection and healing in <100ms; consumes <35MB RAM.
Privacy: 100% offline local AST parsing; zero external network transmission.
Auth & Limits: Zero external credentials or API keys required; zero rate limits.
Error Handling: Emits clean syntax error diagnostic if candidate code fails initial AST parsing.
Usage Guidelines:
When to use: Use when repairing AI-generated code that contains hallucinated method names, phantom imports, or misspelled identifiers against real workspace AST symbol tables.
When NOT to use: Do not use for general codebase static linting (use 'audit_code_quality' instead); do not use when merely checking if code is safe to execute without applying AST repairs (use 'verify_security_guard' instead).
Returns: Formatted Markdown report containing total repaired symbols, confidence percentages, unified AST diff, and healed code block.
Inputs: code (required), workspace_dir. Returns: result
manage_architecture_rulesManage Architectural Boundary and Layer RulesADestructiveIdempotent
Manages the persistent lifecycle of architectural boundary rules and tier constraints in tzero.rules.json, distinguishing from 'enforce_architecture_rules' and 'generate_architecture_blueprint' by configuring layer definitions on disk rather than evaluating codebase compliance or generating visual diagrams.
Parameters:
action: Rule lifecycle operation: 'query' inspects active boundary definitions; 'update' creates or overwrites rule configurations; 'delete' removes a specified rule; 'reset' restores enterprise-default 4-tier rules.project_root: Directory path containing or intended to hold tzero.rules.json; defaults to current working directory.rule_name: Specific rule identifier or layer name (e.g. 'presentation', 'domain', 'persistence', 'forbidden_imports') to target during 'update' or 'delete'.rule_definition: Valid JSON string or Markdown specification defining layer constraints, allowed imports, or forbidden cross-tier dependencies when action is 'update'.
Behavior:
Mutability: State-modifying; writes and updates tzero.rules.json on disk when action is 'update', 'delete', or 'reset'; read-only when action is 'query'.
Idempotency: Idempotent for identical rule definitions and queries; resets restore canonical default JSON.
Privacy & Network: 100% offline local filesystem storage; zero cloud synchronization or external dependencies.
Performance & Resources: Executes in <20ms; atomic file writing prevents file corruption during concurrent operations.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits JSON or Markdown status confirmation of updated, deleted, or queried boundary configurations.
Error Handling: Validates JSON syntax before writing to disk; emits clear error diagnostics on malformed JSON without modifying existing rules.
Usage Guidelines:
When to use: Configure, inspect, update, reset, or remove architectural layer definitions and dependency constraints (e.g. preventing presentation layer from importing persistence layer).
When NOT to use: Do not use for validating whether existing codebase files violate these rules (use 'enforce_architecture_rules' instead); do not use for rendering Mermaid architecture diagrams (use 'generate_architecture_blueprint' instead).
Returns: JSON or Markdown status report detailing active or updated architectural rules and confirmation of modified file path.
Inputs: action, rule_name, project_root, rule_definition. Returns: result
manage_memory_storeManage Persistent Agent Memory Triplet StoreADestructive
Manages the complete lifecycle of persistent agent semantic memory stores, including compression, consolidation, export, listing, reset, and deletion, distinguishing from 'query_memory_store' and 'prune_code_snippet' by storing, compressing, and purging episodic memories rather than querying relations or pruning source code.
Parameters:
operation: Memory lifecycle operation: 'list' displays active memory stores and recent codes; 'compress' encodes text into semantic triples; 'decompress' decodes memory codes; 'consolidate' merges episodic memories; 'export' dumps graph to JSON or interactive HTML; 'reset' clears memory codes; 'delete' removes store file from disk.content: Text document, knowledge snippet, or output file path depending on operation.store_name: Unique identifier of the target memory store to manage (default: 'default').project_root: Workspace directory where memory stores are persisted (default: current directory).
Behavior:
Mutability: State-modifying and destructive; writes, consolidates, resets, or deletes local memory store JSON files on disk.
Idempotency: Non-idempotent for write/reset operations; idempotent for 'list' and 'export' operations.
Privacy & Network: 100% offline local JSON storage; zero external network synchronization.
Performance & Resources: Executes in <50ms consuming <35MB RAM; thread-safe file handling.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits Markdown status report confirming memory consolidation, export file path, list of active memory stores, or deletion confirmation.
Error Handling: Validates operation parameter and returns clear error guidance for unrecognized modes.
Usage Guidelines:
When to use: Store new semantic knowledge, consolidate episodic memories, export knowledge graphs to JSON/HTML, list active memory stores, or clear/reset agent memories.
When NOT to use: Do not use for querying existing knowledge triples or causal chains from memory (use 'query_memory_store' instead); do not use for pruning source code snippets or diff streams (use 'prune_code_snippet' instead).
Returns: Status report confirming memory consolidation, export file path, list of active memory stores, or confirmation of reset/deletion.
Inputs: content, operation, store_name, project_root. Returns: result
orchestrate_agent_swarmOrchestrate Autonomous Multi Agent Swarm ExecutionA
Coordinates autonomous multi-agent task execution, goal decomposition, Byzantine fault-tolerant (PBFT) consensus voting, and self-healing error recovery, distinguishing from 'manage_memory_store' and 'audit_code_quality' by dispatching autonomous multi-agent workflows rather than managing memory stores or auditing code quality.
Parameters:
goal: High-level mission objective, swarm proposal specification, or failing test traceback to heal.orchestration_mode: Swarm coordination strategy: 'goal_execute' decomposes goals into phased agent workflows; 'swarm_consensus' runs Byzantine fault-tolerant voting with 3f+1 quorum; 'self_healing' diagnoses test failures and applies AST surgical patches.agents: Comma-separated list of specialized agent roles participating in swarm execution (e.g. 'architect,coder,tester').project_root: Target repository root directory for swarm task execution and test verification.
Behavior:
Mutability: State-modifying; dispatches sub-tasks, validates proposals, and executes self-healing patches on disk files.
Idempotency: Non-idempotent; execution outcomes adapt to dynamic agent consensus rounds and self-healing iterations.
Privacy & Network: 100% offline local agent orchestration; zero unverified cloud relays or external data leaks.
Performance & Resources: Completes consensus rounds in <100ms; thread-safe agent coordination.
Auth: Zero authentication, external blockchain relays, or cloud credentials required.
Return Structure: Emits structured orchestration summary with phased execution plan, agent task allocations, consensus voting tallies, or self-healing patch results.
Error Handling: Quorum isolation automatically detects, flags, and neutralizes Byzantine faults and anomalous proposals.
Usage Guidelines:
When to use: Execute high-level complex coding goals across multi-agent swarms, validate proposals via Byzantine consensus voting (3f+1 quorum), or diagnose and heal test failures.
When NOT to use: Do not use for querying or managing long-term agent memory (use 'query_memory_store' and 'manage_memory_store' instead); do not use for auditing codebase quality before task execution (use 'audit_code_quality' instead).
Returns: Orchestration summary with phased execution plan, agent task allocations, consensus voting tallies, or self-healing patch results.
Inputs: goal (required), agents, project_root, orchestration_mode. Returns: result
prove_zero_hallucinationRun Hallucination Detection BenchmarkA
Runs a fixed 60-scenario hallucination detection benchmark, distinguishing from 'heal_hallucinated_code' for a single candidate snippet and 'audit_code_quality' for repository findings. Results apply only to the tested cases and do not prove absence of other hallucinations.
Parameters:
workspace_dir(str, optional, default='.'): Target repository root directory containing ground-truth AST symbol definitions.export_docs(bool, optional, default=True): When True, updates docs/ZERO_HALLUCINATION_PROOF.md and docs/zero_hallucination_proof.json.
Behavior:
Mutability: export_docs=True writes benchmark artifacts in docs/ relative to the server working directory; False avoids those writes.
Idempotency: Report timestamps and measured latencies may differ between runs.
100% Offline: Operates entirely locally with zero external network access.
Auth & Rate Limits: Zero authentication or cloud credentials required; completes in <100ms.
Error Handling: Emits clean verification status and confusion matrix.
Usage Guidelines:
When to use: Measure detection and false-positive rates on the bundled scenarios before or after changes.
When NOT to use: Do not use for inspecting a single candidate snippet (use 'heal_hallucinated_code' instead); do not use for secret scans (use 'verify_security_guard' instead).
Returns: Markdown benchmark results with case counts, detection and false-positive rates, and latency.
Inputs: export_docs, workspace_dir. Returns: result
prune_code_snippetPrune In-Memory Code Snippet to AST SignaturesARead-onlyIdempotent
Prunes implementation bodies from in-memory code snippets, API schemas, or unified diff streams while preserving AST interfaces, type annotations, and function signatures, distinguishing from 'build_project_context' and 'audit_code_quality' by stripping function bodies in memory rather than scanning repository file trees or auditing code quality.
Parameters:
code(str, required): Raw source code, schema definition (JSON/YAML), or unified diff text to compress.file_name_or_lang(str, optional, default='snippet.py'): File name or language extension (e.g. 'service.ts', '.go', '.rs', 'schema.json') to select appropriate AST parser.reduction_mode(str, optional, default='ultra'): AST reduction level: 'ultra' for signatures only, 'balanced' for signatures + control structures, 'micro_patch' for surgical unified diff pruning.
Behavior:
Read-only: Processes in-memory text buffers without touching disk files.
Idempotent: Deterministic AST reduction for identical code inputs.
100% Offline: Local AST and regex parsers for Python, TypeScript, Go, Rust, Java, C#, C++, SQL, JSON, YAML.
Auth & Rate Limits: Zero authentication or credentials required; execution latency <10ms.
Error Handling: Gracefully falls back to regex line pruning if parser encounters malformed syntax.
Usage Guidelines:
When to use: Compress raw code strings, function definitions, SQL queries, or diff patches before embedding them in an LLM prompt to achieve 80-95% token savings.
When NOT to use: Do not use for scanning full repository files or building hierarchical project context from disk (use 'build_project_context' instead); do not use for detecting code duplication across modules (use 'audit_code_quality' instead).
Returns: Compact code snippet retaining only structural signatures, interfaces, and docstrings.
Inputs: code (required), reduction_mode, file_name_or_lang. Returns: result
query_memory_storeQuery Persistent Agent Memory Triplet StoreARead-onlyIdempotent
Queries semantic triples, causal reasoning graphs, and MinHash entity clusters from the local agent memory store, distinguishing from 'manage_memory_store' and 'search_codebase' by retrieving episodic reasoning relations rather than modifying memory records or searching repository code.
Parameters:
query: Entity identifier, concept keyword, or natural language query to look up in the persistent semantic memory graph.query_mode: Query strategy: 'semantic' for knowledge triple and relation lookup; 'causal_chain' for temporal cause-and-effect traces; 'minhash' for sub-microsecond entity similarity clustering.project_root: Workspace root directory where the local memory store JSON file is located (defaults to current directory).
Behavior:
Mutability: Strictly read-only; queries persistent memory store without altering stored knowledge, weights, or timestamps.
Idempotency: Deterministic; returns consistent knowledge relations for identical queries on the same memory state.
Privacy & Network: 100% offline local graph and MinHash index lookup; zero cloud synchronization or network traffic.
Performance & Resources: Query latency <10ms for 10,000 triples using <25MB RAM; thread-safe.
Auth: Zero authentication, API keys, or cloud credentials required.
Return Structure: Emits Markdown report with extracted semantic triples, knowledge relationships, or causal inference chains.
Error Handling: Returns clean empty graph notice if the queried entity does not exist in the codebook without raising exceptions.
Usage Guidelines:
When to use: Recall past agent decisions, query knowledge graph entity relations, or trace causal dependency chains across reasoning sessions.
When NOT to use: Do not use for storing, consolidating, or deleting memory stores (use 'manage_memory_store' instead); do not use for searching source code in the repository (use 'search_codebase' instead).
Returns: Markdown report with extracted semantic triples, graph relationships, or causal inference chains.
Inputs: query (required), query_mode, project_root. Returns: result
search_codebaseSearch Codebase via Local Hybrid Lexical IndexARead-onlyIdempotent
Executes private local hybrid search combining BM25 keyword matching and TF-IDF semantic scoring across repository code, distinguishing from 'query_memory_store' and 'build_project_context' by indexing source code identifiers and docstrings rather than querying agent episodic memory or generating context trees.
Parameters:
query: Free-text search phrase, function name, class identifier, or concept description to search across the codebase.project_root: Directory path of the repository to index and search; defaults to current working directory.top_k: Maximum count of ranked results to return (integer between 1 and 20; defaults to 5).
Behavior:
Mutability: Strictly read-only; queries local files without altering code or persisting external indices on disk.
Idempotency: Deterministic; identical queries against the same codebase state produce identical rankings.
Privacy & Network: 100% offline local CPU execution; zero remote embedding APIs, cloud billing, or network egress.
Performance & Resources: Sub-millisecond query latency (<15ms) across 1,000 files with <35MB RAM footprint; thread-safe.
Auth: Zero authentication, API keys, or cloud credentials required.
Return Structure: Emits ranked Markdown list with file paths, matching line ranges, relevance scores, and code snippet extracts.
Error Handling: Returns clean empty-match notice with suggested query terms if no relevant tokens or symbols match.
Usage Guidelines:
When to use: Quickly locate functions, classes, definitions, or architectural concepts in a repository using natural language or symbol names at zero cost.
When NOT to use: Do not use for querying persistent agent semantic memory or causal decision graphs (use 'query_memory_store' instead); do not use for building full hierarchical context trees (use 'build_project_context' instead).
Returns: Ranked list of matching code snippets with file paths, line ranges, relevance scores, and matched symbol definitions.
Inputs: query (required), top_k, project_root. Returns: result
search_toolsProgressive T-Zero MCP Tool Discovery CatalogARead-onlyIdempotent
Progressively discover and search registered T-Zero tools by keyword or domain category rather than loading all schemas at once, distinguishing from 'search_codebase' by discovering server tools and capabilities rather than searching repository source files.
Parameters:
query(optional, default=''): Optional keyword query (e.g., 'secret audit', 'pagerank', 'diff', 'merge').category(optional, default='all'): Domain filter category: 'all', 'context', 'security', 'ast', 'memory', 'swarm', 'design'.limit(optional, default=10): Maximum tool entries returned (integer 1-30; default: 10).
Behavior:
Mutability & Speed: Read-only, idempotent catalog lookup executing in <5ms.
Auth & Boundaries: Zero authentication, external credentials, or network access required.
Usage Guidelines:
When to use: Discover specialized AST, Jarvis, or security tools by keyword; availability varies by tool mode.
When NOT to use: Do not use when searching source files or symbols inside the workspace repository — use 'search_codebase' instead.
Returns: Structured dictionary with query, total_available, and ranked tools (name, category, summary).
Inputs: limit, query, category. Returns: query, tools, total_available
transpile_model_bridgeTranspile Python Data Models to Polyglot SchemasARead-onlyIdempotent
Transpiles Python @dataclass and Pydantic data models into TypeScript interfaces, Rust structs, and Go structs deterministically via AST, distinguishing from 'prune_code_snippet' and 'generate_architecture_blueprint' by generating concrete cross-language type schemas rather than pruning code or diagramming topologies.
Parameters:
file_path(str, required): Path to the Python file containing @dataclass or Pydantic model definitions.target_lang(str, optional, default='ts'): Target programming language: 'ts' (TypeScript), 'rust' (Rust with serde), 'go' (Golang), or 'all' (all languages).
Behavior:
Mutability: Read-only static AST inspection; does not modify source files on disk.
Idempotency: Produces identical type definitions for identical source model input.
Performance & Latency: Completes model transpilation in <40ms; consumes <30MB RAM.
Privacy: 100% offline local AST parsing; zero external network calls.
Auth & Limits: Zero external credentials or API keys required; zero rate limits.
Error Handling: Gracefully reports missing file or syntax error without crashing.
Usage Guidelines:
When to use: Use when transpiling Python @dataclass and Pydantic models into TypeScript interfaces, Rust structs, or Go structs deterministically via AST.
When NOT to use: Do not use for generic Python to JavaScript logic compilation (use specialized external compilers instead); do not use for high-level Mermaid architecture diagrams (use 'generate_architecture_blueprint' instead).
Returns: Formatted Markdown report containing transpiled type definitions in the requested target language.
Inputs: file_path (required), target_lang. Returns: result
verify_security_guardVerify Zero Leak Shannon Entropy Secrets GuardAIdempotent
Scans workspace files and code buffers for hardcoded secrets and API keys, or installs the automated git pre-commit zero-leak guard, distinguishing from 'audit_code_quality' and 'enforce_architecture_rules' by identifying high-entropy credentials and git hooks rather than checking code complexity or enforcing layer rules.
Parameters:
action: Security action: 'scan' inspects workspace files or in-memory text for confidential credentials; 'install_pre_commit' installs the automated git pre-commit security hook into .git/hooks/pre-commit.project_root: Root directory of the repository to scan or install the pre-commit hook into.content: Optional raw in-memory code string or configuration text to scan for secrets directly without touching disk files.
Behavior:
Mutability: Strictly read-only when action is 'scan'; writes executable hook file .git/hooks/pre-commit when action is 'install_pre_commit'.
Idempotency: Scans are strictly idempotent; hook installation is idempotent and will not overwrite custom existing hooks without backup.
Privacy & Network: 100% offline local regex and Shannon entropy calculation; zero secret tokens are ever transmitted over the network.
Performance & Resources: Scans 1,000 files in <100ms using <30MB RAM; hook execution completes in <50ms.
Auth: Zero authentication or cloud credentials required.
Return Structure: Emits security audit report showing 100% Zero-Leak pass status or lists detected secret leaks with file names, line numbers, and redacted tokens.
Error Handling: Gracefully reports if directory is not a git repository when attempting pre-commit installation.
Usage Guidelines:
When to use: Ensure zero confidential credentials (OpenAI, Anthropic, Gemini, GitHub tokens, AWS keys, private certificates) are committed to git or exposed in LLM prompt contexts.
When NOT to use: Do not use for checking code quality, cyclomatic complexity, or duplicate code (use 'audit_code_quality' instead); do not use for enforcing architectural layer boundaries (use 'enforce_architecture_rules' instead).
Returns: Security audit report showing 100% Zero-Leak certification or list of detected secret leaks with line numbers, or hook installation confirmation.
Inputs: action, content, project_root. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 22 tools
Descriptions go unusually far in explicitly stating 'distinguishing from X' and 'when NOT to use', which materially helps selection. However, the surfaces genuinely overlap: build_ast_snapshot/build_project_context/generate_architectural_passport all produce AST context, heal_hallucinated_code/diagnose_and_heal_system/audit_code_quality(hallucinations) all touch repair/validation, and execute_codebase_workflow is a router that duplicates nearly every other tool. An agent must read long disambiguation prose rather than rely on clearly disjoint purposes.
All names are snake_case with a verb_leading pattern, so the set is scannable and predictable (build_*, analyze_*, manage_*, generate_*, search_*). A few deviate from clean verb_noun (prove_zero_hallucination, diagnose_and_heal_system, analyze_change_impact), but they remain readable and on-convention.
22 tools is heavy and sits in the borderline band; several (build_ast_snapshot vs build_project_context, generate_architectural_passport vs generate_architecture_blueprint) feel like fine-grained splits of the same capability. The presence of both a catch-all router (execute_codebase_workflow) and a meta-discovery tool (search_tools) on top of 20 specific tools suggests the surface is larger than needed.
For a codebase-intelligence toolkit, coverage is broad: context/snapshot, search, dependency and impact analysis, architecture rules lifecycle (manage + enforce), security scanning, memory lifecycle (query + manage), quality audit, healing, and transpilation. Gaps exist as dead ends—no tool-level create/edit of source, no test generation, and the router hints at 'sync/merge/generate tests' operations with no dedicated tools—but agents can work around them.
Maintenance
Related MCP Connectors
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
Enterprise code intelligence for M&A, security audits, and tech debt. Hosted server with 200k free.
Code intelligence for coding agents: semantic, AST, graph, and full-text search. 279+ languages.
Deterministic context layer for your codebase: change impact, blast radius, answers with receipts.
Related MCP Servers
- AlicenseAqualityCmaintenanceProvides intelligent code context and analysis through semantic compression, AST parsing, and multi-language support. Offers 60-80% token reduction while enabling AI assistants to understand codebases through local analysis, OpenAI-enhanced insights, and GitHub repository integration.6229 npm3MIT
- AlicenseBqualityBmaintenanceEnables LLMs to efficiently read, write, and refactor code using precise AST-based operations, reducing token usage and context window waste.25318 npm3MIT
- AlicenseNot gradedqualityDmaintenanceMake any LLM a codebase expert instantly. Provides deep code intelligence through semantic search, architecture mapping, security analysis, and smart context that fits perfectly in token windows.MIT
- AlicenseNot gradedqualityCmaintenanceProvides structured, token-efficient code context for AI assistants by indexing codebases with AST-level analysis, supporting 17+ languages, enabling semantic search, call-site tracking, and PR attribution.35 PyPI44MIT