# Mastra
URL: /docs/runtimes/mastra

Wire the Mastra TypeScript agent framework into a React chat UI with assistant-ui, with full streaming, tool calling, multi-agent support, and thread management.

> For AI agents: a documentation index is available at [llms.txt](/llms.txt). Use `.md` for canonical markdown pages; `.mdx` is kept as a backwards-compatible alias on supported URL paths.

[Mastra](https://mastra.ai/) is an open-source TypeScript agent framework. It provides primitives for AI applications: agents with memory and tool calling, deterministic LLM workflows, RAG, model routing, workflow graphs, and automated evals.

> [!info]
>
> This is an integration guide, not a runtime adapter. assistant-ui does not ship a `@assistant-ui/react-mastra` package. You wire up Mastra through the standard [AI SDK runtime](/docs/runtimes/ai-sdk/v7) by routing your API endpoint through Mastra's agent stream.

## Pick a pattern

| Pattern                             | When to pick                                                                                                            |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| [Full-stack](#full-stack)           | One Next.js app: API routes call Mastra in-process. Simpler deployment, single repo.                                    |
| [Separate server](#separate-server) | Mastra runs as its own service; the Next.js frontend hits its API. Independent scaling, clearer separation of concerns. |

Both use the same client-side `useChatRuntime` from [`@assistant-ui/ai-sdk`](/docs/runtimes/ai-sdk/v7). The only difference is where the Mastra agent lives.

Either way you need a Next.js project or another framework that can run AI SDK route handlers, model API keys in your environment, and Node 18 or newer.

## Full-stack

Run Mastra in-process inside your Next.js application. The agent code, the API route, and the assistant-ui frontend all live in one project. There is one deploy target, one set of env vars, and no cross-origin configuration.

1. ### Initialize assistant-ui

   Set up assistant-ui in your project:

   `New project`

   ```
   npx assistant-ui@latest create
   ```

   `Existing project`

   ```
   npx assistant-ui@latest init
   ```

   This installs dependencies and creates a default chat API route at `app/api/chat/route.ts`. For manual setup, see the [getting started guide](/docs).

2. ### Install Mastra packages

   `@mastra/core` provides the agent runtime; `@mastra/ai-sdk` converts Mastra's stream format to AI SDK's UI message stream; `zod` is required for tool schemas.

   ```bash
   npm install @mastra/core@latest @mastra/ai-sdk@latest zod@latest
   ```

3. ### Configure Next.js

   Mastra's runtime depends on Node-only modules. Tell Next.js to bundle Mastra packages externally on the server so they aren't traced into the edge runtime.

   `next.config.mjs`

   ```
   /** @type {import('next').NextConfig} */
   const nextConfig = {
     serverExternalPackages: ["@mastra/*"],
   };

   export default nextConfig;
   ```

   If you skip this step you'll see opaque bundling errors at request time, not at build time.

4. ### Define an agent

   Create a `mastra/` folder at the project root with two files:

   `Project layout`

   ```
   mastra/
   ├── agents/
   │   └── chefAgent.ts
   └── index.ts
   ```

   Define the agent in `chefAgent.ts`:

   `mastra/agents/chefAgent.ts`

   ```
   import { Agent } from "@mastra/core/agent";

   export const chefAgent = new Agent({
     name: "chef-agent",
     instructions:
       "You are Michel, a practical and experienced home chef. " +
       "You help people cook with whatever ingredients they have available.",
     model: "openai/gpt-6-luna",
   });
   ```

   `model: "openai/gpt-6-luna"` uses Mastra's model router. Set the provider key in `.env.local` so Next.js auto-loads it:

   `.env.local`

   ```
   OPENAI_API_KEY=sk-...
   ```

5. ### Register the agent

   Initialize Mastra with the agent so it can be looked up by name:

   `mastra/index.ts`

   ```
   import { Mastra } from "@mastra/core";
   import { chefAgent } from "./agents/chefAgent";

   export const mastra = new Mastra({
     agents: { chefAgent },
   });
   ```

6. ### Wire the API route

   Replace the default route with one that streams from the Mastra agent:

   `app/api/chat/route.ts`

   ```
   import { createUIMessageStream, createUIMessageStreamResponse } from "ai";
   import { toAISdkStream } from "@mastra/ai-sdk";
   import { mastra } from "@/mastra";

   export const maxDuration = 30;

   export async function POST(req: Request) {
     const { messages } = await req.json();

     const agent = mastra.getAgent("chefAgent");
     const stream = await agent.stream(messages);

     const uiMessageStream = createUIMessageStream({
       originalMessages: messages,
       execute: async ({ writer }) => {
         for await (const part of toAISdkStream(stream, { from: "agent", version: "v7" })) {
           await writer.write(part);
         }
       },
     });

     return createUIMessageStreamResponse({ stream: uiMessageStream });
   }
   ```

   `agent.stream()` returns a Mastra-native stream. `toAISdkStream` (from `@mastra/ai-sdk`) adapts each part to the AI SDK shape; `createUIMessageStream` wraps the part loop into the UI message stream that `useChatRuntime` consumes; `createUIMessageStreamResponse` returns it as an HTTP response.

   The `@/mastra` import assumes the `@/*` path alias is configured in `tsconfig.json` (the assistant-ui starter sets this up). If your project uses a different alias, adjust the import path.

7. ### Run and verify

   Start the dev server:

   ```
   npm run dev
   ```

   Open `http://localhost:3000`, send a message like *"What can I make with eggs and rice?"*, and confirm:

   - The response streams in token by token.
   - The browser's network tab shows a single `POST /api/chat` returning `text/event-stream`.
   - No console errors about missing modules; if you see `Cannot find module '@mastra/...'`, revisit the `serverExternalPackages` step.

### Notes

- **Errors in the route bubble to the client as a stream error.** Wrap `agent.stream()` in `try/catch` if you need to log structured errors before they reach the client.
- **Pin compatible versions.** `@mastra/ai-sdk` supports AI SDK v5, v6, and v7. Its `toAISdkStream` default is v5, so set `version` to match the major version of your installed `ai` package.
- **Advanced Mastra features** (memory, tools, workflows, evals) live entirely in the agent definition. assistant-ui sees only the resulting stream, so anything Mastra supports works without further frontend changes. See the [Mastra docs](https://mastra.ai/docs).

## Separate server

Run Mastra as its own service and have the assistant-ui frontend hit it over HTTP. The two halves can deploy, scale, and version independently. The tradeoff is one extra hop and CORS to configure.

The setup has two halves. Steps 1 to 4 happen in the **Mastra server** project; steps 5 to 7 happen in a **separate assistant-ui frontend** project. You'll have two terminals open by the end: one for each dev server.

1. ### Create the Mastra server project

   In a directory separate from your frontend, scaffold a Mastra project:

   ```
   npx create-mastra@latest
   ```

   Follow the wizard's prompts. When it finishes, change into the new directory and add the AI SDK adapter:

   ```
   cd your-mastra-server
   ```

   ```bash
   npm install @mastra/ai-sdk@latest
   ```

   Set the model provider keys (`OPENAI_API_KEY`, etc.) in `.env.development`. The `create-mastra` wizard prompts for some keys, but verify all the providers you plan to call are present.

2. ### Define an agent

   `src/mastra/agents/chefAgent.ts`

   ```
   import { Agent } from "@mastra/core/agent";

   export const chefAgent = new Agent({
     name: "chef-agent",
     instructions:
       "You are Michel, a practical and experienced home chef. " +
       "You help people cook with whatever ingredients they have available.",
     model: "openai/gpt-6-luna",
   });
   ```

3. ### Register the agent, chat route, and CORS

   Open the Mastra entry point. You will set three things in the same `Mastra` constructor: the agent, a chat route, and CORS for the frontend's origin.

   `src/mastra/index.ts`

   ```
   import { Mastra } from "@mastra/core";
   import { chefAgent } from "./agents/chefAgent";
   import { chatRoute } from "@mastra/ai-sdk";

   export const mastra = new Mastra({
     agents: { chefAgent },
     server: {
       cors: {
         origin: process.env.FRONTEND_ORIGIN ?? "http://localhost:3000",
         credentials: true,
       },
       apiRoutes: [
         chatRoute({ path: "/chat/:agentId", version: "v7" }),
       ],
     },
   });
   ```

   A few things to note:

   - `:agentId` matches the **JavaScript key** in the `agents` object, not the agent's `name` field. So `chefAgent` is reachable at `/chat/chefAgent` (camelCase), not `/chat/chef-agent`.
   - Add more agents to the `agents` object and they all become callable through this single route.
   - `FRONTEND_ORIGIN` should be set to your deployed frontend's URL in production. Without CORS configured, the browser blocks the request and the chat silently fails.

4. ### Run the Mastra server

   ```
   npm run dev
   ```

   The server starts on `http://localhost:4111` by default. Leave it running for the rest of the steps.

5. ### Initialize the assistant-ui frontend

   In a **different directory** from the Mastra server, scaffold the frontend:

   `New project`

   ```
   npx assistant-ui@latest create
   ```

   `Existing project`

   ```
   npx assistant-ui@latest init
   ```

   This creates a default chat page and a local API route at `app/api/chat/route.ts`. You won't use the local route, since the agent runs on the separate Mastra server; delete it once the next step is wired.

6. ### Point the runtime at the Mastra server

   Open the file containing `useChatRuntime` (typically `app/assistant.tsx`) and pass an explicit `api` URL:

   `app/assistant.tsx`

   ```
   "use client";

   import { AssistantRuntimeProvider } from "@assistant-ui/react";
   import { AssistantChatTransport, useChatRuntime } from "@assistant-ui/ai-sdk";
   import { Thread } from "@/components/assistant-ui/elements/thread.aui";

   export const Assistant = () => {
     const runtime = useChatRuntime({
       transport: new AssistantChatTransport({
         api: process.env.NEXT_PUBLIC_MASTRA_URL!,
       }),
     });

     return (
       <AssistantRuntimeProvider runtime={runtime}>
         <Thread />
       </AssistantRuntimeProvider>
     );
   };
   ```

   Set the URL in your frontend's environment:

   `.env.local`

   ```
   NEXT_PUBLIC_MASTRA_URL=http://localhost:4111/chat/chefAgent
   ```

   `NEXT_PUBLIC_*` makes the URL available in the browser. In production, point this at your deployed Mastra server. Mastra itself uses `.env.development` for its server keys; the two projects keep separate environment files.

7. ### Run and verify

   Make sure the Mastra server (step 4) is still running in its own terminal, then start the frontend in a new terminal:

   ```
   npm run dev
   ```

   Open `http://localhost:3000`, send a message, and confirm:

   - The response streams in token by token.
   - The network tab shows the `POST` going to `http://localhost:4111/chat/chefAgent`, not the local `/api/chat`.
   - No CORS errors in the console; if you see `blocked by CORS policy`, revisit step 3.

### Notes

- **Auth between frontend and Mastra**: the example above is open. In production, gate the Mastra route with a header or cookie check and forward credentials from the frontend (`AssistantChatTransport` accepts `headers` and `credentials` options).
- **Single agent vs router**: `chatRoute({ path: "/chat/:agentId", version: "v7" })` works for any agent registered on the `Mastra` instance. Switching agents from the frontend is a matter of pointing `NEXT_PUBLIC_MASTRA_URL` at a different agent ID.
- **Match the AI SDK version**: `chatRoute` defaults to v5. Set `version: "v7"` when the frontend uses `ai@7`.
- **Advanced Mastra features** (memory, tools, workflows, evals) live in the agent definition. The frontend sees only the resulting stream. See the [Mastra docs](https://mastra.ai/docs).

## Assistant Cloud

With Assistant Cloud, add `cloud` to the `useChatRuntime` call of either pattern and the app gets the thread list, message persistence, automatic titles, run reports and engagement events; a `messageMetadata` callback on the route fills in the model and usage of each run the same way as on any AI SDK route. See [AI SDK + assistant-ui](/docs/cloud/ai-sdk).

## Next

- [AI SDK runtime](/docs/runtimes/ai-sdk/v7) — The runtime that handles the client side of this integration.