> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 인터페이스 ## 핵심 인터페이스 ### `ObservabilityInstance` Observability을 위한 기본 인터페이스입니다. ```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` 범위 유형을 해당 속성 인터페이스에 매핑합니다. ```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 인터페이스입니다. ```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` 관측 가능성 내보내기를 위한 인터페이스입니다. ```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 } ``` 이벤트 콜백 페이로드는 Observability 이벤트 버스 봉투를 사용합니다. `TracingEvent`는 `exportedSpan`이 포함된 스팬 수명 주기 이벤트를 전달하고, `LogEvent`는 `ExportedLog`를 `log`에, `MetricEvent`는 `ExportedMetric`을 `metric`에, `ScoreEvent`는 `ExportedScore`를 `score`에, `FeedbackEvent`는 `ExportedFeedback`을 `feedback`에 래핑합니다. 이러한 콜백에 대한 Mastra 플랫폼 내보내기 동작은 [MastraPlatform 내보내기 도구](https://mastra.zisheng.pro/ko/reference/observability/tracing/exporters/mastra-platform-exporter)를 참조하세요. `LogEvent`, `MetricEvent`, `FeedbackEvent`와 마찬가지로 `ScoreEvent`는 범위가 제한된 페이로드를 래핑하는 Observability 버스 봉투입니다. 점수의 경우 해당 페이로드는 `ExportedScore`입니다. ### `ScoreEvent` 점수 이벤트는 `onScoreEvent`를 통해 내보내기 도구로 전달됩니다. 이벤트는 신호 유형과 점수 페이로드를 포함하는 작은 봉투입니다. ```typescript interface ScoreEvent { type: 'score' score: ExportedScore } ``` ### `ExportedScore` `ExportedScore`는 내보내기 도구가 `ScoreEvent.score`에서 수신하는 범위가 제한된 페이로드입니다. 여기에는 점수 ID, 대상 Trace 또는 스팬 앵커, 채점기 세부 정보, 값, 선택적 설명 및 상관관계 메타데이터가 포함됩니다. ```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 또는 스팬을 식별합니다. `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` 필드를 사용하세요. ### `ObservabilityDropEvent` 내보내기 파이프라인이 관측 가능성 이벤트를 삭제할 때 구조화된 이벤트가 발생합니다. ```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 } } ``` 사용자 정의 내보내기 도구 또는 브리지에서 `onDroppedEvent`를 사용하여 이러한 이벤트를 외부 메트릭 또는 알림 시스템으로 전달하세요. ### `SpanOutputProcessor` 스팬 출력 프로세서용 인터페이스입니다. ```typescript interface SpanOutputProcessor { /** Processor name */ name: string /** Process span before export */ process(span?: AnySpan): AnySpan | undefined /** Shutdown processor */ shutdown(): Promise } ``` ## 스팬 유형 ### `SpanType` 관련 메타데이터가 포함된 AI 특정 범위 유형입니다. ```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` 모든 범위를 처리해야 하는 경우를 위한 Union 유형입니다. ```typescript type AnySpan = Span ``` ## 스팬 속성 ### `AgentRunAttributes` Agent 실행 속성. ```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 생성 속성. ```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` Observability 내보내기 도구가 Tool 스키마를 표시할 수 있도록 `MODEL_GENERATION` 스팬에서 Model이 사용할 수 있는 단일 Tool의 직렬화된 정의입니다. ```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 단계 속성 - 한 세대 내의 단일 Model 실행을 위한 것입니다. ```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 청크 속성 - 개별 스트리밍 청크/이벤트용. ```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 호출 속성. ```typescript interface ToolCallAttributes { toolId?: string toolType?: string toolDescription?: string toolCallId?: string success?: boolean } ``` ### MCPToolCall속성 MCP Tool 호출 속성. ```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` 프로세서 속성. ```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 실행 속성. ```typescript interface WorkflowRunAttributes { /** Workflow identifier */ workflowId: string /** Workflow status */ status?: WorkflowRunStatus } ``` ### `WorkflowStepAttributes` Workflow 단계 속성. ```typescript interface WorkflowStepAttributes { /** Step identifier */ stepId: string /** Step status */ status?: WorkflowStepStatus } ``` ## 옵션 유형 ### `StartSpanOptions` 새 범위를 시작하기 위한 옵션입니다. ```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` 범위 업데이트 옵션입니다. ```typescript interface UpdateSpanOptions { /** Span attributes */ attributes?: Partial /** Span metadata */ metadata?: Record /** Input data */ input?: any /** Output data */ output?: any } ``` ### `EndSpanOptions` 종료 범위에 대한 옵션입니다. ```typescript interface EndSpanOptions { /** Output data */ output?: any /** Span metadata */ metadata?: Record /** Span attributes */ attributes?: Partial } ``` ### `ErrorSpanOptions` 범위 오류 기록 옵션입니다. ```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 실행을 통해 흐르는 추적을 위한 컨텍스트입니다. ```typescript interface TracingContext { /** Current span for creating child spans and adding metadata */ currentSpan?: AnySpan } ``` ### `TracingProperties` 외부에서 추적 작업을 위해 사용자에게 반환되는 속성입니다. ```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를 생성할 때 적용되는 정책 수준 추적 구성입니다. ```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` 범위에 사용할 관측 가능성 인스턴스를 선택하는 기능입니다. ```typescript type ConfigSelector = ( options: ConfigSelectorOptions, availableConfigs: ReadonlyMap, ) => string | undefined ``` ### `ConfigSelectorOptions` 사용자 정의 추적 구성 선택기를 사용할 때 전달되는 옵션입니다. ```typescript interface ConfigSelectorOptions { /** Request Context */ requestContext?: RequestContext } ``` ## 내부 스팬 ### `InternalSpans` Workflow 또는 Agent 실행에서 다양한 유형의 범위를 내부로 설정하는 비트별 옵션입니다. ```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, } ``` ## 또한보십시오 ### 선적 서류 비치 - [추적 개요](https://mastra.zisheng.pro/ko/docs/observability/tracing/overview): 추적에 대한 전체 가이드 - [하위 범위 만들기](https://mastra.zisheng.pro/ko/docs/observability/tracing/overview): 범위 계층 구조 작업 - [사용자 정의 메타데이터 추가](https://mastra.zisheng.pro/ko/docs/observability/tracing/overview): 흔적을 풍성하게 한다 ### 참조 - [구성](https://mastra.zisheng.pro/ko/reference/observability/tracing/configuration): 레지스트리 및 구성 - [추적 클래스](https://mastra.zisheng.pro/ko/reference/observability/tracing/instances): 핵심 구현 - [스팬 참조](https://mastra.zisheng.pro/ko/reference/observability/tracing/spans): 스팬 수명주기 방법