Mastra
Integration
Section titled “Integration”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.
Prerequisites
Section titled “Prerequisites”- Node.js 20+
- API key from a model provider (e.g. Anthropic, OpenAI)
- Kopai running locally:
npx @kopai/app startCreate a Mastra Project
Section titled “Create a Mastra Project”Scaffold a new project with the Mastra CLI:
npx create-mastra@latestSet your model provider key in .env:
ANTHROPIC_API_KEY=<your-api-key>Add an Agent
Section titled “Add an Agent”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"),});Enable Observability
Section titled “Enable Observability”Install the OTel exporter and observability packages:
npm install @mastra/observability @mastra/otel-exporter @opentelemetry/exporter-trace-otlp-httpRegister 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.
Run and Verify
Section titled “Run and Verify”Start the Mastra dev server:
npm run devOpen 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:
# List recent traces from your agentnpx @kopai/cli traces search --service my-mastra-app --json
# Inspect a specific trace (copy a traceId from above)npx @kopai/cli traces get <traceId> --jsonEach trace contains spans for the full agent interaction — LLM calls, tool executions, and decision steps.
Sending to Kopai.app in the cloud
Section titled “Sending to Kopai.app in the cloud”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", }, }, },});Working Example
Section titled “Working Example”For a complete working example with traces, logs, and metrics: