> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 接口 ## 核心接口 ### `ObservabilityInstance` 可观测性的主要接口。 ```typescript interface ObservabilityInstance { /** Get current configuration */ getConfig(): Readonly> /** 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(options: StartSpanOptions): Span /** Force flush any buffered spans without shutting down */ flush(): Promise /** Shutdown observability and clean up resources */ shutdown(): Promise } ``` ### `SpanTypeMap` Span 类型与其对应属性接口之间的映射。 ```typescript 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 内部使用。 ```typescript interface Span { 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 input?: any output?: any errorInfo?: any /** Tags for categorizing traces (only present on root spans) */ tags?: string[] /** End the span */ end(options?: EndSpanOptions): void /** Record an error for the span, optionally end the span as well */ error(options: ErrorSpanOptions): void /** Update span attributes */ update(options: UpdateSpanOptions): void /** Create child span - can be any span type independent of parent */ createChildSpan( options: ChildSpanOptions, ): Span /** Create event span - can be any span type independent of parent */ createEventSpan( options: ChildEventOptions, ): Span /** 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` 可观测性 Exporter 的接口。 ```typescript 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 /** Handle log events */ onLogEvent?(event: LogEvent): void | Promise /** Handle metric events */ onMetricEvent?(event: MetricEvent): void | Promise /** Handle score events */ onScoreEvent?(event: ScoreEvent): void | Promise /** Handle feedback events */ onFeedbackEvent?(event: FeedbackEvent): void | Promise /** Handle exporter pipeline droppedEvent */ onDroppedEvent?(event: ObservabilityDropEvent): void | Promise /** Export tracing events */ exportTracingEvent(event: TracingEvent): Promise /** * @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 }): Promise /** Force flush any buffered spans without shutting down */ flush(): Promise /** Shutdown exporter */ shutdown(): Promise } ``` 事件回调负载使用可观测性事件总线信封: `TracingEvent` 通过 `exportedSpan` 携带 Span 生命周期事件;`LogEvent` 在 `log` 中封装 `ExportedLog`;`MetricEvent` 在 `metric` 中封装 `ExportedMetric`;`ScoreEvent` 在 `score` 中封装 `ExportedScore`; `FeedbackEvent` 在 `feedback` 中封装 `ExportedFeedback`。有关这些回调在 Mastra 平台 Exporter 中的行为,请参阅 [MastraPlatformExporter](https://mastra.zisheng.pro/reference/observability/tracing/exporters/mastra-platform-exporter)。 与 `LogEvent`、`MetricEvent` 和 `FeedbackEvent` 一样,`ScoreEvent` 是一个 封装有界负载的可观测性总线信封。对于分数,该负载为 `ExportedScore`。 ### `ScoreEvent` 分数事件通过 `onScoreEvent` 发送给 Exporter。该事件是一个小型信封, 其中包含信号类型和分数负载: ```typescript interface ScoreEvent { type: 'score' score: ExportedScore } ``` ### `ExportedScore` `ExportedScore` 是 Exporter 在 `ScoreEvent.score` 中接收的有界负载。 它包含分数标识、目标 Trace 或 Span 锚点、评分器详细信息、值、可选说明和关联元数据。 ```typescript 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 } ``` `traceId` 和 `spanId` 标识被评分的 Trace 或 Span。对评分器进行 Tracing 时, `scoreTraceId` 标识评分运行本身的 Trace。对于新的 Exporter,应优先使用 `scoreSource`,而不是已弃用的 `source` 字段;并优先使用 `correlationContext.experimentId`,而不是已弃用的顶层 `experimentId` 字段。 `EntityType` 是 Mastra 的可观测性实体枚举。当前值包括 `agent`, `scorer`, `rag_ingestion`, `trajectory`, `input_processor`, `input_step_processor`, `output_processor`, `output_step_processor`, `workflow_step`、`tool`、`workflow_run` 和 `memory`。 `CorrelationContext` 是附加到可观测性信号的共享上下文快照。它可以携带实体层级字段、 用户或组织标识符、运行、会话、线程、请求、环境、来源、服务名称、实验和标签。 对于评分目标,应优先使用 `ExportedScore` 的顶层 `traceId` 和 `spanId` 字段。 ### `ObservabilityDropEvent` Exporter 管道丢弃可观测性事件时发出的结构化事件。 ```typescript 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 或桥接器上使用 `onDroppedEvent`,将这些事件转发到外部指标或告警系统。 ### `SpanOutputProcessor` Span 输出处理器的接口。 ```typescript interface SpanOutputProcessor { /** Processor name */ name: string /** Process span before export */ process(span?: AnySpan): AnySpan | undefined /** Shutdown processor */ shutdown(): Promise } ``` ## Span 类型 ### `SpanType` AI 专用的 Span 类型及其关联元数据。 ```typescript 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` 用于需要处理任意 Span 的场景的联合类型。 ```typescript type AnySpan = Span ``` ## Span 属性 ### `AgentRunAttributes` Agent Run 属性。 ```typescript 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` Model Generation 属性。 ```typescript 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` 提供给模型的单个 Tool 的序列化定义,附加到 `MODEL_GENERATION` Span,以便可观测性 Exporter 展示 Tool schema。 ```typescript 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 /** Provider tool id (e.g. 'anthropic.web_search_20250305') for provider-defined tools */ id?: string } ``` ### `ModelStepAttributes` Model Step 属性——用于一次生成过程中的单次模型执行。 ```typescript 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 } ``` ### `ModelChunkAttributes` Model Chunk 属性——用于各个流式数据块或事件。 ```typescript 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` Tool Call 属性。 ```typescript interface ToolCallAttributes { toolId?: string toolType?: string toolDescription?: string toolCallId?: string success?: boolean } ``` ### MCPToolCallAttributes MCP Tool Call 属性。 ```typescript 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` Processor 属性。 ```typescript interface ProcessorRunAttributes { /** Name of the Processor */ processorName: string /** Processor type (input or output) */ processorType: 'input' | 'output' /** Processor index in the agent */ processorIndex?: number } ``` ### `WorkflowRunAttributes` Workflow Run 属性。 ```typescript interface WorkflowRunAttributes { /** Workflow identifier */ workflowId: string /** Workflow status */ status?: WorkflowRunStatus } ``` ### `WorkflowStepAttributes` Workflow Step 属性。 ```typescript interface WorkflowStepAttributes { /** Step identifier */ stepId: string /** Step status */ status?: WorkflowStepStatus } ``` ## 选项类型 ### `StartSpanOptions` 启动新 Span 的选项。 ```typescript interface StartSpanOptions { /** Span type */ type: TType /** Span name */ name: string /** Span attributes */ attributes?: SpanTypeMap[TType] /** Span metadata */ metadata?: Record /** 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` 更新 Span 的选项。 ```typescript interface UpdateSpanOptions { /** Span attributes */ attributes?: Partial /** Span metadata */ metadata?: Record /** Input data */ input?: any /** Output data */ output?: any } ``` ### `EndSpanOptions` 结束 Span 的选项。 ```typescript interface EndSpanOptions { /** Output data */ output?: any /** Span metadata */ metadata?: Record /** Span attributes */ attributes?: Partial } ``` ### `ErrorSpanOptions` 记录 Span 错误的选项。 ```typescript interface ErrorSpanOptions { /** The error associated with the issue */ error: Error /** End the span when true */ endSpan?: boolean /** Span metadata */ metadata?: Record /** Span attributes */ attributes?: Partial } ``` ## 上下文类型 ### `TracingContext` 在 Workflow 和 Agent 执行过程中传递的 Tracing 上下文。 ```typescript interface TracingContext { /** Current span for creating child spans and adding metadata */ currentSpan?: AnySpan } ``` ### `TracingProperties` 返回给用户、用于从外部操作 Trace 的属性。 ```typescript type TracingProperties = { /** Trace ID used on the execution (if the execution was traced) */ traceId?: string } ``` ### `TracingOptions` 启动新的 Agent 或 Workflow 执行时传入的选项。 ```typescript interface TracingOptions { /** Metadata to add to the root trace span */ metadata?: Record /** * 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` 创建 Workflow 或 Agent 时应用的策略级 Tracing 配置。 ```typescript 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` 单个可观测性实例的配置。 ```typescript 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` 完整的可观测性注册表配置。 ```typescript 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 | ObservabilityInstance> /** Optional selector function to choose which tracing instance to use */ configSelector?: ConfigSelector } ``` ## 采样类型 ### `SamplingStrategy` 采样策略配置。 ```typescript type SamplingStrategy = | { type: 'always' } | { type: 'never' } | { type: 'ratio'; probability: number } | { type: 'custom'; sampler: (options?: CustomSamplerOptions) => boolean } ``` ### `CustomSamplerOptions` 使用自定义采样器策略时传入的选项。 ```typescript interface CustomSamplerOptions { requestContext?: RequestContext metadata?: Record } ``` ## 配置选择器类型 ### `ConfigSelector` 用于选择 Span 所使用可观测性实例的函数。 ```typescript type ConfigSelector = ( options: ConfigSelectorOptions, availableConfigs: ReadonlyMap, ) => string | undefined ``` ### `ConfigSelectorOptions` 使用自定义 Tracing 配置选择器时传入的选项。 ```typescript interface ConfigSelectorOptions { /** Request Context */ requestContext?: RequestContext } ``` ## 内部 Span ### `InternalSpans` 用于在 Workflow 或 Agent 执行中将不同类型的 Span 设置为内部 Span 的位选项。 ```typescript 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 概览](https://mastra.zisheng.pro/docs/observability/tracing/overview):Tracing 完整指南 - [创建子 Span](https://mastra.zisheng.pro/docs/observability/tracing/overview):使用 Span 层级结构 - [添加自定义元数据](https://mastra.zisheng.pro/docs/observability/tracing/overview):丰富 Trace 信息 ### 参考 - [配置](https://mastra.zisheng.pro/reference/observability/tracing/configuration):注册表和配置 - [Tracing 类](https://mastra.zisheng.pro/reference/observability/tracing/instances):核心实现 - [Span 参考](https://mastra.zisheng.pro/reference/observability/tracing/spans):Span 生命周期方法