MCP Server

MCP Server

The Metrx MCP Server (@metrxbot/mcp-server) exposes 23 cost intelligence tools via the Model Context Protocol that any MCP-compatible AI agent — Claude, GPT, Gemini, or custom agents — can call to track costs, optimize models, manage budgets, and prove ROI.

Version: 0.2.5 · License: MIT · npm

stdio vs hosted. The numbers above describe the npm package you install with npx — 23 tools across 10 domains. The hosted endpoint at https://metrxbot.com/api/mcp is built from the Metrx monorepo and currently runs ahead of it: 38 tools across 14 domains, adding health scores and rankings, the upgrade business case, the three verification-billing tools, and the three loop-metrics and loop-object tools. Those fourteen are not available over stdio.


Quick Start

1. Get an API key

Sign up at app.metrxbot.com and copy your key from Settings → Security.

2. Test the connection

METRX_API_KEY=sk_live_xxx npx @metrxbot/mcp-server --test

3. Add to your MCP client

Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "metrx": {
      "command": "npx",
      "args": ["@metrxbot/mcp-server"],
      "env": {
        "METRX_API_KEY": "sk_live_your_key_here"
      }
    }
  }
}

Cursor (.cursor/mcp.json):

{
  "mcpServers": {
    "metrx": {
      "command": "npx",
      "args": ["@metrxbot/mcp-server"],
      "env": {
        "METRX_API_KEY": "sk_live_your_key_here"
      }
    }
  }
}

Windsurf (~/.codeium/windsurf/mcp_config.json):

{
  "mcpServers": {
    "metrx": {
      "command": "npx",
      "args": ["@metrxbot/mcp-server"],
      "env": {
        "METRX_API_KEY": "sk_live_your_key_here"
      }
    }
  }
}

Environment Variables

VariableRequiredDescription
METRX_API_KEYYesYour Metrx API key (sk_live_* or sk_test_*)
METRX_API_URLNoOverride API base URL (default: https://app.metrxbot.com/api)

Tools Reference

All tools are prefixed with metrx_ in MCP (e.g., metrx_get_cost_summary).

Dashboard (3 tools)

metrx_get_cost_summary

Get a comprehensive cost summary for your AI agent fleet.

ParameterTypeDefaultDescription
daysnumber (1–90)30Number of days to include

Returns total spend, call counts, error rates, agent breakdown, revenue attribution, and optimization opportunities.

metrx_list_agents

List all AI agents in your organization.

ParameterTypeDefaultDescription
statusactive | idle | error | archivedFilter by status
categorystringFilter by category (e.g., “sales”, “support”)

metrx_get_agent_detail

Get detailed information about a specific agent.

ParameterTypeDefaultDescription
agent_idUUIDrequiredThe agent UUID to look up

Optimization (4 tools)

metrx_get_optimization_recommendations

Get AI-powered cost optimization recommendations including model switching, token guardrails, provider arbitrage, and revenue intelligence insights.

ParameterTypeDefaultDescription
agent_idUUIDSpecific agent to analyze (omit for fleet-wide)
include_revenuebooleantrueInclude revenue-side insights

metrx_apply_optimization

Apply a one-click optimization recommendation to an agent. Only works for suggestions marked as one_click: true.

ParameterTypeDefaultDescription
agent_idUUIDrequiredThe agent to optimize
optimization_typestringrequiredType of optimization (e.g., “token_guardrails”, “model_switch”)
payloadobjectOverride the default optimization payload

metrx_route_model

Get a model routing recommendation for a specific task based on complexity. Routes simple tasks to cheaper models while keeping complex tasks on premium models.

ParameterTypeDefaultDescription
agent_idUUIDrequiredThe agent to route for
task_complexitylow | medium | highrequiredEstimated task complexity
current_modelstringCurrently configured model (e.g., “gpt-4o”)

metrx_compare_models

Compare LLM model pricing and capabilities across providers. Works without usage data (Day 0 value).

ParameterTypeDefaultDescription
current_modelstringModel to compare against (e.g., “gpt-4o”)
tierfrontier | balanced | efficient | budgetCapability tier filter
providerstringProvider filter (e.g., “openai”, “anthropic”, “google”)

Budgets (3 tools)

metrx_get_budget_status

Get the current status of all budget configurations. Shows spending vs limits, warning/exceeded counts, and enforcement modes.

No parameters.

metrx_set_budget

Create or update a budget configuration for an agent or the entire organization.

ParameterTypeDefaultDescription
agent_idUUIDAgent to set budget for (omit for org-wide)
perioddaily | monthlyrequiredBudget period
limit_dollarsnumberrequiredSpending limit in dollars
warning_pctinteger (1–99)80Percentage that triggers a warning
enforcement_modealert_only | soft_block | hard_blockalert_onlyHow to enforce the limit

metrx_update_budget_mode

Change the enforcement mode of an existing budget or pause/resume it.

ParameterTypeDefaultDescription
budget_idUUIDrequiredBudget configuration ID
enforcement_modealert_only | soft_block | hard_blockNew enforcement mode
pausedbooleanPause or resume the budget

Alerts (3 tools)

metrx_get_alerts

Get active alerts and notifications — cost spikes, error rate increases, budget warnings, and system health notifications.

ParameterTypeDefaultDescription
severityinfo | warning | criticalFilter by severity
unread_onlybooleantrueOnly return unread alerts
limitinteger (1–100)25Maximum alerts to return

metrx_acknowledge_alert

Mark one or more alerts as read/acknowledged.

ParameterTypeDefaultDescription
alert_idsUUID[] (1–50)requiredAlert IDs to acknowledge

metrx_get_failure_predictions

Get predictive failure analysis — upcoming risk of error rate breaches, latency degradation, cost overruns, and budget exhaustion.

ParameterTypeDefaultDescription
agent_idUUIDFilter for a specific agent
severityinfo | warning | criticalFilter by severity
statusactive | acknowledged | resolvedactiveFilter by status

Experiments (3 tools)

metrx_create_model_experiment

Start an A/B test comparing two LLM models. Routes a percentage of traffic to the treatment model and tracks cost, latency, error rate, and quality metrics.

ParameterTypeDefaultDescription
agent_idUUIDrequiredAgent to run the experiment on
namestring (1–100)requiredHuman-readable experiment name
treatment_modelstringrequiredCandidate model (e.g., “gpt-4o-mini”)
traffic_pctinteger (1–50)10Percentage of traffic to the treatment
primary_metriccost_per_call | latency_p50 | latency_p95 | error_rate | quality_scorecost_per_callMetric to optimize for
max_duration_daysinteger (1–30)14Maximum experiment duration
auto_promotebooleanfalseAuto-apply the winner when experiment concludes

metrx_get_experiment_results

Get results of a model experiment — sample counts, metric comparisons, statistical significance, and the current winner.

ParameterTypeDefaultDescription
agent_idUUIDFilter by agent
statusrunning | paused | completed | cancelledFilter by status

metrx_stop_experiment

Stop a running experiment. Results are preserved.

ParameterTypeDefaultDescription
experiment_idUUIDrequiredExperiment ID to stop
promote_winnerbooleanfalseApply the winning model as the new default

Cost Leak Detector (1 tool)

metrx_run_cost_leak_scan

Run a comprehensive cost leak audit. Identifies 7 types of cost inefficiencies: idle agents, model overprovisioning, missing caching, high error rates, context bloat, missing budgets, and cross-provider arbitrage opportunities.

ParameterTypeDefaultDescription
agent_idUUIDScan a specific agent (omit for fleet-wide)
include_low_severitybooleanfalseInclude low-severity findings
output_formattext | jsontextOutput format (json for CI/CD pipelines)

Attribution (3 tools)

metrx_attribute_task

Link an agent task/event to a business outcome for ROI tracking.

ParameterTypeDefaultDescription
agent_idUUIDrequiredAgent to attribute
event_idstringSpecific event/task ID
outcome_typerevenue | cost_saving | efficiency | qualityrequiredType of outcome
outcome_sourcestripe | calendly | hubspot | zendesk | webhook | manualrequiredSource of the outcome data
value_centsintegerOutcome value in cents
descriptionstringDescription of the outcome

metrx_get_task_roi

Calculate return on investment for an agent — total costs, total outcomes, ROI multiplier, and breakdown by model and outcome type.

ParameterTypeDefaultDescription
agent_idUUIDrequiredAgent to calculate ROI for
daysinteger (1–365)30Number of days to analyze

metrx_get_attribution_report

Get an attribution report showing which agent actions led to business outcomes.

ParameterTypeDefaultDescription
agent_idUUIDFilter to specific agent
daysinteger (1–365)30Number of days to include
modeldirect | last_touch | first_touchdirectAttribution model

Alert Configuration (1 tool)

metrx_configure_alert_threshold

Set up cost or operational alert thresholds. Alerts run server-side and can trigger email notifications, webhooks, or automatically pause the agent.

ParameterTypeDefaultDescription
agent_idUUIDSpecific agent (omit for org-wide)
metricdaily_cost | monthly_cost | error_rate | latency_p99requiredMetric to monitor
threshold_valuenumberrequiredThreshold (costs: cents, rates: decimal, latency: ms)
actionemail | webhook | pause_agentrequiredAction when threshold is breached

ROI Audit (1 tool)

metrx_generate_roi_audit

Generate a comprehensive ROI audit report for your fleet. Includes per-agent cost/revenue breakdown, attribution confidence scores, optimization opportunities, and risk flags. Suitable for board reporting and compliance.

ParameterTypeDefaultDescription
daysinteger (7–365)30Analysis period
include_methodologybooleantrueInclude methodology notes for auditors
agent_idsUUID[]Specific agents (omit for full fleet)

Upgrade Justification (1 tool)

metrx_get_upgrade_justification

Generate an ROI report for upgrading from Free to a paid tier. Analyzes usage patterns and calculates optimization potential.

ParameterTypeDefaultDescription
daysinteger (7–90)30Days to analyze

Upgrade Business Case (1 tool) — hosted endpoint only

Hosted endpoint only. Not in the npm package; reachable over https://metrxbot.com/api/mcp, not over npx stdio.

metrx_get_upgrade_business_case

Generate a personalized ROI business case for upgrading to a higher tier with projected savings and payback period.

ParameterTypeDefaultDescription
current_tierstarter | lite | prorequiredCurrent subscription tier
monthly_spendnumberKnown monthly LLM spend in cents
agent_countintegerNumber of active agents
primary_use_casecustomer_support | data_processing | content_generation | code_assistantPrimary use case

Health & Rankings (2 tools) — hosted endpoint only

Hosted endpoint only. Not in the npm package; reachable over https://metrxbot.com/api/mcp, not over npx stdio.

metrx_get_health_scores

Health score, grade, and data completeness for every agent in the organization. Scores are composite 0–100 values blending cost efficiency, ROI, error rate, quality drift, failure risk, and latency. Grades: A (80–100), B (60–79), C (40–59), D (20–39), F (0–19).

Takes no parameters.

metrx_get_rankings

Agents sorted by health score with percentile ranking, plus a fleet summary (average score and grade) and stale-score warnings. Use it to find top and bottom performers.

Takes no parameters.


Verify Billing (3 tools) — hosted endpoint only

Hosted endpoint only. Not in the npm package; reachable over https://metrxbot.com/api/mcp, not over npx stdio.

A verification is a causal verdict on whether a model switch holds quality on your own production traffic. The unit noun is “verification” — never “credits”. No verdict, no charge.

metrx_get_balance

How many verifications your organization has remaining. Free to call. Use it before metrx_verify_switch to know whether a purchase is needed first.

Takes no parameters.

metrx_buy_verification

Purchase one verification. Returns a Stripe checkout URL for a human (or payment-capable agent) to complete, plus claim instructions when the purchase is anonymous. This tool does not charge anything itself — payment happens on the returned URL.

ParameterTypeDefaultDescription
callback_urlstring (URL)Optional post-checkout redirect base URL

metrx_verify_switch

Start a purchased verification: would candidate_model hold quality against prod_model on your production traffic? Async — returns a request handle immediately and never blocks; verdicts complete after enough of your own traffic accrues. Poll GET /api/verify/requests/{id}. If the balance is 0 this returns purchase guidance instead of spending.

ParameterTypeDefaultDescription
prod_modelstringrequiredCurrent production model
candidate_modelstringrequiredCandidate model to verify against it
agent_idUUIDAgent to scope the verification to
policy_idUUIDRouting policy to attach to

Loop Metrics (8 tools) — hosted endpoint only

Hosted endpoint only. Not in the npm package; reachable over https://metrxbot.com/api/mcp, not over npx stdio.

These tools return measured-value envelopes: every numeric leaf is {value, ci_low, ci_high, method, data_through}. CI fields are populated only where the source payload carries a real confidence interval — never fabricated. Raw counts use method: "count".

metrx_get_signal_readiness

Org-scoped signal-readiness diagnostics — per-agent event coverage, label lag, join rate, volume-vs-power (days to trial-ready at current volume), estimator eligibility with reasons, and blocked-on-signal proposals cross-linked to the failing readiness dimension. The “what unlocks your first verified verdict” surface.

Takes no parameters.

metrx_get_dashboard_headline

The three-number headline regime: measured spend, attributed (modeled) savings, and verified savings-with-CI — each with basis, provenance, and tone. Values are micro-dollars (dollars = value / 1e6). Requires the optimization_model_v3 flag; while it is off the tool returns a clear next-step error.

ParameterTypeDefaultDescription
days7 | 30 | 9030Window in days

metrx_get_report_snapshot

Fetch one frozen executive-report snapshot by its public share token (the token is the capability). Returns the stored snapshot only — never recomputed — plus its snapshot_hash and methodology_version integrity stamps.

ParameterTypeDefaultDescription
share_tokenstring (16–64 hex)requiredThe report share token

metrx_get_verdicts

Org-scoped current causal-verdict summaries — per (agent, prod model, candidate model, task category): verdict, evidence mode/regime, pair counts, non-inferiority, savings CI, judge model, expiry. Observational (:value) rows are flagged. Summaries only: no gate flags and no evidence-pack contents (those remain dashboard-session-only). Read-only twin route (/api/loop-views/verdicts).

Takes no parameters.

metrx_get_trials

Org-scoped pre-registered trial plans: regime, primary metric, margin, the frozen sample plan (pre-registration), models, status (registered/concluded/voided) and the concluding verdict id. Read-only.

Takes no parameters.

metrx_get_proposals

Org-scoped current candidate proposals: action type/class, D-class, status with blocked_reason, estimated impact, taxonomy axes. Config payloads (config_diff, guardrails, rollback mechanics) are deliberately excluded. Read-only.

Takes no parameters.

metrx_get_actuations

Org-scoped policy actuation records: action class, authority, actor and timing, rollback state with reason, acknowledgement state. Config contents are excluded. Requires the optimization_model_v3 flag (404 while off). Read-only.

Takes no parameters.

metrx_get_decision_queue

The operator decision queue, derived from real loop objects (approvable verdicts, blocked proposals, breaker events, expiring evidence). Read-only: approve/snooze/acknowledge actions remain dashboard-session-only and are not exposed to API-key callers. Requires the optimization_model_v3 flag.

Takes no parameters.


Guided Prompts

MCP prompts are interactive templates that walk agents through multi-step workflows. Use them from any MCP-compatible client.

analyze-costs

Step-by-step cost analysis: fetches cost summary → lists agents → gets optimization recommendations → returns a prioritized breakdown.

ArgumentTypeDescription
daysstring (optional)Number of days to analyze (default: “30”)

find-savings

Discovers optimization opportunities: checks recommendations → runs cost leak scan → explains savings in dollars.

No arguments.

cost-leak-scan

Runs the 7-check waste audit: retry storms, oversized contexts, model mismatch, missing caching, idle agents, missing budgets, and arbitrage gaps.

ArgumentTypeDescription
agent_idstring (optional)Scan a specific agent by UUID, or omit to scan all

Rate Limiting

The MCP server enforces 60 requests per minute per tool to prevent abuse. Hitting the limit returns an error with a retryAfter value.

Error Handling

All tools return standardized error responses:

{
  "content": [{ "type": "text", "text": "Error message" }],
  "isError": true
}
StatusMeaningFix
401Invalid or expired API keyRegenerate key
403Insufficient permissionsCheck key permissions
404Resource not foundUse metrx_list_agents to get valid IDs
429Rate limitedWait for retryAfter seconds
5xxServer errorRetry with backoff

Troubleshooting

“METRX_API_KEY not set” — Set the environment variable before starting:

export METRX_API_KEY=sk_live_your_key
npx @metrxbot/mcp-server

“Rate limit exceeded” — You’ve made more than 60 requests to a single tool within 60 seconds. The MCP client will retry automatically.

“Agent not found” — The agent_id doesn’t exist. Run metrx_list_agents to get valid IDs.

Connection test fails — Run npx @metrxbot/mcp-server --test to verify your API key and network connectivity.