v0.1.1 ON PYPI • ZERO DEPENDENCIES • NATIVE MCP SERVER

The Autonomous Context Firewall
for AI Coding Agents

Stop Cursor, Claude Code, and Windsurf from choking on 40,000-token terminal cascades, giant monorepos, and runaway retry loops.

$ pip install iktisad
$ iktisad --mcp
Zero-Waste Architecture

The 4 Pillars of Autonomous Context Defense

Autonomous coding agents don't just fail on bad prompts—they fail because raw terminal noise, bloated codebases, runaway retry loops, and unrouted frontier models incinerate token budgets.

🧹

1. CLI & Terminal Noise Compactor

Compress pytest, vitest, cargo, docker, and build outputs deterministically. Strips passing dots, worker heartbeats, and internal framework frames while preserving the exact failing assertion and root cause.

⚡ 85% – 98% terminal token reduction
🗺️

2. AST Codebase Skeletonizer

Compress 10,000-line monorepos into semantic structural signatures, classes, and method boundaries in pure Python AST. Provides complete architectural visibility without ingesting private implementation code.

⚡ 90% codebase context preserved
🛑

3. Runaway Loop Circuit Breaker

Tracks retry velocity and repetitive error patterns. Automatically detects when an agent is trapped in an infinite retry loop and trips the circuit breaker before $50+ is wasted on repetitive hallucinated fixes.

⚡ Hard token & financial budget ceiling
🥪

4. Frugal Model Router

Enforces the Bezos Sandwich Protocol: routes heavy terminal and repo ingestion to Gemini 3.8 Flash for brief distillation, and triggers 1-shot Claude Opus 5.5 / o3 only for strategic execution.

⚡ 10x – 50x token ROI leverage
Interactive Context Firewall

Before vs. After Token Bleed Visualizer

Reasoning models generate internal chain-of-thought (CoT) over every token you feed them. Feeding thousands of tokens of noisy terminal stdout inflates reasoning latency, distorts attention, and multiplies costs.

🔴 Raw Terminal Output Tokens: ~1,820 tokens (~$0.027 per loop)
============================= test session starts ============================== platform linux -- Python 3.13.2, pytest-9.2.0, pluggy-1.7.0 -- /home/agent/.venv/bin/python cachedir: .pytest_cache rootdir: /home/agent/workspace/enterprise-core configfile: pyproject.toml plugins: anyio-4.4.0, asyncio-0.24.0, cov-5.0.0, mock-3.14.0, xdist-3.6.1 created: 4/4 workers [gw0] linux -- [gw1] linux -- [gw2] linux -- [gw3] linux scheduling tests via LoadScheduling tests/unit/test_config.py::test_env_parser_valid [gw0] PASSED [ 2%] tests/unit/test_config.py::test_env_override [gw0] PASSED [ 4%] tests/unit/test_crypto.py::test_argon2_hashing [gw1] PASSED [ 6%] tests/unit/test_crypto.py::test_jwt_ed25519_sign [gw1] PASSED [ 8%] tests/unit/test_telemetry.py::test_otlp_batcher [gw2] PASSED [ 10%] tests/unit/test_telemetry.py::test_span_propagation [gw2] PASSED [ 12%] tests/unit/test_cache.py::test_redis_cluster_failover [gw3] PASSED [ 14%] tests/unit/test_cache.py::test_lru_eviction_policy [gw3] PASSED [ 16%] tests/unit/test_rate_limiter.py::test_token_bucket_burst [gw0] PASSED [ 18%] tests/unit/test_rate_limiter.py::test_sliding_window_counter [gw0] PASSED [ 20%] tests/unit/test_storage.py::test_s3_multipart_upload [gw1] PASSED [ 22%] tests/unit/test_storage.py::test_s3_presigned_url [gw1] PASSED [ 24%] tests/unit/test_queue.py::test_sqs_fifo_ordering [gw2] PASSED [ 26%] tests/unit/test_queue.py::test_dead_letter_replay [gw2] PASSED [ 28%] tests/unit/test_audit.py::test_immutable_ledger_hash [gw3] PASSED [ 30%] tests/unit/test_audit.py::test_tamper_evident_signature [gw3] PASSED [ 32%] tests/unit/test_session.py::test_cookie_same_site_strict [gw0] PASSED [ 34%] tests/unit/test_session.py::test_session_invalidation [gw0] PASSED [ 36%] tests/unit/test_database.py::test_connection_pool_saturation [gw1] PASSED [ 38%] tests/unit/test_database.py::test_read_replica_routing [gw1] PASSED [ 40%] tests/unit/test_health.py::test_readiness_probe [gw2] PASSED [ 42%] tests/unit/test_health.py::test_liveness_circuit_breaker [gw2] PASSED [ 44%] tests/unit/test_rbac.py::test_role_hierarchy_admin [gw3] PASSED [ 46%] tests/unit/test_rbac.py::test_permission_deny_default [gw3] PASSED [ 48%] tests/unit/test_events.py::test_kafka_schema_registry [gw0] PASSED [ 50%] tests/unit/test_events.py::test_idempotent_consumer [gw0] PASSED [ 52%] tests/unit/test_webhook.py::test_hmac_sha256_verification [gw1] PASSED [ 54%] tests/unit/test_webhook.py::test_exponential_backoff [gw1] PASSED [ 56%] tests/unit/test_metrics.py::test_prometheus_counter_increment [gw2] PASSED [ 58%] tests/unit/test_metrics.py::test_histogram_quantiles [gw2] PASSED [ 60%] tests/unit/test_tokens.py::test_refresh_token_rotation [gw3] PASSED [ 62%] tests/unit/test_tokens.py::test_blacklisted_jti [gw3] PASSED [ 64%] tests/unit/test_parser.py::test_ast_statement_extraction [gw0] PASSED [ 66%] tests/unit/test_parser.py::test_cst_comment_preservation [gw0] PASSED [ 68%] tests/unit/test_workers.py::test_celery_task_concurrency [gw1] PASSED [ 70%] tests/unit/test_workers.py::test_priority_queue_drain [gw1] PASSED [ 72%] tests/unit/test_pricing.py::test_seat_based_proration [gw2] PASSED [ 74%] tests/unit/test_pricing.py::test_usage_tier_calculation [gw2] PASSED [ 76%] tests/unit/test_email.py::test_dkim_header_signing [gw3] PASSED [ 78%] tests/unit/test_email.py::test_template_injection_escaping [gw3] PASSED [ 80%] tests/unit/test_authz.py::test_jwt_claims_tenant_isolation [gw0] PASSED [ 82%] tests/unit/test_authz.py::test_impersonation_audit_trail [gw0] PASSED [ 84%] tests/unit/test_logging.py::test_json_structured_formatter [gw1] PASSED [ 86%] tests/unit/test_logging.py::test_pii_masking_filter [gw1] PASSED [ 88%] tests/unit/test_graphql.py::test_depth_limit_protection [gw2] PASSED [ 90%] tests/unit/test_graphql.py::test_dataloader_batching [gw2] PASSED [ 92%] tests/unit/test_crypto_vault.py::test_kms_envelope_encryption [gw3] PASSED [ 94%] tests/unit/test_crypto_vault.py::test_zero_knowledge_proof [gw3] PASSED [ 96%] tests/billing/test_subscription_gate.py::test_active_customer_access [gw0] FAILED [ 98%] tests/billing/test_subscription_gate.py::test_enterprise_seat_cap [gw1] PASSED [100%] ==================================== WARNINGS =================================== /home/agent/.venv/lib/python3.13/site-packages/pydantic/_internal/_fields.py:201: PydanticDeprecatedSince20: Using extra keyword arguments on Field is deprecated. /home/agent/.venv/lib/python3.13/site-packages/urllib3/connectionpool.py:1099: InsecureRequestWarning: Unverified HTTPS request to host 'internal-vault'. /home/agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py:1942: SAWarning: Object already exists in session; this will be an error in 2.1. /home/agent/.venv/lib/python3.13/site-packages/pytest_asyncio/plugin.py:734: PytestDeprecationWarning: @pytest.fixture is being applied to an async function. [... 28 additional framework deprecation warnings suppressed by python runtime ...] =================================== FAILURES ==================================== _______________________ test_active_customer_access ____________________________ [gw0] linux -- Python 3.13.2 /home/agent/.venv/bin/python self = <tests.billing.test_subscription_gate.TestSubscriptionGate object at 0x7f9a2d3e1100> client = <starlette.testclient.TestClient object at 0x7f9a2d3e1450> db_session = <sqlalchemy.orm.session.Session object at 0x7f9a2d3e1890> mock_stripe = <unittest.mock.MagicMock object at 0x7f9a2d3e1dd0> @pytest.mark.asyncio async def test_active_customer_access(self, client, db_session, mock_stripe): user = await create_test_tenant(db_session, plan="pro", status="trial_expired") entitlement_svc = EntitlementService(db=db_session, stripe=mock_stripe) > entitlement = await entitlement_svc.check_entitlement(user.id, feature="mcp_unlimited") tests/billing/test_subscription_gate.py:84: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ src/billing/service.py:142: in check_entitlement return self._evaluate_status(user, feature) src/billing/service.py:189: in _evaluate_status assert user.subscription.is_active is True _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ user = <User id='usr_99x8' email='dev@customer.io' tier='pro' grace_period=0> feature = 'mcp_unlimited' > assert user.subscription.is_active is True E AssertionError: assert False is True E + where False = <Subscription id='sub_092a' status='trial_expired' is_active=False>.is_active src/billing/service.py:189: AssertionError ----------------------------- Captured stdout call ----------------------------- 2026-11-10T19:42:01.104Z [DEBUG] (billing.service): Resolving tenant entitlement for usr_99x8 2026-11-10T19:42:01.108Z [DEBUG] (db.pool): Checkout connection <Connection 0x7f9a2d120a> (pool size=10, checked_out=3) 2026-11-10T19:42:01.112Z [DEBUG] (sql.echo): SELECT users.id, subscriptions.status FROM users LEFT JOIN subscriptions ON users.id = subscriptions.user_id WHERE users.id = 'usr_99x8' 2026-11-10T19:42:01.115Z [DEBUG] (billing.cache): Redis cache miss on key 'entitlement:usr_99x8:mcp_unlimited' 2026-11-10T19:42:01.119Z [WARN] (billing.service): Tenant usr_99x8 has status 'trial_expired' with grace_period=0 ----------------------------- Captured stderr call ----------------------------- [urllib3.connectionpool] Resetting dropped connection: internal-vault [opentelemetry.trace] Non-recording span created for parent_id=None =========================== short test summary info ============================ FAILED tests/billing/test_subscription_gate.py::test_active_customer_access - AssertionError: assert False is True ================== 1 failed, 48 passed, 32 warnings in 14.82s ===================
🟢 İktisad Filtered Context Tokens: ~110 tokens (~$0.001 per loop) — 94.0% Reduction
# [iktisad firewall] Distilled ~1,820 tokens -> ~110 tokens (-94.0% Context Reduction) # Cost per loop: ~$0.001 (saved ~$0.026 per agentic retry iteration) SUMMARY: 1 failed, 48 passed, 32 warnings in 14.82s SUPPRESSED: 48 passed tests, 32 deprecation warnings, 12 internal db/pool debug traces FAIL: tests/billing/test_subscription_gate.py::test_active_customer_access File "src/billing/service.py", line 189, in _evaluate_status assert user.subscription.is_active is True AssertionError: assert False is True + where False = <Subscription id='sub_092a' status='trial_expired' is_active=False>.is_active # Isolated Root Cause & Actionable Context: • Target: src/billing/service.py:189 in _evaluate_status() • Cause: user.subscription status is 'trial_expired' with grace_period=0, causing is_active=False. • Clean Fix: Handle 'trial_expired' in entitlement fallback logic or verify mock fixture setup. • Preserved: Zero CoT reasoning token bloat, zero passing test distraction.
~1,820
Raw Tokens Ingested
~110
İktisad Output Tokens
94.0%
Context Reduction
~$0.026
Saved Per Loop
ℹ️ In large CI suites (500+ tests / 35,000+ raw tokens), iktisad achieves the same 90-95% compression, shrinking 35k-token context blowouts to <600 tokens.
Architectural Pattern

The Bezos Sandwich Protocol (2026 Edition)

Type-1 decisions (one-way doors) require deep strategic reasoning. Type-2 decisions (two-way doors) are reversible. Never burn frontier reasoning tokens on mechanical compilation or log scrolling.

Stage 1: Frugal Ingestion

Gemini 3.8 Flash

Extracts 0-token AST code skeletons, compresses noisy terminal logs, and constructs a dense <600-token brief.

➔
Stage 2: 1-Shot Frontier Reasoner

Claude Opus 5.5 / o3 / Fable

Frontier reasoning model ingests ONLY the distilled brief. Solves the core algorithmic failure in a single zero-shot decision without thinking token bloat.

➔
Stage 3: Mechanical Execution

Gemini 3.8 Flash / Local AST

Applies exact code diff, runs local pytest verification through the iktisad firewall, and stages clean commit. Total cost: $0.01 instead of $1.50.

Architecture Input Context Size Frontier CoT Thinking Tokens Cost per Bug Fix Loop Risk
Naive Agentic Loop (Raw Terminal Dumps) 40k – 90k tokens 8,000 – 16,000 tokens $1.20 – $2.80 High (HTTP 429 cascades)
İktisad Sandwich Protocol (Frugal Gateway) < 600 tokens < 800 tokens $0.02 – $0.05 Zero (Circuit breaker protected)
Zero-Configuration Integration

Native Model Context Protocol (MCP) Server

Equip Cursor, Claude Code, and Windsurf with native token defense tools using the official Model Context Protocol.

// In Cursor Settings -> MCP Servers: { "name": "iktisad", "type": "stdio", "command": "iktisad", "args": ["--mcp"] }
Exposed MCP Tool Functionality Token Savings
compress_terminal_log Compresses pytest, compiler, and shell logs, isolating only failed assertions and tracebacks 80% – 97%
extract_ast_skeleton Extracts class/function signatures, docstrings, and line bounds with 0 LLM tokens 100% (0 tokens)
select_frugal_model Evaluates task heaviness/irreversibility and routes between Flash & Frontier reasoners 50% – 90%
check_circuit_breaker Enforces hourly/daily token quotas, automatically killing runaway agent retry loops Protects Budgets
Rate Limit Armor & Reverse Proxy

iktisad Frugal Gateway

A drop-in reverse proxy that intercepts outbound LLM API requests, silently strips terminal noise, enforces local SQLite token velocity, and protects against HTTP 429 cascades.

🛡️

Reverse Proxy Interceptor

Point your agents to http://localhost:8000/v1. Compatible with OpenAI, Anthropic, and Gemini wire protocols. Automatically strips raw test logs before forwarding upstream.

$ iktisad --serve-gateway --port 8000
⚡

Runaway Loop Circuit Breaker

If an autonomous agent is caught in an infinite error-fix loop consuming tokens without moving the needle, iktisad trips the breaker and stops the bleed before your card gets billed.

$ iktisad --circuit-status
🗺️

Zero-Token AST Skeletonizer

Extract class definitions, method signatures, and line boundaries in pure Python AST. Read 2,000-line repositories in 30 lines without ingesting entire files into LLM context.

$ iktisad --ast-skeleton my_file.py

Ready to Deploy Autonomous Frugality?

Open-source under MIT. Upgrade to the Polar Pro Tier ($10/mo) for enterprise commercial clearance and dedicated developer support:

⚖️
Commercial Team Usage License

Legal clearance for proprietary enterprise codebases and professional client workflows.

⚡
Direct Priority Developer Support

Direct priority support via kenzailabs@gmail.com with <24h turnaround time.

🛠️
Custom Gateway Proxy Presets

Local JSON configurations and optimized prompt filters for Cursor, Claude Code, and Windsurf.

🎯
Priority GitHub Issue & Feature Queue

Fast-tracked triage, bug resolution, and prioritized community feature requests.

Subscribe on Polar Pro ($10/mo)