Skip to main content
Glama
README.md
# Δ°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+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)]()
[![Model Context Protocol](https://img.shields.io/badge/MCP-Native%20Server-purple.svg)](https://modelcontextprotocol.io/)
[![GitHub Action](https://img.shields.io/badge/GitHub%20Action-iktisad--action-blue.svg)](https://github.com/shiny-apricot/iktisad)
[![PyPI version](https://img.shields.io/pypi/v/iktisad.svg)](https://pypi.org/project/iktisad/)
[![Polar Pro ($10/mo)](https://img.shields.io/badge/Polar%20Pro-%2410%2Fmo-purple.svg)](https://buy.polar.sh/polar_cl_yzz3PkDzy0RGI5tD7PCly2oMkieyP5jUPKrF11bpqcA)
[![Inquiries](https://img.shields.io/badge/Inquiries-kenzailab%40gmail.com-blue.svg)](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

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