ctxfw
ctxfw exposes a local MCP server for pruning source code into compact AST context, evaluating specs and patches against determinism/security gates, and verifying hash-chained audit records.
Prune individual source files into full, interface, or nominal AST stubs across Python, TypeScript, JavaScript, Go, and Java, with optional docstring stripping.
Build token-pruned Markdown context bundles from topological dependency graphs, with breaker-state degradation and optional session budget tracking.
Score architectural briefs for determinism against ACI ≥ 0.9000 rules, returning status, remediation notes, and manifest hash.
Evaluate unified git diffs through SWE-Gate constraints such as cyclomatic delta, type-ignore bans, disallowed imports, and test verdicts.
Query and verify SWE-Gate evaluation records and TraceKit SHA-256 hash-chained audit sessions/blocks for forensic and compliance checks.
Provides centralized firewall gateway governance for OpenAI streaming SSE endpoints, enabling team-wide budget circuit breakers and policy controls.
CTXFW
Deterministic Zero-Egress Prompt Injection Firewall (SARA), Polyglot AST Context Compactor, and MCP Governance Engine for AI Coding Agents.
Quickstart • How It Works • Empirical Benchmarks • MCP & CLI Reference • Architecture • Editions • Docs Index • Changelog
Quickstart
Install ctxfw (v4.2.1, Python 3.10–3.13) with zero cloud accounts or outbound telemetry:
# Core MCP server, SARA firewall, CLI & TraceKit SQLite WAL ledger
pip install ctxfw
# Or isolated CLI installation via pipx
pipx install ctxfw
# Optional: include Tree-sitter TypeScript/Go/Java grammars + local HTTP reverse proxy
pip install "ctxfw[polyglot,proxy]"Standalone zero-Python executables for Linux, macOS, and Windows are published on GitHub Releases.
Configure Claude Code, Claude Desktop, Cursor, and Windsurf in one idempotent command (creating .bak.<timestamp> backups automatically):
# Auto-detect and wire installed IDEs
ctxfw init
# Targeted Claude setup, repository pre-commit sentry, and environment verification
ctxfw install --claude
ctxfw init --repo .
ctxfw doctorFor non-MCP agents (Aider, OpenCode Interpreter, Continue.dev), start the local loopback proxy:
ctxfw proxy --port 8765
export ANTHROPIC_BASE_URL="http://localhost:8765/v1"
export OPENAI_BASE_URL="http://localhost:8765/v1"Related MCP server: redcon
How It Works
Autonomous coding agents suffer from three failure modes when reading unfiltered repositories and untrusted MCP tool outputs: peripheral token bloat, indirect prompt injection (IPI), and ungrounded code synthesis. ctxfw enforces a deterministic CPU perimeter before data leaves the workstation or CI runner (100% Zero-Egress):
Topological AST Compaction (
D0 -> D3+TraceLite): Preserves the focal file under edit (D0) 100% byte-for-byte (AXIOM-3), strips peripheral dependencies (D1,D2) into typed interface contracts using Pythonastand Tree-sitter CSTs (Python,TypeScript/JavaScript,Go,Java), emits a compactD3symbol catalog (≤ 1,000tokens), and compresses multi-step agent traces (TraceLite:-82.43%tokens).Pre-Ingestion MCP Security (
SARA·mcp_guard·PASAC·Provenance): Screens tool observations in< 1 msP50 across 7 languages (es,fr,de,pt,zh,ja,ko), Cyrillic/Greek/Armenian intra-token homoglyphs, Trojan-Source bidirectional Unicode escapes (U+202A–U+202E),1..4-round percent-encoded path traversals (%XX), SHA-256 tool-schema rug-pulls, Gate0dcapability laundering, and multi-hop causal poisoning.Axiomatic Sieve, SWE-Gate & Hash-Chained Ledger: Enforces specification completeness (
ACI ≥ 0.9000,≥ 5negative invariants, finite bounds, FSM transitions, 4-class error taxonomy), gates unified diffs oncyclomatic_delta ≤ 10and zero# type: ignoresuppressions, and seals every decision in a local SQLite WAL SHA-256 hash chain (tracekit.db).
Empirical Benchmarks
All security, OCR, and AST compaction suites are deterministically reproducible offline (network_egress_calls = 0).
1. Security, Wave 2 & Spanish Regulatory/OCR Suites (ctxfw v4.2.1)
Suite / Engine | Measured Scope | Recall / Reduction | False Positive Rate | P50 / P95 Latency | Dossier |
| 24 vectors ( |
|
|
| |
|
|
|
|
| |
|
|
|
|
| |
| Causal |
|
|
| |
| 60 Spanish regulatory/financial noisy OCR docs ( |
|
|
|
Reproduce offline from a repository checkout:
python benchmarks/run_sara_security_benchmark.py --json
python benchmarks/run_wave2_v42_benchmark.py --json
python benchmarks/run_regulatory_ocr_benchmark.py --json2. Topological AST Context Compaction (D0–D3)
Measured offline (0 bytes stdout JSON-RPC leak, 100% PASS via ast.parse()). Full report: Trilogy Empirical Benchmark.
Target Repository | Focal | Raw Tokens | Pruned Tokens | Peripheral | Latency / Throughput |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Internal core package |
|
|
|
|
Cost Mechanics: Because stateless LLM APIs re-send conversation history on every turn, pruning ~72.4% of peripheral AST noise on Turn 1 yields 4.2x compounded cost savings across a 15-turn coding session (at a baseline reference of USD 3.00 per 1M tokens, roughly USD 87.70 saved per 1,000 calls on ctxfw/cli.py's dependency graph).
3. Pre-Ingestion Local Boundary vs. Cloud Runtime WAFs
Dimension | CTXFW ( | Cloud Runtime WAFs ( |
Enforcement Point | Local AST, CLI, Git Hook, MCP | Cloud HTTP edge after payload assembly |
Data Sovereignty |
| Outbound code/context transmission to third-party API |
AST Token Compaction |
|
|
Latency |
|
|
Licensing & Packaging | Open-Core ( | Proprietary enterprise cloud contracts |
Entity Disambiguation: CTXFW (
Context Firewallby Heurístico Lab) —github.com/heuristicolab/ctxfw,pypi.org/project/ctxfw,ctxfw.heuristicolab.com— is an open-core AST & MCP governance engine and is not affiliated withContextWall(contextwall.io).
MCP Tools and CLI Reference
Exposed MCP stdio Tools (ctxfw mcp)
MCP Tool | Purpose | Key Parameters |
| Prune target or dependency AST while keeping focal contracts |
|
| Build topological |
|
| Score formal specification against ACI |
|
| Enforce |
|
| Retrieve & verify |
|
Core CLI Commands
Command | Role |
| Compact |
| Configure Claude Code CLI, Claude Desktop, Cursor, Windsurf, or git pre-commit hook |
| Verify Python runtime, |
| Start pure JSON-RPC 2.0 MCP |
| Start loopback OpenAI/Anthropic reverse proxy |
| Deterministic CI/CD PR gatekeeper ( |
| Topological PR dependency & FinOps analyzer |
| Verify specification axioms, bounds, FSM, and error taxonomy ( |
| Verify append-only SHA-256 hash chain integrity across |
| Measure real AST token reduction and projected savings on a repository |
| Export local FinOps reports or manage background OS service |
Agent Skills & Ecosystem Directories:
npx -y skills add heuristicolab/ctxfw --skill context-firewall --agent claude-code
npx -y skills add heuristicolab/ctxfw --skill axiom-sieve --agent claude-code
npx -y skills add heuristicolab/ctxfw --skill eval-benchmark --agent claude-code
npx -y skills add heuristicolab/ctxfw --skill precommit-sentry --agent claude-codeStandards & Registries: OWASP DevSecOps Guideline · Official Anthropic MCP Registry (
io.github.heuristicolab/ctxfw) · Glama MCP (Grade A) · Skills Directory · MCPMarket · PulseMCP · DevList.
Architecture
UNTRUSTED / PROBABILISTIC DOMAIN DETERMINISTIC LAYER-0 PERIMETER (LOCAL CPU)
+-------------------------------+ +--------------------------------------------------+
| Autonomous AI Coding Agent | | CTXFW ENGINE (Zero-Egress / Offline-Ready) |
| Claude / Gemini / Cursor / CI | | 1. LexicalSanitizer + SARA + mcp_guard + PASAC |
+---------------+---------------+ | 2. Polyglot AST Compactor (D0 -> D3) + TraceLite|
| | 3. Axiomatic Sieve (ACI >= 0.90) & SWE-Gate |
v | 4. TraceKit Append-Only SHA-256 SQLite WAL |
+-------------------------------+ +-------------------+--------------------+---------+
| MCP stdio / Loopback Proxy |----------------------------->| |
+-------------------------------+ v v
[ VERIFIED ] [ QUARANTINED ]
Allow & Hash Seal Strip / Execution HaltSee the full User Manual and formal invariants in SPEC.axioms.md.
Editions and Enterprise
The entire single-developer CLI, 5-tool MCP server, SARA firewall, SWE-Gate, and TraceKit engine remain 100% open-source under Apache 2.0. Commercial editions fund multi-developer governance and enterprise infrastructure:
Edition | Scope | Reference |
Community Open-Core ( | Full 5-tool MCP | Free · |
Team Governance & CI Gate | Automated squad PR gates ( | |
CTXFW Enterprise (Custom VPC / Air-Gapped) | Multi-vault |
Official GitHub Action
- name: CTXFW SWE-Gate & FinOps PR Audit
uses: heuristicolab/ctxfw@v4
with:
license-key: ${{ secrets.CTXFW_LICENSE_KEY }}
diff-range: "origin/main...HEAD"Documentation & Governance
Available Tools
5 toolsevaluate_patchA
Verify a unified git diff patch (diff_text, with optional commit_sha, author_kind 'AGENT'|'HUMAN', pr_id, diff_size_bytes, repo_name, and repo_id) against SWE-Gate architectural constraints (max_cyclomatic_delta default 10, forbid_type_ignores default true, disallowed_import_modules) and functional test results (tests_passed default 1, tests_failed default 0, functional_verdict 'PASSED'|'FAILED') before allowing merge. Appends immutable audit records (EVL-...) in SweGateStore and seals cryptographic blocks in TraceKitStore; use query_audit_ledger to retrieve or verify persisted records.
Inputs: diff_text (required), pr_id, repo_id, repo_name, +9 more. Returns: content, isError
evaluate_spec_axiomsARead-onlyIdempotent
Evaluate an architectural specification brief (brief_text) against formal determinism rules, requiring at least 5 explicit negative invariants ('never' or 'shall never'), bounded variable domains, deterministic finite-state machine (FSM) transitions, and a 4-class error taxonomy to reach VERIFIED status (aci_score >= 0.9000 and SHA-256 manifest_hash; otherwise QUARANTINED with remediation notes). Use this during intake or planning phases before writing code; for verifying unified git diff patches, use evaluate_patch instead.
Inputs: brief_text (required). Returns: content, isError
prune_fileARead-onlyIdempotent
Extract semantic interfaces, types, pydantic models, sanitized raises, and signatures from a source file (path) at a given pruning depth ('full' retains full AST with sanitized raises, 'interface' replaces procedural bodies with ... stubs [default], or 'nominal' retains top-level symbol declarations only) and language ('python' [default], 'typescript', 'javascript', 'go', 'java'), optionally stripping docstrings (strip_docs, default false). Use this when you only need to inspect contracts or APIs of an individual dependency without ingesting raw implementation code; for multi-module dependency graphs, use resolve_context_bundle instead.
Inputs: path (required), depth, language, strip_docs. Returns: content, isError
query_audit_ledgerARead-onlyIdempotent
Retrieve persisted SWE-Gate patch evaluation records and violation findings by evaluation_id (EVL-<16 lowercase hex chars>), or verify cryptographic SHA-256 hash-chained audit sessions in TraceKitStore by session_id (SES-...) with optional block pagination (include_blocks default true, max_blocks 1..256 default 50); at least one of evaluation_id or session_id must be provided. Use this for forensic inspection and compliance verification after running evaluate_patch or context tools.
Inputs: max_blocks, session_id, evaluation_id, include_blocks. Returns: content, isError
resolve_context_bundleARead-onlyIdempotent
Calculate topological dependency graph distances (D0 full target_file, D1 interface stubs, D2 nominal symbols) within project_root (defaults to target_file's parent directory) and compile a token-pruned Markdown context bundle, with optional reactive degradation via breaker_state ('CLOSED', 'TRIPPED' strips D2+ modules, or 'HALTED' compacts D1 to nominal stubs) and session_id ('SES-...' linked to TokenCast budget tracking). Use this as your primary context builder before editing a file in a multi-module project; for inspecting isolated files, use prune_file instead.
Inputs: target_file (required), session_id, project_root, breaker_state. Returns: content, isError
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool targets a distinct operation: single-file pruning, multi-module bundle compilation, spec evaluation, patch evaluation, and audit retrieval. Descriptions explicitly disambiguate boundaries, e.g. prune_file says 'for multi-module dependency graphs, use resolve_context_bundle instead' and evaluate_spec_axioms points to evaluate_patch for diffs.
All five tools use snake_case with a leading verb (prune_file, resolve_context_bundle, evaluate_spec_axioms, evaluate_patch, query_audit_ledger). The verb_noun pattern is predictable and the two evaluate_* tools share a consistent prefix for their judgment family.
Five tools is well-scoped for a context-bundling and verification framework: two for context generation, two for evaluation gates, one for audit. No tool looks redundant and none of the sub-capabilities appear padded.
The prune/bundle, spec-evaluate, patch-evaluate, and audit-query lifecycle forms a coherent closed loop, but session management is an implicit dependency: session_id (SES-...) is consumed as input with no tool to create or list sessions, and TokenCast budget state is referenced but never exposed.
Maintenance
Related MCP Connectors
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
Memory that reasons: continual learning for stateful agents. Better context, fewer tokens.
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Persistent memory, inline redaction, per-agent access, and code localization for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceReduces token consumption for AI coding agents by 50-70% through intelligent code context filtering, Git delta tracking, and local SQLite/Tree-sitter indexing.167 npmMIT
- AlicenseAqualityCmaintenanceDeterministic repository context packing for AI coding agents: selects, compresses, and budgets only the files a task needs. Measured 83% fewer input tokens at the same task coverage, fully local, no LLM in the loop.924 PyPI9Functional Source , Version 1.1, MIT Future
- AlicenseAqualityBmaintenanceEnables AI coding agents to reduce token usage by condensing source code into AST skeletons, extracting specific symbols, compressing logs, and estimating token budgets.4MIT
- AlicenseAqualityBmaintenanceNeuro-symbolic deterministic context pruning middleware. Reduces tokens by 60%, drops local CPU TTFT by 62%, and prevents IP leakage via formal SPARQL contracts.23MIT