Skip to main content
Glama

İktisad (iktisad)

Deterministic token defense engine & native MCP server for AI coding agents.
Compresses terminal test logs by 80–99% and extracts Python AST code skeletons (-93.1% context reduction) to prevent context bloat, rate-limit cascades, and runaway token bills.

Python 3.10+ License: MIT Zero Dependencies Model Context Protocol GitHub Action PyPI version Polar Pro ($10/mo) Inquiries


📊 Benchmarks (reproducible)

Measured with python benchmarks/run_benchmark.py (Python 3.12.3, pytest 9.0.2, Linux). Inputs are generated by the script; full output of 3 runs is in benchmarks/RESULTS.md.

Scenario

Raw chars (est. tokens)

iktisad chars (est. tokens)

Reduction

Time

pytest -v: 20 failing + 80 passing tests

21,842 (5,460)

1,194 (298)

-94.5%

1.59 ms

pytest -v: 99 passing tests

8,256 (2,064)

22 (6)

-99.7%

0.19 ms

AST recon: iktisad/*.py (5 files, 3,637 LOC)

130,567 (32,642)

8,977 (2,244)

-93.1%

17.52 ms

est. tokens = chars / 4 (no tokenizer; real counts differ). Time = median of 50 runs of the compression/skeleton call only. For failing runs, compression strips PASSED progress noise and prioritizes === FAILURES ===, assertion diffs (E ...), and file:line traceback markers alongside the trailing FAILED summary within the max_chars=1200 default budget (truncating only excess middle failure blocks when >1,200 chars). AST skeletons are computed locally with zero LLM calls, but the skeleton text itself still costs tokens when sent to a model.


Related MCP server: knitbrain

⚡ Quickstart

1. Pipe Terminal Logs Directly into LLMs

pip install iktisad

# Single-line pipe: compress test failures and pipe directly to an LLM
pytest | iktisad compress | llm

# Or wrap any command directly (preserves exit code, prints compressed summary):
iktisad run -- pytest tests/ -v

2. GitHub Marketplace Action

Drop iktisad directly into any GitHub Actions CI workflow to compress failing logs and protect agent tokens:

- name: Run Pytest with iktisad Token Defense
  uses: shiny-apricot/iktisad@v0.3.0
  with:
    run: pytest tests/ -v

3. Native Model Context Protocol (MCP) Server

Launch as an stdio MCP server for Cursor, Claude Code, Windsurf, or Claude Desktop:

iktisad --mcp
# or via dedicated binary
iktisad-mcp

Claude Desktop Configuration (claude_desktop_config.json):

{
  "mcpServers": {
    "iktisad": {
      "command": "iktisad-mcp"
    }
  }
}

Registered with Smithery.ai & Glama.ai via smithery.json.


🛠️ Core Engines

  • 🛡️ Deterministic CLI Output Firewall: Compresses noisy pytest and compiler outputs by 80–97%, isolating failure tracebacks and collapsing passing runs to a single OK status line.

  • 🗺️ AST Code Skeletonizer: Extracts function/class signatures, line ranges, and docstrings from Python source files with -93.1% context reduction (computed locally with zero LLM calls using Python's native ast parser).

  • 🚪 Dynamic Model Routing & Sandwich Protocol: Evaluates task reversibility (Type-1 irreversible vs. Type-2 reversible). Routes mechanical tasks to sub-cent fast models, reserving frontier reasoning models for high-stakes decisions under a <600-token brief.

  • ⚡ Rate Limit Armor & Circuit Breaker: Tracks local token velocity in SQLite and halts runaway loops before exhausting API budgets or hitting HTTP 429 rate limits.

  • 🔌 Native Model Context Protocol (MCP): JSON-RPC stdio server exposing compress_terminal_log, extract_ast_skeleton, select_frugal_model, check_circuit_breaker, and run_release_preflight_audit.

  • 🔐 GitHub App CI Guard (iktisad.github_app): Local fail-closed HMAC-SHA256 webhook verification, marketplace_purchase entitlement parsing, AST-skeleton PR preflight audit & Check Run payload builder, and stdlib webhook server + manifest generator (local module; not yet published on GitHub Marketplace).


🔌 Exposed MCP Tools

Tool

Parameters

Description

compress_terminal_log

raw_log (str), max_chars (int)

Compresses terminal output by 80–99%, isolating critical traceback frames

extract_ast_skeleton

file_path (str) or code (str)

Extracts AST outlines, line ranges, and signatures (-93.1% context reduction, computed locally)

select_frugal_model

task_kind, heaviness, importance

Recommends optimal model tier via reversible vs. irreversible routing

check_circuit_breaker

daily_budget (int), db_path (str)

Checks daily token velocity and halts loops if spending threshold is breached

run_release_preflight_audit

base_dir (str)

Verifies package version alignment, Polar.sh checkout links, and release readiness


🚀 CLI Usage

# 1. Pipe terminal logs
pytest | iktisad compress | llm

# 2. Run command under context firewall (preserves exit code)
iktisad run -- pytest tests/ -v

# 3. Compress existing log file
iktisad compress pytest_output.log

# 4. Extract Python AST skeleton (-93.0% context reduction, zero LLM calls)
iktisad --ast-skeleton src/billing_service.py

# 5. Route task dynamically
iktisad --route-task refactor_db --heaviness 8.0 --importance 9.0 --irreversible

# 6. Launch local reverse-proxy gateway
iktisad --serve-gateway --port 8000 --daily-token-budget 1000000

# 7. Print GitHub App CI Guard manifest JSON or run local webhook server
iktisad github-app --manifest
iktisad github-app --serve --host 127.0.0.1 --port 8080

🐍 Python API

from iktisad import (
    compress_cli_observation,
    extract_python_ast_skeleton,
    select_model_dynamically,
    get_gateway_daily_stats,
)

# 1. Compress terminal outputs before sending to LLM context
obs = compress_cli_observation(raw_terminal_stream)
if obs.has_error:
    agent.send(obs.pruned_text)
else:
    agent.send(f"Tests passed ({obs.savings_pct:.1f}% tokens saved)")

# 2. Extract AST skeleton for fast agent codebase reconnaissance
skeleton = extract_python_ast_skeleton("src/engine.py")
print(skeleton.render_compact())

# 3. Dynamic model routing
decision = select_model_dynamically(
    task_kind="fix_security_flaw",
    heaviness=8.0,
    importance=9.0,
    is_irreversible=True,
)
print(f"Tier {decision.tier}: {decision.model_name}")

# 4. Local Token Circuit Breaker
stats = get_gateway_daily_stats(db_path=".cache/iktisad_gateway.db", daily_budget=1_000_000)
if stats.circuit_breaker_tripped:
    raise RuntimeError("Daily token budget reached! Halting agent loop.")

💰 Licensing & Polar Pro ($10/mo)

Tier

Pricing

Licensing & Capabilities

Delivery

OSS Core (MIT)

$0 (100% Free)

MIT License. Core CLI, Python AST Skeletonizer & stdio MCP server (GitHub & Glama MCP Grade A).

pip install iktisad

Polar Pro

Polar Pro ($10/mo)

Commercial team presets (iktisad --export-presets), automated Polar license key fulfillment, and priority support (<24h SLA).

Instant Polar License Key


📜 License

MIT License. Open-source software developed by Kenz Technologies.

Available Tools

5 tools
check_circuit_breakerA

Inspect daily token consumption, remaining budget, and circuit breaker status from the local SQLite ledger to prevent runaway agent loops and $50/day bill spikes.

Inputs: db_path, daily_budget.

compress_terminal_logA

Compress noisy terminal, pytest, or compiler stdout/stderr by 80-97%. Strips ANSI codes, progress bars, and passing tests while strictly isolating root-cause tracebacks and assertion errors to stop thinking token bloat.

Inputs: raw_log (required), max_chars.

extract_ast_skeletonA

Extract class and function signatures, line ranges, and docstrings from Python source code at 0 LLM tokens. Allows agents to locate target functions without reading entire files.

Inputs: code, file_path.

run_release_preflight_auditB

Audits repository and package artifacts for version alignment, Polar.sh link integrity, canonical pricing ($10/mo), and interactive visualizer math concordances before deployment or release.

Inputs: base_dir.

select_frugal_modelB

Dynamically routes tasks based on Bezos Type-1 (irreversible) vs Type-2 (reversible) doors. Recommends frugal sub-cent models (Gemini 3.8 Flash, local models) for mechanical tasks, or the 2026 Sandwich Protocol (prep <600 tokens -> Claude Opus 5.5 / Claude Fable / o3 / DeepSeek-R1 -> Flash exec) for irreversible architectural decisions.

Inputs: task_kind (required), heaviness, importance, is_irreversible.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 5 tools

    Disambiguation4/5

    Each tool targets a fairly distinct object: terminal output (compress_terminal_log), Python source (extract_ast_skeleton), model selection policy (select_frugal_model), budget ledger (check_circuit_breaker), and release artifacts (run_release_preflight_audit). The two cost-related tools (select_frugal_model vs check_circuit_breaker) sit in the same domain and could be momentarily confused, but one advises and the other reports, so descriptions resolve it.

    Naming Consistency5/5

    All five names use the same snake_case verb_noun pattern (compress_*, extract_*, select_*, check_*, run_*). Verbs are meaningful and predict the action; no style mixing.

    Tool Count5/5

    Five tools is well within the well-scoped range and each addresses a concrete, non-trivial operation. Nothing feels padded or trivially thin for a token-economy/dev-hygiene helper.

    Completeness3/5

    The token-economy side is strong (compression, AST extraction, routing advice, budget inspection), but the circuit breaker is read-only — no reset, threshold configuration, or ledger mutation — and select_frugal_model yields a recommendation with no tool to act on it. run_release_preflight_audit is a single read-only check with no companion tools for remediation, and there is no general file/trace compression beyond terminal logs.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      A local-first MCP server that gives AI coding agents persistent memory and controlled commands. Features a git-backed markdown knowledge vault with FTS5 search, surgical section edits, token-aware context budgeting, and a sandboxed command engine with human approval gates. Works with Claude Code, Cursor, Copilot, Gemini, and more.
      62
      1
      Apache 2.0
    • A
      license
      A
      quality
      C
      maintenance
      Local-first MCP server that gives any AI coding agent per-project memory, workflow intelligence, and always-on, lossless token & context optimization.
      37
      31 npm
      6
      MIT
    • -
      license
      Not graded
      quality
      Not graded
      maintenance
      AST-aware code exploration MCP server for AI agents, optimized for token efficiency.
      -
    • A
      license
      A
      quality
      C
      maintenance
      Provides reversible context compression for AI agents, reducing token usage while preserving the ability to retrieve original content, and serves as an MCP server for integration with tools like GitHub Copilot and Claude Code.
      3
      1
      Apache 2.0