Mcp Cost Tracker Router

io.github.dbsectrainer由 GitHub 帳號 dbsectrainer 發布v1.0.1更新於 Nov 4, 2026

Real-time cost awareness for MCP agent workflows

發布方自己的服務:370.ai — AI Gateway: 100+ Chat Models, Image & Speech Generation

概覽

AI 產生的概覽

本機 MCP 伺服器,用來統計代理工作階段的 token 用量與估算美元成本、發出預算警示並建議更省錢的模型路由。

可以做什麼
  • 檢視目前工作階段及依工具劃分的 token 總量與估算美元成本,並記錄工具呼叫的用量
  • 設定預算門檻並在達到 80%/100% 時警示,可選擇阻擋超限呼叫,並匯出執行稽核日誌
  • 依日、週、月查詢歷史花費及模型與工具明細,並在執行前估算多步驟工作流程成本
  • 依任務類型推薦模型,並檢查某模型在路由策略下是否被允許
  • 將工作階段標記到專案、檢視專案成本並匯出分攤報告
  • 產生單一檔案 HTML 花費報告
適用情境
適合使用付費 LLM API 執行代理工作流程、想了解哪些工具與模型最花錢,並在超出預算前取得提醒的情境。也適合希望成本資料留在本機而不經過代理服務的團隊。
執行需求
透過 npx 以 npm 套件形式在本機執行,需要 Node.js v20.19 或更新版本及 npm。宣告了一個名為 YOUR_API_KEY 的必需密鑰環境變數。選用參數可設定預算警示、SQLite 資料庫路徑(預設 ~/.mcp/costs.db)、自訂價格表、預設模型、預算強制執行以及 HTTP 傳輸埠。
安裝前請注意
成本是依本機價格表估算,可能與供應商帳單不一致。啟用 --enforce-budget 後,達到門檻時工具呼叫可能被阻擋。工具呼叫中繼資料(token 數、模型名稱、時間戳記)會存入本機 SQLite 檔案,但不儲存提示詞與回覆內容。清單宣告了必需的 YOUR_API_KEY 密鑰,而 README 未說明其用途。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Mcp Cost Tracker Router,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

MCP Cost Tracker & Router

npm mcp-cost-tracker-router package

Local-first cost awareness for MCP agent workflows. Token counts are calculated offline using js-tiktoken — no proxy, no API round-trip, no spend data leaving your machine. When costs climb, routing suggestions point you to cheaper models before the invoice arrives.

Tool reference | Configuration | Contributing | Troubleshooting

Key features

  • Per-tool cost breakdown: See exactly which tool calls are consuming the most tokens and budget.
  • Budget alerts: Set a session spend threshold and get warned at 80% and 100% before you exceed it.
  • Offline token counting: Uses js-tiktoken for accurate counts — no API calls required.
  • Model routing suggestions: Recommends cheaper models for the current task type (advisory, never enforced without opt-in).
  • Multi-provider pricing: Tracks costs across Claude, OpenAI, and Gemini models from a single configurable pricing table.
  • Spend history: Query daily, weekly, and monthly totals by model or tool.
  • Project cost allocation: Tag sessions to named projects and generate chargeback reports.
  • HTML spend reports: Export a single-file, self-contained HTML report with charts and budget status.
  • Audit log: Append-only log of every budget enforcement decision.

Why this over proxy-based cost trackers?

Most cost-tracking tools work by routing all your API traffic through their server and measuring tokens server-side. That means your prompts and responses transit a third-party service, and you're dependent on their uptime.

mcp-cost-tracker-routerProxy-based trackers (Helicone, LLMonitor, etc.)
Token countingOffline via js-tiktoken — no network callCounted server-side after traffic is proxied
Data residencyLocal SQLite onlyPrompts + responses pass through vendor servers
Model routingBuilt-in suggest_model_routing toolRarely included; usually a separate paid tier
Multi-providerClaude, OpenAI, Gemini in one pricing tableOften single-provider or requires separate setup
Uptime dependencyNone — fully offlineBreaks if proxy is down

If your prompts contain sensitive information or you can't route traffic through a third party, this is the right tool. If you need a managed dashboard with team sharing, a proxy-based service may suit you better.

Disclaimers

mcp-cost-tracker-router stores tool call metadata (token counts, model names, timestamps) locally in SQLite. It does not store prompt or response content. Cost calculations are estimates based on a local pricing table and may not exactly match your provider's invoice.

Requirements

  • Node.js v20.19 or newer.
  • npm.

Getting started

Add the following config to your MCP client:

json
{  "mcpServers": {    "cost-tracker": {      "command": "npx",      "args": ["-y", "mcp-cost-tracker-router@latest"]    }  }}

To set a session budget alert:

json
{  "mcpServers": {    "cost-tracker": {      "command": "npx",      "args": ["-y", "mcp-cost-tracker-router@latest", "--budget-alert=5.00"]    }  }}

MCP Client configuration

Amp · Claude Code · Cline · Cursor · VS Code · Windsurf · Zed

Your first prompt

Enter the following in your MCP client to verify everything is working:

How much has this session cost so far?

Your client should return a token and USD cost summary for the current session.

Tools

Session (4 tools)

  • get_session_cost — Returns token totals and USD cost estimates for the current session. Read-only.
  • get_tool_costs — Returns per-tool cost breakdown for the session, sorted by cost descending. Read-only.
  • reset_session — Start a new cost-tracking session. Previous session data is retained in history.
  • record_usage — Record token usage for a tool call. Takes tool_name, model (optional), input_tokens, and output_tokens. Emits a budget warning notification if 80% of threshold is reached.

Budgets & routing (3 tools)

  • set_budget_alert — Set a budget threshold in USD (threshold_usd). Warns at 80% and 100% of the threshold. Use with --enforce-budget to block calls beyond the limit.
  • suggest_model_routing — Heuristic model recommendation by task type. Takes task_description and optional constraints.max_cost_usd. Returns recommended model with reasoning and estimated cost.
  • check_routing_policy — Check whether a model is allowed for a given task type under the routing policy. Takes task_type and model.

History & reports (4 tools)

  • get_spend_history — Query historical spend aggregated by period (day/week/month). Returns breakdown by model and tool. Read-only.
  • estimate_workflow_cost — Pre-run cost estimation for a multi-step workflow. Takes a steps array with tool_name, estimated_input_tokens, estimated_output_tokens, and optional model. Read-only.
  • export_spend_report — Generate a single-file HTML spend report with session breakdown, historical spend, model cost comparison, and budget status. Read-only.
  • export_budget_audit — Export the audit log of budget enforcement decisions. Accepts optional from_date, to_date, and format (json/csv). Read-only.

Project allocation (4 tools)

  • set_project — Create or update a project with an optional budget_usd. Takes project_name.
  • tag_session — Tag the current session with a project_name for cost allocation.
  • get_project_costs — Get cost report for a project. Takes project_name and optional since (ISO date). Read-only.
  • export_chargeback — Generate a chargeback report for internal billing. Takes from_date, to_date, optional group_by (project/session), and optional format (json/csv). Read-only.

Configuration

--budget-alert

Session spend threshold in USD. A warning is returned when session costs reach 80% and again at 100% of this threshold.

Type: number

--db / --db-path

Path to the SQLite database file used to store cost history.

Type: string Default: ~/.mcp/costs.db

--pricing-table

Path to a JSON file containing custom model pricing ($/1K tokens). Merged with the built-in table; missing models fall back to defaults.

Type: string

--default-model

Model name to attribute costs to when no model can be inferred from context.

Type: string Default: claude-sonnet-4-6

--enforce-budget

Block tool calls that would cause the session to exceed the budget alert threshold. Requires --budget-alert to be set.

Type: boolean Default: false

--http-port

Start in HTTP mode using Streamable HTTP transport instead of stdio. Useful for sharing a single cost-tracking instance across a team.

Type: number Default: disabled (uses stdio)

Pass flags via the args property in your JSON config:

json
{  "mcpServers": {    "cost-tracker": {      "command": "npx",      "args": [        "-y",        "mcp-cost-tracker-router@latest",        "--budget-alert=2.00",        "--enforce-budget"      ]    }  }}

Supported models and pricing

Built-in pricing table (USD per 1K tokens):

ModelInputOutput
claude-opus-4-6$0.0150$0.0750
claude-sonnet-4-6$0.0030$0.0150
claude-haiku-4-5$0.0008$0.0040
gpt-4o$0.0025$0.0100
gpt-4o-mini$0.000150$0.000600
gemini-1.5-pro$0.001250$0.005000
gemini-1.5-flash$0.000075$0.000300
gemini-2.0-flash$0.000100$0.000400

Override individual model prices with --pricing-table. All costs are estimates.

Verification

Before publishing a new version, verify the server with MCP Inspector to confirm all tools are exposed correctly and the protocol handshake succeeds.

Interactive UI (opens browser):

bash
npm run build && npm run inspect

CLI mode (scripted / CI-friendly):

bash
# List all toolsnpx @modelcontextprotocol/inspector --cli node dist/index.js --method tools/list
# List resources and promptsnpx @modelcontextprotocol/inspector --cli node dist/index.js --method resources/listnpx @modelcontextprotocol/inspector --cli node dist/index.js --method prompts/list
# Call a read-only toolnpx @modelcontextprotocol/inspector --cli node dist/index.js \  --method tools/call --tool-name get_session_cost
# Call record_usage with argumentsnpx @modelcontextprotocol/inspector --cli node dist/index.js \  --method tools/call --tool-name record_usage \  --tool-arg tool_name=my_tool --tool-arg input_tokens=500 --tool-arg output_tokens=200

Run before publishing to catch regressions in tool registration and runtime startup.

Contributing

Update src/pricing.ts when new models are released. All cost calculation changes must include unit tests with known token counts and expected USD values. Routing suggestions live in src/tools/routing.ts.

bash
npm install && npm test

MCP Registry & Marketplace

This plugin is available on:

Search for mcp-cost-tracker-router.

來源:README.md,提交 7a8f731

工具

15

get_session_cost

Returns token totals and USD cost estimates for the current session. All costs are estimates; verify with your LLM provider's billing dashboard.

無需輸入參數。

get_tool_costs

Returns per-tool cost breakdown for the current session, sorted by cost descending. Useful for identifying the most expensive operations. All costs are estimates.

無需輸入參數。

set_budget_alert

Set a budget threshold in USD. A warning is emitted when session costs reach 80% or 100% of this threshold. Use with --enforce-budget to block calls beyond the limit.

輸入參數threshold_usd必填

reset_session

Start a new cost-tracking session. Previous session data is retained in history and accessible via get_spend_history.

無需輸入參數。

get_spend_history

Query historical spend aggregated by time period (day/week/month). Returns breakdown by model and tool across all sessions. All costs are estimates.

輸入參數period

record_usage

Record token usage for a tool call. Logs LLM API cost estimates into the tracker. Emits a budget warning (notifications/message) if 80% of threshold is reached. Pricing table versions are tracked in CHANGELOG.md.

輸入參數modeltool_name必填input_tokens必填output_tokens必填

suggest_model_routing

Heuristic model recommendation by task type. Analyzes the task description and returns a recommended model with reasoning and estimated cost per 1K tokens. Optionally factors in cost constraints.

輸入參數constraintstask_description必填

estimate_workflow_cost

Pre-run cost estimation for a multi-step workflow. Provide a list of tool steps with estimated token counts and models to get total and per-step cost estimates. Output is clearly labeled as ESTIMATE.

輸入參數steps必填

export_spend_report

Generate a single-file HTML spend report with session cost breakdown, historical spend by period, model cost comparison chart (CSS bars), and budget status. No external CDN dependencies.

無需輸入參數。

export_budget_audit

Export audit log of budget enforcement decisions. Optionally filter by date range and format as JSON or CSV.

輸入參數formatto_datefrom_date

set_project

Create or update a project with an optional budget in USD.

輸入參數budget_usdproject_name必填

get_project_costs

Get cost report for a project, optionally filtered by a since date.

輸入參數sinceproject_name必填

tag_session

Tag the current session with a project name for cost allocation.

輸入參數project_name必填

export_chargeback

Generate a chargeback report for internal team billing, grouped by project or session.

輸入參數formatto_date必填group_byfrom_date必填

check_routing_policy

Check whether a model is allowed for a given task type under the routing policy.

輸入參數model必填task_type必填

版本歷史

2
  1. v1.0.1最新Nov 4, 2026
  2. v1.0.0Sep 16, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分
  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分

其他 Router 整合