Introducing the Metrics API for Mastra Platform

Query cost, latency, and errors by agent, thread, or time.

Paul ScanlonPaul Scanlon·

Oct 13, 2026

·

4 min read

You can now query token usage, model cost, latency, and error rates with Mastra platform's Metrics API. Use the Mastra Client SDK, Mastra CLI, or observability endpoints to get totals, breakdowns, time series, and percentile data from production Mastra projects.

Traces show what happened in a single run, while metrics aggregate across every run. This lets you see which model, conversation, or tool calls cost the most, run the slowest, or fail most often. You can combine query types with time ranges and status filters to surface important insights to share with your team.

We launched metrics earlier this year, letting you view model costs, latency, and error counts in Mastra platform and Studio. Today, using the Metrics API, you can construct your own queries to generate custom reports, build dashboards, send data to downstream services, or post alerts to connected chat platforms when model costs or error rates rise.

You can combine the Metrics API with code mode to build agents capable of constructing their own queries on the fly to answer questions, summarize insights, or generate PDFs for team members and stakeholders.

Get started

Metric queries need a platform access token and your project ID, sent with each request. Use the correct Mastra observability base URL for your project's region:

  • US: https://observability.mastra.ai
  • EU: https://observability.eu.mastra.ai

Each example below asks for total token usage and estimated cost for the last 30 days. The timestamp filter is optional. If start and end are omitted, queries return all available data.

Mastra Client SDK

Use the analytics methods with Mastra Client SDK:

GNU BashTerminal
npm install @mastra/client-js@latest
note
Requires @mastra/client-js@1.9.0 or later, added in PR #14270.
TypeScriptsrc/metrics.ts
import { MastraClient } from "@mastra/client-js";
 
const mastraClient = new MastraClient({
  baseUrl: "https://observability.mastra.ai",
  headers: {
    Authorization: `Bearer ${process.env.MASTRA_PLATFORM_ACCESS_TOKEN}`,
    "X-Mastra-Project-Id": process.env.MASTRA_PROJECT_ID!
  }
});
 
await mastraClient.getMetricAggregate({
  name: ["mastra_model_total_input_tokens", "mastra_model_total_output_tokens"],
  aggregation: "sum",
  filters: {
    timestamp: {
      start: new Date("2026-09-13T00:00:00Z"),
      end: new Date("2026-10-13T00:00:00Z")
    }
  },
  comparePeriod: "previous_period"
});

Mastra CLI

Install or upgrade the Mastra CLI globally:

GNU BashTerminal
npm install -g mastra@latest
note
Requires mastra@1.9.2 or later, added in PR #16563.

Run the mastra api metric commands from your terminal. The CLI reads MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID from your environment:

GNU BashTerminal
mastra api --url https://observability.mastra.ai metric aggregate '{"name":["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],"aggregation":"sum","filters":{"timestamp":{"start":"2026-09-13T00:00:00Z","end":"2026-10-13T00:00:00Z"}},"comparePeriod":"previous_period"}'

Observability endpoints

Send a POST request to one of the Metrics API endpoints. Include the MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID variables in the request:

GNU BashTerminal
curl -X POST "https://observability.mastra.ai/api/observability/metrics/aggregate" \
  -H "Authorization: Bearer $MASTRA_PLATFORM_ACCESS_TOKEN" \
  -H "X-Mastra-Project-Id: $MASTRA_PROJECT_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "name": ["mastra_model_total_input_tokens", "mastra_model_total_output_tokens"],
    "aggregation": "sum",
    "filters": { "timestamp": { "start": "2026-09-13T00:00:00Z", "end": "2026-10-13T00:00:00Z" } },
    "comparePeriod": "previous_period"
  }'

Example Response

All requests are returned as JSON:

{
  "value": 6332830,
  "estimatedCost": 14.66,
  "costUnit": "USD",
  "previousValue": 866647,
  "previousEstimatedCost": null,
  "changePercent": 630.7,
  "costChangePercent": null
}

Example queries

The following examples show how to query cost by token type, the most expensive conversations, daily token usage, latency percentiles, and failed runs. Each example uses the Mastra Client SDK, but the same queries work with the Mastra CLI and observability endpoints.

Cost by token type

Query each token type on its own to see what drives cost. Cache writes, cache reads, and output tokens are priced differently:

const cacheWrites = await mastraClient.getMetricAggregate({
  name: ["mastra_model_input_cache_write_tokens"],
  aggregation: "sum"
  // ...
});

Cost by conversation

Group token usage by threadId to rank conversations by cost:

const conversations = await mastraClient.getMetricBreakdown({
  name: ["mastra_model_total_input_tokens", "mastra_model_total_output_tokens"],
  groupBy: ["threadId"],
  aggregation: "sum"
  // ...
});

The same call with groupBy: ["model"] gives cost by model, and groupBy: ["rootEntityName"] gives cost by the agent or workflow.

Tokens per day

Get token usage for each day:

const daily = await mastraClient.getMetricTimeSeries({
  name: ["mastra_model_total_input_tokens", "mastra_model_total_output_tokens"],
  interval: "1d",
  aggregation: "sum"
  // ...
});

Latency percentiles

Get p50 and p95 agent run durations for each day:

const latency = await mastraClient.getMetricPercentiles({
  name: "mastra_agent_duration_ms",
  percentiles: [0.5, 0.95],
  interval: "1d"
  // ...
});

Failed runs

Filter duration metrics by their status label to count failed runs:

const failedRuns = await mastraClient.getMetricAggregate({
  name: ["mastra_agent_duration_ms"],
  aggregation: "count",
  filters: {
    labels: { status: "error" }
  }
});

For more information and full configuration options, see:

Share on X or LinkedIn
Paul Scanlon
Paul ScanlonTechnical Product Marketing Manager

Paul Scanlon sits between Developer Education and Product Marketing at Mastra. Previously, he was a Technical Product Marketing Manager at Neon and worked in Developer Relations at Gatsby, where he created educational content and developer experiences.

All articles by Paul Scanlon →