Mastra

Mastra is a TypeScript framework for building AI agents. To configure tracing with Braintrust:

  • For generateVNext/streamVNext: use AI SDK v5 wrappers
  • For generate/stream: use OpenTelemetry export

wrapMastraAgent (AI SDK v5)

To trace Mastra agents, use wrapMastraAgent and wrapLanguageModel.

trace-mastra-agent-with-tools.ts
import { initLogger, wrapMastraAgent, BraintrustMiddleware } from "braintrust";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
import { openai } from "@ai-sdk/openai";
import { wrapLanguageModel } from "ai";
 
// Initialize Braintrust logging (no-op if omitted)
initLogger({
  projectName: "Mastra Agent",
  apiKey: process.env.BRAINTRUST_API_KEY,
});
 
// Simple calculator tool
const calculator = createTool({
  id: "calculator",
  description: "Add two numbers",
  inputSchema: z.object({ a: z.number(), b: z.number() }),
  outputSchema: z.object({ result: z.number() }),
  execute: async ({ context }) => ({ result: context.a + context.b }),
});
 
const agent = new Agent({
  name: "Tooling Agent",
  instructions: "Use tools when helpful.",
  // wrapLanguageModel with BraintrustMiddleware optionally traces AI SDK 5 spans
  model: wrapLanguageModel({
    model: openai("gpt-4o-mini"),
    middleware: BraintrustMiddleware(),
  }),
  tools: { calculator },
});
 
// Wrap agent in place for tracing
const wrappedAgent = wrapMastraAgent(agent, { span_name: "toolAgent" });
 
async function main() {
  // Use generateVNext (AI SDK v5 method) with tools
  const res = await wrappedAgent.generateVNext(
    "What is 21 + 21? Use tools if needed.",
  );
  console.log(res?.text ?? res);
 
  // Use streamVNext for streaming responses
  const stream = await wrappedAgent.streamVNext(
    "What is 21 + 21? Use tools if needed.",
  );
  console.log(await stream.text);
}
 
main();

Mastra OTeL (AI SDK v4)

To trace AI SDK v4 spans with Braintrust, configure these environment variables:

OTEL_EXPORTER_OTLP_ENDPOINT=https://api.braintrust.dev/otel
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer <Your API Key>, x-bt-parent=project_name:<Your Project Name>"

When you create your agent, enable telemetry and export the data using OpenTelemetry:

import { Mastra } from "@mastra/core";
 
export const mastra = new Mastra({
  // ... other config
  telemetry: {
    serviceName: "your-service-name",
    enabled: true,
    export: {
      type: "otlp",
    },
  },
});

This will automatically send interactions, tool calls, and performance metrics to Braintrust for monitoring and evaluation.

Mastra logs

On this page

Mastra - Docs - Braintrust