介面
核心介面「核心介面」的直接連結
ObservabilityInstance「observabilityinstance」的直接連結
可觀測性的主要介面。
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 類型與其對應屬性介面的 mapping。
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
}
此 mapping 定義建立或處理 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」的直接連結
可觀測性 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 使用可觀測性 event bus envelope:
TracingEvent 以 exportedSpan 攜帶 span 生命週期事件,LogEvent
以 log 包裝 ExportedLog,MetricEvent 以 metric 包裝
ExportedMetric,ScoreEvent 以 score 包裝 ExportedScore,而
FeedbackEvent 以 feedback 包裝 ExportedFeedback。如需這些 callback 的
Mastra platform exporter 行為,請參閱 MastraPlatformExporter。
與 LogEvent、MetricEvent 及 FeedbackEvent 相同,ScoreEvent 是
包裝有界 payload 的可觀測性 bus envelope。對分數而言,該 payload
為 ExportedScore。
ScoreEvent「scoreevent」的直接連結
分數事件會透過 onScoreEvent 傳送至 exporter。此事件是一個包含
signal 類型與分數 payload 的小型 envelope:
interface ScoreEvent {
type: 'score'
score: ExportedScore
}
ExportedScore「exportedscore」的直接連結
ExportedScore 是 exporter 在 ScoreEvent.score 內收到的有界 payload。
其中包含分數識別資訊、目標 trace 或 span 定位依據、scorer 詳細資料、值、
選用說明與關聯 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 與 spanId 用於識別被評分的 trace 或 span。當該 scorer 經過
tracing 時,scoreTraceId 會識別評分 run 本身的 trace。對新的 exporter,
請優先使用 scoreSource,而非已淘汰的 source 欄位;並優先使用
correlationContext.experimentId,而非已淘汰的頂層 experimentId 欄位。
EntityType 是 Mastra 的可觀測性實體 enum。目前的值包括
agent, scorer, rag_ingestion, trajectory, input_processor,
input_step_processor, output_processor, output_step_processor,
workflow_step、tool、workflow_run 與 memory。
CorrelationContext 是附加至可觀測性 signal 的共用 context 快照。
它可攜帶實體階層欄位、使用者或組織識別碼、run、session、thread、request、
環境、來源、服務名稱、實驗與標籤。對評分目標,請優先使用
ExportedScore 上的頂層 traceId 與 spanId 欄位。
ObservabilityDropEvent「observabilitydropevent」的直接連結
Exporter pipeline 捨棄可觀測性事件時產生的結構化事件。
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
}
}
在自訂 exporter 或 bridge 上使用 onDroppedEvent,將這些事件轉送至外部指標或 alert 系統。
SpanOutputProcessor「spanoutputprocessor」的直接連結
Span 輸出 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」的直接連結
AI 專屬 span 類型及其相關 metadata。
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」的直接連結
提供給模型之單一 Tool 的序列化定義,會附加至 MODEL_GENERATION span,讓可觀測性 exporter 能呈現 Tool schema。
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」的直接連結
Model Step 屬性,用於 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>
}
ModelChunkAttributes「modelchunkattributes」的直接連結
Model Chunk 屬性,用於個別串流 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 層級 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」的直接連結
單一可觀測性執行個體的設定。
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」的直接連結
完整的可觀測性 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
}
取樣型別「取樣型別」的直接連結
SamplingStrategy「samplingstrategy」的直接連結
取樣策略設定。
type SamplingStrategy =
| { type: 'always' }
| { type: 'never' }
| { type: 'ratio'; probability: number }
| { type: 'custom'; sampler: (options?: CustomSamplerOptions) => boolean }
CustomSamplerOptions「customsampleroptions」的直接連結
使用自訂 sampler 策略時傳入的選項。
interface CustomSamplerOptions {
requestContext?: RequestContext
metadata?: Record<string, any>
}
Config selector 型別「Config selector 型別」的直接連結
ConfigSelector「configselector」的直接連結
選取 span 要使用之可觀測性執行個體的函式。
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 設為內部 span 的位元選項。
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,
}
另請參閱「另請參閱」的直接連結
文件「文件」的直接連結
- Tracing 概覽:Tracing 完整指南
- 建立子 Span:使用 span 階層
- 新增自訂 Metadata:豐富 trace 資訊
參考「參考」的直接連結
- 設定:Registry 與設定
- Tracing 類別:核心實作
- Span 參考:Span 生命週期方法