
agent-cost-guard
io.github.rwachtendorff/agent-cost-guard
Zero-dep MCP cost estimator, prompt-injection scanner, live USD Claude hooks, and loop breaker.
Documentation
AgentCostGuard (agent-cost-guard)
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.
- Install (PyPI):
pip install agent-cost-guard(or zero-install viauvx agent-cost-guard mcp-server) - Container (Zero Python):
docker run -i --rm ghcr.io/rwachtendorff/agent-cost-guard:0.6.2 - 1-Click Claude Desktop Extension (
.mcpb): https://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.6.2/agent-cost-guard-mcp-0.6.2.mcpb - 1-Second Health Check (
doctor):agent-cost-guard doctor(audits MCP configs, Claude Code hooks, and past session loops) - Claude Code Plugin, Live USD Hooks & Session Audit:
.claude-plugin/plugin.json+agent-cost-guard install-hooks .claude/settings.json --max-usd 2.50 --write --backup+agent-cost-guard scan-sessions - Live Project Page & Interactive Simulator: https://rwachtendorff.github.io/agent-cost-guard/
- Live HTML Audit Demo: https://rwachtendorff.github.io/agent-cost-guard/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 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-buildDockerfile). - 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/PostToolUseHooks (claude-hook/install-hooks): Stop infiniteBash/Edit/WebFetchretry loops, enforce live--max-usdsession 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 (
MCPToolGuardMiddlewareinmcp_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.pyHUD + 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.)
agent-cost-guardpip install agent-cost-guardhttps://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.6.2/agent-cost-guard-mcp-0.6.2.mcpb# mcpb: https://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.6.2/agent-cost-guard-mcp-0.6.2.mcpbghcr.io/rwachtendorff/agent-cost-guard:0.6.2docker pull ghcr.io/rwachtendorff/agent-cost-guard:0.6.2:undefined