API Reference

Complete reference for all Metrxbot API endpoints, including authentication, request/response formats, error codes, and rate limits.

Version: 1.11.0

Base URLs

  • Gateway: https://gateway.metrxbot.com (proxy for LLM calls)
  • Web API: https://app.metrxbot.com (dashboard and team management)

Authentication

Gateway Authentication

The Gateway uses API key authentication. Include your API key in the Authorization header:

Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx

API keys are validated by:

  1. SHA-256 hash lookup in Cloudflare KV cache (fast path)
  2. Cache miss → Supabase lookup with rate limiting
  3. Cached for 1 hour to minimize database queries

Header Format:

Authorization: Bearer <api_key>

Example:

curl -H "Authorization: Bearer sk_live_abc123def456"

Web API Authentication

The Web API uses Clerk for authentication. Sign in at app.metrxbot.com to obtain a session token (automatically managed by the dashboard).

Gateway Endpoints

The Gateway proxies requests to LLM providers while tracking costs and events.

GET /health

Health check endpoint. Requires no authentication.

Request:

curl -X GET https://gateway.metrxbot.com/health

Response (200 OK):

{
  "status": "ok",
  "timestamp": "2024-02-20T12:34:56.789Z",
  "version": "1.0.0"
}

GET /v1/models

List all supported models and their pricing. This endpoint needs no authentication. The response below is a synthetic example of the shape; the live endpoint is the only source of current prices.

Request:

curl -X GET https://gateway.metrxbot.com/v1/models \
  -H "Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx"

Response (200 OK):

{
  "object": "list",
  "data": [
    {
      "id": "gpt-4",
      "object": "model",
      "created": 0,
      "owned_by": "openai",
      "pricing": {
        "input_per_million_cents": 3000,
        "output_per_million_cents": 6000
      }
    },
    {
      "id": "gpt-4-turbo",
      "object": "model",
      "created": 0,
      "owned_by": "openai",
      "pricing": {
        "input_per_million_cents": 1000,
        "output_per_million_cents": 3000
      }
    },
    {
      "id": "gpt-3.5-turbo",
      "object": "model",
      "created": 0,
      "owned_by": "openai",
      "pricing": {
        "input_per_million_cents": 50,
        "output_per_million_cents": 150
      }
    }
  ]
}

POST /v1/chat/completions

OpenAI-compatible chat completions endpoint. Proxies requests to OpenAI, Anthropic, Google, or xAI based on the model name.

Request Headers:

HeaderRequiredDescription
AuthorizationYesAPI key: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx
Content-TypeYesapplication/json
X-Provider-KeyYesYour LLM provider API key (e.g., OpenAI key)
X-Agent-IDNoCustom agent identifier (default: “default”)
X-Session-IDNoSession/conversation ID for grouping
X-Customer-IDNoEnd-customer identifier (for multi-tenant apps)

Request Body (OpenAI format):

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Hello, how are you?"
    }
  ],
  "temperature": 0.7,
  "max_tokens": 1000,
  "stream": false
}

Response (200 OK — Non-Streaming):

{
  "id": "chatcmpl-123abc",
  "object": "chat.completion",
  "created": 1708419296,
  "model": "gpt-4",
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 20,
    "total_tokens": 30
  },
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! I'm doing well, thank you for asking."
      },
      "finish_reason": "stop"
    }
  ]
}

Response Headers (Non-Streaming):

Content-Type: application/json
X-Gateway-Latency: 245ms
X-Gateway-Cost: 1500

Response (200 OK — Streaming):

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
X-Gateway-Latency: streaming

data: {"id":"chatcmpl-123abc","object":"chat.completion.chunk","created":1708419296,"model":"gpt-4","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-123abc","object":"chat.completion.chunk","created":1708419296,"model":"gpt-4","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-123abc","object":"chat.completion.chunk","created":1708419296,"model":"gpt-4","choices":[{"index":0,"delta":{"content":" there"},"finish_reason":null}]}

data: [DONE]

curl Example:

curl -X POST https://gateway.metrxbot.com/v1/chat/completions \
  -H "Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "X-Provider-Key: sk_openai_xxxxxxxxxxxxxxxxxxxx" \
  -H "X-Agent-ID: my-agent-1" \
  -H "X-Session-ID: session-abc123" \
  -d '{
    "model": "gpt-4",
    "messages": [{"role": "user", "content": "Hello!"}],
    "stream": false
  }'

POST /v1/messages

Anthropic-compatible messages endpoint. Routes to Anthropic’s API (Claude models).

Request Headers (same as /v1/chat/completions):

  • Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx
  • X-Provider-Key: sk_anthropic_xxxxxxxxxxxxxxxxxxxx
  • X-Agent-ID (optional)
  • X-Session-ID (optional)
  • X-Customer-ID (optional)

Request Body (Anthropic format):

{
  "model": "claude-3-opus-20240229",
  "max_tokens": 1000,
  "messages": [
    {
      "role": "user",
      "content": "Hello, Claude!"
    }
  ]
}

Response (200 OK):

{
  "id": "msg_123abc",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello! I'm Claude, an AI assistant made by Anthropic."
    }
  ],
  "model": "claude-3-opus-20240229",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 10,
    "output_tokens": 25
  }
}

curl Example:

curl -X POST https://gateway.metrxbot.com/v1/messages \
  -H "Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "X-Provider-Key: sk_anthropic_xxxxxxxxxxxxxxxxxxxx" \
  -d '{
    "model": "claude-3-opus-20240229",
    "max_tokens": 1000,
    "messages": [{"role": "user", "content": "Hello, Claude!"}]
  }'

POST /v1/embeddings

Embeddings endpoint. Routes to OpenAI or other embedding providers.

Request Headers:

  • Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx
  • X-Provider-Key: sk_openai_xxxxxxxxxxxxxxxxxxxx
  • X-Agent-ID (optional)
  • X-Session-ID (optional)

Request Body:

{
  "model": "text-embedding-3-small",
  "input": "The quick brown fox jumps over the lazy dog.",
  "encoding_format": "float"
}

Response (200 OK):

{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.123, 0.456, -0.789, ...]
    }
  ],
  "model": "text-embedding-3-small",
  "usage": {
    "prompt_tokens": 8,
    "total_tokens": 8
  }
}

curl Example:

curl -X POST https://gateway.metrxbot.com/v1/embeddings \
  -H "Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "X-Provider-Key: sk_openai_xxxxxxxxxxxxxxxxxxxx" \
  -d '{
    "model": "text-embedding-3-small",
    "input": "Hello world"
  }'

Web API Endpoints

The Web API handles team management, billing, webhooks, and outcome tracking. Requires Clerk authentication.

GET /api/health

Health check endpoint (no authentication required).

Response (200 OK):

{
  "status": "ok",
  "timestamp": "2024-02-20T12:34:56.789Z",
  "version": "0.1.0",
  "uptime": 12345,
  "services": {
    "supabase": "ok",
    "redis": "ok"
  }
}

GET /api/agents

List all agents for the current organization.

Authentication: Clerk session required

Response (200 OK):

{
  "agents": [
    {
      "id": "agent_123abc",
      "name": "Customer Service Bot",
      "organization_id": "org_123abc",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-02-20T09:15:00Z",
      "metadata": {
        "description": "Handles customer inquiries",
        "team": "support"
      }
    }
  ]
}

GET /api/agents/{id}

Get details for a specific agent.

Authentication: Clerk session required

Response (200 OK):

{
  "id": "agent_123abc",
  "name": "Customer Service Bot",
  "organization_id": "org_123abc",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-02-20T09:15:00Z",
  "metadata": {
    "description": "Handles customer inquiries",
    "team": "support"
  }
}

GET /api/agents/{id}/metrics

Get cost and usage metrics for an agent.

Authentication: Clerk session required

Query Parameters:

ParameterTypeDefaultDescription
fromISO 860130 days agoStart date
toISO 8601NowEnd date
group_bystringdayday, week, month

Response (200 OK):

{
  "agent_id": "agent_123abc",
  "period": {
    "from": "2024-01-21T00:00:00Z",
    "to": "2024-02-20T23:59:59Z"
  },
  "totals": {
    "call_count": 1234,
    "input_tokens": 45678,
    "output_tokens": 23456,
    "cost_microcents": 1234567
  },
  "by_model": [
    {
      "model": "gpt-4",
      "call_count": 800,
      "cost_microcents": 1000000
    },
    {
      "model": "gpt-3.5-turbo",
      "call_count": 434,
      "cost_microcents": 234567
    }
  ],
  "by_day": [
    {
      "date": "2024-02-20",
      "call_count": 45,
      "cost_microcents": 54321
    }
  ]
}

POST /api/webhooks/generic/{orgId}

Send a business outcome from any tool that can make an HTTP request with a custom header (Zapier, Make, n8n, your own code). This is the URL shown on Settings > Integrations under Custom Webhook.

Authentication: X-Api-Key header with an active Metrxbot API key that belongs to {orgId} and grants write. No key, or a key for another org, returns 401. A read-only key returns 403.

Tier: Pro and above.

Request Body (after any field mappings saved for the org are applied):

{
  "outcome_type": "deal_won",
  "value_cents": 50000,
  "agent_id": "550e8400-e29b-41d4-a716-446655440000",
  "customer_id": "cust_123",
  "reference_id": "deal_456"
}

Only outcome_type is required. value_cents is capped at 100000000 cents; larger values are rejected.

Response (200 OK):

{ "received": true, "outcome_id": "..." }

If an outcome from this webhook already has the same reference_id, nothing new is written and the response is { "received": true, "outcome_id": "<existing id>", "deduplicated": true }.

Errors: 400 invalid JSON, a validation error, or value_cents over the cap; 401 missing key or a key for another org; 403 read-only key or tier below Pro; 429 rate limited; 500 the outcome could not be written.

Providers that cannot set a custom header (for example Stripe and Shopify webhooks) cannot use this endpoint. Connect Stripe through its own card under Outcome Sources.


POST /api/webhooks/generic?source={source}&org_id={orgId}

The per-source form of the generic webhook. source is lower-case letters, digits, _ and - (max 40), and cannot be a provider that has its own integration (stripe, zendesk, calendly, generic, …): those return 400.

What works for which source. Signed delivery and per-source field mappings need an integration row for source, and today one can exist only for source=salesforce. No Metrxbot screen or API creates that row: it exists only if Metrxbot provisions it on request (see Signed delivery below). Every other source (for example custom) has no integration row: it authenticates with X-Api-Key and uses the default mapping (notion included: there is no Notion-specific mapping). The default mapping reads:

  • outcome type: type, event_type or status (otherwise {source}_event);
  • value: the first of amount, value or cost that is a JSON number, in dollars, converted to cents. 0 counts as a value; a string such as "500" is ignored;
  • agent: agent_id or agent.id, which must be a Metrxbot agent id (a UUID);
  • customer: customer_id, account_id or customer.id.

For salesforce, the defaults read Amount and AccountId from fields, and Closed Won becomes deal_closed. The agent is not mapped by default: OwnerId is a Salesforce user id, not a Metrxbot agent id.

Authentication (one of):

  1. API key: X-Api-Key header, exactly as for /api/webhooks/generic/{orgId}. This is the self-serve option, and the only option for any source other than salesforce.

  2. Signed delivery (currently source=salesforce only): there is no self-serve setting for this. The signing secret is provisioned by Metrxbot on request; contact support. With one in place, send both headers:

    • x-webhook-timestamp: the current unix time in seconds. It must be within 300 seconds of Metrxbot’s clock, or the request is rejected with 401 and the reason.
    • x-webhook-signature: sha256= followed by the hex HMAC-SHA256, keyed with the signing secret, of the string {timestamp}.{raw request body}.

    Because the timestamp is signed, a captured signature cannot be re-sent with a fresh timestamp. Inside the 300-second window, an identical signed delivery is accepted once; repeats return { "received": true, "deduplicated": true }. So include a unique id or nonce in every body (for example your event id): two different events with byte-identical bodies signed in the same second would otherwise count as one.

const timestamp = Math.floor(Date.now() / 1000).toString();
const body = JSON.stringify(payload);
const signature =
  'sha256=' +
  crypto.createHmac('sha256', signingSecret).update(`${timestamp}.${body}`).digest('hex');
// headers: { 'x-webhook-timestamp': timestamp, 'x-webhook-signature': signature }

Until 2026-10-13 the signature covered the body alone. That form no longer verifies.

Responses:

  • 200 with { "received": true, "outcome_id": "...", "outcome_type": "..." }: the outcome was recorded.
  • 200 with "deduplicated": true: a repeat of a signed delivery already accepted. Nothing new is written.
  • 200 with { "received": true, "warning": "Could not map webhook: ..." }: the payload could not be mapped to an outcome, so nothing was written. Fix the payload or the field mappings and re-send.
  • 400: bad parameters, invalid JSON, or value_cents over the cap.
  • 401: no credential, a wrong-org or unknown key, a missing, malformed or stale timestamp, or a signature that did not verify. The reason is in error.
  • 403: read-only key, or tier below Pro.
  • 404: deactivated organization.
  • 410: disconnected integration.
  • 429: rate limited.
  • 500: a lookup or write failed. Safe to retry.

Webhook Events

Webhooks send JSON payloads with event data. Each webhook is signed with X-Webhook-Signature using HMAC-SHA256.

Event: event.created

Sent whenever an LLM call completes.

{
  "event_type": "event.created",
  "timestamp": "2024-02-20T12:34:56.789Z",
  "data": {
    "id": "event_123abc",
    "org_id": "org_123abc",
    "agent_key": "customer-service",
    "provider": "openai",
    "model": "gpt-4",
    "input_tokens": 150,
    "output_tokens": 75,
    "cost_microcents": 9000,
    "latency_ms": 1250,
    "status": "success",
    "session_id": "session_abc123",
    "customer_id": "cust_xyz789"
  }
}

Event: outcome.confirmed

Sent when an outcome is confirmed (business result achieved).

{
  "event_type": "outcome.confirmed",
  "timestamp": "2024-02-20T12:35:00.000Z",
  "data": {
    "id": "outcome_xyz789",
    "org_id": "org_123abc",
    "name": "Successfully handled customer inquiry",
    "session_id": "session_abc123",
    "confirmed_by": "user_abc123",
    "confirmed_at": "2024-02-20T12:35:00Z",
    "related_events": 3
  }
}

Custom Headers

The Gateway supports custom headers for flexible cost tracking and outcome management:

HeaderTypeDescriptionExample
X-Agent-IDStringCustom agent identifiersupport-bot-v2
X-Session-IDStringSession or conversation IDsession-2024-02-20-001
X-Customer-IDStringEnd-customer identifier (multi-tenant)cust_12345
X-ProviderStringForce provider (OpenAI, Anthropic, etc.)openai
X-Provider-KeyStringCustomer’s LLM provider API keysk_openai_abc123...

Rate Limits

Rate limits are enforced per organization tier and reset monthly:

TierMonthly CallsBurst LimitOverage Handling
Starter10,00010/min429 Too Many Requests
Lite50,000100/min429 Too Many Requests
Pro100,000500/min429 Too Many Requests
EnterpriseUnlimited10,000/minCustom handling

See metrxbot.com/pricing for current pricing.

Response (429 Too Many Requests):

{
  "error": "Rate limit exceeded",
  "limit": 100000,
  "current": 104231,
  "reset_at": "2024-03-20T23:59:59Z",
  "retry_after": 3600
}

Tier-Based Access

Some endpoints are not included in the free plan. A request from an org whose plan does not include the endpoint receives a 402 Payment Required response that says which plan includes it.

Plan Limits

PlanAgentsMonthly CallsHistory Days
Free (starter)310,0007
PlatformUnlimitedUnlimitedUnlimited
EnterpriseUnlimitedUnlimitedUnlimited

Orgs still on a retired Lite or Pro plan keep their limits; those plans are not sold.

Gated Endpoints

These endpoints are not included in the free plan and return 402 there. They are included in Platform and Enterprise, and an org on a retired plan keeps the access that plan had. The list is not exhaustive; for example:

  • GET/PATCH /api/alerts and GET/PATCH /api/alerts/preferences
  • POST /api/alerts/test
  • GET /api/optimization/cost-leak-scan
  • GET /api/audit/trail
  • GET /api/agents/{id}/roi
  • the outcome endpoints under /api/outcomes

402 Response

Abridged; the full body also carries buyable_now and the price fields in metrx_usage_summary.

{
  "error": "payment_required",
  "current_tier": "starter",
  "limit_hit": "lite_tier_required",
  "upgrade_options": [
    { "tier": "platform", "price": "Talk to us", "features_unlocked": ["..."] },
    { "tier": "enterprise", "price": "Custom", "features_unlocked": ["..."] }
  ],
  "upgrade_url": "https://app.metrxbot.com/settings/billing",
  "metrx_usage_summary": { "current_plan": "Free", "next_recommended_tier": "platform" }
}

limit_hit and required_tier are stable machine codes and can name a retired plan. Read upgrade_options for what can be bought.

History Day Limits

The days query parameter on data endpoints is automatically clamped to your tier’s maximum:

EndpointDefaultTier Limit Applied
GET /api/dashboard30Yes
GET /api/analytics30Yes
GET /api/agents/{id}/metrics30Yes

A Starter-tier org requesting ?days=30 receives 7 days of data. No error is returned.


Error Codes

Standard HTTP status codes with JSON error responses:

CodeMeaningExample
400Bad RequestInvalid JSON body, missing required field
401UnauthorizedMissing or invalid API key
402Payment RequiredFeature requires higher subscription tier
403ForbiddenAPI key valid but org is inactive/suspended
404Not FoundEndpoint doesn’t exist
413Payload Too LargeRequest body > 10MB
429Too Many RequestsRate limit exceeded
500Internal Server ErrorGateway error (rare)
502Bad GatewayLLM provider unreachable
504Gateway TimeoutLLM provider timeout (>60s)

Error Response Format:

{
  "error": "Unsupported model",
  "model": "gpt-5",
  "supported_providers": ["openai", "anthropic", "google", "xai"]
}

Request/Response Examples

Complete Flow: Chat Completion with Outcome Tracking

Step 1: Make a request through the Gateway

curl -X POST https://gateway.metrxbot.com/v1/chat/completions \
  -H "Authorization: Bearer sk_live_abc123def456" \
  -H "Content-Type: application/json" \
  -H "X-Provider-Key: sk_openai_live_abc123def456" \
  -H "X-Agent-ID: support-bot" \
  -H "X-Session-ID: session-2024-02-20-001" \
  -H "X-Customer-ID: cust_12345" \
  -d '{
    "model": "gpt-4",
    "messages": [
      {"role": "system", "content": "You are a helpful support agent."},
      {"role": "user", "content": "How do I reset my password?"}
    ],
    "temperature": 0.7
  }'

Step 2: Receive the response

{
  "id": "chatcmpl-8x9y0z",
  "object": "chat.completion",
  "created": 1708419296,
  "model": "gpt-4",
  "usage": {
    "prompt_tokens": 34,
    "completion_tokens": 87,
    "total_tokens": 121
  },
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "To reset your password, please visit our account settings page and click on 'Change Password'. You'll receive a verification code via email."
      },
      "finish_reason": "stop"
    }
  ]
}

Step 3: Events are logged automatically

An event is queued in Redis with:

  • Org ID, agent key, model, tokens (34 input, 87 output)
  • Cost calculation: (input_tokens x input price + output_tokens x output price) / 1,000,000, using the model’s per-million-token prices from GET /v1/models. Stored in cost_microcents (micro-dollars)
  • Latency: 1234ms
  • Status: success
  • Session ID and customer ID for grouping

Step 4: (Optional) Report an outcome

Via webhook or dashboard, mark this session as successful:

  • “Customer received helpful password reset instructions”
  • ROI calculation: the logged cost compared with the value you attach to resolving a support ticket

Pricing Reference

Costs are stored in the *_microcents columns, which hold micro-dollars: 1,000,000 units make one dollar (dollars = value / 1,000,000). The column name is historical; the unit is micro-dollars.

Per-model prices change, so this page carries none. Call the live endpoint, which returns current input and output prices per million tokens for every supported model and needs no authentication:

curl https://gateway.metrxbot.com/v1/models

Each entry’s pricing.input_per_million_cents and pricing.output_per_million_cents are in cents per one million tokens. The cost of a call is input_tokens / 1,000,000 * input price + output_tokens / 1,000,000 * output price.


Budget Endpoints

Manage spending limits and budget enforcement.

GET /api/budgets

List all budgets for the organization.

Authentication: Clerk session required

Response (200 OK):

{
  "budgets": [
    {
      "id": "budget_123abc",
      "period": "monthly",
      "limit_microcents": 1000000000,
      "warning_pct": 80,
      "enforcement_mode": "hard_block",
      "agent_id": "agent_123abc",
      "organization_id": "org_123abc",
      "current_spending_microcents": 750000000,
      "resets_at": "2024-03-01T00:00:00Z",
      "created_at": "2024-02-01T10:00:00Z"
    }
  ]
}

POST /api/budgets

Create a new budget.

Authentication: Clerk session required

Request Body:

{
  "period": "monthly",
  "limit_microcents": 1000000000,
  "warning_pct": 80,
  "enforcement_mode": "hard_block",
  "agent_id": "agent_123abc"
}

Parameters:

  • period (string, required): daily or monthly
  • limit_microcents (integer, required): Maximum spending in micro-dollars (the _microcents suffix is historical; 1,000,000 units make one dollar)
  • warning_pct (integer, optional): Alert threshold percentage (0-100)
  • enforcement_mode (string, required): alert_only, soft_block, or hard_block
  • agent_id (string, optional): Apply to specific agent; if omitted, applies organization-wide

Response (201 Created):

{
  "id": "budget_456def",
  "period": "monthly",
  "limit_microcents": 1000000000,
  "warning_pct": 80,
  "enforcement_mode": "hard_block",
  "agent_id": "agent_123abc",
  "organization_id": "org_123abc",
  "current_spending_microcents": 0,
  "resets_at": "2024-03-01T00:00:00Z",
  "created_at": "2024-02-22T10:00:00Z"
}

DELETE /api/budgets/:id

Delete a budget.

Authentication: Clerk session required

Response (204 No Content)


POST /api/budgets/:id/resume

Resume a paused budget (e.g., after manual reset).

Authentication: Clerk session required

Request Body:

{
  "reset_spending": true
}

Parameters:

  • reset_spending (boolean, optional): If true, reset current spending to zero

Response (200 OK):

{
  "id": "budget_456def",
  "status": "active",
  "current_spending_microcents": 0,
  "resets_at": "2024-03-01T00:00:00Z"
}

GET /api/budgets/status

Get current budget status and spending across all budgets.

Authentication: Clerk session required

Response (200 OK):

{
  "organization_id": "org_123abc",
  "total_spending_microcents": 750000000,
  "budgets": [
    {
      "id": "budget_123abc",
      "limit_microcents": 1000000000,
      "current_spending_microcents": 750000000,
      "percentage_used": 75,
      "enforcement_mode": "hard_block",
      "status": "active",
      "days_remaining": 8,
      "resets_at": "2024-03-01T00:00:00Z"
    }
  ],
  "alerts_triggered": 0
}

Alert Endpoints

Configure and manage notifications.

GET /api/alerts

List all alert events.

Authentication: Clerk session required

Query Parameters:

  • limit (integer, optional): Max results (default: 50)
  • offset (integer, optional): Pagination offset (default: 0)
  • type (string, optional): Filter by alert type

Response (200 OK):

{
  "alerts": [
    {
      "id": "alert_789xyz",
      "type": "cost_spike",
      "triggered_at": "2024-02-22T12:34:56Z",
      "severity": "warning",
      "message": "Daily spending jumped 50% to $145",
      "metadata": {
        "current_spending": 145000000,
        "average_spending": 95000000,
        "percentage_increase": 52.6
      }
    },
    {
      "id": "alert_456def",
      "type": "budget_warning",
      "triggered_at": "2024-02-22T10:00:00Z",
      "severity": "info",
      "message": "Monthly budget 80% spent ($800 of $1000)",
      "metadata": {
        "budget_id": "budget_123abc",
        "percentage_used": 80
      }
    }
  ]
}

GET /api/alerts/preferences

Get alert notification preferences.

Authentication: Clerk session required

Response (200 OK):

{
  "organization_id": "org_123abc",
  "email": "team@company.com",
  "slack_webhook": "https://hooks.slack.com/services/...",
  "telegram_chat_id": "123456789",
  "webhook_url": "https://your-app.com/webhooks/metrx-alerts",
  "alert_types": {
    "cost_spike": {
      "enabled": true,
      "threshold_pct": 50,
      "channels": ["email", "slack"]
    },
    "error_rate": {
      "enabled": true,
      "threshold_pct": 5,
      "channels": ["email"]
    },
    "usage_spike": {
      "enabled": true,
      "threshold_multiplier": 2,
      "channels": ["slack", "webhook"]
    },
    "idle_agent": {
      "enabled": false,
      "threshold_hours": 168,
      "channels": []
    },
    "budget_warning": {
      "enabled": true,
      "threshold_pct": 80,
      "channels": ["email", "telegram"]
    }
  }
}

PATCH /api/alerts/preferences

Update alert preferences.

Authentication: Clerk session required

Request Body:

{
  "email": "alerts@company.com",
  "slack_webhook": "https://hooks.slack.com/services/...",
  "telegram_chat_id": "123456789",
  "webhook_url": "https://your-app.com/webhooks/metrx-alerts",
  "cost_spike_enabled": true,
  "cost_spike_threshold_pct": 50,
  "cost_spike_channels": ["email", "slack"],
  "error_rate_enabled": true,
  "error_rate_threshold_pct": 5,
  "error_rate_channels": ["email"],
  "usage_spike_enabled": true,
  "usage_spike_threshold_multiplier": 2,
  "usage_spike_channels": ["slack"],
  "idle_agent_enabled": false,
  "idle_agent_threshold_hours": 168,
  "idle_agent_channels": [],
  "budget_warning_enabled": true,
  "budget_warning_threshold_pct": 80,
  "budget_warning_channels": ["email", "telegram"]
}

Response (200 OK):

{
  "organization_id": "org_123abc",
  "updated_at": "2024-02-22T12:34:56Z",
  "alert_types": ["cost_spike", "error_rate", "usage_spike", "budget_warning"]
}

Analytics Endpoint

GET /api/analytics

Get analytics data with trends, model distribution, and summary statistics.

Authentication: Clerk session required

Query Parameters:

  • from (ISO 8601, optional): Start date (default: 30 days ago)
  • to (ISO 8601, optional): End date (default: now)
  • agent_id (string, optional): Filter to specific agent

Response (200 OK):

{
  "summary": {
    "total_calls": 5234,
    "total_cost_microcents": 2345600000,
    "avg_latency_ms": 1234,
    "error_rate": 0.02,
    "period": {
      "from": "2024-01-23T00:00:00Z",
      "to": "2024-02-22T23:59:59Z"
    }
  },
  "by_model": [
    {
      "model": "gpt-4",
      "call_count": 2500,
      "cost_microcents": 1500000000,
      "avg_latency_ms": 1500
    },
    {
      "model": "gpt-3.5-turbo",
      "call_count": 2734,
      "cost_microcents": 845600000,
      "avg_latency_ms": 900
    }
  ],
  "trend": [
    {
      "date": "2024-02-22",
      "call_count": 145,
      "cost_microcents": 67500000,
      "avg_latency_ms": 1200
    },
    {
      "date": "2024-02-21",
      "call_count": 132,
      "cost_microcents": 61200000,
      "avg_latency_ms": 1180
    }
  ]
}

Next Steps: See the Integration Guide for implementation examples.