agent-cost-guard 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rolando Wachtendorff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-cost-guard
3
+ Version: 0.6.0
4
+ Summary: Zero-dependency Python cost caps, loop detection, MCP stdio proxy, and tool guardrails for AI agents
5
+ Author-email: Rolando Wachtendorff <rolando@wachtendorff.cl>
6
+ License: MIT
7
+ Project-URL: Homepage, https://rwachtendorff.github.io/agent-cost-guard/
8
+ Project-URL: Repository, https://github.com/rwachtendorff/agent-cost-guard
9
+ Project-URL: Demo, https://rwachtendorff.github.io/agent-cost-guard/demo-report.html
10
+ Keywords: ai-agents,mcp,model-context-protocol,circuit-breaker,llm,guardrails,finops
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # AgentCostGuard (`agent-cost-guard`)
21
+
22
+ [![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)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
24
+ [![agent-cost-guard on otra.city](https://otra.city/badge/agent-cost-guard.svg)](https://otra.city/s/agent-cost-guard)
25
+ [![Listed on chen.media/mcp](https://chen.media/mcp/badge/github-rwachtendorff-agent-cost-guard.svg)](https://chen.media/mcp/github-rwachtendorff-agent-cost-guard)
26
+
27
+ Find us on the [Chen Media MCP Directory](https://chen.media/mcp)
28
+
29
+ **Zero-dependency Python circuit breaker for autonomous AI agents & MCP tool loops.**
30
+
31
+ 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.
32
+
33
+ - **Install:** `pip install git+https://github.com/rwachtendorff/agent-cost-guard.git`
34
+ - **Container (Zero Python):** `docker run -i --rm ghcr.io/rwachtendorff/agent-cost-guard:0.6.0`
35
+ - **1-Click Claude Desktop Extension (`.mcpb`):** https://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.6.0/agent-cost-guard-mcp-0.6.0.mcpb
36
+ - **1-Second Health Check (`doctor`):** `agent-cost-guard doctor` (audits MCP configs, Claude Code hooks, and past session loops)
37
+ - **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`
38
+ - **Live Project Page & Interactive Simulator:** https://rwachtendorff.github.io/agent-cost-guard/
39
+ - **Live HTML Audit Demo:** https://rwachtendorff.github.io/agent-cost-guard/demo-report.html
40
+ - **Pro Production Policy & MCP Pack ($7 USD):** https://www.paypal.com/paypalme/rwachtendorff/7USD
41
+
42
+ ## Why this exists
43
+ 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.
44
+
45
+ `agent-cost-guard` runs purely on Python 3.9+ standard library (zero external dependencies, zero telemetry, 100% local) and gives you:
46
+
47
+ - **Hard USD & Token Caps (`BudgetExceededError`)** across Gemini, OpenAI, Anthropic, or custom/local models.
48
+ - **Tool Loop & Oscillation Detection (`LoopDetectedError`)** using canonical SHA-256 argument hashing + sliding-window ping-pong detection.
49
+ - **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.
50
+ - **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`).
51
+ - **1-Second Health Check (`agent-cost-guard doctor`)** to verify unprotected MCP configs, active Claude Code hooks, and historical loop savings in one pass.
52
+ - **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.
53
+ - **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.
54
+ - **Auto-Discovery Audit & Wrapper (`audit` / `wrap-config --discover`)** to scan and protect existing Claude, Cursor, Windsurf, and VS Code MCP configs.
55
+ - **Tool & Untrusted-Text Guardrails (`PolicyViolationError`)** to block forbidden tools or prompt-injection attempts inside scraped content.
56
+ - **Structured JSONL Trace + Standalone HTML Audit Report** (`agent-cost-guard report trace.jsonl`).
57
+
58
+ ## Measured Benchmark (`examples/benchmark_loop.py`)
59
+
60
+ | Scenario | Model | Unprotected Cost | Guarded Cost | Blocked At | Cost Reduction |
61
+ |---|---|---:|---:|---:|---:|
62
+ | 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%** |
63
+ | Ping-pong oscillation `A <-> B` (30 steps) | `gpt-4o` | $1.5353 (579,900 tok) | $0.1153 (40,400 tok) | Step 6 (`LoopDetectedError`) | **92.49%** |
64
+
65
+ Measured overhead across 1,000 turns: **~9.9 µs per turn**.
66
+
67
+ ## Quick Start
68
+
69
+ ```python
70
+ from agent_cost_guard import GuardConfig, GuardError, SessionGuard
71
+
72
+ guard = SessionGuard(
73
+ session_id="research-run-01",
74
+ config=GuardConfig(
75
+ max_cost_usd=0.50,
76
+ max_total_tokens=120_000,
77
+ max_steps=25,
78
+ repeat_tool_threshold=3,
79
+ oscillation_window=6,
80
+ blocked_tools=("drop_database",),
81
+ jsonl_log_path="traces/agent_run.jsonl",
82
+ ),
83
+ )
84
+
85
+ try:
86
+ for step in guard.guard_loop():
87
+ # Call your LLM + tool here, then record the turn:
88
+ guard.record_turn(
89
+ model="gemini-2.5-flash",
90
+ input_tokens=1400,
91
+ output_tokens=320,
92
+ tool_name="web_fetch",
93
+ tool_args={"url": "https://example.com"},
94
+ untrusted_text="clean page output",
95
+ )
96
+ break
97
+ except GuardError as exc:
98
+ print("Circuit breaker triggered:", exc)
99
+
100
+ print(guard.summary())
101
+ ```
102
+
103
+ ### Zero-Dep SDK Response Adapter (OpenAI / Anthropic / Gemini)
104
+ Pass raw SDK response objects or API JSON dicts directly to `record_llm_response()`—no extra dependencies required:
105
+
106
+ ```python
107
+ # Works out of the box with OpenAI, Anthropic, or Google Gemini SDK responses:
108
+ guard.record_llm_response(
109
+ response,
110
+ model="gemini-2.5-flash", # optional if response.model is present
111
+ tool_name="web_fetch",
112
+ tool_args={"url": "https://example.com"},
113
+ )
114
+ ```
115
+
116
+ ## CLI Demo, MCP STDIO Proxy, Benchmark & HTML Report
117
+
118
+ ```bash
119
+ # Wrap ANY stdio MCP server (Claude Desktop, Cursor, Windsurf, Hermes):
120
+ agent-cost-guard mcp-proxy --repeat-limit 3 --blocked-tools drop_table --log mcp.jsonl -- npx -y @modelcontextprotocol/server-filesystem .
121
+
122
+ # Run AgentCostGuard's own native MCP stdio server (5 diagnostic & FinOps tools):
123
+ agent-cost-guard mcp-server
124
+
125
+ # Audit past Claude Code sessions (~/.claude/projects) for runaway loops & savings:
126
+ agent-cost-guard doctor
127
+ agent-cost-guard scan-sessions --html claude_audit.html
128
+
129
+ # Quick CLI cost estimate or list all 32 built-in 2026 model rates:
130
+ agent-cost-guard estimate gpt-5 --input-tokens 50000 --output-tokens 5000
131
+ agent-cost-guard estimate --list-models
132
+
133
+ # Auto-discover & audit existing Claude / Cursor / Windsurf / VS Code MCP configs:
134
+ agent-cost-guard audit
135
+ agent-cost-guard wrap-config --discover --repeat-limit 3 --log-dir ./mcp_traces
136
+
137
+ # Protect Claude Code built-in tools via PreToolUse & PostToolUse hooks (with optional live $2.50 cap):
138
+ agent-cost-guard install-hooks .claude/settings.json --max-usd 2.50 --write --backup
139
+
140
+ python3 examples/benchmark_loop.py
141
+ python3 examples/mcp_and_llm_quickstart.py
142
+ python3 -m agent_cost_guard.cli demo --log demo_trace.jsonl --html demo_report.html
143
+ python3 -m agent_cost_guard.cli report demo_trace.jsonl --out audit.html
144
+ ```
145
+
146
+ Drop-in `claude_desktop_config.json` / Cursor `mcp.json` snippet:
147
+
148
+ ```json
149
+ {
150
+ "mcpServers": {
151
+ "filesystem-guarded": {
152
+ "command": "agent-cost-guard",
153
+ "args": ["mcp-proxy", "--repeat-limit", "3", "--log", "mcp_trace.jsonl", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "."]
154
+ }
155
+ }
156
+ }
157
+ ```
158
+
159
+ ## Running Tests
160
+
161
+ ```bash
162
+ python3 -m unittest discover -s tests -v
163
+ ```
164
+
165
+ ## Pro Production Policy & MCP Pack ($7 USD)
166
+
167
+ The core library above is MIT-licensed and free forever. If you want production-ready presets and plug-and-play integration assets:
168
+
169
+ - **5 pre-tuned JSON policy profiles** (`Gemini 2.5`, `GPT-4o/4.1`, `Claude 3.7/4`, `claude_code_strict`, local Ollama)
170
+ - **Drop-in sync & async MCP tool-wrapper middleware** (`MCPToolGuardMiddleware` in `mcp_wrapper_middleware.py`) with automatic turn accounting
171
+ - **Extended 15-vector prompt-injection & secret-exfiltration test suite**
172
+ - **Zero-dep PII & Secret Redactor** (`redact_secrets` / `redact_record`) for safe JSONL audit sharing
173
+ - **Claude Desktop, Cursor & Windsurf MCP templates** + live `claude_statusline.py` HUD + **FinOps Threshold Playbook** + direct email support
174
+
175
+ **Get it here ($7 USD via PayPal):** https://www.paypal.com/paypalme/rwachtendorff/7USD
176
+ *(Include your email in the PayPal note — or send your transaction ID to `rolando@wachtendorff.cl` — to receive the Pro Pack archive.)*
@@ -0,0 +1,157 @@
1
+ # AgentCostGuard (`agent-cost-guard`)
2
+
3
+ [![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)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
+ [![agent-cost-guard on otra.city](https://otra.city/badge/agent-cost-guard.svg)](https://otra.city/s/agent-cost-guard)
6
+ [![Listed on chen.media/mcp](https://chen.media/mcp/badge/github-rwachtendorff-agent-cost-guard.svg)](https://chen.media/mcp/github-rwachtendorff-agent-cost-guard)
7
+
8
+ Find us on the [Chen Media MCP Directory](https://chen.media/mcp)
9
+
10
+ **Zero-dependency Python circuit breaker for autonomous AI agents & MCP tool loops.**
11
+
12
+ 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.
13
+
14
+ - **Install:** `pip install git+https://github.com/rwachtendorff/agent-cost-guard.git`
15
+ - **Container (Zero Python):** `docker run -i --rm ghcr.io/rwachtendorff/agent-cost-guard:0.6.0`
16
+ - **1-Click Claude Desktop Extension (`.mcpb`):** https://github.com/rwachtendorff/agent-cost-guard/releases/download/v0.6.0/agent-cost-guard-mcp-0.6.0.mcpb
17
+ - **1-Second Health Check (`doctor`):** `agent-cost-guard doctor` (audits MCP configs, Claude Code hooks, and past session loops)
18
+ - **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`
19
+ - **Live Project Page & Interactive Simulator:** https://rwachtendorff.github.io/agent-cost-guard/
20
+ - **Live HTML Audit Demo:** https://rwachtendorff.github.io/agent-cost-guard/demo-report.html
21
+ - **Pro Production Policy & MCP Pack ($7 USD):** https://www.paypal.com/paypalme/rwachtendorff/7USD
22
+
23
+ ## Why this exists
24
+ 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.
25
+
26
+ `agent-cost-guard` runs purely on Python 3.9+ standard library (zero external dependencies, zero telemetry, 100% local) and gives you:
27
+
28
+ - **Hard USD & Token Caps (`BudgetExceededError`)** across Gemini, OpenAI, Anthropic, or custom/local models.
29
+ - **Tool Loop & Oscillation Detection (`LoopDetectedError`)** using canonical SHA-256 argument hashing + sliding-window ping-pong detection.
30
+ - **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.
31
+ - **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`).
32
+ - **1-Second Health Check (`agent-cost-guard doctor`)** to verify unprotected MCP configs, active Claude Code hooks, and historical loop savings in one pass.
33
+ - **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.
34
+ - **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.
35
+ - **Auto-Discovery Audit & Wrapper (`audit` / `wrap-config --discover`)** to scan and protect existing Claude, Cursor, Windsurf, and VS Code MCP configs.
36
+ - **Tool & Untrusted-Text Guardrails (`PolicyViolationError`)** to block forbidden tools or prompt-injection attempts inside scraped content.
37
+ - **Structured JSONL Trace + Standalone HTML Audit Report** (`agent-cost-guard report trace.jsonl`).
38
+
39
+ ## Measured Benchmark (`examples/benchmark_loop.py`)
40
+
41
+ | Scenario | Model | Unprotected Cost | Guarded Cost | Blocked At | Cost Reduction |
42
+ |---|---|---:|---:|---:|---:|
43
+ | 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%** |
44
+ | Ping-pong oscillation `A <-> B` (30 steps) | `gpt-4o` | $1.5353 (579,900 tok) | $0.1153 (40,400 tok) | Step 6 (`LoopDetectedError`) | **92.49%** |
45
+
46
+ Measured overhead across 1,000 turns: **~9.9 µs per turn**.
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ from agent_cost_guard import GuardConfig, GuardError, SessionGuard
52
+
53
+ guard = SessionGuard(
54
+ session_id="research-run-01",
55
+ config=GuardConfig(
56
+ max_cost_usd=0.50,
57
+ max_total_tokens=120_000,
58
+ max_steps=25,
59
+ repeat_tool_threshold=3,
60
+ oscillation_window=6,
61
+ blocked_tools=("drop_database",),
62
+ jsonl_log_path="traces/agent_run.jsonl",
63
+ ),
64
+ )
65
+
66
+ try:
67
+ for step in guard.guard_loop():
68
+ # Call your LLM + tool here, then record the turn:
69
+ guard.record_turn(
70
+ model="gemini-2.5-flash",
71
+ input_tokens=1400,
72
+ output_tokens=320,
73
+ tool_name="web_fetch",
74
+ tool_args={"url": "https://example.com"},
75
+ untrusted_text="clean page output",
76
+ )
77
+ break
78
+ except GuardError as exc:
79
+ print("Circuit breaker triggered:", exc)
80
+
81
+ print(guard.summary())
82
+ ```
83
+
84
+ ### Zero-Dep SDK Response Adapter (OpenAI / Anthropic / Gemini)
85
+ Pass raw SDK response objects or API JSON dicts directly to `record_llm_response()`—no extra dependencies required:
86
+
87
+ ```python
88
+ # Works out of the box with OpenAI, Anthropic, or Google Gemini SDK responses:
89
+ guard.record_llm_response(
90
+ response,
91
+ model="gemini-2.5-flash", # optional if response.model is present
92
+ tool_name="web_fetch",
93
+ tool_args={"url": "https://example.com"},
94
+ )
95
+ ```
96
+
97
+ ## CLI Demo, MCP STDIO Proxy, Benchmark & HTML Report
98
+
99
+ ```bash
100
+ # Wrap ANY stdio MCP server (Claude Desktop, Cursor, Windsurf, Hermes):
101
+ agent-cost-guard mcp-proxy --repeat-limit 3 --blocked-tools drop_table --log mcp.jsonl -- npx -y @modelcontextprotocol/server-filesystem .
102
+
103
+ # Run AgentCostGuard's own native MCP stdio server (5 diagnostic & FinOps tools):
104
+ agent-cost-guard mcp-server
105
+
106
+ # Audit past Claude Code sessions (~/.claude/projects) for runaway loops & savings:
107
+ agent-cost-guard doctor
108
+ agent-cost-guard scan-sessions --html claude_audit.html
109
+
110
+ # Quick CLI cost estimate or list all 32 built-in 2026 model rates:
111
+ agent-cost-guard estimate gpt-5 --input-tokens 50000 --output-tokens 5000
112
+ agent-cost-guard estimate --list-models
113
+
114
+ # Auto-discover & audit existing Claude / Cursor / Windsurf / VS Code MCP configs:
115
+ agent-cost-guard audit
116
+ agent-cost-guard wrap-config --discover --repeat-limit 3 --log-dir ./mcp_traces
117
+
118
+ # Protect Claude Code built-in tools via PreToolUse & PostToolUse hooks (with optional live $2.50 cap):
119
+ agent-cost-guard install-hooks .claude/settings.json --max-usd 2.50 --write --backup
120
+
121
+ python3 examples/benchmark_loop.py
122
+ python3 examples/mcp_and_llm_quickstart.py
123
+ python3 -m agent_cost_guard.cli demo --log demo_trace.jsonl --html demo_report.html
124
+ python3 -m agent_cost_guard.cli report demo_trace.jsonl --out audit.html
125
+ ```
126
+
127
+ Drop-in `claude_desktop_config.json` / Cursor `mcp.json` snippet:
128
+
129
+ ```json
130
+ {
131
+ "mcpServers": {
132
+ "filesystem-guarded": {
133
+ "command": "agent-cost-guard",
134
+ "args": ["mcp-proxy", "--repeat-limit", "3", "--log", "mcp_trace.jsonl", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "."]
135
+ }
136
+ }
137
+ }
138
+ ```
139
+
140
+ ## Running Tests
141
+
142
+ ```bash
143
+ python3 -m unittest discover -s tests -v
144
+ ```
145
+
146
+ ## Pro Production Policy & MCP Pack ($7 USD)
147
+
148
+ The core library above is MIT-licensed and free forever. If you want production-ready presets and plug-and-play integration assets:
149
+
150
+ - **5 pre-tuned JSON policy profiles** (`Gemini 2.5`, `GPT-4o/4.1`, `Claude 3.7/4`, `claude_code_strict`, local Ollama)
151
+ - **Drop-in sync & async MCP tool-wrapper middleware** (`MCPToolGuardMiddleware` in `mcp_wrapper_middleware.py`) with automatic turn accounting
152
+ - **Extended 15-vector prompt-injection & secret-exfiltration test suite**
153
+ - **Zero-dep PII & Secret Redactor** (`redact_secrets` / `redact_record`) for safe JSONL audit sharing
154
+ - **Claude Desktop, Cursor & Windsurf MCP templates** + live `claude_statusline.py` HUD + **FinOps Threshold Playbook** + direct email support
155
+
156
+ **Get it here ($7 USD via PayPal):** https://www.paypal.com/paypalme/rwachtendorff/7USD
157
+ *(Include your email in the PayPal note — or send your transaction ID to `rolando@wachtendorff.cl` — to receive the Pro Pack archive.)*
@@ -0,0 +1,73 @@
1
+ """agent_cost_guard: Zero-dependency cost caps, loop detection, and tool guardrails for AI agents."""
2
+
3
+ from ._version import __version__
4
+ from .adapters import ExtractedUsage, extract_usage_from_response
5
+ from .claude_hooks import (
6
+ evaluate_claude_hook_event,
7
+ install_claude_hooks_config,
8
+ run_claude_hook_cli,
9
+ )
10
+ from .config_wrap import (
11
+ audit_mcp_servers_config,
12
+ discover_mcp_config_paths,
13
+ wrap_mcp_servers_config,
14
+ )
15
+ from .guard import (
16
+ BudgetExceededError,
17
+ GuardConfig,
18
+ GuardError,
19
+ LoopDetectedError,
20
+ PolicyViolationError,
21
+ SessionGuard,
22
+ StepRecord,
23
+ )
24
+ from .mcp_proxy import MCPStdioProxy, run_mcp_stdio_proxy
25
+ from .mcp_server import (
26
+ MCP_PROMPTS,
27
+ MCP_RESOURCES,
28
+ MCP_TOOLS,
29
+ call_mcp_tool,
30
+ handle_mcp_server_message,
31
+ run_mcp_server,
32
+ )
33
+ from .pricing import MODEL_PRICING_PER_1M, estimate_cost_usd, register_model_pricing
34
+ from .report_html import generate_html_report
35
+ from .session_scan import (
36
+ discover_claude_session_files,
37
+ scan_claude_sessions,
38
+ scan_session_jsonl,
39
+ )
40
+
41
+ __all__ = [
42
+ "BudgetExceededError",
43
+ "ExtractedUsage",
44
+ "GuardConfig",
45
+ "GuardError",
46
+ "LoopDetectedError",
47
+ "MCP_PROMPTS",
48
+ "MCP_RESOURCES",
49
+ "MCP_TOOLS",
50
+ "MCPStdioProxy",
51
+ "MODEL_PRICING_PER_1M",
52
+ "PolicyViolationError",
53
+ "SessionGuard",
54
+ "StepRecord",
55
+ "__version__",
56
+ "audit_mcp_servers_config",
57
+ "call_mcp_tool",
58
+ "discover_claude_session_files",
59
+ "discover_mcp_config_paths",
60
+ "estimate_cost_usd",
61
+ "evaluate_claude_hook_event",
62
+ "extract_usage_from_response",
63
+ "generate_html_report",
64
+ "handle_mcp_server_message",
65
+ "install_claude_hooks_config",
66
+ "register_model_pricing",
67
+ "run_claude_hook_cli",
68
+ "run_mcp_server",
69
+ "run_mcp_stdio_proxy",
70
+ "scan_claude_sessions",
71
+ "scan_session_jsonl",
72
+ "wrap_mcp_servers_config",
73
+ ]
@@ -0,0 +1,3 @@
1
+ """Package version for agent-cost-guard."""
2
+
3
+ __version__ = "0.6.0"
@@ -0,0 +1,111 @@
1
+ """Zero-dependency duck-typed usage extractors for OpenAI, Anthropic, and Gemini responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Mapping, Optional
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class ExtractedUsage:
11
+ model: str
12
+ input_tokens: int
13
+ output_tokens: int
14
+ cached_input_tokens: int = 0
15
+ provider: str = "unknown"
16
+
17
+
18
+ def _get(obj: Any, key: str, default: Any = None) -> Any:
19
+ if obj is None:
20
+ return default
21
+ if isinstance(obj, Mapping):
22
+ return obj.get(key, default)
23
+ return getattr(obj, key, default)
24
+
25
+
26
+ def _as_int(val: Any, default: int = 0) -> int:
27
+ if val is None:
28
+ return default
29
+ try:
30
+ return max(0, int(val))
31
+ except (TypeError, ValueError):
32
+ return default
33
+
34
+
35
+ def extract_usage_from_response(
36
+ response: Any,
37
+ model: Optional[str] = None,
38
+ ) -> ExtractedUsage:
39
+ """Extract (model, input_tokens, output_tokens, cached_input_tokens) without SDK imports.
40
+
41
+ Supports:
42
+ - Google Gemini (`usage_metadata`: `prompt_token_count`, `candidates_token_count`, `cached_content_token_count`)
43
+ - OpenAI Chat Completions (`usage`: `prompt_tokens`, `completion_tokens`, `prompt_tokens_details.cached_tokens`)
44
+ - OpenAI Responses API & Anthropic Messages (`usage`: `input_tokens`, `output_tokens`, `cache_read_input_tokens` / `input_tokens_details.cached_tokens`)
45
+ """
46
+ resolved_model = model or _get(response, "model") or _get(response, "model_version")
47
+
48
+ # 1. Google Gemini (`usage_metadata`)
49
+ gemini_meta = _get(response, "usage_metadata")
50
+ if gemini_meta is not None:
51
+ prompt_tok = _as_int(_get(gemini_meta, "prompt_token_count"))
52
+ cand_tok = _as_int(
53
+ _get(gemini_meta, "candidates_token_count")
54
+ or _get(gemini_meta, "output_token_count")
55
+ )
56
+ cached_tok = _as_int(_get(gemini_meta, "cached_content_token_count"))
57
+ if not resolved_model:
58
+ resolved_model = "gemini-2.5-flash"
59
+ return ExtractedUsage(
60
+ model=str(resolved_model),
61
+ input_tokens=prompt_tok,
62
+ output_tokens=cand_tok,
63
+ cached_input_tokens=cached_tok,
64
+ provider="gemini",
65
+ )
66
+
67
+ # 2. OpenAI / Anthropic (`usage`)
68
+ usage = _get(response, "usage")
69
+ if usage is not None:
70
+ # OpenAI Chat Completions style
71
+ if _get(usage, "prompt_tokens") is not None or _get(usage, "completion_tokens") is not None:
72
+ in_tok = _as_int(_get(usage, "prompt_tokens"))
73
+ out_tok = _as_int(_get(usage, "completion_tokens"))
74
+ details = _get(usage, "prompt_tokens_details")
75
+ cached_tok = _as_int(_get(details, "cached_tokens"))
76
+ if not resolved_model:
77
+ resolved_model = "gpt-4o"
78
+ return ExtractedUsage(
79
+ model=str(resolved_model),
80
+ input_tokens=in_tok,
81
+ output_tokens=out_tok,
82
+ cached_input_tokens=cached_tok,
83
+ provider="openai",
84
+ )
85
+
86
+ # OpenAI Responses API / Anthropic Messages style
87
+ if _get(usage, "input_tokens") is not None or _get(usage, "output_tokens") is not None:
88
+ in_tok = _as_int(_get(usage, "input_tokens"))
89
+ out_tok = _as_int(_get(usage, "output_tokens"))
90
+ anthropic_cached = _get(usage, "cache_read_input_tokens")
91
+ if anthropic_cached is not None:
92
+ cached_tok = _as_int(anthropic_cached)
93
+ provider = "anthropic"
94
+ fallback_model = "claude-3.7-sonnet"
95
+ else:
96
+ details = _get(usage, "input_tokens_details")
97
+ cached_tok = _as_int(_get(details, "cached_tokens"))
98
+ provider = "openai"
99
+ fallback_model = "gpt-4.1"
100
+ return ExtractedUsage(
101
+ model=str(resolved_model or fallback_model),
102
+ input_tokens=in_tok,
103
+ output_tokens=out_tok,
104
+ cached_input_tokens=cached_tok,
105
+ provider=provider,
106
+ )
107
+
108
+ raise ValueError(
109
+ "Could not extract token usage from LLM response. "
110
+ "Expected `.usage` (OpenAI/Anthropic) or `.usage_metadata` (Gemini)."
111
+ )