メインコンテンツへ移動

インターフェース

主要インターフェース
主要インターフェースへの直接リンク

ObservabilityInstance
observabilityinstanceへの直接リンク

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>
}

SpanTypeMap
spantypemapへの直接リンク

span 型と対応する属性インターフェースのマッピングです。

interface SpanTypeMap {
AGENT_RUN: AgentRunAttributes
WORKFLOW_RUN: WorkflowRunAttributes
MODEL_GENERATION: ModelGenerationAttributes
MODEL_STEP: ModelStepAttributes
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
GENERIC: AIBaseAttributes
}

このマッピングは、span の作成時または処理時に各 span 型で使用する属性インターフェースを定義します。

Span
Spanへの直接リンク

tracing で内部的に使用される Span インターフェースです。

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?: any
output?: any
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
}

ObservabilityExporter
observabilityexporterへの直接リンク

observability exporter のインターフェースです。

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>
}

イベント callback の payload には observability event bus の envelope を使用します。 TracingEventexportedSpan で span のライフサイクルイベントを運び、LogEventExportedLoglog に、MetricEventExportedMetricmetric に、ScoreEventExportedScorescore に、FeedbackEventExportedFeedbackfeedback にラップします。これらの callback に対する Mastra platform exporter の動作については、MastraPlatformExporterを参照してください。

LogEventMetricEventFeedbackEvent と同様に、ScoreEvent は範囲が限定された payload をラップする observability bus envelope です。score の場合、その payload は ExportedScore です。

ScoreEvent
scoreeventへの直接リンク

score イベントは onScoreEvent を通じて exporter に送信されます。このイベントは、 signal 型と score payload を持つ小さな envelope です。

interface ScoreEvent {
type: 'score'
score: ExportedScore
}

ExportedScore
exportedscoreへの直接リンク

ExportedScore は、exporter が ScoreEvent.score 内で受信する範囲限定の payload です。 score の識別情報、対象の Trace または span の anchor、scorer の詳細、値、任意の説明、 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>
}

traceIdspanId は、score 対象の Trace または span を識別します。scoreTraceId は、 scorer が traced された場合に scoring run 自体の Trace を識別します。新しい exporter では、 非推奨の source フィールドより scoreSource を優先し、非推奨の最上位 experimentId フィールドより correlationContext.experimentId を優先してください。

EntityType は Mastra の observability entity enum です。現在の値には agent, scorer, rag_ingestion, trajectory, input_processor, input_step_processor, output_processor, output_step_processor, workflow_steptoolworkflow_runmemory があります。

CorrelationContext は observability signal に付加される共有 context snapshot です。 entity 階層フィールド、ユーザーまたは組織の識別子、run、session、thread、request、 environment、source、service name、experiment、tag を保持できます。score 対象には、 ExportedScore の最上位 traceId および spanId フィールドを優先してください。

ObservabilityDropEvent
observabilitydropeventへの直接リンク

exporter pipeline が observability イベントを破棄したときに発行される構造化イベントです。

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
}
}

これらのイベントを外部の metrics または alerting system に転送するには、カスタム exporter または bridge で onDroppedEvent を使用します。

SpanOutputProcessor
spanoutputprocessorへの直接リンク

span output processor のインターフェースです。

interface SpanOutputProcessor {
/** Processor name */
name: string

/** Process span before export */
process(span?: AnySpan): AnySpan | undefined

/** Shutdown processor */
shutdown(): Promise<void>
}

Span 型
Span 型への直接リンク

SpanType
spantypeへの直接リンク

関連する metadata を持つ AI 固有の span 型です。

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',

/** Individual model streaming chunk/event */
MODEL_CHUNK = 'model_chunk',

/** MCP (Model Context Protocol) tool execution */
MCP_TOOL_CALL = 'mcp_tool_call',

/** Input or Output Processor execution */
PROCESSOR_RUN = 'processor_run',

/** 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',
}

AnySpan
anyspanへの直接リンク

任意の span を処理する必要がある場合の Union 型です。

type AnySpan = Span<keyof SpanTypeMap>

Span 属性
Span 属性への直接リンク

AgentRunAttributes
agentrunattributesへの直接リンク

Agent Run の属性です。

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
}

ModelGenerationAttributes
modelgenerationattributesへの直接リンク

Model Generation の属性です。

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
}

ModelToolDefinition
modeltooldefinitionへの直接リンク

モデルで利用できる 1 つの Tool の serialize 済み定義です。observability exporter が Tool schema を表示できるよう、MODEL_GENERATION span に付加されます。

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
}

ModelStepAttributes
modelstepattributesへの直接リンク

generation 内の 1 回のモデル実行に対する Model Step 属性です。

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>
}

ModelChunkAttributes
modelchunkattributesへの直接リンク

個々の streaming chunk/event に対する Model Chunk 属性です。

interface ModelChunkAttributes {
/** Type of chunk (text-delta, reasoning-delta, tool-call, etc.) */
chunkType?: string

/** Sequence number of this chunk in the stream */
sequenceNumber?: number
}

ToolCallAttributes
toolcallattributesへの直接リンク

Tool Call の属性です。

interface ToolCallAttributes {
toolId?: string
toolType?: string
toolDescription?: string
toolCallId?: string
success?: boolean
}

MCPToolCallAttributes
MCPToolCallAttributesへの直接リンク

MCP Tool Call の属性です。

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
}

ProcessorRunAttributes
processorrunattributesへの直接リンク

Processor の属性です。

interface ProcessorRunAttributes {
/** Name of the Processor */
processorName: string

/** Processor type (input or output) */
processorType: 'input' | 'output'

/** Processor index in the agent */
processorIndex?: number
}

WorkflowRunAttributes
workflowrunattributesへの直接リンク

Workflow Run の属性です。

interface WorkflowRunAttributes {
/** Workflow identifier */
workflowId: string

/** Workflow status */
status?: WorkflowRunStatus
}

WorkflowStepAttributes
workflowstepattributesへの直接リンク

Workflow Step の属性です。

interface WorkflowStepAttributes {
/** Step identifier */
stepId: string

/** Step status */
status?: WorkflowStepStatus
}

オプション型
オプション型への直接リンク

StartSpanOptions
startspanoptionsへの直接リンク

新しい span を開始するためのオプションです。

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?: any

/** Parent span */
parent?: AnySpan

/** Policy-level tracing configuration */
tracingPolicy?: TracingPolicy

/** Options passed when using a custom sampler strategy */
customSamplerOptions?: CustomSamplerOptions
}

UpdateSpanOptions
updatespanoptionsへの直接リンク

span を更新するためのオプションです。

interface UpdateSpanOptions<TType extends SpanType> {
/** Span attributes */
attributes?: Partial<SpanTypeMap[TType]>

/** Span metadata */
metadata?: Record<string, any>

/** Input data */
input?: any

/** Output data */
output?: any
}

EndSpanOptions
endspanoptionsへの直接リンク

span を終了するためのオプションです。

interface EndSpanOptions<TType extends SpanType> {
/** Output data */
output?: any

/** Span metadata */
metadata?: Record<string, any>

/** Span attributes */
attributes?: Partial<SpanTypeMap[TType]>
}

ErrorSpanOptions
errorspanoptionsへの直接リンク

span のエラーを記録するためのオプションです。

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 型
Context 型への直接リンク

TracingContext
tracingcontextへの直接リンク

Workflow と Agent の実行を通じて伝播する Tracing の context です。

interface TracingContext {
/** Current span for creating child spans and adding metadata */
currentSpan?: AnySpan
}

TracingProperties
tracingpropertiesへの直接リンク

外部から Trace を操作するためにユーザーへ返されるプロパティです。

type TracingProperties = {
/** Trace ID used on the execution (if the execution was traced) */
traceId?: string
}

TracingOptions
tracingoptionsへの直接リンク

新しい Agent または Workflow の実行を開始するときに渡すオプションです。

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
}

TracingPolicy
tracingpolicyへの直接リンク

Workflow または Agent の作成時に適用される policy level の tracing 設定です。

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
}

設定型
設定型への直接リンク

ObservabilityInstanceConfig
observabilityinstanceconfigへの直接リンク

単一の observability インスタンスの設定です。

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[]
}

ObservabilityRegistryConfig
observabilityregistryconfigへの直接リンク

observability registry の完全な設定です。

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 型
Sampling 型への直接リンク

SamplingStrategy
samplingstrategyへの直接リンク

sampling strategy の設定です。

type SamplingStrategy =
| { type: 'always' }
| { type: 'never' }
| { type: 'ratio'; probability: number }
| { type: 'custom'; sampler: (options?: CustomSamplerOptions) => boolean }

CustomSamplerOptions
customsampleroptionsへの直接リンク

カスタム sampler strategy を使用するときに渡すオプションです。

interface CustomSamplerOptions {
requestContext?: RequestContext
metadata?: Record<string, any>
}

Config selector 型
Config selector 型への直接リンク

ConfigSelector
configselectorへの直接リンク

span に使用する observability インスタンスを選択する関数です。

type ConfigSelector = (
options: ConfigSelectorOptions,
availableConfigs: ReadonlyMap<string, ObservabilityInstance>,
) => string | undefined

ConfigSelectorOptions
configselectoroptionsへの直接リンク

カスタム tracing config selector を使用するときに渡すオプションです。

interface ConfigSelectorOptions {
/** Request Context */
requestContext?: RequestContext
}

内部 span
内部 spanへの直接リンク

InternalSpans
internalspansへの直接リンク

Workflow または Agent の実行で、各種 span を内部として設定する bitwise オプションです。

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,
}

関連項目
関連項目への直接リンク

ドキュメント
ドキュメントへの直接リンク

リファレンス
リファレンスへの直接リンク