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

1import { createOpenAI } from "@ai-sdk/openai";
2import { Agent } from "@mastra/core/agent";
3import { Mastra } from "@mastra/core/mastra";
4import { SpanType } from "@mastra/core/observability";
5import { Observability, SamplingStrategyType } from "@mastra/observability";
6import { MastraInstrumentor } from "@respan/instrumentation-mastra";
7import { Respan } from "@respan/respan";
8
9const instrumentor = new MastraInstrumentor();
10const respan = new Respan({
11 apiKey: process.env.RESPAN_API_KEY,
12 baseURL: process.env.RESPAN_BASE_URL,
13 appName: "mastra-app",
14 instrumentations: [instrumentor],
15});
16await respan.initialize();
17
18const openai = createOpenAI({
19 apiKey: process.env.OPENAI_API_KEY,
20});
21
22const assistantAgent = new Agent({
23 id: "assistant-agent",
24 name: "Assistant Agent",
25 instructions: "Answer concisely.",
26 model: openai("gpt-4.1-nano"),
27});
28
29const mastra = new Mastra({
30 agents: { assistantAgent },
31 observability: new Observability({
32 configs: {
33 default: {
34 serviceName: "mastra-app",
35 sampling: { type: SamplingStrategyType.ALWAYS },
36 exporters: [instrumentor],
37 excludeSpanTypes: [
38 SpanType.MODEL_CHUNK,
39 SpanType.MODEL_STEP,
40 SpanType.MODEL_INFERENCE,
41 ],
42 },
43 },
44 sensitiveDataFilter: false,
45 }),
46});
47
48try {
49 const result = await respan.withWorkflow({ name: "mastra_assistant" }, async () => {
50 const agent = mastra.getAgent("assistantAgent");
51 return agent.generate("Describe Mastra in one sentence.");
52 });
53 console.log(result.text);
54} finally {
55 await respan.flush();
56}
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.

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

With propagateAttributes

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

1await respan.propagateAttributes(
2 {
3 customer_identifier: "user_123",
4 thread_identifier: "conversation_456",
5 trace_group_identifier: "Mastra Support.workflow",
6 metadata: { plan: "pro", feature: "support-agent" },
7 },
8 () => respan.withWorkflow({ name: "Mastra Support.workflow" }, async () => {
9 const agent = mastra.getAgent("assistantAgent");
10 return agent.generate("Help this customer with billing.");
11 })
12);
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.

1import { createTool } from "@mastra/core/tools";
2import { z } from "zod";
3
4const getWeather = createTool({
5 id: "get_weather",
6 description: "Get the weather for a city.",
7 inputSchema: z.object({ city: z.string() }),
8 execute: async ({ city }) => ({ city, forecast: "sunny", temperature_f: 72 }),
9});
10
11const weatherAgent = new Agent({
12 id: "weather-agent",
13 name: "Weather Agent",
14 instructions: "Use the weather tool before answering.",
15 model: openai("gpt-4.1-nano"),
16 tools: { getWeather },
17});

Streaming

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

1const stream = await mastra
2 .getAgent("assistantAgent")
3 .stream("Describe Respan tracing for a Mastra TypeScript application.");
4
5for await (const chunk of stream.textStream) {
6 process.stdout.write(chunk);
7}