Metadata-Version: 2.4
Name: openclaw-cost-tracker-mcp
Version: 1.1.0
Summary: MCP server for AI agent token-cost telemetry + quota-window awareness across Anthropic, OpenAI, Gemini, Ollama, AWS Bedrock — per-agent + per-provider attribution, spend-spike anomaly detection, cheaper-model routing recommendations, monthly forecast, and 429-prediction + throttle-target tools that read anthropic-ratelimit-* headers to project rate-limit exhaustion before it happens. Reads cost-log JSONL with the standard schema; OpenClaw ~/.openclaw/cost-logs/ is supported natively.
Project-URL: Homepage, https://github.com/temurkhan13/openclaw-cost-tracker-mcp
Project-URL: Documentation, https://github.com/temurkhan13/openclaw-cost-tracker-mcp/blob/main/SPEC.md
Project-URL: Bug Tracker, https://github.com/temurkhan13/openclaw-cost-tracker-mcp/issues
Project-URL: Custom MCP Build, https://github.com/temurkhan13/openclaw-cost-tracker-mcp#need-this-adapted-to-your-stack
Project-URL: Changelog, https://github.com/temurkhan13/openclaw-cost-tracker-mcp/blob/main/CHANGELOG.md
Author-email: Temur Khan <temur@pixelette.tech>
License: MIT License
        
        Copyright (c) 2026 Temur Khan
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: 429-prediction,agent-ops,ai-agent,anomaly-detection,anthropic,claude,cost-tracking,finops,llm-cost,mcp,model-context-protocol,openai,openclaw,production-ai,quota,rate-limit,throttle,token-cost
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.11
Requires-Dist: mcp>=1.0.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Description-Content-Type: text/markdown

# openclaw-cost-tracker-mcp

<!-- mcp-name: io.github.temurkhan13/openclaw-cost-tracker-mcp -->

> **MCP server for AI agent token-cost telemetry — built for the operator who woke up to a surprise bill.** Catches the failure modes vendor dashboards miss: silent re-routing to API billing ([HERMES.md bug](https://old.reddit.com/r/ClaudeAI/comments/1svdm1w/psa_the_string_hermesmd_in_your_git_commit/), 1,464 upvotes), [unattended `/loop` overnight burns ($6k in 26 hours, real story](https://old.reddit.com/r/ClaudeAI/comments/1t11mmy/i_accidentally_burned_6000_of_claude_usage/)), per-agent attribution buried behind aggregate provider totals, multi-day dashboard lag that surfaces the spike *after* the money is gone. Cross-provider: Anthropic, OpenAI, Gemini, Ollama, AWS Bedrock. Per-agent + per-provider attribution, spend-spike anomaly detection (per-agent median × threshold), cheaper-routing recommendations with 30-day savings estimates, monthly forecast. Reads any cost-log JSONL with the standard `{request_id, timestamp, provider, model, agent_id, prompt_tokens, completion_tokens, cost_usd}` schema. **OpenClaw operators get native `~/.openclaw/cost-logs/` parsing; other deployments wrap their provider calls with the included logging shim or commission a Custom MCP Build adapter.** Keywords: Claude API cost surprise, /loop overnight burn, HERMES.md billing routing, dashboard lag, AI agent FinOps, LLM cost attribution, token spend monitoring.

[![Status: v1.1.0](https://img.shields.io/badge/status-v1.1.0-brightgreen)](https://github.com/temurkhan13/openclaw-cost-tracker-mcp) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE) [![MCP](https://img.shields.io/badge/protocol-MCP-purple)](https://modelcontextprotocol.io/) [![PyPI](https://img.shields.io/pypi/v/openclaw-cost-tracker-mcp)](https://pypi.org/project/openclaw-cost-tracker-mcp/)

---

## What it does

Production AI deployments are leaking money in ways the vendor dashboards don't surface in time. Real stories from the last 30 days on r/ClaudeAI:

- A developer woke up to a **$6,000 overnight burn** from a single `/loop` command running 26 hours unattended on Claude Opus 4.7 ([1,175 upvotes, 314 comments, May 1 2026](https://old.reddit.com/r/ClaudeAI/comments/1t11mmy/i_accidentally_burned_6000_of_claude_usage/)). The Anthropic dashboard lagged by days; the spike was invisible until the limit email landed. Verbatim from the OP: *"By the time it shows a spike, the money is already spent."*
- Another lost **$200 because a string in a git commit silently routed Claude Code billing from Max subscription to API tier** — the [HERMES.md bug](https://old.reddit.com/r/ClaudeAI/comments/1svdm1w/psa_the_string_hermesmd_in_your_git_commit/) (1,464 upvotes, 202 comments). Anthropic refused a refund.
- A third left a test loop running and woke up to a [surprise $80 Claude bill](https://dev.to/godnick/what-happened-when-i-got-a-surprise-80-claude-bill-5d83). Verbatim: *"No alerts. No cap. No warning. Just a bill."*
- A fourth got [$1,800 in API charges in two days](https://github.com/anthropics/claude-code/issues/37686) after the built-in `claude-code-guide` agent recommended a command that bypasses Max-plan billing.

In every case the dashboard lagged, the per-agent attribution was invisible, and Anthropic's own hard-cap mechanism either failed or arrived too late. This MCP server surfaces per-agent + per-provider cost attribution **live**, queryable from inside Claude or any MCP-aware client, **before** the bill arrives:

```
> claude: where did our LLM spend go this week?
[MCP tools: cost_overview + top_cost_drivers]

Total spend last 7 days: $42.18
By provider:
  Anthropic    $30.40 (72%) — claude-sonnet-4 dominates
  OpenAI       $9.20  (22%) — chat-bot agent
  Gemini       $1.86  (4%)  — cron-summarizer (cheap-route working)
  Ollama       $0.00  (local, free)

Top 3 cost drivers:
  data-extraction-agent      $28.50 (68%)
  chat-bot                   $9.20  (22%)
  cron-summarizer            $1.86  (4%)

1 anomaly flagged — see find_cost_anomalies for details.
```

```
> claude: any cheaper-routing opportunities?
[MCP tool: model_routing_recommendations]

Recommendation: data-extraction-agent currently runs claude-sonnet-4
with avg 400-token completions — extraction-style work that
gemini-2.5-flash usually handles at ~95% quality for ~5% the cost.
Estimated savings: $27.10/30d if migrated. Test on a 10% slice first.
```

**v1.1 — quota-window awareness.** The cost tracker now also answers "will my agent hit a 429 *before* the window resets?" *before* it actually does. This is the HERMES.md / overnight-burn detector — projecting per-dimension exhaustion ETA from your active burn rate vs the rate-limit headers your provider already returns:

```
> claude: am I about to 429?
[MCP tool: predict_429_in_window]

severity: CRITICAL
provider: anthropic
burn_rate_tokens_per_min: 8000
dimension_predictions:
  tokens          : will 429 in ~6.5 min  (resets in 22 min) ⚠
  output_tokens   : will 429 in ~11.7 min (resets in 22 min) ⚠
  input_tokens    : safe through reset (headroom 70k at reset)
  requests        : safe through reset (headroom 858 at reset)

summary: tokens projected to 429 in ~6.5 min at current burn (8000/min).
Window resets in 22 min — throttle now.
```

```
> claude: what burn rate keeps me safe?
[MCP tool: recommend_throttle_target target_buffer_pct=10]

target_buffer_pct: 10
targets:
  tokens          : current 8000/min, max safe 545/min — must throttle
  output_tokens   : current 3000/min, max safe 1136/min — must throttle
  input_tokens    : current 5000/min, max safe 6818/min — safe
  requests        : current 1/min,    max safe 35/min   — safe

summary: throttle required on tokens, output_tokens to keep 10% buffer at reset.
```

---

## Why `openclaw-cost-tracker-mcp`

Four things existing tools (provider billing dashboards, generic FinOps tools, custom scripts, even paid SaaS like [Lava](https://www.lava.so/) or [AgentShield](https://useagentshield.net/)) don't do well together:

1. **Per-agent attribution, not just per-provider totals.** Provider dashboards show "$X spent on Anthropic" — they can't tell you which of your six agents drove 78% of that. Cost tracker reads per-request cost-log JSONL and aggregates with the agent_id intact.

2. **Cost-spike anomaly detection per agent.** A single 120k-token paste into chat — or an unattended `/loop` running overnight — costs more than a week of normal traffic. The default 3x-median-per-agent threshold flags those before they show up in the month-end bill. Catches the same shape as the [$6k overnight thread](https://old.reddit.com/r/ClaudeAI/comments/1t11mmy/i_accidentally_burned_6000_of_claude_usage/) and the [silent re-routing patterns](https://old.reddit.com/r/ClaudeAI/comments/1svdm1w/psa_the_string_hermesmd_in_your_git_commit/) that vendor dashboards miss.

3. **Routing recommendations grounded in actual usage.** Generic "use cheaper models" advice is useless. This server identifies *specific* agents whose volume + completion-length pattern suggests a cheaper provider would deliver the same outcome, with concrete 30-day savings estimates.

4. **Local-only, MCP-native, no traffic interception.** Lava + similar paid gateways sit between your app and the provider — your traffic routes through them. AgentShield is a callback for LangChain/CrewAI/OpenAI SDK, not MCP. Cost-tracker is **read-only**: it parses your existing cost logs and surfaces them via MCP tools your Claude conversation can query directly. No proxy, no traffic routing, no subscription, no vendor lock-in.

Built for the **production-AI operator** running real workloads with real spend that matters — whether on OpenClaw, Claude Code with `claude -p`, raw Anthropic API, OpenAI Assistants, or any combination.

---

## Tool surface

| Tool | What it returns |
|------|-----------------|
| `cost_overview` | Total spend + by-provider + top agents + top models + anomaly count for a window |
| `costs_by_agent` | Per-agent breakdown with avg-cost-per-request + share of total |
| `costs_by_provider` | Per-provider breakdown with token counts |
| `find_cost_anomalies` | Requests flagged as 3x+ above their agent's median cost |
| `top_cost_drivers` | Top N spending agents + models, no other noise |
| `model_routing_recommendations` | Specific cheaper-model suggestions with 30d savings estimates |
| `forecast_monthly_cost` | Projects 30-day total + per-provider with confidence note |
| `current_quota_usage` *(v1.1)* | Per-dimension rate-limit utilization + most-pressured-dimension headline |
| `predict_429_in_window` *(v1.1)* | Projects per-dimension 429 ETA from recent burn rate. CRITICAL/WARNING/INFO severity |
| `recommend_throttle_target` *(v1.1)* | Max safe burn rate per dimension to land at `target_buffer_pct` headroom at reset |

Resources:
- `cost://overview` — 7-day snapshot
- `cost://forecast` — 30-day projection
- `cost://anomalies` — recent flagged anomalies
- `cost://quota` *(v1.1)* — current quota-state snapshot

Prompts:
- `diagnose-cost-spike` — walk a recent spike to its root cause + corrective action
- `weekly-cost-digest` — 200-word weekly cost digest
- `diagnose-quota-pressure` *(v1.1)* — walk current quota + burn rate, recommend a specific throttle action

---

## Quickstart

### Install

```bash
pip install openclaw-cost-tracker-mcp
```

### Configure for Claude Desktop

Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

```json
{
  "mcpServers": {
    "openclaw-cost": {
      "command": "python",
      "args": ["-m", "openclaw_cost_tracker_mcp"],
      "env": {
        "OPENCLAW_COST_BACKEND": "mock"
      }
    }
  }
}
```

### Backends

| Backend | Status | Description |
|---------|--------|-------------|
| `mock` | ✅ v1.0 | Sample data with deliberate anomalies + routing opportunities for protocol verification. **v1.1**: includes near-exhausted token-quota snapshot + recent loop-burst entries so `predict_429_in_window` returns CRITICAL out of the box |
| `openclaw-jsonl` | ✅ v1.0 | Parses OpenClaw's native cost-log JSONL files (default `~/.openclaw/cost-logs/`, configurable via `OPENCLAW_COST_LOGS`). **v1.1**: also parses optional `quota-snapshots.jsonl` in the same dir (one record per provider response, schema in `backends/openclaw_jsonl.py` docstring) |
| `provider-direct` | ⏳ v1.2 | Reads Anthropic + OpenAI billing APIs directly (no log shim required) |

### JSONL log format

Each line is one JSON record:

```json
{"request_id":"req-abc123","timestamp":"2026-05-04T12:34:56Z","provider":"anthropic","model":"claude-sonnet-4","agent_id":"data-extraction-agent","skill_id":"extract-structured-data","prompt_tokens":8500,"completion_tokens":600,"total_tokens":9100,"cost_usd":0.0345,"duration_ms":4823}
```

If your OpenClaw deployment doesn't emit this format, wrap your provider calls with a small logging shim — sample shim in `examples/`.

---

## Roadmap

| Version | Scope | Status |
|---------|-------|--------|
| v1.0 | mock + openclaw-jsonl backends, 7 tools / 3 resources / 2 prompts, anomaly detection + routing + forecast, GitHub Actions CI matrix, PyPI Trusted Publishing | ✅ |
| v1.1 | **Quota-window awareness** — `QuotaSnapshot` data model, `get_latest_quota_state()` backend method, 3 new tools (`current_quota_usage`, `predict_429_in_window`, `recommend_throttle_target`), `cost://quota` resource, `diagnose-quota-pressure` prompt. Reads `anthropic-ratelimit-*` headers (or equivalents) and projects per-dimension 429 ETA from recent burn rate. Folded in from research-pass-2 P01 candidate after incumbent validation against Lava + AgentShield + Nornr | ✅ |
| v1.2 | `provider-direct` backend (Anthropic + OpenAI billing API integrations); backend federation; budget alerts + threshold breach detection; `/loop` overnight-burn detector (folded from P05 watch-list candidate) | ⏳ |
| v1.x | Per-channel cost attribution; webhook emitter for budget + quota alerts | ⏳ |

---

## Need this adapted to your stack?

If your AI deployment doesn't use OpenClaw's cost-log format — different agent harness, custom logging, AWS Bedrock metering, vendor billing API — and you want the same attribution + anomaly + routing visibility, that's a **Custom MCP Build** engagement.

| Tier | Scope | Investment | Timeline |
|------|-------|------------|----------|
| Simple | Single backend adapter for your existing cost-data source | **$8,000–$10,000** | 1–2 weeks |
| Standard | Custom backend + custom anomaly rules + integration with your alerting | **$15,000–$20,000** | 2–4 weeks |
| Complex | Multi-backend federation + budget enforcement + custom routing logic | **$25,000–$35,000** | 4–8 weeks |

**To engage:**
1. Email **temur@pixelette.tech** with subject `Custom MCP Build inquiry`
2. Include: a 1-paragraph description of your stack + which tier you're considering
3. Reply within 2 business days with a 30-min discovery call slot

This server is part of a **production-AI infrastructure MCP suite** — companion to [silentwatch-mcp](https://github.com/temurkhan13/silentwatch-mcp) (cron silent-failure detection) and [openclaw-health-mcp](https://github.com/temurkhan13/openclaw-health-mcp) (deployment health). Install all three for full operational visibility.

---

## Production AI audits

If you're running production AI and want an outside practitioner to score readiness, find the failure patterns already present (cost overruns being one of the most common), and write the corrective-action plan:

| Tier | Scope | Investment | Timeline |
|------|-------|------------|----------|
| Audit Lite | One system, top-5 findings, written report | **$1,500** | 1 week |
| Audit Standard | Full audit, all 14 patterns, 5 Cs findings, 90-day follow-up | **$3,000** | 2–3 weeks |
| Audit + Workshop | Standard audit + 2-day team workshop + first monthly audit included | **$7,500** | 3–4 weeks |

Same email channel: **temur@pixelette.tech** with subject `AI audit inquiry`.

---

## Contributing

PRs welcome. Backends are pluggable — see `src/openclaw_cost_tracker_mcp/backends/` for the contract.

To add a new backend:

1. Subclass `CostBackend` in `backends/<your_backend>.py`
2. Implement `get_entries()` (cost telemetry); optionally override `get_latest_quota_state()` if your data source carries rate-limit headers (default returns `None` for graceful degrade)
3. Register in `backends/__init__.py`
4. Add tests in `tests/test_backend_<your_backend>.py`

Bug reports + feature requests: open a GitHub issue.

---

## License

MIT — see [LICENSE](./LICENSE).

---

## Related

- [Production-AI MCP Suite (Gumroad bundle)](https://temurah.gumroad.com/l/production-ai-mcp-suite) — this server plus 4 others in one curated bundle with a decision tree, day-one drill, and Custom MCP Build CTA. $99, or $49 with `LAUNCH50` for the first 30 days.
- [silentwatch-mcp](https://github.com/temurkhan13/silentwatch-mcp) — cron silent-failure detection
- [openclaw-health-mcp](https://github.com/temurkhan13/openclaw-health-mcp) — deployment health
- [openclaw-skill-vetter-mcp](https://github.com/temurkhan13/openclaw-skill-vetter-mcp) — ClawHub skill security vetting
- [openclaw-upgrade-orchestrator-mcp](https://github.com/temurkhan13/openclaw-upgrade-orchestrator-mcp) — read-only upgrade advisor
- [AI Production Discipline Framework](https://temurah.gumroad.com/l/ai-production-discipline-framework) — Notion template, $29 — the methodology these MCP tools implement (cost overruns are pattern P3.x in the catalog)
- [SPEC.md](./SPEC.md) — full server design

---

Built by [Temur Khan](https://www.notion.so/@temurkhan) — independent practitioner on production AI systems.
Contact: **temur@pixelette.tech**
