Skip to main content

DatadogBridge

warning

The Datadog Bridge is currently experimental. APIs and configuration options may change in future releases.

Enables bidirectional integration between Mastra tracing and Datadog. Creates native dd-trace APM spans in real time so that auto-instrumented operations inside tools and processors are correctly nested under their parent Mastra span. Emits LLM Observability data through dd-trace's pipeline when spans end.

Constructor
Direct link to Constructor

new DatadogBridge(config?: DatadogBridgeConfig)

DatadogBridgeConfig
Direct link to datadogbridgeconfig

interface DatadogBridgeConfig extends BaseExporterConfig {
apiKey?: string
mlApp?: string
site?: string
service?: string
env?: string
agentless?: boolean
integrationsEnabled?: boolean
flushGraceMs?: number
requestContextKeys?: string[]
}

Extends BaseExporterConfig, which includes:

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

Methods
Direct link to Methods

createSpan
Direct link to createspan

createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined

Called by the Mastra observability instance during span construction. Creates a dd-trace APM span eagerly via tracer.startSpan() and returns Mastra-compatible identifiers. The returned IDs are used by Mastra throughout the span's lifetime. The dd-trace span object is stored internally and used for scope activation.

Returns: SpanIds | undefined - { spanId, traceId, parentSpanId }, or undefined if the bridge is disabled.

executeInContext
Direct link to executeincontext

executeInContext<T>(spanId: string, fn: () => Promise<T>): Promise<T>

Executes an async function within the dd-trace context of a Mastra span. dd-trace auto-instrumented operations running inside the function (HTTP, database, etc.) will be parented to this span.

Returns: Promise<T> - The result of the function execution.

executeInContextSync
Direct link to executeincontextsync

executeInContextSync<T>(spanId: string, fn: () => T): T

Executes a synchronous function within the dd-trace context of a Mastra span.

Returns: T - The result of the function execution.

onFeedbackEvent
Direct link to onfeedbackevent

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

Exports a feedback event to Datadog LLM Observability. See Feedback export.

flush
Direct link to flush

async flush(): Promise<void>

Force-flushes any buffered LLM Observability data to Datadog without shutting down the bridge. Useful in serverless environments where you need to ensure data is exported before the runtime terminates.

The flush is best-effort: dd-trace sends LLM Observability data from a background writer and gives no way to await the request, so flush() waits flushGraceMs (default 2000 ms) after asking dd-trace to flush, then flushes the APM exporter. Each flush that sent new data costs that full wait, so a serverless handler that awaits flush() per request pays it per request. Raise it if spans from short-lived processes are missing in Datadog, or set it to 0 to skip the wait when something else keeps the process alive.

shutdown
Direct link to shutdown

async shutdown(): Promise<void>

Force-finishes any APM spans that weren't closed cleanly and flushes pending LLM Observability data. It then disables the integration and clears all internal state.

Usage examples
Direct link to Usage examples

Basic usage
Direct link to Basic usage

import tracer from 'dd-trace'

tracer.init({
service: process.env.DD_SERVICE || 'my-mastra-app',
env: process.env.DD_ENV || 'production',
})

import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { DatadogBridge } from '@mastra/datadog'

const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-mastra-app',
bridge: new DatadogBridge({
mlApp: process.env.DD_LLMOBS_ML_APP!,
}),
},
},
}),
agents: { myAgent },
})

Agentless mode (LLM observability only, no local agent)
Direct link to Agentless mode (LLM observability only, no local agent)

If you don't have a local Datadog Agent and only want LLM Observability data, enable agentless mode:

new DatadogBridge({
mlApp: process.env.DD_LLMOBS_ML_APP!,
apiKey: process.env.DD_API_KEY!,
agentless: true,
})

Note: APM data can't be sent in agentless mode. If you only need LLM Observability data without dd-trace APM, the Datadog Exporter is a simpler choice.

With additional exporters
Direct link to With additional exporters

The bridge can be combined with non-Datadog exporters to send traces to additional destinations:

import { Mastra } from '@mastra/core'
import { Observability, MastraStorageExporter } from '@mastra/observability'
import { DatadogBridge } from '@mastra/datadog'

const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-mastra-app',
bridge: new DatadogBridge({
mlApp: process.env.DD_LLMOBS_ML_APP!,
}),
exporters: [
new MastraStorageExporter(), // Studio access
],
},
},
}),
})
note

Don't combine DatadogBridge with DatadogExporter in the same configuration. Both emit to LLM Observability and would double-write the same data.

Setup requirements
Direct link to Setup requirements

The DatadogBridge requires dd-trace to be initialized before any other imports so its auto-instrumentation can patch HTTP, database, and framework libraries at load time.

See the DatadogBridge Guide for complete setup instructions, including dd-trace initialization, bundler externals, and agent configuration.

Span mapping
Direct link to Span mapping

Mastra span types are mapped to Datadog LLM Observability span kinds. When your @mastra/core and @mastra/observability versions emit MODEL_INFERENCE spans (the model-inference-span feature), MODEL_INFERENCE is the llm span and MODEL_STEP becomes a workflow span that wraps it:

Mastra SpanTypeDatadog Kind
AGENT_RUNagent
MODEL_GENERATIONworkflow
MODEL_STEPllm, or workflow when MODEL_INFERENCE spans are emitted
MODEL_INFERENCEllm
TOOL_CALLtool
MCP_TOOL_CALLtool
WORKFLOW_RUNworkflow
All other typestask

Tags support
Direct link to Tags support

tracingOptions.tags values become structured LLM Observability annotation tags: key:value entries are split into key/value pairs, and tags without a colon are set to true.

const result = await agent.generate('Hello', {
tracingOptions: {
tags: ['production', 'instance_name:career-scout-api'],
},
})

This produces:

{
"production": true,
"instance_name": "career-scout-api"
}

Feedback export
Direct link to Feedback export

Feedback recorded with addFeedback() is exported to Datadog as end-user feedback. Feedback with a spanId targets that span, and feedback with only a traceId targets the trace. The Datadog LLM Observability trace ID is the Mastra trace ID, so late feedback still reaches the run. A run that continues an LLM Observability trace from an upstream service keeps that trace, so only feedback with a spanId reaches it. HTTP calls made from inside the run carry its LLM Observability trace ID, so spans from Datadog-instrumented services they call join the run. Fields map the same way as in the DatadogExporter.

Environment variables
Direct link to Environment variables

The bridge reads configuration from these environment variables:

VariableDescription
DD_API_KEYDatadog API key (only required for agentless mode)
DD_LLMOBS_ML_APPML application name
DD_SITEDatadog site
DD_ENVEnvironment name
DD_LLMOBS_AGENTLESS_ENABLEDSet to 'true' or '1' to enable agentless mode