Skip to main content

MastraPlatformExporter

Added in: @mastra/observability@1.12.0. Earlier releases (@mastra/observability@1.8.0 through 1.11.x) export the same exporter as the deprecated CloudExporter.

Sends tracing spans, logs, metrics, scores, and feedback to the Mastra platform for online visualization and monitoring.

note

MastraPlatformExporter was previously called CloudExporter. The original CloudExporter class is still exported from @mastra/observability so existing imports keep working, but it's deprecated and will be removed in a future major version. New code should use MastraPlatformExporter.

Span previews
Direct link to Span previews

MastraPlatformExporter automatically generates short, readable inputPreview, outputPreview, and errorPreview summaries based on the span type. Each preview contains up to 100 characters plus an ellipsis when truncated. Full payloads remain available separately.

Constructor
Direct link to Constructor

new MastraPlatformExporter(config?: MastraPlatformExporterConfig)

MastraPlatformExporterConfig
Direct link to mastraplatformexporterconfig

interface MastraPlatformExporterConfig extends BaseExporterConfig {
/** Maximum number of buffered events per batch (spans, logs, metrics, scores, feedback). Default: 1000 */
maxBatchSize?: number

/** Maximum wait time before flushing in milliseconds. Default: 5000 */
maxBatchWaitMs?: number

/** Opt into byte-triggered batches and upload concurrency control */
byteBatching?: {
maxBatchBytes?: number // Default: 8 MiB
maxConcurrentUploads?: number // Default: 2
uploadTimeoutMs?: number // Default: 30000
}

/** Maximum retry attempts for collector batches. Default: 3 */
maxRetries?: number

/** Mastra Observability access token (from env or config) */
accessToken?: string

/** Project ID for project-scoped collector routes (letters, numbers, hyphens, underscores) */
projectId?: string

/** Base observability endpoint */
endpoint?: string

/** Explicit traces endpoint override */
tracesEndpoint?: string

/** Explicit logs endpoint override */
logsEndpoint?: string

/** Explicit metrics endpoint override */
metricsEndpoint?: string

/** Explicit scores endpoint override */
scoresEndpoint?: string

/** Explicit feedback endpoint override */
feedbackEndpoint?: string

/**
* When false, `accessToken`, `projectId` and the traces endpoint are taken
* from config only and the environment variables below are ignored. Use this
* when embedding Mastra in another tool so a user project's `.env` cannot
* redirect the host's own telemetry. Default: true
*/
resolveFromEnv?: boolean
}

Extends BaseExporterConfig, which includes:

  • logger?: IMastraLogger - Logger instance
  • logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error' - Log level (default: INFO)

Environment variables
Direct link to Environment variables

The exporter reads these environment variables if not provided in config:

  • MASTRA_PLATFORM_ACCESS_TOKEN - Authentication token for MastraPlatformExporter requests
  • MASTRA_PROJECT_ID - Project ID to use when deriving project-scoped collector routes such as /projects/:projectId/ai/spans/publish
  • MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT - Observability endpoint override, read by the exporter in @mastra/observability@1.17.4 and later. Pass either a base origin such as https://observability.eu.mastra.ai or a full traces publish URL ending in /spans/publish. The other signal endpoints are derived from it. Defaults to https://observability.mastra.ai
  • MASTRA_CLOUD_TRACES_ENDPOINT - Legacy traces endpoint override. Takes precedence over MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT when both are set

All of these are ignored when resolveFromEnv is false.

Properties
Direct link to Properties

readonly name = 'mastra-platform-exporter';

The deprecated CloudExporter class continues to use 'mastra-cloud-observability-exporter' as its name for backward compatibility.

Methods
Direct link to Methods

exportTracingEvent
Direct link to exporttracingevent

async exportTracingEvent(event: TracingEvent): Promise<void>

Processes tracing events for export to the Mastra platform.

Only SPAN_ENDED tracing events are exported. SPAN_STARTED and SPAN_UPDATED are ignored. Matching spans are buffered and uploaded to the traces endpoint on the next flush.

Returns: Promise<void> after the tracing event has been accepted for buffering or ignored.

onLogEvent
Direct link to onlogevent

async onLogEvent(event: LogEvent): Promise<void>

Processes log signals for export.

Every LogEvent passed to this handler is buffered and exported to the logs endpoint derived from the configured base endpoint. Unlike tracing, there is no additional event-status filtering at the MastraPlatformExporter level. If the exporter is disabled, this method becomes a no-op.

Returns: Promise<void> after the log event has been accepted for buffering.

onMetricEvent
Direct link to onmetricevent

async onMetricEvent(event: MetricEvent): Promise<void>

Processes metric signals for export.

Every MetricEvent passed to this handler is buffered and exported to the metrics endpoint derived from the configured base endpoint. No additional filtering by metric subtype or status inside MastraPlatformExporter is performed. The exporter forwards every metric event it receives unless it's disabled.

Returns: Promise<void> after the metric event has been accepted for buffering.

onScoreEvent
Direct link to onscoreevent

async onScoreEvent(event: ScoreEvent): Promise<void>

Schedules a score for export using the feedback and score delivery behavior. Events are ignored when the exporter is disabled or shutdown has started. If Platform needs to look up the trace, a missing trace ID causes the record to be dropped.

Returns: Promise<void> when the event has been scheduled or ignored. Call flush() to wait for pending deliveries, because this return value doesn't confirm delivery.

onFeedbackEvent
Direct link to onfeedbackevent

async onFeedbackEvent(event: FeedbackEvent): Promise<void>

Schedules feedback for export using the feedback and score delivery behavior. Events are ignored when the exporter is disabled or shutdown has started. If Platform needs to look up the trace, a missing trace ID causes the record to be dropped.

Returns: Promise<void> when the event has been scheduled or ignored. Call flush() to wait for pending deliveries, because this return value doesn't confirm delivery.

flush
Direct link to flush

async flush(): Promise<void>

Force flushes any buffered events to the Mastra platform without shutting down the exporter. Useful in serverless environments where you need to ensure spans are exported before the runtime terminates.

shutdown
Direct link to shutdown

async shutdown(): Promise<void>

Flushes remaining events and performs cleanup.

Behavior
Direct link to Behavior

Authentication
Direct link to Authentication

If no access token is provided via config or environment variable, the exporter:

  • Logs a warning with sign-up information
  • Operates as a no-op (discards all events)

Batching
Direct link to Batching

The exporter batches traces, logs, and metrics, along with feedback and scores that already include their trace details:

  • Flushes when total buffered event count reaches maxBatchSize
  • Flushes when maxBatchWaitMs elapsed since the first buffered signal in the batch
  • Flushes on shutdown()

Feedback and score delivery
Direct link to Feedback and score delivery

Feedback and scores received by the exporter can reference a trace stored in Platform using its trace ID and an optional span ID. If the record needs details from that trace, the exporter sends it immediately instead of waiting for a batch.

Call flush() before ending a short-lived process, or shutdown() when stopping the exporter, to wait for pending deliveries and retries. These methods finish when records have been accepted or dropped after a failure. Accepted feedback and scores may take time to appear in Platform.

Byte batching
Direct link to Byte batching

Set byteBatching to flush by serialized byte size and control concurrent uploads:

import { MastraPlatformExporter } from '@mastra/observability'

const exporter = new MastraPlatformExporter({
byteBatching: {
maxBatchBytes: 8 * 1024 * 1024,
maxConcurrentUploads: 2,
uploadTimeoutMs: 30_000,
},
})

Without byteBatching, the exporter keeps its existing count-based batching behavior.

  • maxBatchBytes triggers an upload when a batch reaches 8 MiB by default. Larger records are sent intact, without truncation or size-based drops.
  • maxConcurrentUploads controls concurrent collector batch uploads. The default is two.
  • uploadTimeoutMs sets the upload deadline, including retries. The default is 30 seconds.

Record-count and timer-based flush triggers still apply. Queued records are retained when uploads fall behind, so queue memory can grow.

Inspect the current queue with exporter.getByteBatchingStats().

Error handling
Direct link to Error handling

  • Uses exponential backoff retry for collector batches with maxRetries attempts
  • Drops batches after all retries fail
  • Logs errors but continues processing new events

Errors raised by MastraPlatformExporter use the MASTRA_PLATFORM_EXPORTER_* id prefix. The deprecated CloudExporter continues to emit CLOUD_EXPORTER_* ids.

Quota pause
Direct link to Quota pause

When an organization has exhausted its observability quota, the Mastra platform rejects publish requests with 402 Payment Required plus the x-mastra-observability: disabled header. When the exporter sees a 402 (or the header) on any publish route, it:

  • Drops the rejected batch without retrying it
  • Pauses collector batches for traces, logs, metrics, scores, and feedback, dropping buffered and incoming batch records
  • Logs a warning that telemetry is paused
  • Probes the platform periodically with an empty batch, using the interval from the x-mastra-observability-retry-after header (seconds), or every 5 minutes if the header is absent
  • Resumes exporting automatically and logs a warning once the platform stops rejecting with 402

The probe timer doesn't keep the Node.js process alive, so short-lived and serverless processes exit normally while paused.

Every collector request (batch uploads and the traces recovery probe) includes the x-mastra-observability-capabilities: quota-pause-v1 header. This tells the platform that the client understands the quota-pause contract, so it can safely respond with 402 instead of silently dropping telemetry for older clients that would retry it.

Endpoint routing
Direct link to Endpoint routing

  • Base origins derive signal endpoints automatically
  • Without projectId, derived routes use /ai/{signal}/publish
  • With projectId or MASTRA_PROJECT_ID, derived routes use /projects/:projectId/ai/{signal}/publish
  • Explicit full publish URLs are used as-is, even when projectId is configured

Event processing
Direct link to Event processing

  • exportTracingEvent() only exports SPAN_ENDED tracing events
  • onLogEvent() and onMetricEvent() buffer events
  • onScoreEvent() and onFeedbackEvent() deliver records as described in Feedback and score delivery
  • All supported signal batches are uploaded to their matching publish endpoints during flush() and shutdown()

Span wire format
Direct link to Span wire format

The shape of each span sent to Mastra platform is documented here for reference only: it's not exported from @mastra/observability and shouldn't be imported. The exporter spreads the original AnyExportedSpan (so the source field names are preserved) and layers a small set of platform-friendly aliases on top:

type MastraPlatformSpanRecord = AnyExportedSpan & {
// Aliases derived from the source span
spanId: string // alias for span.id
spanType: string // alias for span.type
startedAt: Date // alias for span.startTime
endedAt: Date | null // alias for span.endTime ?? null
error: AnyExportedSpan['errorInfo'] | null

// Stamped at export time
createdAt: Date
updatedAt: Date | null
}

The spread AnyExportedSpan also carries the original id, type, name, traceId, parentSpanId, isRootSpan, isEvent, startTime, endTime, entityType, entityId, entityName, tags, attributes, metadata, input, output, and errorInfo. See Interfaces for AnyExportedSpan.

Usage
Direct link to Usage

import { MastraPlatformExporter } from '@mastra/observability'

// Uses environment variable for token
const exporter = new MastraPlatformExporter()

// Explicit configuration
const customExporter = new MastraPlatformExporter({
accessToken: 'your-token',
projectId: 'project_123',
maxBatchSize: 500,
maxBatchWaitMs: 2000,
logLevel: 'debug',
})

Migrating from CloudExporter
Direct link to migrating-from-cloudexporter

Both classes share the same constructor signature, environment variables, and behavior. To migrate, replace the import and constructor:

// Before
import { CloudExporter } from '@mastra/observability'
const exporter = new CloudExporter()

// After
import { MastraPlatformExporter } from '@mastra/observability'
const exporter = new MastraPlatformExporter()

The original CloudExporter is preserved unchanged so dashboards or alert rules that match the previous CLOUD_EXPORTER_* error IDs or mastra-cloud-observability-exporter exporter name keep working until you migrate.

See also
Direct link to See also

Documentation
Direct link to Documentation

Other Exporters
Direct link to Other Exporters

Reference
Direct link to Reference