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.
Mastra 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 by routing your API endpoint through Mastra's agent stream.
Pick a pattern
| Pattern | When to pick |
|---|---|
| Full-stack | One Next.js app: API routes call Mastra in-process. Simpler deployment, single repo. |
| 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. 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.
Initialize assistant-ui
Set up assistant-ui in your project:
npx assistant-ui@latest createnpx assistant-ui@latest initThis installs dependencies and creates a default chat API route at app/api/chat/route.ts. For manual setup, see the getting started guide.
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.
npm install @mastra/core@latest @mastra/ai-sdk@latest zod@latestConfigure 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.
/** @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.
Define an agent
Create a mastra/ folder at the project root with two files:
mastra/
├── agents/
│ └── chefAgent.ts
└── index.tsDefine the agent in 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:
OPENAI_API_KEY=sk-...Register the agent
Initialize Mastra with the agent so it can be looked up by name:
import { Mastra } from "@mastra/core";
import { chefAgent } from "./agents/chefAgent";
export const mastra = new Mastra({
agents: { chefAgent },
});Wire the API route
Replace the default route with one that streams from the Mastra agent:
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.
Run and verify
Start the dev server:
npm run devOpen 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/chatreturningtext/event-stream. - No console errors about missing modules; if you see
Cannot find module '@mastra/...', revisit theserverExternalPackagesstep.
Notes
- Errors in the route bubble to the client as a stream error. Wrap
agent.stream()intry/catchif you need to log structured errors before they reach the client. - Pin compatible versions.
@mastra/ai-sdksupports AI SDK v5, v6, and v7. ItstoAISdkStreamdefault is v5, so setversionto match the major version of your installedaipackage. - 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.
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.
Create the Mastra server project
In a directory separate from your frontend, scaffold a Mastra project:
npx create-mastra@latestFollow the wizard's prompts. When it finishes, change into the new directory and add the AI SDK adapter:
cd your-mastra-servernpm install @mastra/ai-sdk@latestSet 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.
Define an agent
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",
});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.
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:
:agentIdmatches the JavaScript key in theagentsobject, not the agent'snamefield. SochefAgentis reachable at/chat/chefAgent(camelCase), not/chat/chef-agent.- Add more agents to the
agentsobject and they all become callable through this single route. FRONTEND_ORIGINshould be set to your deployed frontend's URL in production. Without CORS configured, the browser blocks the request and the chat silently fails.
Run the Mastra server
npm run devThe server starts on http://localhost:4111 by default. Leave it running for the rest of the steps.
Initialize the assistant-ui frontend
In a different directory from the Mastra server, scaffold the frontend:
npx assistant-ui@latest createnpx assistant-ui@latest initThis 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.
Point the runtime at the Mastra server
Open the file containing useChatRuntime (typically app/assistant.tsx) and pass an explicit api URL:
"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:
NEXT_PUBLIC_MASTRA_URL=http://localhost:4111/chat/chefAgentNEXT_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.
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 devOpen http://localhost:3000, send a message, and confirm:
- The response streams in token by token.
- The network tab shows the
POSTgoing tohttp://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 (
AssistantChatTransportacceptsheadersandcredentialsoptions). - Single agent vs router:
chatRoute({ path: "/chat/:agentId", version: "v7" })works for any agent registered on theMastrainstance. Switching agents from the frontend is a matter of pointingNEXT_PUBLIC_MASTRA_URLat a different agent ID. - Match the AI SDK version:
chatRoutedefaults to v5. Setversion: "v7"when the frontend usesai@7. - Advanced Mastra features (memory, tools, workflows, evals) live in the agent definition. The frontend sees only the resulting stream. See the Mastra 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.