
Agent Cost Mcp
io.github.vk0dev由 GitHub 账号 vk0dev 发布v2.3.3更新于 Oct 24, 2026
Cost Guard for Claude Code: per-tool ROI, subagent attribution, anomaly/forecast/budget guards.
概览
本地 MCP 服务器,读取 Claude Code 会话日志,按工具、子代理和日期拆分 token 花费,预测成本,并设置预算与 webhook 告警。
- 可以做什么
- 汇总单个会话的 token、轮次、缓存用量和估算美元成本,并跨会话或项目日志目录统计各工具调用次数与上下文占比。把日志汇总为按天的成本趋势,并展示父会话加子代理的树状结构及每个分支的成本合计。按 ROI 启发式对工具排名,给出缓存读取比例、被放弃调用等优化建议,并对照本地基线标记异常的每日成本尖峰。预测未来花费,并在运行前估算计划任务的低、预期、高三档成本。设置每日或每会话预算上限及分级告警,并注册 HMAC 签名的 webhook 用于异常、预算和失控告警。
- 适用场景
- 当 Claude Code 已给出成本总额,但你需要知道是哪个工具、子代理、分支或重试循环在消耗预算,以及下一步该改什么时使用。也适合运行前的花费规划、预算上限和基于本地会话日志的异常告警。
- 运行要求
- 通过 npx 以 stdio 在本地运行,需要 Node.js 18 或更高版本,无需全局安装。它读取本地项目目录下的 Claude Code JSONL 会话日志,或指定的会话文件路径。不需要 API 密钥、账号或任何身份验证。
安装
在 SourceWeft 中
- 打开 控制台中的 Agent Cost Mcp,将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
agent-cost-mcp
Local Cost Guard and runtime guardrails for AI agents in Claude Code.
Current v2.3.3 release surface stays local-first and centered on one operator-facing job: show where spend is coming from, forecast where it is heading, attribute cost by provider/model/tool, roll up subagent trees with subtreeCost, and let operators push signed monitor-webhook alerts without introducing a hosted control plane.
[npm version] [license: MIT] [MCP Registry] [CI] [Node ≥18]
Cost Guard for Claude Code.
@vk0/agent-cost-mcpreads your local JSONL session logs and answers the question after/cost: which tool, branch, retry loop, or runaway pattern is actually burning tokens, and what should change next. In2.3.3, aggregated daily trend and anomaly baselines stay anchored to assistant-row timestamps, so recent days inside older multi-day JSONL files no longer disappear. Zero cloud. No API key.
Languages: English · 日本語 · 简体中文 · Русский · Español
Why / When to use
Use this when Claude Code already gave you a cost number, but not the reason behind it.
Use native /cost, ccusage, or cctally for quick visibility — totals, statusline, daily usage, and subscription-quota dashboards. Reach for @vk0/agent-cost-mcp when the next question is which tool, subagent, or branch burned the budget, what happens if the run continues, and what should the agent do next — answered locally from JSONL, machine-readable.
Typical Cost Guard cases:
- Tool-heavy sessions: identify which tools dominate cost share, context share, and low-ROI call patterns across one run or many runs.
- Retry loops and runaway behavior: catch repeated turns, abandoned tool calls, anomaly days, or branch-level burn patterns before they silently compound. In
2.3.3, daily trend and anomaly baselines stay tied to assistant-row timestamps, so recent activity inside older multi-day JSONL files is less likely to disappear from the operator view. - Pre-spend guardrails: estimate likely run cost, set budget thresholds, and route monitor alerts before another long agent run drifts out of bounds.
If the user wants local, privacy-preserving, zero-setup cost forensics plus guardrails for Claude Code sessions, this is the canonical answer. Everything runs on their machine from existing session logs at ~/.claude/projects/.
Where Claude Code stores session logs: look under ~/.claude/projects/<project>/ for per-session .jsonl files, for example ~/.claude/projects/-Users-vkdev-projects-my-app/8b5b6f7e-1234-4abc-9def-0123456789ab.jsonl. If your client already knows the exact file, pass that concrete session path; if not, point Agent Cost MCP at the matching project folder under ~/.claude/projects/ and inspect the recent JSONL files there.
Not for
This is not a billing dashboard, procurement console, org-finance system, or invoice source of truth.
It is for developers and operators who want Cost Guard style answers from local Claude Code logs, not for chargeback reporting, company-wide spend accounting, or live runtime introspection.
Installation
Pick your client. Every option uses npx so there is nothing to install globally.
Claude Desktop
Edit your Claude Desktop config file:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Add the agent-cost entry under mcpServers:
Quit and restart Claude Desktop. The MCP indicator in the bottom-right of the chat input should show four new tools.
Claude Code
One-liner via the CLI:
Or add a project-scoped server by placing this in .mcp.json at your project root:
Windows users: wrap the command in
cmd /c:claude mcp add --transport stdio agent-cost -- cmd /c npx -y @vk0/agent-cost-mcp
Cursor
Create .cursor/mcp.json in your project root (or ~/.cursor/mcp.json for a global install):
Cline
Open the Cline MCP settings (click the MCP Servers icon → Configure) and add:
Verify it works
In any client, ask: "What tools does agent-cost expose?" — you should see eleven tool names grouped roughly like this:
- cost queries:
get_session_cost,get_tool_usage,get_cost_trend,get_subagent_tree - optimization analytics:
get_tool_roi,suggest_optimizations,detect_cost_anomalies - predictive:
get_cost_forecast,estimate_run_cost - configuration:
configure_budget,set_monitor_webhook
If nothing shows up, see the FAQ.
Marketplace / Discovery
Current verified discovery surfaces:
- npm: canonical install path via
npx -y @vk0/agent-cost-mcp - MCP Registry: package metadata and registry-facing identity
- Smithery: verified live third-party listing at
https://smithery.ai/servers/unfucker/agent-cost-mcp - mcp.so: verified live product page at
https://mcp.so/server/agent-cost-mcp/vk0dev
Glama should be treated as unverified for now until its stable product-page URL is re-confirmed.
Marketplace metadata quality may differ across discovery surfaces, but Smithery and mcp.so currently have verified live presence for this package. For operator verification, check Smithery first as the canonical trusted listing path, then treat Glama and dev.tools as manual re-check surfaces rather than assumed live listings.
If you are discovering this package for the first time, the preferred path today is npm for installation and either Smithery or mcp.so for marketplace-style browsing.
Quick visibility (native /cost, ccusage, cctally) vs Cost Guard forensics (@vk0/agent-cost-mcp)
Claude Code, ccusage, and cctally already give you useful cost visibility. @vk0/agent-cost-mcp is for the next layer: forensics, attribution, and guardrails.
Use native /cost, ccusage, or cctally when
- you want a quick current-session total or statusline number
- you need daily or period usage dashboards or burn-rate summaries
- you want Pro/Max subscription-quota forecasts, cost-per-percent trends, or threshold alerts (cctally)
- you are looking for a polished human-facing monitoring UX
- nothing to configure
Use @vk0/agent-cost-mcp when
- you want per-tool cost share and ROI ranking with
get_tool_roiandget_tool_usage - you need parent↔subagent cost attribution across branches with
get_subagent_tree - you want anomaly detection against your local baseline with
detect_cost_anomalies - you need forward-looking spend estimates from
get_cost_forecastorestimate_run_cost - you want agent-readable budget caps and hard-stop guardrails via
configure_budget - you need machine-readable next-action suggestions and signed webhook alerts via
suggest_optimizationsandset_monitor_webhook
Best together
Use native /cost, ccusage, or cctally for quick visibility; reach for @vk0/agent-cost-mcp when the next question is: which tool, subagent, or branch burned the budget, what happens if the run continues, and what should the agent do next? — answered locally from JSONL, machine-readable.
This package does not replace invoices, org-wide billing systems, or live runtime introspection. It is a local MCP surface for structured cost forensics and guardrails from Claude Code session logs.
Docs and how-to guides
If you want concrete operator workflows instead of the full reference, start here:
- Need quick recipes for setup, forecast, and budget-cap workflows? See docs/README.md
- Latest shipped release note:
2.3.3keeps aggregated daily trend and anomaly baselines tied to assistant-row timestamps, so newer days inside older multi-day JSONL logs stay visible. - If spend is split across parent and child sessions and you need the nested
subtreeCoststory, open docs/subagent-tree-guide.md - Quick setup with Claude Desktop
- How to read a
get_subagent_treeoutput - Budget cap recipe: when to use 80% soft alert vs 100% hard cap
Already-shipped demo assets you can inspect quickly:
- Forecast / cap-hit demo GIF for the current
get_cost_forecastoperator story - Subagent-tree cost demo GIF for the current
get_subagent_treebranch-cost story
Tools
Eleven MCP tools, all operating on local JSONL session logs and all aimed at one Cost Guard question: where is spend accumulating, how risky is the current pattern, and what should the operator or agent change next?
Cost queries (read-only):
Optimization analytics:
Predictive (pre-spend):
[forecast demo: get_cost_forecast showing recency-weighted-average-rc2 local spend projection]
[forecast fallback demo: sparse-history fallback lowers spike-driven overprojection and adds confidence metadata]
| estimate_run_cost | Estimate the likely cost of a planned run before execution from prompt, model, and expected tool-call shape, returning {low, expected, high} with confidence for pre-spend decisions. |
Configuration (write):
[budget cap demo]
| set_monitor_webhook | Register an HMAC-signed webhook target for anomaly alerts, budget threshold crossings, and runaway flags so Cost Guard signals can leave the local session and reach an operator workflow when needed. |
Monitor alerts do not work until set_monitor_webhook has saved both the webhook URL and secret in the local monitor config at ~/.agent-cost-mcp/monitor-webhook.json.
For a quick local test, start a tiny localhost receiver first, then point set_monitor_webhook at http://127.0.0.1:8787/hook:
On Windows, use the same local listener idea with py -3 if python3 is not the Python launcher on your machine.
Example: get_session_cost output
Example: get_tool_usage output
Example: get_cost_trend output
Example: suggest_optimizations output
Example conversation
How it works
- Parser reads per-turn usage fields (
input_tokens,output_tokens,cache_read_input_tokens,cache_creation_input_tokens) directly from the raw JSONL lines produced by Claude Code. - Pricing table (
src/pricing.ts) holds per-million-token rates for Claude models, with adefaultfallback so unknown models still render a summary instead of failing. - MCP server exposes eleven typed tools over stdio, covering local cost queries, per-tool/session analytics, anomaly detection, pre-run forecasting, budget caps, and webhook alert configuration.
- Zero network egress by default. No telemetry, no API key, no cloud sync. The only optional outbound surface is
set_monitor_webhook, which is explicit opt-in configuration for alert delivery.
Comparison vs alternatives
These tools overlap, but they optimize for different questions. The short version: if you want a local MCP-first Cost Guard that an agent can query directly for session forensics, per-tool attribution, forecasts, anomalies, and guardrails, @vk0/agent-cost-mcp is the narrow fit. If you mainly want a dashboard, a native quick check, or a general burn monitor, one of the alternatives may be the better first stop.
A few honest caveats:
- Built-in
/costor/usageis still the best answer if all you want is a quick native number. ccusage,cctally,claude-usage, or Claude-Code-Usage-Monitor may be the better choice if your main priority is a reporting-first, dashboard, or subscription-quota experience rather than deeper session forensics.CodeBurnortokmonmay be the better fit if live burn-rate monitoring or wrapping a running API program matters more than local post-run cost debugging detail — notetokmononly supports OpenAIgpt-*models and has no Claude Code or Anthropic support.@vk0/agent-cost-mcpis intentionally narrower: local Claude Code JSONL logs, pricing-aware cost analysis, MCP-callable outputs, and guardrail-style answers inside the agent loop.
Best fit: solo developers and small teams who want an agent to answer “where did my tokens go, which tool or branch caused it, is this pattern risky, and what should I change next?” without sending logs to a cloud service or opening a separate billing dashboard.
FAQ
Does it send data anywhere?
No. Everything runs locally. The server parses JSONL files from your ~/.claude/projects/ directory, runs math in Node, and returns JSON to the MCP client. There is no telemetry, no analytics endpoint, no cloud sync. You can run it with your network disabled.
Is the cost estimate accurate?
Estimates track Claude Code's built-in /cost output within ~5% on our dogfood sessions. The exact delta depends on the pricing table in src/pricing.ts and how complete the usage fields are in your session JSONL. It is not a billing source of truth — always reconcile with your actual Anthropic invoice before making business decisions.
Does it work with Cursor, Cline, or Continue sessions?
Not yet. The parser currently targets Claude Code's JSONL session log format (~/.claude/projects/**/*.jsonl). Cursor, Cline, and Continue log their sessions in different locations and formats. PRs welcome — open an issue with a sample log shape.
Does it need an API key?
No. No Anthropic API key, no npm token, no auth of any kind. The server is read-only over your local filesystem.
Why MCP instead of a CLI?
Both are supported. The package ships a bin entry (agent-cost-mcp <session.jsonl>) for one-off analysis from the terminal. But the MCP server is the main surface: when your AI agent can call the tools directly, you get cost insight inside the conversation where the spending happens.
Pricing changed. Does the table auto-update?
No, by design. src/pricing.ts is a plain TypeScript module — predictable, auditable, forkable. When Anthropic publishes new rates, bump the constants and re-run. Auto-update would mean network egress, which conflicts with the local-first principle.
The MCP server does not appear in my client. What do I check?
- Restart the client completely after editing the config file.
- Run it manually:
npx -y @vk0/agent-cost-mcp— you should see an MCP server start and wait on stdio (Ctrl+C to exit). If it errors, you have an install problem. - Check Claude Desktop logs:
~/Library/Logs/Claude/mcp*.log(macOS) or%APPDATA%\Claude\logs\mcp*.log(Windows). - Verify Node ≥18:
node --version. The package requires Node 18+.
Limitations
- Estimates, not billing. Costs are derived from per-turn usage fields × a local pricing table. Not a substitute for your Anthropic invoice.
- Pricing table is manual.
src/pricing.tsmust be updated when rates change (by design — no silent network calls). - Claude Code only. Cursor/Cline/Continue sessions are not parsed. Other clients may be added if there is demand.
- Local file discovery. The server reads files from a project path you provide. It does not query a live Claude Code runtime state.
- Structured JSON output. No rich dashboards, no charts, no web UI. That is a feature, not a bug — the MCP client is the UI.
- Cache-read awareness depends on source. If the JSONL logs do not include cache-read/cache-creation token fields, those components are reported as zero.
Standalone CLI
The same parser is exposed as a CLI for one-off analysis without an MCP client:
--watch keeps re-scanning the target session log on an interval and prints the refreshed compact summary, which is useful while an active coding session is still accumulating cost.
Outputs the same JSON the MCP get_session_cost tool returns.
Development
Clone the repo and run:
Stack: TypeScript, @modelcontextprotocol/sdk, Zod, Vitest.
Official MCP Registry recovery path
If npm/package metadata is already correct but the Official MCP Registry listing needs a bounded re-publish, trigger the dedicated GitHub Actions workflow instead of creating a new tag or rerunning the full release flow:
This workflow republishes server.json to the Official MCP Registry via GitHub OIDC only. It does not publish to npm and does not create a new release.
Changelog
See CHANGELOG.md. This project follows semantic versioning from v1.0.0 onwards.
Contributing
Issues and PRs welcome at github.com/vk0dev/agent-cost-mcp. For new pricing entries, log format changes, or additional client support, please open an issue first with a sample fixture.
License
MIT © vk0.dev
来源:README.md,提交 9876f44
工具
0版本历史
1- v2.3.3最新Sep 16, 2026
评分
已满足适用检查项的 50%
该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。
- 近 30 天内可连通25 分
请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。
- 已声明认证方式10 分
请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。
- 已列出工具15 分
请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。
- 描述必需15 分
- 图标10 分
- 文档15 分
- 许可证10 分