MetricsContext
MetricsContext emits custom metrics from your code. Tools and workflow steps receive it as metrics, scoped to the span of the current tool call or step. Custom metrics are stored and exported alongside automatic metrics, and you query them by name with the metric query APIs.
For an introduction, see Emit custom metrics.
Usage exampleDirect link to Usage example
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const searchDocs = createTool({
id: 'search-docs',
description: 'Searches the documentation index',
inputSchema: z.object({ query: z.string() }),
execute: async ({ query }, context) => {
const results = await searchIndex(query)
context.metrics?.emit('docs_search_results', results.length, {
empty: results.length === 0 ? 'true' : 'false',
})
return { results }
},
})
In a workflow step, metrics is a property of the execute parameters:
import { createStep } from '@mastra/core/workflows'
import { z } from 'zod'
const indexDocuments = createStep({
id: 'index-documents',
inputSchema: z.object({ documents: z.array(z.string()) }),
outputSchema: z.object({ indexed: z.number() }),
execute: async ({ inputData, metrics }) => {
metrics?.emit('documents_indexed', inputData.documents.length, { source: 'upload' })
return { indexed: inputData.documents.length }
},
})
metrics is typed as optional on tool and step contexts, so use optional chaining. When observability isn't configured, metrics is a no-op context and emit() does nothing.
MethodsDirect link to Methods
emit(name, value, labels?, options?)Direct link to emitname-value-labels-options
Records one observation of a metric. Each call stores a separate row, and aggregation such as sum, average, or percentiles happens at query time. Returns void.
name:
mastra_ prefix used by automatic metrics.value:
1 for a count or a duration in milliseconds. Mastra drops the observation if the value is negative, NaN, or infinite.labels?:
options?:
costContext?:
provider, model, estimatedCost, costUnit, and costMetadata, all optional.usageId?:
Deprecated methodsDirect link to Deprecated methods
counter(name), gauge(name), and histogram(name) return objects whose add(), set(), and record() methods call emit(). Use emit() directly instead.
Trace correlationDirect link to Trace correlation
Every observation records the trace and span ID of the tool call or step that emitted it, plus the same correlation context as automatic metrics, such as the entity, environment, and service name. Use these fields to go from a metric to the trace that produced it. They're stored separately from labels, so cardinality filtering doesn't remove them.
Cardinality protectionDirect link to Cardinality protection
Each distinct combination of label values creates a separate series, and unbounded values such as IDs can make metric storage and queries expensive. Before Mastra stores a metric, it removes:
- labels whose name is in the blocked list, compared case-insensitively. The default list is
trace_id,span_id,run_id,request_id,user_id,resource_id,session_id, andthread_id. - labels whose value is a UUID, unless
blockUUIDsisfalse.
The same filter applies to automatic metrics. Configure it with the cardinality option of an observability instance:
import { Mastra } from '@mastra/core/mastra'
import { DEFAULT_BLOCKED_LABELS } from '@mastra/core/observability'
import { Observability, MastraStorageExporter } from '@mastra/observability'
export const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'mastra',
exporters: [new MastraStorageExporter()],
cardinality: {
blockedLabels: [...DEFAULT_BLOCKED_LABELS, 'order_id'],
},
},
},
}),
})
blockedLabels?:
DEFAULT_BLOCKED_LABELS from @mastra/core/observability into your list. Pass [] to allow every label name.