MCP Server

MCP Server

The Metrx MCP Server (@metrxbot/mcp-server) exposes 24 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.2 · License: MIT · npm


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)

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

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.