Skip to main content

AgentCostGuard (agent-cost-guard)

CI PyPI License: MIT agent-cost-guard on otra.city Listed on chen.media/mcp

Find us on the Chen Media MCP Directory

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.

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 5 tools (estimate_llm_cost, scan_prompt_injection, audit_mcp_config, summarize_jsonl_trace, audit_claude_sessions), 2 MCP resources (pricing/models, docs/quick-reference), and 2 guided prompts (audit-ai-spend, harden-mcp-workspace) over JSON-RPC 2.0 stdio (plus ready-to-build Dockerfile).
  • 1-Second Health Check (agent-cost-guard doctor) to verify unprotected MCP configs, active Claude Code hooks, and historical loop savings in one pass.
  • Retrospective Claude Code Session Audit (agent-cost-guard scan-sessions) to scan ~/.claude/projects/*/*.jsonl, quantify real spend by model/tool, catch historical retry/ping-pong loops, and compute potential USD savings.
  • Claude Code Plugin & PreToolUse/PostToolUse Hooks (claude-hook / install-hooks): Stop infinite Bash/Edit/WebFetch retry loops, enforce live --max-usd session budgets directly from Claude Code transcripts, and block prompt-injected outputs in real time.
  • 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

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:

# 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

# 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 (5 diagnostic & FinOps tools):
agent-cost-guard mcp-server

# Audit past Claude Code sessions (~/.claude/projects) for runaway loops & savings:
agent-cost-guard doctor
agent-cost-guard scan-sessions --html claude_audit.html

# Quick CLI cost estimate or list all 32 built-in 2026 model rates:
agent-cost-guard estimate gpt-5 --input-tokens 50000 --output-tokens 5000
agent-cost-guard estimate --list-models

# Auto-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

# Protect Claude Code built-in tools via PreToolUse & PostToolUse hooks (with optional live $2.50 cap):
agent-cost-guard install-hooks .claude/settings.json --max-usd 2.50 --write --backup

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:

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

Running Tests

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:

  • 5 pre-tuned JSON policy profiles (Gemini 2.5, GPT-4o/4.1, Claude 3.7/4, claude_code_strict, local Ollama)
  • Drop-in sync & async MCP tool-wrapper middleware (MCPToolGuardMiddleware in mcp_wrapper_middleware.py) with automatic turn accounting
  • Extended 15-vector prompt-injection & secret-exfiltration test suite
  • Zero-dep PII & Secret Redactor (redact_secrets / redact_record) for safe JSONL audit sharing
  • Claude Desktop, Cursor & Windsurf MCP templates + live claude_statusline.py HUD + FinOps Threshold Playbook + direct email 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.)

Metadata

Release files for agent-cost-guard 0.6.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agent-cost-guard 0.6.2
File Size Uploaded Provenance Actions
agent_cost_guard-0.6.2.tar.gz 41.9 kB With provenance Details for agent_cost_guard-0.6.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agent-cost-guard 0.6.2
File Interpreter ABI Platform Actions
agent_cost_guard-0.6.2-py3-none-any.whl Python 3 none any Details for agent_cost_guard-0.6.2-py3-none-any.whl

Total release size: 80.5 kB

Release files / agent_cost_guard-0.6.2.tar.gz

Download URL agent_cost_guard-0.6.2.tar.gz
Size 41.9 kB
Tags Source
SHA-256 checksum
How to use checksums
2a15d9d803cc7813081c0b9a77865f0df55d702c62b173203e4b11e2c6c21e17
BLAKE2b-256 checksum
How to use checksums
2710d00e3556dc3312447dba0e862803fe8232ef4686cd0a0c2553dcd555bfd9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / agent_cost_guard-0.6.2-py3-none-any.whl

Download URL agent_cost_guard-0.6.2-py3-none-any.whl
Size 38.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f3e415238e06535a91a2b8ac3393e26262108d72c3f30e4b30cd18b868b9ad2e
BLAKE2b-256 checksum
How to use checksums
04b0abf315829469e3075d50e3ae011ab8628c52589980cab0ddca80f8ab24a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for agent-cost-guard 0.6.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for agent_cost_guard-0.6.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page