Mastra (tracing)

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

Create an account at platform.respan.ai and grab an API key. For gateway, also add credits or a provider key.

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

Setup

1

Install packages

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

Set environment variables

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.

3

Initialize and run

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);
4

View your trace

Open the Traces page to see workflows with agent spans, LLM generations, and tool calls.

Configuration

ParameterTypeDefaultDescription
apiKeystring | undefinedRESPAN_API_KEYRespan API key used for tracing.
baseURLstring | undefinedRESPAN_BASE_URLOptional Respan trace export API URL.
instrumentationsRespanInstrumentation[][]Include new MastraInstrumentor() and reuse the same instance in Mastra exporters.
appNamestringrespan-appService name shown on traces.
excludeSpanTypesstring[]model_chunkMastra span types to skip. Exclude chunks and internal model steps to avoid noisy traces.
serviceNamestringMastra defaultService name in Mastra observability config.

Attributes

In Respan()

Set tracing defaults when constructing Respan.

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

With propagateAttributes

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

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.");
})
);
AttributeTypeDescription
customer_identifierstringIdentifies the end user in Respan analytics.
thread_identifierstringGroups related messages into a conversation.
trace_group_identifierstringSets the visible workflow grouping for trace lookup.
metadataobjectCustom key-value pairs merged into spans.

Examples

Tool calls

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

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.

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