> ## Documentation Index
> Fetch the complete documentation index at: https://arize-ax.mintlify.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Mastra

> Trace Mastra agents and workflows with the official @mastra/arize exporter and view traces in Arize AX.

[Mastra](https://mastra.ai/) is a TypeScript framework for building agents, workflows, and tool integrations on top of the Vercel AI SDK. Arize AX captures every Mastra agent run via the [official `@mastra/arize` exporter](https://mastra.ai/docs/observability/tracing/exporters/arize), which Mastra invokes from its observability layer when the dev server is running.

## Prerequisites

* Node.js 18+
* An Arize AX account ([sign up](https://arize.com/sign-up/))
* An `OPENAI_API_KEY` from the [OpenAI Platform](https://platform.openai.com/api-keys) (or any other provider supported by `@ai-sdk/*`)

<Note>
  The `Mastra` constructor registers the OTel SDK and the `ArizeExporter` as soon as it runs, so any entry point that imports your configured `mastra` value will emit spans — `mastra dev` is the easiest way to get there (it bundles your code and starts an HTTP playground at `http://localhost:4111`), but a plain `tsx` script that imports `mastra` and calls `mastra.getAgent("...").generate(...)` works just as well. The [Running programmatically](#running-programmatically) section below shows that pattern.
</Note>

## Launch Arize AX

1. Sign in to your [Arize AX account](https://app.arize.com/).
2. From **Space Settings**, copy your **Space ID** and **API Key**. You will set them as `ARIZE_SPACE_ID` and `ARIZE_API_KEY` below.

## Install

Bootstrap a Mastra project (if you don't already have one), then add the Arize AX exporter:

```bash theme={null}
npm create mastra@latest
# answer the prompts: include "agent", "tools", and the example
cd <chosen-project-name>

npm install @mastra/arize @mastra/observability @mastra/core
npm install --save-dev mastra
```

## Configure credentials

```bash theme={null}
export ARIZE_SPACE_ID="<your-space-id>"
export ARIZE_API_KEY="<your-api-key>"
export ARIZE_PROJECT_NAME="mastra-tracing-example"
export OPENAI_API_KEY="<your-openai-api-key>"
```

The `ArizeExporter` reads `ARIZE_SPACE_ID`, `ARIZE_API_KEY`, and `ARIZE_PROJECT_NAME` from the environment. You can also pass them explicitly to the constructor (see below).

## Setup tracing

Edit your project's main Mastra entry point (typically `src/mastra/index.ts`) to register the exporter:

```typescript theme={null}
// src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { Observability } from "@mastra/observability";
import { ArizeExporter } from "@mastra/arize";
import { weatherAgent } from "./agents/weather-agent";

export const mastra = new Mastra({
  agents: { weatherAgent },
  observability: new Observability({
    configs: {
      arize: {
        serviceName: process.env.ARIZE_PROJECT_NAME ?? "mastra-tracing-example",
        exporters: [new ArizeExporter()],
      },
    },
  }),
});
```

If you'd rather hard-code credentials (e.g. for a one-off test), pass them to `ArizeExporter`:

```typescript theme={null}
new ArizeExporter({
  apiKey: process.env.ARIZE_API_KEY!,
  spaceId: process.env.ARIZE_SPACE_ID!,
  projectName: process.env.ARIZE_PROJECT_NAME,
})
```

## Run Mastra

Start the dev server — this is what wires OTel into your app:

```bash theme={null}
mastra dev
```

`mastra dev` does four things:

1. Generates OTel bootstrap files into `.mastra/output/`.
2. Registers the `ArizeExporter` against the global tracer provider.
3. Starts the Mastra playground at [`http://localhost:4111/playground`](http://localhost:4111/playground).
4. Begins streaming spans to Arize AX as agents are invoked.

Open the playground and chat with one of your agents — for example, ask the weather agent "What's the weather in Berlin?" Each prompt produces an agent run that is exported to Arize AX.

### Expected output

```text wrap theme={null}
[mastra dev] Starting Mastra dev server on http://localhost:4111
[mastra dev] Observability configured: arize → otlp.arize.com
[mastra dev] Playground ready at http://localhost:4111/playground
```

### Running programmatically

For automated tests, batch jobs, or production code that doesn't need the playground UI, import the `mastra` value and call `getAgent(...).generate(...)` directly. The `Mastra` constructor registers OTel + the `ArizeExporter` at module load, so spans flow exactly as they do under `mastra dev`:

```typescript theme={null}
// run-mastra.ts
import { mastra } from "./src/mastra/index";

async function main() {
  console.log("Arize AX tracing initialized for Mastra.");

  const agent = mastra.getAgent("oceanAgent");
  const result = await agent.generate([
    {
      role: "user",
      content: "Why is the ocean salty? Answer in two sentences.",
    },
  ]);

  console.log(result.text);

  // BatchSpanProcessor batches spans before export — wait for the
  // wrapping invoke_agent root span to flush before the process exits.
  await new Promise((r) => setTimeout(r, 8000));
}

main().catch((err) => { console.error(err); process.exit(1); });
```

Run it with `tsx`:

```bash theme={null}
npx tsx run-mastra.ts
```

You'll see the agent's reply on stdout and the same `invoke_agent` / `model_step` / `model_chunk` span tree appear in Arize AX. This is the mode our integration test harness drives — see the doc's [GitHub source](https://github.com/Arize-ai/docs/blob/main/.agents/skills/test-integration/scripts/ensure_mastra.sh) for the full scaffold.

## Verify in Arize AX

1. Open your Arize AX space and select project **`mastra-tracing-example`**.
2. Trigger an agent from the playground at [`http://localhost:4111/playground`](http://localhost:4111/playground), then return to Arize AX. You should see a new trace within \~30 seconds with this shape: an `invoke_agent <agentName>` root span (AGENT) wraps `model_step <agentName>` and `model_chunk <agentName>` LLM child spans, plus a `chat <model-id>` LLM span with the prompt, response, and token usage attached.
3. If no traces appear, see [Troubleshooting](#troubleshooting).

## Troubleshooting

* **No traces in Arize AX.** Check that you actually import the `mastra` value before calling the agent — the `Mastra` constructor is what registers OTel. A script that imports an agent directly from `./agents/<name>` without ever touching the configured `mastra` instance will run the agent but skip registration. The pattern in the [Running programmatically](#running-programmatically) section imports `mastra` first.
* **`BatchSpanProcessor: span dropped` warnings, or partial traces.** The process exited before the span batch was flushed. Add `await new Promise((r) => setTimeout(r, 8000))` (or `mastra.shutdown()` if you're on a version that exposes it) before the script exits, so the OTel exporter has time to drain. `mastra dev` handles this automatically because the dev server stays alive.
* **`401` from OpenAI.** Verify `OPENAI_API_KEY` is set and your model selection is valid. The dev server inherits the shell environment that started it.
* **Auth errors from Arize AX.** Re-check `ARIZE_SPACE_ID` and `ARIZE_API_KEY` were set before `mastra dev` started. Restart the dev server after exporting them — already-running processes do not pick up new env vars.
* **Production / serverless deployments.** Outside the dev server, you must register OTel yourself before Mastra runs. The `@mastra/arize` exporter still works, but you wire it in via your platform's instrumentation entry point (e.g. `instrumentation.ts` in Next.js). See the [Mastra observability docs](https://mastra.ai/docs/observability/tracing/exporters/arize) for the platform-specific setup.

## Resources

<CardGroup>
  <Card icon="book-open" href="https://mastra.ai/docs" title="Mastra Documentation" horizontal />

  <Card icon="terminal" href="https://mastra.ai/docs/observability/tracing/exporters/arize" title="Mastra Arize AX Exporter Reference" horizontal />

  <Card icon="github" href="https://github.com/mastra-ai/mastra" title="Mastra GitHub" horizontal />
</CardGroup>
