Skip to main content
Glama
README.md
# AgentCostGuard (`agent-cost-guard`)

[![CI](https://github.com/rwachtendorff/agent-cost-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/rwachtendorff/agent-cost-guard/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![agent-cost-guard on otra.city](https://otra.city/badge/agent-cost-guard.svg)](https://otra.city/s/agent-cost-guard)

**Zero-dependency Python circuit breaker for autonomous AI agents & MCP tool loops.**

Stops runaway token bills, infinite `tool_call` loops, ping-pong oscillations (`A -> B -> A -> B`), and common prompt-injection/secret-exfiltration patterns before they drain your API budget.

- **Install:** `pip install git+https://github.com/rwachtendorff/agent-cost-guard.git`
- **1-Click Claude Desktop Extension (`.mcpb`):** https://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.2.0/agent-cost-guard-mcp-0.2.0.mcpb
- **Live Project Page & Interactive Simulator:** https://htmlpreview.github.io/?https://github.com/rwachtendorff/agent-cost-guard/blob/main/docs/index.html
- **Live HTML Audit Demo:** https://htmlpreview.github.io/?https://github.com/rwachtendorff/agent-cost-guard/blob/main/docs/demo-report.html
- **Pro Production Policy & MCP Pack ($7 USD):** https://www.paypal.com/paypalme/rwachtendorff/7USD

## Why this exists
Most agent frameworks make it easy to start a tool loop, and surprisingly easy to wake up to a $40–$200 surprise bill because an agent retried the same failing call 35 times.

`agent-cost-guard` runs purely on Python 3.9+ standard library (zero external dependencies, zero telemetry, 100% local) and gives you:

- **Hard USD & Token Caps (`BudgetExceededError`)** across Gemini, OpenAI, Anthropic, or custom/local models.
- **Tool Loop & Oscillation Detection (`LoopDetectedError`)** using canonical SHA-256 argument hashing + sliding-window ping-pong detection.
- **MCP STDIO Circuit-Breaker Proxy (`agent-cost-guard mcp-proxy`)** to wrap any Claude Desktop, Cursor, Windsurf, or Hermes stdio MCP server without changing server code.
- **Native MCP Server (`agent-cost-guard mcp-server`)** exposing `estimate_llm_cost`, `scan_prompt_injection`, `audit_mcp_config`, and `summarize_jsonl_trace` over JSON-RPC 2.0 stdio.
- **Auto-Discovery Audit & Wrapper (`audit` / `wrap-config --discover`)** to scan and protect existing Claude, Cursor, Windsurf, and VS Code MCP configs.
- **Tool & Untrusted-Text Guardrails (`PolicyViolationError`)** to block forbidden tools or prompt-injection attempts inside scraped content.
- **Structured JSONL Trace + Standalone HTML Audit Report** (`agent-cost-guard report trace.jsonl`).

## Measured Benchmark (`examples/benchmark_loop.py`)

| Scenario | Model | Unprotected Cost | Guarded Cost | Blocked At | Cost Reduction |
|---|---|---:|---:|---:|---:|
| Identical retry loop (40 steps) | `claude-3.7-sonnet` | $3.9240 (1,240,800 tok) | $0.0945 (26,460 tok) | Step 4 (`LoopDetectedError`) | **97.59%** |
| Ping-pong oscillation `A <-> B` (30 steps) | `gpt-4o` | $1.5353 (579,900 tok) | $0.1153 (40,400 tok) | Step 6 (`LoopDetectedError`) | **92.49%** |

Measured overhead across 1,000 turns: **~9.9 µs per turn**.

## Quick Start

```python
from agent_cost_guard import GuardConfig, GuardError, SessionGuard

guard = SessionGuard(
    session_id="research-run-01",
    config=GuardConfig(
        max_cost_usd=0.50,
        max_total_tokens=120_000,
        max_steps=25,
        repeat_tool_threshold=3,
        oscillation_window=6,
        blocked_tools=("drop_database",),
        jsonl_log_path="traces/agent_run.jsonl",
    ),
)

try:
    for step in guard.guard_loop():
        # Call your LLM + tool here, then record the turn:
        guard.record_turn(
            model="gemini-2.5-flash",
            input_tokens=1400,
            output_tokens=320,
            tool_name="web_fetch",
            tool_args={"url": "https://example.com"},
            untrusted_text="clean page output",
        )
        break
except GuardError as exc:
    print("Circuit breaker triggered:", exc)

print(guard.summary())
```

### Zero-Dep SDK Response Adapter (OpenAI / Anthropic / Gemini)
Pass raw SDK response objects or API JSON dicts directly to `record_llm_response()`—no extra dependencies required:

```python
# Works out of the box with OpenAI, Anthropic, or Google Gemini SDK responses:
guard.record_llm_response(
    response,
    model="gemini-2.5-flash",  # optional if response.model is present
    tool_name="web_fetch",
    tool_args={"url": "https://example.com"},
)
```

## CLI Demo, MCP STDIO Proxy, Benchmark & HTML Report

```bash
# Wrap ANY stdio MCP server (Claude Desktop, Cursor, Windsurf, Hermes):
agent-cost-guard mcp-proxy --repeat-limit 3 --blocked-tools drop_table --log mcp.jsonl -- npx -y @modelcontextprotocol/server-filesystem .

# Run AgentCostGuard's own native MCP stdio server (4 diagnostic & FinOps tools):
agent-cost-guard mcp-server

# Discover & audit existing Claude / Cursor / Windsurf / VS Code MCP configs:
agent-cost-guard audit
agent-cost-guard wrap-config --discover --repeat-limit 3 --log-dir ./mcp_traces

python3 examples/benchmark_loop.py
python3 examples/mcp_and_llm_quickstart.py
python3 -m agent_cost_guard.cli demo --log demo_trace.jsonl --html demo_report.html
python3 -m agent_cost_guard.cli report demo_trace.jsonl --out audit.html
```

Drop-in `claude_desktop_config.json` / Cursor `mcp.json` snippet:

```json
{
  "mcpServers": {
    "filesystem-guarded": {
      "command": "agent-cost-guard",
      "args": ["mcp-proxy", "--repeat-limit", "3", "--log", "mcp_trace.jsonl", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "."]
    }
  }
}
```

## Running Tests

```bash
python3 -m unittest discover -s tests -v
```

## Pro Production Policy & MCP Pack ($7 USD)

The core library above is MIT-licensed and free forever. If you want production-ready presets and plug-and-play integration assets:

- **Pre-tuned JSON policy profiles** (`Gemini 2.5`, `GPT-4o/4.1`, `Claude 3.7/4`, local Ollama)
- **Drop-in MCP tool-wrapper middleware** (`mcp_wrapper_middleware.py`) with automatic turn accounting
- **Extended 15-vector prompt-injection & secret-exfiltration test suite**
- **FinOps Threshold Playbook** + direct email integration support

**Get it here ($7 USD via PayPal):** https://www.paypal.com/paypalme/rwachtendorff/7USD  
*(Include your email in the PayPal note — or send your transaction ID to `rolando@wachtendorff.cl` — to receive the Pro Pack archive.)*