인터페이스
핵심 인터페이스핵심 인터페이스에 대한 직접 링크
ObservabilityInstanceobservabilityinstance에 대한 직접 링크
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>
}
SpanTypeMapspantypemap에 대한 직접 링크
범위 유형을 해당 속성 인터페이스에 매핑합니다.
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 인터페이스입니다.
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
}
ObservabilityExporterobservabilityexporter에 대한 직접 링크
관측 가능성 내보내기를 위한 인터페이스입니다.
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>
}
이벤트 콜백 페이로드는 Observability 이벤트 버스 봉투를 사용합니다. TracingEvent는 exportedSpan이 포함된 스팬 수명 주기 이벤트를 전달하고, LogEvent는 ExportedLog를 log에, MetricEvent는 ExportedMetric을 metric에, ScoreEvent는 ExportedScore를 score에, FeedbackEvent는 ExportedFeedback을 feedback에 래핑합니다. 이러한 콜백에 대한 Mastra 플랫폼 내보내기 동작은 MastraPlatform 내보내기 도구를 참조하세요.
LogEvent, MetricEvent, FeedbackEvent와 마찬가지로 ScoreEvent는 범위가 제한된 페이로드를 래핑하는 Observability 버스 봉투입니다. 점수의 경우 해당 페이로드는 ExportedScore입니다.
ScoreEventscoreevent에 대한 직접 링크
점수 이벤트는 onScoreEvent를 통해 내보내기 도구로 전달됩니다. 이벤트는 신호 유형과 점수 페이로드를 포함하는 작은 봉투입니다.
interface ScoreEvent {
type: 'score'
score: ExportedScore
}
ExportedScoreexportedscore에 대한 직접 링크
ExportedScore는 내보내기 도구가 ScoreEvent.score에서 수신하는 범위가 제한된 페이로드입니다. 여기에는 점수 ID, 대상 Trace 또는 스팬 앵커, 채점기 세부 정보, 값, 선택적 설명 및 상관관계 메타데이터가 포함됩니다.
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 또는 스팬을 식별합니다. scoreTraceId는 해당 채점기를 추적한 경우 채점 실행 자체의 Trace를 식별합니다. 새 내보내기 도구에서는 더 이상 사용되지 않는 source 필드보다 scoreSource를 사용하고, 더 이상 사용되지 않는 최상위 experimentId 필드보다 correlationContext.experimentId를 사용하세요.
EntityType은 Mastra의 Observability 엔터티 열거형입니다. 현재 값에는 agent, scorer, rag_ingestion, trajectory, input_processor, input_step_processor, output_processor, output_step_processor, workflow_step, tool, workflow_run, memory가 포함됩니다.
CorrelationContext는 Observability 신호에 연결된 공유 컨텍스트 스냅샷입니다. 엔터티 계층 구조 필드, 사용자 또는 조직 식별자, 실행, 세션, 스레드, 요청, 환경, 소스, 서비스 이름, 실험 및 태그를 전달할 수 있습니다. 점수가 매겨진 대상에는 ExportedScore의 최상위 traceId 및 spanId 필드를 사용하세요.
ObservabilityDropEventobservabilitydropevent에 대한 직접 링크
내보내기 파이프라인이 관측 가능성 이벤트를 삭제할 때 구조화된 이벤트가 발생합니다.
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
}
}
사용자 정의 내보내기 도구 또는 브리지에서 onDroppedEvent를 사용하여 이러한 이벤트를 외부 메트릭 또는 알림 시스템으로 전달하세요.
SpanOutputProcessorspanoutputprocessor에 대한 직접 링크
스팬 출력 프로세서용 인터페이스입니다.
interface SpanOutputProcessor {
/** Processor name */
name: string
/** Process span before export */
process(span?: AnySpan): AnySpan | undefined
/** Shutdown processor */
shutdown(): Promise<void>
}
스팬 유형스팬 유형에 대한 직접 링크
SpanTypespantype에 대한 직접 링크
관련 메타데이터가 포함된 AI 특정 범위 유형입니다.
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',
}
AnySpananyspan에 대한 직접 링크
모든 범위를 처리해야 하는 경우를 위한 Union 유형입니다.
type AnySpan = Span<keyof SpanTypeMap>
스팬 속성스팬 속성에 대한 직접 링크
AgentRunAttributesagentrunattributes에 대한 직접 링크
Agent 실행 속성.
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
}
ModelGenerationAttributesmodelgenerationattributes에 대한 직접 링크
Model 생성 속성.
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
}
ModelToolDefinitionmodeltooldefinition에 대한 직접 링크
Observability 내보내기 도구가 Tool 스키마를 표시할 수 있도록 MODEL_GENERATION 스팬에서 Model이 사용할 수 있는 단일 Tool의 직렬화된 정의입니다.
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
}
ModelStepAttributesmodelstepattributes에 대한 직접 링크
Model 단계 속성 - 한 세대 내의 단일 Model 실행을 위한 것입니다.
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>
}
ModelChunkAttributesmodelchunkattributes에 대한 직접 링크
Model 청크 속성 - 개별 스트리밍 청크/이벤트용.
interface ModelChunkAttributes {
/** Type of chunk (text-delta, reasoning-delta, tool-call, etc.) */
chunkType?: string
/** Sequence number of this chunk in the stream */
sequenceNumber?: number
}
ToolCallAttributestoolcallattributes에 대한 직접 링크
Tool 호출 속성.
interface ToolCallAttributes {
toolId?: string
toolType?: string
toolDescription?: string
toolCallId?: string
success?: boolean
}
MCPToolCall속성MCPToolCall속성에 대한 직접 링크
MCP Tool 호출 속성.
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
}
ProcessorRunAttributesprocessorrunattributes에 대한 직접 링크
프로세서 속성.
interface ProcessorRunAttributes {
/** Name of the Processor */
processorName: string
/** Processor type (input or output) */
processorType: 'input' | 'output'
/** Processor index in the agent */
processorIndex?: number
}
WorkflowRunAttributesworkflowrunattributes에 대한 직접 링크
Workflow 실행 속성.
interface WorkflowRunAttributes {
/** Workflow identifier */
workflowId: string
/** Workflow status */
status?: WorkflowRunStatus
}
WorkflowStepAttributesworkflowstepattributes에 대한 직접 링크
Workflow 단계 속성.
interface WorkflowStepAttributes {
/** Step identifier */
stepId: string
/** Step status */
status?: WorkflowStepStatus
}
옵션 유형옵션 유형에 대한 직접 링크
StartSpanOptionsstartspanoptions에 대한 직접 링크
새 범위를 시작하기 위한 옵션입니다.
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
}
UpdateSpanOptionsupdatespanoptions에 대한 직접 링크
범위 업데이트 옵션입니다.
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
}
EndSpanOptionsendspanoptions에 대한 직접 링크
종료 범위에 대한 옵션입니다.
interface EndSpanOptions<TType extends SpanType> {
/** Output data */
output?: any
/** Span metadata */
metadata?: Record<string, any>
/** Span attributes */
attributes?: Partial<SpanTypeMap[TType]>
}
ErrorSpanOptionserrorspanoptions에 대한 직접 링크
범위 오류 기록 옵션입니다.
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]>
}
컨텍스트 유형컨텍스트 유형에 대한 직접 링크
TracingContexttracingcontext에 대한 직접 링크
Workflow 및 Agent 실행을 통해 흐르는 추적을 위한 컨텍스트입니다.
interface TracingContext {
/** Current span for creating child spans and adding metadata */
currentSpan?: AnySpan
}
TracingPropertiestracingproperties에 대한 직접 링크
외부에서 추적 작업을 위해 사용자에게 반환되는 속성입니다.
type TracingProperties = {
/** Trace ID used on the execution (if the execution was traced) */
traceId?: string
}
TracingOptionstracingoptions에 대한 직접 링크
새 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
}
TracingPolicytracingpolicy에 대한 직접 링크
Workflow 또는 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
}
구성 유형구성 유형에 대한 직접 링크
ObservabilityInstanceConfigobservabilityinstanceconfig에 대한 직접 링크
단일 관측 가능성 인스턴스에 대한 구성입니다.
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[]
}
ObservabilityRegistryConfigobservabilityregistryconfig에 대한 직접 링크
관찰성 레지스트리 구성을 완료합니다.
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
}
샘플링 유형샘플링 유형에 대한 직접 링크
SamplingStrategysamplingstrategy에 대한 직접 링크
샘플링 전략 구성.
type SamplingStrategy =
| { type: 'always' }
| { type: 'never' }
| { type: 'ratio'; probability: number }
| { type: 'custom'; sampler: (options?: CustomSamplerOptions) => boolean }
CustomSamplerOptionscustomsampleroptions에 대한 직접 링크
맞춤 샘플러 전략을 사용할 때 전달되는 옵션입니다.
interface CustomSamplerOptions {
requestContext?: RequestContext
metadata?: Record<string, any>
}
구성 선택기 유형구성 선택기 유형에 대한 직접 링크
ConfigSelectorconfigselector에 대한 직접 링크
범위에 사용할 관측 가능성 인스턴스를 선택하는 기능입니다.
type ConfigSelector = (
options: ConfigSelectorOptions,
availableConfigs: ReadonlyMap<string, ObservabilityInstance>,
) => string | undefined
ConfigSelectorOptionsconfigselectoroptions에 대한 직접 링크
사용자 정의 추적 구성 선택기를 사용할 때 전달되는 옵션입니다.
interface ConfigSelectorOptions {
/** Request Context */
requestContext?: RequestContext
}
내부 스팬내부 스팬에 대한 직접 링크
InternalSpansinternalspans에 대한 직접 링크
Workflow 또는 Agent 실행에서 다양한 유형의 범위를 내부로 설정하는 비트별 옵션입니다.
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,
}
또한보십시오또한보십시오에 대한 직접 링크
선적 서류 비치선적 서류 비치에 대한 직접 링크
- 추적 개요: 추적에 대한 전체 가이드
- 하위 범위 만들기: 범위 계층 구조 작업
- 사용자 정의 메타데이터 추가: 흔적을 풍성하게 한다