---
title: "Mastra (tracing)"
description: "Trace Mastra TypeScript agents and workflows with Respan: agent spans, model generations, tool calls, gateway routing, and full observability."
---

The [Mastra](https://mastra.ai/) framework helps you build TypeScript AI agents, tools, and workflows. Respan captures Mastra agent runs, LLM generations, tool calls, and workflow spans, and can route model calls through the Respan gateway.

<Accordion title="Set up Respan">
Create an account at [platform.respan.ai](https://platform.respan.ai) and grab an [API key](https://platform.respan.ai/platform/gateway/api-keys). For gateway, also add [credits](https://platform.respan.ai/platform/gateway/credits) or a [provider key](https://platform.respan.ai/platform/gateway/api-keys?providers=1).
</Accordion>

<Tabs>
<Tab title="Tracing">

Paste this into your coding agent:

```text
Help me set up Respan tracing with the Mastra integration.
Follow https://www.respan.ai/docs/integrations/mastra.md
```

## Setup

<Steps>
<Step title="Install packages">

```bash
npm install @mastra/core @mastra/observability @ai-sdk/openai @respan/respan @respan/tracing @respan/instrumentation-mastra
```

</Step>

<Step title="Set environment variables">

```bash
export OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
```

`OPENAI_API_KEY` is used by Mastra's model provider. `RESPAN_API_KEY` is used to export traces to Respan.

</Step>

<Step title="Initialize and run">

```typescript
import { createOpenAI } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { Mastra } from "@mastra/core/mastra";
import { SpanType } from "@mastra/core/observability";
import { Observability, SamplingStrategyType } from "@mastra/observability";
import { MastraInstrumentor } from "@respan/instrumentation-mastra";
import { Respan } from "@respan/respan";

const instrumentor = new MastraInstrumentor();
const respan = new Respan({
  apiKey: process.env.RESPAN_API_KEY,
  baseURL: process.env.RESPAN_BASE_URL,
  appName: "mastra-app",
  instrumentations: [instrumentor],
});
await respan.initialize();

const openai = createOpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const assistantAgent = new Agent({
  id: "assistant-agent",
  name: "Assistant Agent",
  instructions: "Answer concisely.",
  model: openai("gpt-4.1-nano"),
});

const mastra = new Mastra({
  agents: { assistantAgent },
  observability: new Observability({
    configs: {
      default: {
        serviceName: "mastra-app",
        sampling: { type: SamplingStrategyType.ALWAYS },
        exporters: [instrumentor],
        excludeSpanTypes: [
          SpanType.MODEL_CHUNK,
          SpanType.MODEL_STEP,
          SpanType.MODEL_INFERENCE,
        ],
      },
    },
    sensitiveDataFilter: false,
  }),
});

const result = await respan.withWorkflow({ name: "mastra_assistant" }, async () => {
  const agent = mastra.getAgent("assistantAgent");
  return agent.generate("Describe Mastra in one sentence.");
});
console.log(result.text);
```

</Step>

<Step title="View your trace">

Open the [Traces page](https://platform.respan.ai/platform/traces) to see workflows with agent spans, LLM generations, and tool calls.

</Step>
</Steps>

## Configuration

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `apiKey` | `string \| undefined` | `RESPAN_API_KEY` | Respan API key used for tracing. |
| `baseURL` | `string \| undefined` | `RESPAN_BASE_URL` | Optional Respan trace export API URL. |
| `instrumentations` | `RespanInstrumentation[]` | `[]` | Include `new MastraInstrumentor()` and reuse the same instance in Mastra exporters. |
| `appName` | `string` | `respan-app` | Service name shown on traces. |
| `excludeSpanTypes` | `string[]` | `model_chunk` | Mastra span types to skip. Exclude chunks and internal model steps to avoid noisy traces. |
| `serviceName` | `string` | Mastra default | Service name in Mastra observability config. |

## Attributes

### In Respan()

Set tracing defaults when constructing `Respan`.

```typescript
const respan = new Respan({
  appName: "agent-api",
  instrumentations: [new MastraInstrumentor()],
});
```

### With propagateAttributes

Attach per-request identifiers and metadata around a Mastra run.

```typescript
await respan.propagateAttributes(
  {
    customer_identifier: "user_123",
    session_identifier: "conversation_456",
    trace_group_identifier: "Mastra Support.workflow",
    metadata: { plan: "pro", feature: "support-agent" },
  },
  () => respan.withWorkflow({ name: "Mastra Support.workflow" }, async () => {
    const agent = mastra.getAgent("assistantAgent");
    return agent.generate("Help this customer with billing.");
  })
);
```

| Attribute | Type | Description |
|-----------|------|-------------|
| `customer_identifier` | `string` | Identifies the end user in Respan analytics. |
| `session_identifier` | `string` | Groups related messages into a conversation. |
| `trace_group_identifier` | `string` | Sets the visible workflow grouping for trace lookup. |
| `metadata` | `object` | Custom key-value pairs merged into spans. |

### Sessions

When you don't set `session_identifier`, the agent call's memory thread becomes the session id, so every turn of one conversation lands in one [session](/docs/documentation/features/custom-attributes#sessions). This needs `@respan/instrumentation-mastra` 0.3.0 or later.

```typescript
const result = await agent.generate("And tomorrow?", {
  memory: { thread: "chat_42", resource: "user_8f21" },
});
```

## Examples

### Tool calls

Tool executions are captured as `tool` spans with input, output, timing, and parent agent context.

```typescript
import { createTool } from "@mastra/core/tools";
import { z } from "zod";

const getWeather = createTool({
  id: "get_weather",
  description: "Get the weather for a city.",
  inputSchema: z.object({ city: z.string() }),
  execute: async ({ city }) => ({ city, forecast: "sunny", temperature_f: 72 }),
});

const weatherAgent = new Agent({
  id: "weather-agent",
  name: "Weather Agent",
  instructions: "Use the weather tool before answering.",
  model: openai("gpt-4.1-nano"),
  tools: { getWeather },
});
```

### Streaming

Streaming responses are traced as model generation spans with final content and usage metadata.

```typescript
const stream = await mastra
  .getAgent("assistantAgent")
  .stream("Describe Respan tracing for a Mastra TypeScript application.");

for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}
```

</Tab>
<Tab title="Gateway">

Route Mastra LLM calls through the Respan gateway to use 1000+ models from different providers. Only your Respan API key is needed; no separate provider key is required.

## Setup

<Steps>
<Step title="Set environment variables">

```bash
export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
export RESPAN_BASE_URL="https://api.respan.ai/api"
```

No `OPENAI_API_KEY` is needed when you use the Respan gateway.

</Step>

<Step title="Point Mastra models to the Respan gateway">

```typescript
import { createOpenAI } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";

const openai = createOpenAI({
  apiKey: process.env.RESPAN_API_KEY,
  baseURL: process.env.RESPAN_BASE_URL ?? "https://api.respan.ai/api",
});

const agent = new Agent({
  id: "assistant-agent",
  name: "Assistant Agent",
  instructions: "Answer concisely.",
  model: openai("gpt-4.1-nano"),
});
```

</Step>
</Steps>

## Switch models

Change the model string to route to another supported provider through the same gateway.

```typescript
const agent = new Agent({
  id: "assistant-agent",
  name: "Assistant Agent",
  instructions: "Answer concisely.",
  model: openai("claude-sonnet-4-5-20250929"),
});
```

See the [full model list](https://platform.respan.ai/platform/models).

</Tab>
</Tabs>
