ctxfw
This MCP server provides context-pruning and specification-gating tools for coding agents, reducing token bloat and enforcing axiomatic integrity before code generation.
prune_file: Extracts semantic interfaces, types, pydantic models, sanitized raises, and signatures from a source file, replacing procedural bodies with AST stubs (supports python, typescript, javascript, go, java; depths: full/interface/nominal; optional docstring stripping; in-memory, no file modification).
resolve_context_bundle: Computes the topological dependency graph for a target file and compiles a token-pruned Markdown context bundle (D0 full implementation, D1 interface stubs, D2 nominal symbols) for efficient multi-module editing workflows.
evaluate_spec_axioms: Evaluates an architectural brief against formal determinism rules, negative invariant floors, and the Axiom Completeness Index (ACI), returning a JSON report with aci_score, negative_invariants_count, extracted_never_clauses, status, remediation_notes, and manifest_hash.
All tools are read-only and idempotent, return structured text content with error flags, and align with CTXFW's zero-telemetry, high-assurance design for safe AI-assisted development.
Provides centralized firewall gateway governance for OpenAI streaming SSE endpoints, enabling team-wide budget circuit breakers and policy controls.
CTXFW // CONTEXT FIREWALL
High-Assurance Axiomatic Gatekeeper & In-Memory AST Pruning for Coding Agents
The deterministic boundary between probabilistic LLM hallucination and production infrastructure.
Installation • Benchmarks • Diagnostic • Architecture • Enterprise Governance
Executive Abstract
Autonomous coding agents (Claude, Gemini, Cursor, Antigravity) consume massive context windows with bloated peripheral dependencies, triggering token exhaustion, context drift, and security degradation.
CTXFW is an open-core context firewall and Model Context Protocol (MCP) gatekeeper. It combines an in-memory polyglot AST pruner with a deterministic axiomatic intake sieve:
Compacts Peripheral Code (72.4% token reduction): Replaces distance-1 and distance-2+ module implementations with clean interface signatures, type definitions, and functional stubs.
Enforces Axiomatic Integrity (ACI $\ge$ 0.9000): Rejects ungrounded or deficient architecture briefs missing negative invariants ($N \ge 5$), bounded variable domains, deterministic state machines, or formal error taxonomies.
Zero Telemetry Egress: Guaranteed local execution with zero network telemetry leakage on standard operating mode.
Related MCP server: ContextBridge
AST Pruning Benchmarks
CTXFW operates directly at the syntax tree layer using native polyglot grammars:
Benchmark Dimension | Raw Context Ingestion | CTXFW Topological Compactor | Performance Gain / Impact |
Token Consumption | 100% (Raw Files) | 27.6% (Interface Stubs) | 72.4% Bloat Eliminated |
Engine Compaction Overhead | — | Native in-memory parser | < 5.0 ms |
Warm Cache Hit Overhead | — | SQLite WAL semantic cache | < 0.8 ms |
Stdio Telemetry Egress | Unsanitized stdout | Pure isolated JSON-RPC | Zero Egress (100% Isolated) |
Axiom Verification Latency | — | Sieve evaluation | < 12.0 ms |
CI/CD Pre-Commit Latency | — | Headless git sentry | < 85.0 ms |
Empirical Case Study: ctxfw/cli.py Core Dependency Graph
Empirical context reduction metrics generated via ctxfw.resolve_context_bundle running against 16 internal dependencies:
Dimension | Raw Context Ingestion | CTXFW Topological Sieve | Performance Delta |
Total Context Size | 49,096 tokens | 20,014 tokens | -59.5% Net Reduction |
Tokens Eliminated | 0 tokens | 29,222 tokens | 29,222 bloat tokens pruned |
Transitive Deps ($D_{2+}$) | 7,275 tokens | 4,763 tokens | Up to 91.9% reduction |
FinOps Cost Impact | Base Cost | Reduced by $0.0877 USD / prompt | ~$87.70 USD saved per 1K calls |
AST Compaction Latency | — | 1,407.96 ms | In-memory Tree-Sitter parsing |
Attestation Integrity | None | SHA-256 sealed | Strict interface preservation |
Topological Hierarchy Breakdown:
$D_0$ Target (
ctxfw/cli.py): 100% Full Implementation preserved.$D_1$ Direct Deps (e.g.
gatekeeper.py,mcp.py): Implementation truncated to typed stubs (...). Token savings: 73% – 86%.$D_{2+}$ Transitive Deps (e.g.
polyglot.py): Nominal symbols only. Token savings: 91.9%.
Installation
1. PyPI (Official Package)
Install via pip or isolated environment manager:
pip install ctxfwOr for global CLI availability using pipx:
pipx install ctxfw2. Native MCP Stdio Configuration
Register the stdio server directly in your IDE or client configuration (claude_desktop_config.json, Cursor, Windsurf, or Antigravity):
{
"mcpServers": {
"ctxfw": {
"command": "ctxfw",
"args": ["mcp"]
}
}
}3. Verified MCP Registry (Glama)
CTXFW is indexed and verified with Grade A compliance on the official Glama MCP registry:
Direct access to tool inspection, schemas, and live diagnostic telemetry on Glama.
System Diagnostics
Validate local environment readiness, stdio isolation purity, SQLite WAL concurrency, and Tree-Sitter grammars with a single command:
ctxfw doctor========================================================================
CTXFW DOCTOR // HIGH-ASSURANCE HEALTH & ISOLATION DIAGNOSTIC
========================================================================
[PASS] Python Package & sys.path ctxfw v3.5.0 loaded cleanly.
[PASS] MCP stdio Stream Isolation 100% pure JSON-RPC on stdout. Diagnostic logs isolated to stderr.
[PASS] Global CLI Executable (PATH) Binary 'ctxfw' found in PATH.
[PASS] Axiomatic Sieve Engine Evaluation verified (ACI: 1.0000, Invariants: 5).
[PASS] SQLite WAL Cache & Concurrency Journal mode: WAL, Busy timeout: 5000ms.
[PASS] Polyglot Tree-Sitter Grammars Initialized language parsers (typescript, go, java).
------------------------------------------------------------------------
Overall Verdict: [HEALTHY] [ATTESTED] Perimeter defense operational.
========================================================================
CTXFW // 72.4% AST Bloat Eliminated. Zero Telemetry Egress.
Need team-wide budget circuit breakers or multi-node proxy governance?
Control Plane & Enterprise Licensing: https://ctxfw.heuristicolab.com
========================================================================Architecture
CTXFW enforces a strict deterministic perimeter dividing probabilistic agent code from the core codebase:
PROBABILISTIC DOMAIN DETERMINISTIC PERIMETER
┌───────────────────────┐ ┌────────────────────────────────────────┐
│ Autonomous AI Agent │ │ CTXFW ENGINE │
│ (Claude / Gemini / │ │ │
│ Cursor / Antigravity│ │ ┌──────────────────────────────────┐ │
└───────────┬───────────┘ │ │ Polyglot AST Topological Engine│ │
│ │ │ - Python (ast) │ │
│ Target Context / Brief │ │ - TypeScript / Go / Java (CST) │ │
▼ │ │ - Multi-Depth Interface Stubs │ │
┌───────────────────────┐ │ └────────────────┬─────────────────┘ │
│ MCP Stdio Interceptor ├─────────────────►│ │ │
└───────────────────────┘ │ ┌────────────────┴─────────────────┐ │
│ │ SQLite WAL High-Concurrency │ │
│ │ Semantic Cache (<5ms warm hit) │ │
│ └────────────────┬─────────────────┘ │
│ ▼ │
│ [ ACI >= 0.9000? ] │
│ / \ │
│ YES NO │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌─────────────────┐ │
│ │ VERIFIED │ │ QUARANTINED │ │
│ │ SHA-256 Seal │ │ Execution Halt │ │
│ └──────┬───────┘ └────────┬────────┘ │
└────────┼────────────────────┼──────────┘
│ │
▼ ▼
[ Code Generation ] [ Forensic Report ]
[ & Git Permitted ] [ Pre-Commit Abort]Key Subsystems:
Polyglot Tree-Sitter Pruner:
Compiles topological dependency trees. Distance 0 (target file) is preserved in full; Distance 1 dependencies retain signatures and docstrings while pruning implementation logic; Distance 2+ dependencies are reduced to compact type stubs.
Built-in support for Python, TypeScript/JavaScript, Go, and Java.
SQLite WAL High-Concurrency Semantic Cache:
Atomic multi-process caching configured with Write-Ahead Logging (
PRAGMA journal_mode=WAL) andbusy_timeout=5000ms, delivering sub-millisecond warm cache hits.
Axiomatic Sieve Engine:
Formal specification gatekeeper evaluating requirements against 5 negative invariants (
shall never), explicit mathematical bounds, deterministic state machines, and a 4-class error taxonomy.
Zero-Touch Provisioning
Inject perimeter rules, MCP server declarations, and pre-commit sentinels into your workspace:
Global IDE Integration
ctxfw init --globalAutomatically configures Google Antigravity, Cursor, and Claude Desktop.
Repository Pre-Commit Sentry
ctxfw init --repo .Deploys .git/hooks/pre-commit to prevent uncertified code commits lacking an attested specification brief.
Enterprise Governance
For distributed engineering teams requiring centralized policy controls:
Team-wide LLM budget circuit breakers: Hard token and dollar thresholds with automatic killswitches.
Multi-node reverse proxy governance: Centralized firewall gateways supporting OpenAI and Anthropic streaming SSE endpoints.
FinOps Telemetry Ledger: Aggregate tokens saved, cost elusion analytics, and tamper-evident audit trails.
Control Plane & Enterprise Licensing: https://ctxfw.heuristicolab.com
Available Tools
3 toolsevaluate_spec_axiomsARead-onlyIdempotent
Evaluate an architectural brief against formal determinism rules, negative invariant floors, and the Axiom Completeness Index (ACI 1.0000). Use this during intake or planning phases before writing code. Pure analytical evaluation with no side effects.
| Name | Required | Description | Default |
|---|---|---|---|
| brief_text | Yes | Markdown content of the architectural intake brief to evaluate |
Output Schema
| Name | Required | Description |
|---|---|---|
| content | Yes | JSON-serialized architectural determinism verification report |
| isError | Yes | True if brief specification evaluation encountered an unhandled error |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare readOnly, idempotent, and non-destructive behavior. The description adds 'Pure analytical evaluation with no side effects,' which reinforces and clarifies the tool's behavior without contradicting the annotations. No additional behavioral surprises are hidden.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is three sentences, front-loads the core purpose, includes usage timing, and ends with a side-effect guarantee. Every sentence earns its place and there is no redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With one fully documented parameter, robust annotations, an output schema present, and clear phase-based usage guidance, the description covers everything an agent needs to select and invoke this tool correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100% and the single parameter brief_text is already described as 'Markdown content of the architectural intake brief to evaluate.' The description adds no new parameter-level detail, so the baseline of 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Evaluate') with a clear resource ('architectural brief') and names concrete evaluation criteria (determinism rules, invariant floors, ACI 1.0000). It is clearly distinguishable from siblings like prune_file and resolve_context_bundle.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description states exactly when to use the tool ('during intake or planning phases before writing code'), giving clear temporal context. It does not explicitly enumerate when not to use it, but the stated phase guidance is sufficient for typical routing.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
prune_fileARead-onlyIdempotent
Extract semantic interfaces, types, pydantic models, sanitized raises, and signatures from a source file while replacing procedural bodies with AST stubs. Use this when you only need to inspect contracts or APIs of an individual dependency without ingesting raw implementation code. Does not modify files on disk (pure in-memory AST operation).
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Absolute or relative path to the source file | |
| depth | No | Pruning depth: 'full', 'interface', or 'nominal' | interface |
| language | No | Programming language (python, typescript, javascript, go, java) | python |
| strip_docs | No | Whether to strip docstrings entirely |
Output Schema
| Name | Required | Description |
|---|---|---|
| content | Yes | Semantic interface stubs extracted via in-memory Tree-Sitter AST |
| isError | Yes | True if pruning encountered a fatal parsing or file resolution failure |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare readOnlyHint=true, destructiveHint=false, and idempotentHint=true. The description adds the crucial detail that it is a 'pure in-memory AST operation' and does not modify files, which reinforces the read-only nature. It also explains the stubbing behavior ('replacing procedural bodies with AST stubs'), a behavioral trait not captured by annotations. No contradictions with annotations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is three sentences: the first states what it does, the second gives a usage condition, and the third clarifies safety. It is front-loaded with the core behavior and has no filler. It could be slightly tightened ('pure in-memory AST operation' is mentioned both implicitly and explicitly) but remains efficient and well-structured.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With an output schema present, the description does not need to document return values. The tool has moderate complexity (4 parameters) but the schema covers them all. The description covers purpose, usage, and safety assumptions. Missing are potential edge cases (e.g., unsupported language, invalid path), but these are not essential for basic selection and invocation. A 4 reflects sufficiency without exhaustive detail.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so every parameter (path, depth, language, strip_docs) has a descriptive comment. The description does not add additional parameter-specific meaning beyond the schema, but the baseline for high coverage is 3. It neither improves nor detracts from the schema, so a 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's function: extracting semantic interfaces, types, models, raises, and signatures while stubbing bodies. It names specific output artifacts and contrasts with 'ingesting raw implementation code,' making its purpose precise. The sibling tools (resolve_context_bundle, evaluate_spec_axioms) are distinct enough that no further differentiation is needed.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly says 'Use this when you only need to inspect contracts or APIs of an individual dependency without ingesting raw implementation code.' This gives a clear condition for use. It does not explicitly name alternatives or say when not to use it, but the context is sufficient for an agent to decide. A 4 reflects the strong 'when' but lack of explicit 'when-not' or named alternatives.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
resolve_context_bundleARead-onlyIdempotent
Calculate topological dependency graph distances (D0 full target, D1 interface stubs, D2 nominal symbols) for an active target file and compile a token-pruned Markdown context bundle. Use this as your primary context builder before editing a file in a multi-module project. For inspecting isolated files, use prune_file instead. Read-only operation.
| Name | Required | Description | Default |
|---|---|---|---|
| target_file | Yes | Path to the active target file in editing (D0) | |
| project_root | No | Root directory of the project. Defaults to target file's directory. |
Output Schema
| Name | Required | Description |
|---|---|---|
| content | Yes | Compiled topological Markdown prompt context bundle |
| isError | Yes | True if dependency resolution or file traversal failed |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The annotations already cover read-only, idempotent, and non-destructive behavior, so the description does not need to restate safety. It adds meaningful behavioral context beyond annotations by specifying the D0/D1/D2 distance levels and the token-pruned Markdown output format. The 'Read-only operation' sentence is redundant with annotations but not contradictory.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences with no wasted words. The core function is front-loaded, usage context follows, and the alternative tool is named in the final sentence. The only minor redundancy is 'Read-only operation,' but it is one short clarifying phrase.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a read-only context-building tool with full schema description coverage and an output schema, the description covers purpose, usage timing, alternatives, and output format. An agent has all necessary information to decide when to call it and what to expect from it.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents both target_file and project_root. The description reinforces target_file's role as the active target file but adds no new parameter-level meaning, such as how project_root affects traversal or what values are valid.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb-resource pair: it calculates topological dependency graph distances and compiles a token-pruned Markdown context bundle. It also differentiates itself from prune_file by framing itself as the primary context builder, so an agent can select it confidently without inspecting siblings.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives explicit when-to-use guidance: 'primary context builder before editing a file in a multi-module project.' It also names the alternative for isolated files: 'use prune_file instead.' This is direct, actionable routing guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v3.5.6- Changed
evaluate_spec_axioms1 field changed- changed
Output schema / (root)Previous value: -nullNew value: +{ + "properties": { + "content": { + "description": "JSON-serialized architectural determinism verification report", + "items": { + "properties": { + "text": { + "description": "JSON report containing aci_score, negative_invariants_count, extracted_never_clauses, status, remediation_notes, and manifest_hash", + "type": "string" + }, + "type": { + "enum": [ + "text" + ], + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "type": "object" + }, + "type": "array" + }, + "isError": { + "description": "True if brief specification evaluation encountered an unhandled error", + "type": "boolean" + } + }, + "required": [ + "content", + "isError" + ], + "type": "object" +}
- Changed
prune_file1 field changed- changed
Output schema / (root)Previous value: -nullNew value: +{ + "properties": { + "content": { + "description": "Semantic interface stubs extracted via in-memory Tree-Sitter AST", + "items": { + "properties": { + "text": { + "description": "Pruned source code with AST stubs", + "type": "string" + }, + "type": { + "enum": [ + "text" + ], + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "type": "object" + }, + "type": "array" + }, + "isError": { + "description": "True if pruning encountered a fatal parsing or file resolution failure", + "type": "boolean" + } + }, + "required": [ + "content", + "isError" + ], + "type": "object" +}
- Changed
resolve_context_bundle1 field changed- changed
Output schema / (root)Previous value: -nullNew value: +{ + "properties": { + "content": { + "description": "Compiled topological Markdown prompt context bundle", + "items": { + "properties": { + "text": { + "description": "Token-optimized Markdown context bundle", + "type": "string" + }, + "type": { + "enum": [ + "text" + ], + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "type": "object" + }, + "type": "array" + }, + "isError": { + "description": "True if dependency resolution or file traversal failed", + "type": "boolean" + } + }, + "required": [ + "content", + "isError" + ], + "type": "object" +}
3 tool updates
v3.5.0- First observed
evaluate_spec_axioms - First observed
prune_file - First observed
resolve_context_bundle
TDQS
Scored across 3 tools
Each tool has a clearly distinct purpose: prune_file handles single-file interface extraction, resolve_context_bundle builds multi-module context, and evaluate_spec_axioms checks architectural specs. Cross-references in descriptions (e.g., 'use prune_file for isolated files') reinforce the boundaries, leaving no ambiguity.
All three tool names follow the same verb_noun snake_case convention: prune_file, resolve_context_bundle, evaluate_spec_axioms. The verbs are specific and match the action, making the pattern predictable and easy to follow.
Three tools is within the ideal 3-15 range and each earns its place. The server covers a focused workflow—file pruning, context resolution, and spec evaluation—without redundancy or bloat.
The tool surface covers the core pipeline (inspect single file, build context bundle, evaluate specs) with no obvious dead ends. Minor gaps exist like a dedicated tool for persisting or comparing context bundles, but agents can complete the core workflow without missing critical operations.
Maintenance
Related MCP Connectors
Memory that reasons: continual learning for stateful agents. Better context, fewer tokens.
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Local-first, governed memory and session continuity for AI coding agents. No cloud, no telemetry.
Shared distillation cache for AI agents — every fetch ~73-89% fewer tokens via a shared cache.
Related MCP Servers
- AlicenseAqualityCmaintenanceStructural memory for coding agents — 60% fewer tokens, refactor-safe, runs entirely on your machine.431 npm15Apache 2.0
- FlicenseNot gradedqualityAmaintenanceLocal-first code retrieval for AI agents — cuts codebase context from thousands of tokens to a few hundred, with zero hallucinated file paths.3-
- AlicenseNot gradedqualityDmaintenanceDeterministic context compression for MCP agents, reducing token usage via 11 tools for prompts, history, shell output, file deltas, and code navigation without ML or GPU.8MIT
- 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