Interfaces
Core interfacesDirect link to Core interfaces
ObservabilityInstanceDirect link to observabilityinstance
Primary interface for observability.
interface ObservabilityInstance {
/** Get current configuration */
getConfig(): Readonly<Required<ObservabilityInstanceConfig>>
/** Get all exporters */
getExporters(): readonly ObservabilityExporter[]
/** Get all span output processors */
getSpanOutputProcessors(): readonly SpanOutputProcessor[]
/** Get the logger instance (for exporters and other components) */
getLogger(): IMastraLogger
/** Start a new span of a specific SpanType */
startSpan<TType extends SpanType>(options: StartSpanOptions<TType>): Span<TType>
/** Force flush any buffered spans without shutting down */
flush(): Promise<void>
/** Shutdown observability and clean up resources */
shutdown(): Promise<void>
}
BatchDeleteTracesArgsDirect link to batchdeletetracesargs
Arguments for ObservabilityStorage.batchDeleteTraces(). The method deletes matching traces and spans, then cascades to metrics, logs, scores, and feedback linked by trace ID. Signals without a trace ID are preserved.
interface BatchDeleteTracesArgs {
traceIds: string[]
organizationId?: string
resourceId?: string
}
When organizationId or resourceId is provided, only records matching the scope are deleted. Storage adapters that don't support tenant-scoped trace deletion throw an error rather than applying an unscoped delete.
For ClickHouse vNext, the method records the complete predicate and waits for lightweight delete masks to be applied. Normal reads no longer return the rows matched by that operation when the call resolves. Lightweight deletion is hide-only through ClickHouse's _row_exists mask. Physical removal depends on merges and deployment-configured retention TTLs, which Mastra OSS doesn't configure by default. Deletion requests aren't purged automatically in Mastra OSS. Automatic retirement will be introduced with future database-agnostic retention configuration.
SpanTypeMapDirect link to spantypemap
Mapping of span types to their corresponding attribute interfaces. The list below is abbreviated. The SpanTypeMap interface in @mastra/core/observability is the complete one.
interface SpanTypeMap {
AGENT_RUN: AgentRunAttributes
WORKFLOW_RUN: WorkflowRunAttributes
MODEL_GENERATION: ModelGenerationAttributes
MODEL_STEP: ModelStepAttributes
MODEL_INFERENCE: ModelInferenceAttributes
MODEL_CHUNK: ModelChunkAttributes
TOOL_CALL: ToolCallAttributes
CLIENT_TOOL_CALL: ClientToolCallAttributes
PROVIDER_TOOL_CALL: ProviderToolCallAttributes
MCP_TOOL_CALL: MCPToolCallAttributes
PROCESSOR_RUN: ProcessorRunAttributes
WORKFLOW_STEP: WorkflowStepAttributes
WORKFLOW_CONDITIONAL: WorkflowConditionalAttributes
WORKFLOW_CONDITIONAL_EVAL: WorkflowConditionalEvalAttributes
WORKFLOW_PARALLEL: WorkflowParallelAttributes
WORKFLOW_LOOP: WorkflowLoopAttributes
WORKFLOW_SLEEP: WorkflowSleepAttributes
WORKFLOW_WAIT_EVENT: WorkflowWaitEventAttributes
MEMORY_OPERATION: MemoryOperationAttributes
WORKSPACE_ACTION: WorkspaceActionAttributes
SKILL_ACTION: SkillActionAttributes
AGENT_SIGNAL: AgentSignalAttributes
SKILL_RESOLUTION: SkillResolutionAttributes
GENERIC: AIBaseAttributes
}
This mapping defines which attribute interface is used for each span type when creating or processing spans.
SpanInputMap and SpanOutputMapDirect link to spaninputmap-and-spanoutputmap
Mapping of the span types whose input and output Mastra writes itself with a fixed shape. Every other span type keeps any: tool arguments and workflow data are caller-defined, MODEL_CHUNK carries several chunk shapes on one span type, and GENERIC is the escape hatch for custom spans.
interface SpanInputMap {
AGENT_RUN: AgentRunInput
MODEL_GENERATION: ModelGenerationInput
MODEL_STEP: ModelStepInput
MODEL_INFERENCE: ModelStepInput
}
interface SpanOutputMap {
AGENT_RUN: AgentRunOutput
MODEL_GENERATION: ModelGenerationOutput
MODEL_STEP: ModelStepOutput
MODEL_INFERENCE: ModelStepResult
}
/** The mapped shape when the map lists the type, otherwise `any` */
type SpanInput<TType extends SpanType> = TType extends keyof SpanInputMap
? SpanInputMap[TType]
: any
type SpanOutput<TType extends SpanType> = TType extends keyof SpanOutputMap
? SpanOutputMap[TType]
: any
Narrow a span by its type to read the typed payload. On a stored SpanRecord, use isSpanRecordOfType:
import { SpanType, isSpanRecordOfType } from '@mastra/core/observability'
if (isSpanRecordOfType(span, SpanType.MODEL_GENERATION)) {
span.input?.messages // MessageListInput
span.attributes?.usage // UsageStats | undefined
}
To pick a renderer without checking shapes yourself, describe the payload. The tag is derived at read time from spanType and the value's shape. Nothing is stored.
import {
describeSpanError,
describeSpanInput,
describeSpanOutput,
} from '@mastra/core/observability'
const input = describeSpanInput(span)
// { type: 'text' | 'messages' | 'agent-run-resume' | 'json'; value } | undefined
const output = describeSpanOutput(span)
// { type: 'interrupted' | 'agent-run-result' | 'model-generation-result' | 'model-step-result' | 'text' | 'json'; value } | undefined
switch (output?.type) {
case 'interrupted':
return output.value.status // 'suspended' | 'aborted'
case 'model-generation-result':
return output.value.text
}
describeSpanError(span) // SpanErrorInfo | undefined
SpanDirect link to Span
Span interface, used internally for tracing.
interface Span<TType extends SpanType> {
readonly id: string
readonly traceId: string
readonly type: TType
readonly name: string
/** Is an internal span? (spans internal to the operation of mastra) */
isInternal: boolean
/** Parent span reference (undefined for root spans) */
parent?: AnySpan
/** Pointer to the ObservabilityInstance instance */
observabilityInstance: ObservabilityInstance
attributes?: SpanTypeMap[TType]
metadata?: Record<string, any>
input?: SpanInput<TType>
output?: SpanOutput<TType>
errorInfo?: any
/** Tags for categorizing traces (only present on root spans) */
tags?: string[]
/** End the span */
end(options?: EndSpanOptions<TType>): void
/** Record an error for the span, optionally end the span as well */
error(options: ErrorSpanOptions<TType>): void
/** Update span attributes */
update(options: UpdateSpanOptions<TType>): void
/** Create child span - can be any span type independent of parent */
createChildSpan<TChildType extends SpanType>(
options: ChildSpanOptions<TChildType>,
): Span<TChildType>
/** Create event span - can be any span type independent of parent */
createEventSpan<TChildType extends SpanType>(
options: ChildEventOptions<TChildType>,
): Span<TChildType>
/** Returns TRUE if the span is the root span of a trace */
get isRootSpan(): boolean
/** Returns TRUE if the span is a valid span (not a NO-OP Span) */
get isValid(): boolean
}
ObservabilityExporterDirect link to observabilityexporter
Interface for observability exporters.
interface ObservabilityExporter {
/** Exporter name */
name: string
/** Initialize exporter with tracing configuration and/or access to Mastra */
init?(options: InitExporterOptions): void
/** Handle tracing events */
onTracingEvent?(event: TracingEvent): void | Promise<void>
/** Handle log events */
onLogEvent?(event: LogEvent): void | Promise<void>
/** Handle metric events */
onMetricEvent?(event: MetricEvent): void | Promise<void>
/** Handle score events */
onScoreEvent?(event: ScoreEvent): void | Promise<void>
/** Handle feedback events */
onFeedbackEvent?(event: FeedbackEvent): void | Promise<void>
/** Handle exporter pipeline droppedEvent */
onDroppedEvent?(event: ObservabilityDropEvent): void | Promise<void>
/** Export tracing events */
exportTracingEvent(event: TracingEvent): Promise<void>
/**
* @deprecated Implement `onScoreEvent` instead. Eval scores now flow through the
* unified observability bus as `ScoreEvent`s. This method is preserved on the
* interface for backwards compatibility with existing exporters; new exporters
* should not implement it.
*/
addScoreToTrace?({
traceId,
spanId,
score,
reason,
scorerName,
metadata,
}: {
traceId: string
spanId?: string
score: number
reason?: string
scorerName: string
metadata?: Record<string, any>
}): Promise<void>
/** Force flush any buffered spans without shutting down */
flush(): Promise<void>
/** Shutdown exporter */
shutdown(): Promise<void>
}
Event callback payloads use observability event bus envelopes:
TracingEvent carries span lifecycle events with exportedSpan, LogEvent
wraps ExportedLog in log, MetricEvent wraps ExportedMetric in
metric, ScoreEvent wraps ExportedScore in score, and FeedbackEvent
wraps ExportedFeedback in feedback. For Mastra platform exporter behavior for these
callbacks, see MastraPlatformExporter.
Like LogEvent, MetricEvent, and FeedbackEvent, ScoreEvent is an
observability bus envelope that wraps a bounded payload. For scores, that
payload is ExportedScore.
ScoreEventDirect link to scoreevent
Score events are sent to exporters through onScoreEvent. The event is a small
envelope with the signal type and the score payload:
interface ScoreEvent {
type: 'score'
score: ExportedScore
}
ExportedScoreDirect link to exportedscore
ExportedScore is the bounded payload that exporters receive inside
ScoreEvent.score. It contains the score identity, target trace or span anchor,
scorer details, value, optional explanation, and correlation metadata.
interface ExportedScore {
scoreId: string
timestamp: Date
traceId?: string
spanId?: string
scorerId: string
scorerName?: string
scorerVersion?: string
source?: string
scoreSource?: string
score: number
reason?: string
experimentId?: string
scoreTraceId?: string
targetEntityType?: EntityType
correlationContext?: CorrelationContext
metadata?: Record<string, unknown>
}
traceId and spanId identify the trace or span being scored. scoreTraceId
identifies the trace of the scoring run itself when that scorer was traced. For
new exporters, prefer scoreSource over the deprecated source field, and
prefer correlationContext.experimentId over the deprecated top-level
experimentId field.
EntityType is Mastra's observability entity enum. Current values include
agent, scorer, rag_ingestion, trajectory, input_processor,
input_step_processor, output_processor, output_step_processor,
workflow_step, tool, workflow_run, and memory.
CorrelationContext is the shared context snapshot attached to observability
signals. It can carry entity hierarchy fields, user or organization identifiers,
run, session, thread, request, environment, source, service name, experiment,
and tags. Prefer the top-level traceId and spanId fields on
ExportedScore for the scored target.
ObservabilityDropEventDirect link to observabilitydropevent
Structured event emitted when the exporter pipeline drops observability events.
type ObservabilityDropSignal = 'tracing' | 'log' | 'metric' | 'score' | 'feedback'
type ObservabilityDropReason = 'unsupported-storage' | 'retry-exhausted'
interface ObservabilityDropEvent {
type: 'drop'
signal: ObservabilityDropSignal
reason: ObservabilityDropReason
count: number
timestamp: Date
exporterName: string
storageName?: string
error?: {
id?: string
domain?: string
message: string
}
}
Use onDroppedEvent on a custom exporter or bridge to forward these events to external metrics or alerting systems.
SpanOutputProcessorDirect link to spanoutputprocessor
Interface for span output processors.
interface SpanOutputProcessor {
/** Processor name */
name: string
/** Process span before export */
process(span?: AnySpan): AnySpan | undefined
/** Shutdown processor */
shutdown(): Promise<void>
}
Span typesDirect link to Span types
SpanTypeDirect link to spantype
AI-specific span types with their associated metadata. The list below is abbreviated. The SpanType enum in @mastra/core/observability is the complete one.
enum SpanType {
/** Agent run - root span for agent processes */
AGENT_RUN = 'agent_run',
/** Generic span for custom operations */
GENERIC = 'generic',
/** Model generation with model calls, token usage, prompts, completions */
MODEL_GENERATION = 'model_generation',
/** Single model execution step within a generation (one API call) */
MODEL_STEP = 'model_step',
/** Model provider call within a step - wraps only the inference, excluding processors and tool executions */
MODEL_INFERENCE = 'model_inference',
/** Individual model streaming chunk/event */
MODEL_CHUNK = 'model_chunk',
/** MCP (Model Context Protocol) tool execution */
MCP_TOOL_CALL = 'mcp_tool_call',
/**
* Processor execution. This is the default; a processor can declare a
* different span type so its span names the subsystem it belongs to.
* See `Processor.spanType`.
*/
PROCESSOR_RUN = 'processor_run',
/** Memory read or write, including the observational memory model passes */
MEMORY_OPERATION = 'memory_operation',
/** Workspace filesystem, sandbox, search, or mount operation */
WORKSPACE_ACTION = 'workspace_action',
/** Skill lifecycle operation: resolve, inject, activate, search, or read */
SKILL_ACTION = 'skill_action',
/**
* An agent state signal entering the model's context. Recorded as an event
* span, so it has a start time and no duration.
*/
AGENT_SIGNAL = 'agent_signal',
/**
* @deprecated Use `SKILL_ACTION` with `operation: 'resolve'`. No longer
* emitted; retained so stored traces keep resolving.
*/
SKILL_RESOLUTION = 'skill_resolution',
/** Function/tool execution with inputs, outputs, errors */
TOOL_CALL = 'tool_call',
/**
* Client-side tool execution marker. The server creates this span
* when the model emits a client tool call, injects its W3C carrier
* into the outgoing tool-call chunk, then ends the span once tool
* args are available. Child spans/logs from the client SDK flow back
* as OTLP/JSON via the ClientObservabilityProxy interface in
* @mastra/observability and parent themselves under this span.
* See the "Client tools" section in the @mastra/client-js reference
* for the full flow.
*/
CLIENT_TOOL_CALL = 'client_tool_call',
/**
* Provider-executed (server-side) tool span. Reconstructed from
* tool-call and tool-result stream chunks for tools the model
* provider executes (e.g. Anthropic code execution, server-side
* web search). Created on the tool-result chunk under the model
* step that delivered it, with the start time backdated to the
* tool-call chunk.
*/
PROVIDER_TOOL_CALL = 'provider_tool_call',
/** Workflow run - root span for workflow processes */
WORKFLOW_RUN = 'workflow_run',
/** Workflow step execution with step status, data flow */
WORKFLOW_STEP = 'workflow_step',
/** Workflow conditional execution with condition evaluation */
WORKFLOW_CONDITIONAL = 'workflow_conditional',
/** Individual condition evaluation within conditional */
WORKFLOW_CONDITIONAL_EVAL = 'workflow_conditional_eval',
/** Workflow parallel execution */
WORKFLOW_PARALLEL = 'workflow_parallel',
/** Workflow loop execution */
WORKFLOW_LOOP = 'workflow_loop',
/** Workflow sleep operation */
WORKFLOW_SLEEP = 'workflow_sleep',
/** Workflow wait for event operation */
WORKFLOW_WAIT_EVENT = 'workflow_wait_event',
}
AnySpanDirect link to anyspan
Union type for cases that need to handle any span.
type AnySpan = Span<keyof SpanTypeMap>
Span attributesDirect link to Span attributes
AgentRunAttributesDirect link to agentrunattributes
Agent Run attributes.
interface AgentRunAttributes {
/** Agent identifier */
agentId: string
/** Agent Instructions */
instructions?: string
/** Agent Prompt */
prompt?: string
/** Available tools for this execution */
availableTools?: string[]
/** Maximum steps allowed */
maxSteps?: number
}
ModelGenerationAttributesDirect link to modelgenerationattributes
Model Generation attributes.
interface ModelGenerationAttributes {
/** Model name (e.g., 'gpt-5.4', 'claude-opus-4-6') */
model?: string
/** Model provider (e.g., 'openai', 'anthropic') */
provider?: string
/**
* Definitions of the tools made available to the model for this generation
* (name, description, and JSON-schema parameters), captured once per
* generation. Per-step tool names live on MODEL_INFERENCE spans as
* `availableTools`.
*/
tools?: ModelToolDefinition[]
/** Type of result/output this model call produced */
resultType?: 'tool_selection' | 'response_generation' | 'reasoning' | 'planning'
/** Token usage statistics */
usage?: {
promptTokens?: number
completionTokens?: number
totalTokens?: number
promptCacheHitTokens?: number
promptCacheMissTokens?: number
}
/** Model parameters */
parameters?: {
maxOutputTokens?: number
temperature?: number
topP?: number
topK?: number
presencePenalty?: number
frequencyPenalty?: number
stopSequences?: string[]
seed?: number
maxRetries?: number
}
/** Whether this was a streaming response */
streaming?: boolean
/** Reason the generation finished */
finishReason?: string
}
ModelToolDefinitionDirect link to modeltooldefinition
Serialized definition of one tool made available to the model, attached to MODEL_GENERATION spans so observability exporters can surface tool schemas.
interface ModelToolDefinition {
/** Tool type: 'function' for standard tools, or the provider tool type (e.g. 'provider-defined') */
type: string
name: string
description?: string
/** JSON schema of the tool's input parameters (function tools) */
parameters?: Record<string, unknown>
/** Provider tool id (e.g. 'anthropic.web_search_20250305') for provider-defined tools */
id?: string
}
ModelStepAttributesDirect link to modelstepattributes
Model Step attributes - for a single model execution within a generation.
interface ModelStepAttributes {
/** Index of this step in the generation (0, 1, 2, ...) */
stepIndex?: number
/** Token usage statistics */
usage?: UsageStats
/** Reason this step finished (stop, tool-calls, length, etc.) */
finishReason?: string
/** Should execution continue */
isContinued?: boolean
/** Result warnings */
warnings?: Record<string, any>
}
ModelChunkAttributesDirect link to modelchunkattributes
Model Chunk attributes - for individual streaming chunks/events.
interface ModelChunkAttributes {
/** Type of chunk (text-delta, reasoning-delta, tool-call, etc.) */
chunkType?: string
/** Sequence number of this chunk in the stream */
sequenceNumber?: number
}
ToolCallAttributesDirect link to toolcallattributes
Tool Call attributes.
interface ToolCallAttributes {
toolId?: string
toolType?: string
toolDescription?: string
toolCallId?: string
success?: boolean
}
MCPToolCallAttributesDirect link to MCPToolCallAttributes
MCP Tool Call attributes.
interface MCPToolCallAttributes {
/** Id of the MCP tool/function */
toolId: string
/** MCP server identifier */
mcpServer: string
/** MCP server version */
serverVersion?: string
/** Tool description */
toolDescription?: string
toolCallId?: string
/** Whether tool execution was successful */
success?: boolean
}
ProcessorRunAttributesDirect link to processorrunattributes
Processor attributes.
interface ProcessorRunAttributes {
/** Name of the Processor */
processorName: string
/** Processor type (input or output) */
processorType: 'input' | 'output'
/** Processor index in the agent */
processorIndex?: number
}
WorkflowRunAttributesDirect link to workflowrunattributes
Workflow Run attributes.
interface WorkflowRunAttributes {
/** Workflow identifier */
workflowId: string
/** Workflow status */
status?: WorkflowRunStatus
}
WorkflowStepAttributesDirect link to workflowstepattributes
Workflow Step attributes.
interface WorkflowStepAttributes {
/** Step identifier */
stepId: string
/** Step status */
status?: WorkflowStepStatus
}
Span payloadsDirect link to Span payloads
AgentRunInputDirect link to agentruninput
Input recorded on AGENT_RUN spans: the messages the caller passed for a fresh run, or the resume data for a resumed run.
type AgentRunInput = MessageListInput | { messages: MessageListInput } | AgentRunResumeInput
interface AgentRunResumeInput {
/** Resume data, kept nested when it names a different tool than the suspended one */
resumeData?: unknown
/** Tool the run resumes into */
toolName?: string
/** Tool call the run resumes into */
toolCallId?: string
[key: string]: unknown
}
AgentRunOutputDirect link to agentrunoutput
Output recorded on AGENT_RUN spans.
type AgentRunOutput = AgentRunResult | InterruptedSpanOutput
interface AgentRunResult {
/** Final response text */
text?: string
/** Final structured output */
object?: unknown
/** Generated files */
files?: unknown[]
/** Tripwire that aborted the run */
tripwire?: StepTripwireData
}
ModelGenerationInputDirect link to modelgenerationinput
Input recorded on MODEL_GENERATION spans.
Mastra's own loop records the normalized model messages, system messages first. SDK agents record the raw messages the caller passed, so messages keeps the full MessageListInput shape.
interface ModelGenerationInput {
/** Messages sent to the model */
messages: MessageListInput
/** Output schema, when structured output was requested */
schema?: unknown
}
ModelGenerationOutputDirect link to modelgenerationoutput
Output recorded on MODEL_GENERATION spans: a ModelGenerationResult when the generation finishes, or an InterruptedSpanOutput when the run stops first. Every field of ModelGenerationResult is optional: a durable run records only text.
type ModelGenerationOutput = ModelGenerationResult | InterruptedSpanOutput
interface ModelGenerationResult {
text?: string
object?: unknown
reasoning?: unknown
reasoningText?: string
files?: unknown[]
sources?: unknown[]
toolCalls?: unknown[]
warnings?: unknown[]
}
ModelStepInputDirect link to modelstepinput
Input recorded on MODEL_STEP and MODEL_INFERENCE spans: a shallow preview of what the step sent to the model.
type ModelStepInput = ModelStepMessage[] | Record<string, unknown> | string
interface ModelStepMessage {
/** Message role (e.g., 'system', 'user', 'assistant', 'tool') */
role: string
/** Message text, with non-text parts summarized */
content: string
}
ModelStepOutputDirect link to modelstepoutput
Output recorded on MODEL_STEP spans. A finished step records a ModelStepResult, which is the step output without usage (that lives on the attributes). A step cut short by a suspension or an abort records an InterruptedSpanOutput instead. MODEL_INFERENCE spans always record a ModelStepResult.
type ModelStepOutput = ModelStepResult | InterruptedSpanOutput
interface ModelStepResult {
text?: string
toolCalls?: unknown[]
steps?: unknown[]
object?: unknown
}
InterruptedSpanOutputDirect link to interruptedspanoutput
Output recorded on AGENT_RUN, MODEL_GENERATION and MODEL_STEP spans when the run stops before the span's own result exists: a durable run suspended, or the caller aborted. MODEL_INFERENCE spans never carry it.
interface InterruptedSpanOutput {
status: 'suspended' | 'aborted'
/** Why the run stopped */
reason?: string
/** Tool that suspended the run */
toolName?: string
/** Tool call that suspended the run */
toolCallId?: string
}
Options typesDirect link to Options types
StartSpanOptionsDirect link to startspanoptions
Options for starting new spans.
interface StartSpanOptions<TType extends SpanType> {
/** Span type */
type: TType
/** Span name */
name: string
/** Span attributes */
attributes?: SpanTypeMap[TType]
/** Span metadata */
metadata?: Record<string, any>
/** Input data */
input?: SpanInput<TType>
/** Parent span */
parent?: AnySpan
/** Policy-level tracing configuration */
tracingPolicy?: TracingPolicy
/** Options passed when using a custom sampler strategy */
customSamplerOptions?: CustomSamplerOptions
}
UpdateSpanOptionsDirect link to updatespanoptions
Options for updating spans.
interface UpdateSpanOptions<TType extends SpanType> {
/** Span attributes */
attributes?: Partial<SpanTypeMap[TType]>
/** Span metadata */
metadata?: Record<string, any>
/** Input data */
input?: SpanInput<TType>
/** Output data */
output?: SpanOutput<TType>
}
EndSpanOptionsDirect link to endspanoptions
Options for ending spans.
interface EndSpanOptions<TType extends SpanType> {
/** Output data */
output?: SpanOutput<TType>
/** Span metadata */
metadata?: Record<string, any>
/** Span attributes */
attributes?: Partial<SpanTypeMap[TType]>
}
ErrorSpanOptionsDirect link to errorspanoptions
Options for recording span errors.
interface ErrorSpanOptions<TType extends SpanType> {
/** The error associated with the issue */
error: Error
/** End the span when true */
endSpan?: boolean
/** Span metadata */
metadata?: Record<string, any>
/** Span attributes */
attributes?: Partial<SpanTypeMap[TType]>
}
Context typesDirect link to Context types
TracingContextDirect link to tracingcontext
Context for Tracing that flows through workflow and agent execution.
interface TracingContext {
/** Current span for creating child spans and adding metadata */
currentSpan?: AnySpan
}
TracingPropertiesDirect link to tracingproperties
Properties returned to the user for working with traces externally.
type TracingProperties = {
/** Trace ID used on the execution (if the execution was traced) */
traceId?: string
}
TracingOptionsDirect link to tracingoptions
Options passed when starting a new agent or workflow execution.
interface TracingOptions {
/** Metadata to add to the root trace span */
metadata?: Record<string, any>
/**
* Additional RequestContext keys to extract as metadata for this trace.
* These keys are added to the requestContextKeys config.
* Supports dot notation for nested values (e.g., 'user.id', 'session.data.experimentId').
*/
requestContextKeys?: string[]
/**
* Trace ID to use for this execution (1-32 hexadecimal characters).
* If provided, this trace will be part of the specified trace rather than starting a new one.
*/
traceId?: string
/**
* Parent span ID to use for this execution (1-16 hexadecimal characters).
* If provided, the root span will be created as a child of this span.
*/
parentSpanId?: string
/**
* Tags to apply to this trace.
* Tags are string labels that can be used to categorize and filter traces
* Note: Tags are only applied to the root span of a trace.
*/
tags?: string[]
/**
* When true, input data will be hidden from all spans in this trace.
* Useful for protecting sensitive data from being logged.
*/
hideInput?: boolean
/**
* When true, output data will be hidden from all spans in this trace.
* Useful for protecting sensitive data from being logged.
*/
hideOutput?: boolean
}
TracingPolicyDirect link to tracingpolicy
Policy-level tracing configuration applied when creating a workflow or agent.
interface TracingPolicy {
/**
* Bitwise options to set different types of spans as Internal in
* a workflow or agent execution. Internal spans are hidden by
* default in exported traces.
*/
internal?: InternalSpans
}
Configuration typesDirect link to Configuration types
ObservabilityInstanceConfigDirect link to observabilityinstanceconfig
Configuration for a single observability instance.
interface ObservabilityInstanceConfig {
/** Unique identifier for this config in the observability registry */
name: string
/** Service name for observability */
serviceName: string
/** Sampling strategy - controls whether tracing is collected (defaults to ALWAYS) */
sampling?: SamplingStrategy
/** Custom exporters */
exporters?: ObservabilityExporter[]
/** Custom span output processors */
spanOutputProcessors?: SpanOutputProcessor[]
/** Set to true if you want to see spans internal to the operation of mastra */
includeInternalSpans?: boolean
/** RequestContext keys to automatically extract as metadata for all spans */
requestContextKeys?: string[]
}
ObservabilityRegistryConfigDirect link to observabilityregistryconfig
Complete observability registry configuration.
interface ObservabilityRegistryConfig {
/** Enables default exporters, with sampling: always, and sensitive data filtering */
default?: {
enabled?: boolean
}
/** Map of tracing instance names to their configurations or pre-instantiated instances */
configs?: Record<string, Omit<ObservabilityInstanceConfig, 'name'> | ObservabilityInstance>
/** Optional selector function to choose which tracing instance to use */
configSelector?: ConfigSelector
}
Sampling typesDirect link to Sampling types
SamplingStrategyDirect link to samplingstrategy
Sampling strategy configuration.
type SamplingStrategy =
| { type: 'always' }
| { type: 'never' }
| { type: 'ratio'; probability: number }
| { type: 'custom'; sampler: (options?: CustomSamplerOptions) => boolean }
CustomSamplerOptionsDirect link to customsampleroptions
Options passed when using a custom sampler strategy.
interface CustomSamplerOptions {
requestContext?: RequestContext
metadata?: Record<string, any>
}
Config selector typesDirect link to Config selector types
ConfigSelectorDirect link to configselector
Function to select which observability instance to use for a span.
type ConfigSelector = (
options: ConfigSelectorOptions,
availableConfigs: ReadonlyMap<string, ObservabilityInstance>,
) => string | undefined
ConfigSelectorOptionsDirect link to configselectoroptions
Options passed when using a custom tracing config selector.
interface ConfigSelectorOptions {
/** Request Context */
requestContext?: RequestContext
}
Internal spansDirect link to Internal spans
InternalSpansDirect link to internalspans
Bitwise options to set different types of spans as internal in a workflow or agent execution.
enum InternalSpans {
/** No spans are marked internal */
NONE = 0,
/** Workflow spans are marked internal */
WORKFLOW = 1 << 0,
/** Agent spans are marked internal */
AGENT = 1 << 1,
/** Tool spans are marked internal */
TOOL = 1 << 2,
/** Model spans are marked internal */
MODEL = 1 << 3,
/** All spans are marked internal */
ALL = (1 << 4) - 1,
}
See alsoDirect link to See also
DocumentationDirect link to Documentation
- Tracing Overview: Complete guide to Tracing
- Creating Child Spans: Working with span hierarchies
- Adding Custom Metadata: Enriching traces
ReferenceDirect link to Reference
- Configuration: Registry and configuration
- Tracing Classes: Core implementations
- Spans Reference: Span lifecycle methods