AgentCostGuard
Supports parsing Google Gemini SDK response objects and API JSON to record token usage and enforce cost and token caps; includes Gemini 2.5 policy profiles.
Supports parsing OpenAI SDK response objects and API JSON to record token usage and enforce cost and token caps; includes GPT-4o/4.1 policy profiles.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
AgentCostGuard (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.git1-Click Claude Desktop Extension (
.mcpb): https://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.2.0/agent-cost-guard-mcp-0.2.0.mcpbLive 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) exposingestimate_llm_cost,scan_prompt_injection,audit_mcp_config, andsummarize_jsonl_traceover 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).
Related MCP server: mcpsentry
Measured Benchmark (examples/benchmark_loop.py)
Scenario | Model | Unprotected Cost | Guarded Cost | Blocked At | Cost Reduction |
Identical retry loop (40 steps) |
| $3.9240 (1,240,800 tok) | $0.0945 (26,460 tok) | Step 4 ( | 97.59% |
Ping-pong oscillation |
| $1.5353 (579,900 tok) | $0.1153 (40,400 tok) | Step 6 ( | 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 (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.htmlDrop-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 -vPro 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 accountingExtended 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.)
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
LLM cost optimization gateway, repo token-waste auditor & model arbitrage MCP server.
Zero-LLM deterministic security auditor for MCP configs, SKILL.md rules, and agent budgets.
Health, token bloat, SHA-256 Rug Pull & prompt injection audit API for remote MCPs.
Scan prompts for injection attacks, redact PII, and audit LLM SDK usage from any MCP client
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceDiagnose MCP servers — health checks, tool testing, token cost audits, conflict detection, and security scanning with 50+ prompt injection patterns. Works as CLI or MCP server inside Claude Desktop.1MIT
- AlicenseNot gradedqualityDmaintenanceSecurity scanner and runtime proxy for MCP servers. Catches tool poisoning, prompt injection, and rug-pull attacks (silent tool description changes) before they reach your AI agent. Includes a static scanner and a runtime stdio proxy.104 npmMIT
- FlicenseAqualityCmaintenanceAn MCP server that exposes governance, trust-scoring, compliance, guardrail, cost, drift, and supply-chain scanning tools and resources to any MCP client over stdio, Streamable HTTP, or legacy HTTP+SSE. It lets agents route every tool call through a deterministic five-way decision (allow, redact, require approval, deny, or quarantine) with hash-chained evidence, human approval workflows, and in-agent trust gates for LangChain, LangGraph, and Google ADK.30-
- FlicenseNot gradedqualityBmaintenanceEnables autonomous agents and MCP-compatible clients to route inputs through a deterministic firewall that flags and sanitizes prompt injection, jailbreaks, system prompt exfiltration, and tool hijacking. It supports JSON-RPC stdio integration for tools like Claude Desktop, Cursor, and multi-agent frameworks.7-