Skip to content

Mastra

Add observability to your Mastra AI agents using Mastra’s OpenTelemetry exporter. Capture the full lifecycle of agent runs — from LLM calls and tool executions to workflow steps — and inspect them in Kopai.

  • Node.js 20+
  • API key from a model provider (e.g. Anthropic, OpenAI)
  • Kopai running locally:
Terminal window
npx @kopai/app start

Scaffold a new project with the Mastra CLI:

Terminal window
npx create-mastra@latest

Set your model provider key in .env:

Terminal window
ANTHROPIC_API_KEY=<your-api-key>

Define an agent in src/mastra/agents/travelAgent.ts:

import { anthropic } from "@ai-sdk/anthropic";
import { Agent } from "@mastra/core/agent";
export const travelAgent = new Agent({
name: "travel-agent",
instructions:
"You are a friendly travel assistant. " +
"Help users plan trips, suggest destinations, and answer questions about travel logistics.",
model: anthropic("claude-haiku-4-5-20251001"),
});

Install the OTel exporter and observability packages:

Terminal window
npm install @mastra/observability @mastra/otel-exporter @opentelemetry/exporter-trace-otlp-http

Register the agent and wire up telemetry in src/mastra/index.ts:

import { Mastra } from "@mastra/core";
import { Observability } from "@mastra/observability";
import { OtelExporter } from "@mastra/otel-exporter";
import { travelAgent } from "./agents/travelAgent";
export const mastra = new Mastra({
agents: { travelAgent },
observability: new Observability({
configs: {
otel: {
serviceName: "my-mastra-app",
exporters: [
new OtelExporter({
provider: {
custom: {
endpoint: "http://localhost:4318/v1/traces",
},
},
}),
],
},
},
}),
});

This sends all agent and tool traces to Kopai’s local OTLP endpoint on port 4318.

Start the Mastra dev server:

Terminal window
npm run dev

Open the playground at http://localhost:4111 and send a few messages to your agent.

Note: Traces are sent to Kopai, not Mastra Studio’s built-in trace viewer. Use the Kopai CLI or dashboard at http://localhost:8000 to inspect them.

Verify that traces arrived using the Kopai CLI:

Terminal window
# List recent traces from your agent
npx @kopai/cli traces search --service my-mastra-app --json
# Inspect a specific trace (copy a traceId from above)
npx @kopai/cli traces get <traceId> --json

Each trace contains spans for the full agent interaction — LLM calls, tool executions, and decision steps.

Swap the OtelExporter config in src/mastra/index.ts to point at https://otlp-http.kopai.app with an auth header:

new OtelExporter({
provider: {
custom: {
endpoint: "https://otlp-http.kopai.app",
headers: {
authorization: "Bearer YOUR_BACKEND_TOKEN",
},
},
},
});

For a complete working example with traces, logs, and metrics:

Mastra Example