
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 分