接口
🌐 Interfaces
核心接口Direct 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>;
}
SpanTypeMapDirect link to SpanTypeMap
将跨度类型映射到其对应的属性接口。
🌐 Mapping of span types to their corresponding attribute interfaces.
interface SpanTypeMap {
AGENT_RUN: AgentRunAttributes;
WORKFLOW_RUN: WorkflowRunAttributes;
MODEL_GENERATION: ModelGenerationAttributes;
MODEL_STEP: ModelStepAttributes;
MODEL_CHUNK: ModelChunkAttributes;
TOOL_CALL: ToolCallAttributes;
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;
}
此映射定义了在创建或处理跨度时,每种跨度类型使用的属性接口。
🌐 This mapping defines which attribute interface is used for each span type when creating or processing spans.
跨度Direct link to 跨度
🌐 Span
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?: 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;
}
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;
/** Export tracing events */
exportTracingEvent(event: TracingEvent): Promise<void>;
/** Add score to a trace (optional) */
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>;
}
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>;
}
跨度类型Direct link to 跨度类型
🌐 Span Types
SpanTypeDirect link to SpanType
具有相关元数据的 AI 特定跨度类型。
🌐 AI-specific span types with their associated 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",
/** 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>;
跨度属性Direct 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-4', 'claude-3') */
model?: string;
/** Model provider (e.g., 'openai', 'anthropic') */
provider?: string;
/** 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;
}
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;
success?: boolean;
}
MCP工具调用属性Direct link to MCP工具调用属性
🌐 MCPToolCallAttributes
MCP 工具调用属性。
🌐 MCP Tool Call attributes.
interface MCPToolCallAttributes {
/** Id of the MCP tool/function */
toolId: string;
/** MCP server identifier */
mcpServer: string;
/** MCP server version */
serverVersion?: 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;
}
选项类型Direct 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?: any;
/** 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?: any;
/** Output data */
output?: any;
}
EndSpanOptionsDirect link to EndSpanOptions
结束跨度的选项。
🌐 Options for ending spans.
interface EndSpanOptions<TType extends SpanType> {
/** Output data */
output?: any;
/** 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]>;
}
上下文类型Direct 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;
}
配置类型Direct 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;
}
抽样类型Direct 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>;
}
配置选择器类型Direct link to 配置选择器类型
🌐 Config Selector Types
ConfigSelectorDirect link to ConfigSelector
用于选择在给定跨度中使用哪个可观测性实例的函数。
🌐 Function to select which observability instance to use for a given 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;
}
内部跨度Direct 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,
}
另请参阅Direct link to 另请参阅
🌐 See Also
文档Direct link to 文档
🌐 Documentation
参考Direct link to 参考
🌐 Reference