> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://respan.ai/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://respan.ai/_mcp/server.

# Mastra (tracing)

> 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.

#### Set up Respan

Create an account at [platform.respan.ai](https://platform.respan.ai) and grab an [API key](https://platform.respan.ai/platform/api/api-keys). For gateway, also add [credits](https://platform.respan.ai/platform/api/billing) or a [provider key](https://platform.respan.ai/platform/api/providers).

Run `npx @respan/cli setup` to set up with your coding agent.

#### Example projects

* [Example project repository](https://github.com/respanai/respan-example-projects)

#### Tracing

## Setup

#### Install packages

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

#### 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.

#### 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);
```

#### View your trace

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

## 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",
    thread_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.         |
| `thread_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.            |

## 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);
}
```

#### Gateway

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

## Setup

#### 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.

#### 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"),
});
```

## 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).