iktisad
# Δ°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.*
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
[]()
[](https://modelcontextprotocol.io/)
[](https://github.com/shiny-apricot/iktisad)
[](https://pypi.org/project/iktisad/)
[](https://buy.polar.sh/polar_cl_yzz3PkDzy0RGI5tD7PCly2oMkieyP5jUPKrF11bpqcA)
[](mailto:kenzailab@gmail.com)
---
## π 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`](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.*
---
## β‘ Quickstart
### 1. Pipe Terminal Logs Directly into LLMs
```bash
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:
```yaml
- 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:
```bash
iktisad --mcp
# or via dedicated binary
iktisad-mcp
```
**Claude Desktop Configuration (`claude_desktop_config.json`)**:
```json
{
"mcpServers": {
"iktisad": {
"command": "iktisad-mcp"
}
}
}
```
Registered with [Smithery.ai](https://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
```bash
# 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
```python
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)](https://buy.polar.sh/polar_cl_yzz3PkDzy0RGI5tD7PCly2oMkieyP5jUPKrF11bpqcA)** | Commercial team presets (`iktisad --export-presets`), automated Polar license key fulfillment, and priority support (<24h SLA). | Instant Polar License Key |
- **Official Polar Pro Checkout**: [Subscribe on Polar Pro ($10/mo)](https://buy.polar.sh/polar_cl_yzz3PkDzy0RGI5tD7PCly2oMkieyP5jUPKrF11bpqcA)
- **Commercial Team Presets & Direct Support**: `kenzailab@gmail.com`
- **Source Repository**: [https://github.com/shiny-apricot/iktisad](https://github.com/shiny-apricot/iktisad)
---
## π License
MIT License. Open-source software developed by **Kenz Technologies**.
TDQS
Scored across 5 tools
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.
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.
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.
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.