# OpenTelemetry bridge

> **Warning:** The OpenTelemetry Bridge is currently **experimental**. APIs and configuration options may change in future releases.

The OpenTelemetry (OTEL) Bridge enables bidirectional integration between Mastra's tracing system and existing OpenTelemetry infrastructure. Unlike exporters that send trace data to external platforms, the bridge creates native OTEL spans that participate in your distributed tracing context.

> **Looking to send traces without existing OTEL infrastructure?:** If you don't have existing OpenTelemetry instrumentation, the [OpenTelemetry Exporter](https://mastra.ai/docs/observability/tracing/exporters/otel) may be simpler — it sends traces directly without requiring an OTEL SDK setup.

## When to use the bridge

Use the OtelBridge when you:

- Have existing OTEL instrumentation in your application (HTTP servers, database clients, etc.)
- Want Mastra operations to appear as child spans of your existing OTEL traces
- Need OTEL-instrumented code inside Mastra tools to maintain proper parent-child relationships
- Are building a distributed system where trace context must propagate across services

## How it works

The OtelBridge provides two-way integration:

**From OTEL to Mastra:**

- Reads from OTEL ambient context (AsyncLocalStorage) automatically
- Inherits trace ID and parent span ID from active OTEL spans
- Respects OTEL sampling decisions — if a trace isn't sampled, Mastra won't create spans for it
- No manual trace ID passing required when OTEL auto-instrumentation is active

**From Mastra to OTEL:**

- Creates native OTEL spans for Mastra operations (agents, LLM calls, tools, workflows)
- Maintains proper parent-child relationships in distributed traces
- Allows OTEL-instrumented code (HTTP clients, database calls) within Mastra operations to nest correctly

## Installation

**npm**:

```bash
npm install @mastra/otel-bridge
```

**pnpm**:

```bash
pnpm add @mastra/otel-bridge
```

**Yarn**:

```bash
yarn add @mastra/otel-bridge
```

**Bun**:

```bash
bun add @mastra/otel-bridge
```

The bridge works with your existing OpenTelemetry setup. Depending on your configuration, you may also need some of these packages:

- `@opentelemetry/sdk-node` - Core Node.js SDK for OTEL
- `@opentelemetry/auto-instrumentations-node` - Auto-instrumentation for common libraries
- `@opentelemetry/exporter-trace-otlp-proto` - OTLP exporter (Protobuf over HTTP)
- `@opentelemetry/exporter-trace-otlp-http` - OTLP exporter (JSON over HTTP)
- `@opentelemetry/exporter-trace-otlp-grpc` - OTLP exporter (gRPC)
- `@opentelemetry/sdk-trace-base` - Base tracing SDK (for BatchSpanProcessor, etc.)
- `@opentelemetry/core` - Core utilities (for W3CTraceContextPropagator, etc.)

## Configuration

Using the OtelBridge requires two steps:

1. Configure OpenTelemetry instrumentation in your application
2. Add the OtelBridge to your Mastra observability config

### Step 1: OpenTelemetry Instrumentation

Create an instrumentation file that initializes OTEL. This must run before your application code:

```typescript
import { NodeSDK } from '@opentelemetry/sdk-node'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { W3CTraceContextPropagator } from '@opentelemetry/core'

const sdk = new NodeSDK({
  serviceName: 'my-service',
  spanProcessors: [
    new BatchSpanProcessor(
      new OTLPTraceExporter({
        url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
      }),
    ),
  ],
  instrumentations: [getNodeAutoInstrumentations()],
  textMapPropagator: new W3CTraceContextPropagator(),
})

sdk.start()

export { sdk }
```

### Step 2: Mastra Configuration

Add the OtelBridge to your Mastra observability config:

```typescript
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { OtelBridge } from '@mastra/otel-bridge'

export const mastra = new Mastra({
  observability: new Observability({
    configs: {
      default: {
        serviceName: 'my-service',
        bridge: new OtelBridge(),
      },
    },
  }),
  agents: {
    /* your agents */
  },
})
```

No Mastra exporters are required when using the bridge — traces are sent via your OTEL SDK configuration. You can optionally add Mastra exporters if you want to send traces to additional destinations.

### Running Your Application

Use the `--import` flag to ensure instrumentation loads before your application:

```bash
tsx --import ./instrumentation.ts ./src/index.ts
```

## Semantic conventions

The OtelBridge exports Mastra spans using [OpenTelemetry Semantic Conventions for GenAI v1.38.0](https://github.com/open-telemetry/semantic-conventions/tree/v1.38.0/docs/gen-ai). This includes standardized span names (`chat {model}`, `execute_tool {tool_name}`, etc.) and attributes (`gen_ai.usage.input_tokens`, `gen_ai.request.model`, etc.).

For details on span naming and attributes, see the [OpenTelemetry Exporter semantic conventions](https://mastra.ai/docs/observability/tracing/exporters/otel).

## Trace hierarchy

With the OtelBridge, your traces maintain proper hierarchy across OTEL and Mastra boundaries:

```text
HTTP POST /api/chat (from Hono middleware)
└── agent.assistant (from Mastra via OtelBridge)
    ├── chat gpt-5.4 (LLM call)
    ├── tool.execute search (tool execution)
    │   └── HTTP GET api.example.com (from OTEL auto-instrumentation)
    └── chat gpt-5.4 (follow-up LLM call)
```

## Multi-service distributed tracing

The OtelBridge enables trace propagation across service boundaries. When Service A calls Service B via HTTP, trace context propagates automatically:

```text
Service A: HTTP POST /api/process
└── HTTP POST service-b/api/analyze (outgoing call)

Service B: HTTP POST /api/analyze (incoming call - same trace!)
└── agent.analyzer (Mastra agent inherits trace context)
    └── chat gpt-5.4
```

Both services must have:

1. OTEL instrumentation configured
2. W3C Trace Context propagator enabled
3. Mastra with OtelBridge configured

## Using tags

Tags help you categorize and filter traces in your OTEL backend. Add tags when executing agents or workflows:

```typescript
const result = await agent.generate('Hello', {
  tracingOptions: {
    tags: ['production', 'experiment-v2', 'user-request'],
  },
})
```

Tags are exported as a JSON string in the `mastra.tags` span attribute for broad backend compatibility. Common use cases include:

- Environment labels: `"production"`, `"staging"`
- Experiment tracking: `"experiment-v1"`, `"control-group"`
- Priority levels: `"priority-high"`, `"batch-job"`

## Troubleshooting

If traces aren't displaying or connecting as expected:

- Verify OTEL SDK is initialized before Mastra (use `--import` flag or import at top of entry point)
- Ensure the OtelBridge is added to your observability config
- Check that your OTEL backend is running and accessible

## Related

- [Tracing Overview](https://mastra.ai/docs/observability/tracing/overview)
- [OpenTelemetry Exporter](https://mastra.ai/docs/observability/tracing/exporters/otel): For sending traces to OTEL backends
- [OtelBridge Reference](https://mastra.ai/reference/observability/tracing/bridges/otel): API documentation