ctxfw
CTXFW is an MCP server that prunes code context and enforces architecture brief quality for coding agents.
prune_file: Extract semantic interfaces, types, stubs, and sanitized raises from a source file at configurable depths (
full,interface,nominal) across Python, TypeScript/JavaScript, Go, and Java, with optional docstring stripping.resolve_context_bundle: Analyze a target file's dependency graph, classify dependencies by topological distance (D0 full, D1 interface, D2 nominal), and return a bundled Markdown context for efficient token usage.
evaluate_spec_axioms: Validate architectural briefs against deterministic requirements, negative invariants, and compute an Axiom Completeness Index (ACI) to approve or reject ungrounded specs.
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. Smithery MCP Registry
CTXFW is certified for automatic client configuration via the Smithery CLI:
npx -y @smithery/cli install ctxfw --client claudeOr register the stdio server manually in your .mcp.json or IDE config:
{
"mcpServers": {
"ctxfw": {
"command": "ctxfw",
"args": ["mcp"]
}
}
}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_axiomsB
Evaluate architectural brief determinism, negative invariants floor, and Axiom Completeness Index (ACI).
| Name | Required | Description | Default |
|---|---|---|---|
| brief_text | Yes | Markdown content of the architectural intake brief to evaluate |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of disclosing behavior. It only says 'Evaluate', without stating whether the tool is read-only, whether it returns a report or score, whether it modifies anything, or how the evaluation is performed. This leaves significant ambiguity about side effects and expected behavior.
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?
A single, tightly worded sentence contains no filler and front-loads the action. It efficiently communicates the tool's scope in three parallel items without unnecessary explanation.
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?
Given the lack of annotations and output schema, the description omits what the tool returns, how results are expressed, and what the caller can expect after invocation. An agent would know what the tool evaluates but not what it will get back, making the definition incomplete for a tool with no other structured context.
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 coverage for the single required parameter is 100%, so the schema already documents brief_text as Markdown content. The description adds the evaluation dimensions (determinism, negative invariants, ACI) but does not elaborate on how brief_text is used or formatted beyond what the schema states. Baseline 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 begins with a specific verb, 'Evaluate', and identifies the resource ('architectural brief') plus three concrete evaluation dimensions: determinism, negative invariants floor, and ACI. This clearly distinguishes it from sibling tools like prune_file and resolve_context_bundle, which operate on different resources with different purposes.
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?
Usage context is implied: it is used when an architectural brief needs evaluation. However, there is no explicit statement of when to prefer this tool over alternatives, no exclusions, and no guidance about prerequisites or typical invocation scenarios.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
prune_fileC
Extract semantic interfaces, types, sanitized raises, and stubs from a source file.
| 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 |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the full burden falls on the description. It says 'extract' but not whether the file is modified in place, what is returned (if anything), or how 'sanitized raises' are handled. The name 'prune_file' hints at mutation, creating ambiguity that the description fails to resolve.
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?
A single dense sentence with no filler; the action, resource, and output order is natural and front-loaded. No wasted clauses or redundant restatements of the tool name.
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?
Although the schema covers parameters, there is no output schema and no annotations, so the agent depends on the description for the tool's overall contract. The description does not say whether the tool returns a pruned representation, writes files, or how depth affects output, leaving important invocation context missing.
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?
The input schema already describes all four parameters with 100% coverage, so the baseline applies. The description adds no special parameter semantics beyond naming the outputs, which only loosely maps to what depth and strip_docs control.
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?
Description names the action (Extract) and the resource (a source file) and enumerates outputs (semantic interfaces, types, sanitized raises, stubs), so the agent knows what kind of operation it is. It does not explicitly contrast with siblings, but the resource/outputs are specific enough to avoid obvious confusion.
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?
No statement of when to call prune_file versus resolve_context_bundle or evaluate_spec_axioms, and no preconditions or exclusions are given. The only hint is the purpose sentence, which leaves the decision entirely to inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
resolve_context_bundleB
Calculate topological dependency distances (D0 full, D1 interface, D2 nominal) and return bundled Markdown context.
| 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. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the burden. It discloses that the tool calculates distances and returns Markdown context, which implies a read-only analysis operation. However, it does not disclose whether the tool modifies files, requires specific permissions, or has side effects. The description is not misleading, but it lacks depth about behavior beyond the basic operation.
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 a single sentence that is concise and front-loaded with the main action. It includes the key output type (Markdown context) and the three distance types, which are useful details. It is efficient, though it could be slightly more structured with a second sentence for usage context.
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?
Given the tool has no output schema and no annotations, the description should explain what the returned Markdown context contains and any side effects. It mentions the distance types and output format, but does not describe the structure of the bundled context or how the distances are presented. For a tool with two simple parameters, this is adequate but not complete.
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 parameters. The description adds the D0 label to target_file, which clarifies its role in the distance calculation, and project_root is implied by the schema. The description does not add significant meaning beyond the schema, so baseline 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 states a specific verb ('Calculate') and resource ('topological dependency distances'), and names the output ('bundled Markdown context'). It distinguishes itself from siblings like prune_file and evaluate_spec_axioms by focusing on dependency distance calculation and context bundling. However, it does not explicitly name a sibling or contrast itself, so it is clear but not fully differentiated.
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 implies usage: it is for calculating dependency distances and returning context, likely when an agent needs topological context for a target file. It does not state when to use this tool versus alternatives like prune_file or evaluate_spec_axioms, nor does it provide exclusions. The context is implied but not explicit.
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.0- First observed
evaluate_spec_axioms - First observed
prune_file - First observed
resolve_context_bundle
TDQS
Scored across 3 tools
Each tool occupies a distinct stage: single-file interface extraction, dependency/context resolution, and spec axiom evaluation. There is no functional overlap between them.
All three tool names follow the same verb_noun snake_case convention (prune_file, resolve_context_bundle, evaluate_spec_axioms), making the action and target of each call predictable.
Three tools is small but well-scoped for this specialized analysis server. Each tool earns its place as a necessary stage in a single coherent workflow.
The extract, resolve, evaluate pipeline covers the server's apparent read-only analysis purpose without dead ends. Minor gaps exist around batch/multi-file processing and enumeration/management of source inputs, but these are generally workable.
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.
Shared distillation cache for AI agents — every fetch ~73-89% fewer tokens via a shared cache.
Context engineering for AI coding agents: product context, project missions, and 360 memory.
Related MCP Servers
- AlicenseAqualityCmaintenanceStructural memory for coding agents — 60% fewer tokens, refactor-safe, runs entirely on your machine.426 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.7MIT
- 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