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.
Set up Respan
Create an account at platform.respan.ai and grab an API key . For gateway, also add credits or a provider key .
Paste this into your coding agent:
Help me set up Respan tracing with the Mastra integration.
Follow https://www.respan.ai/docs/integrations/mastra.mdSetup
Install packages
npm install @mastra/core @mastra/observability @ai-sdk/openai @respan/respan @respan/tracing @respan/instrumentation-mastraSet 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.
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);View your trace
Open the Traces page 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.
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.");
})
);| 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.
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);
}