> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
# Using CopilotKit
[CopilotKit](https://www.copilotkit.ai/) provides React components to quickly integrate customizable AI copilots into your application. Combined with Mastra, you can build sophisticated AI apps featuring bidirectional state synchronization and interactive UIs.
CopilotKit talks to Mastra through the [AG-UI protocol](https://docs.ag-ui.com/). The `@ag-ui/mastra` package exposes your Mastra agents as an AG-UI endpoint, and CopilotKit's React hooks and components consume it. This unlocks a spectrum of experiences on top of ordinary chat: [generative UI, human-in-the-loop, and frontend tools](https://mastra.ai/guides/build-your-ui/copilotkit/generative-ui), plus deploying the same agent to [messaging channels like Slack](https://mastra.ai/guides/build-your-ui/copilotkit/channels).
Visit the [CopilotKit documentation](https://docs.copilotkit.ai/) to learn more about CopilotKit concepts, components, and advanced usage patterns.
> **Info:** For a full-stack integration approach where Mastra runs directly in your Next.js API routes, see the [CopilotKit Quickstart](https://docs.copilotkit.ai/mastra/quickstart) guide.
Visit Mastra's ["UI Dojo"](https://ui-dojo.mastra.ai/) to see real-world examples of CopilotKit integrated with Mastra.
## Integration guide
Run Mastra as a standalone server and connect your Next.js frontend (with CopilotKit) to its API endpoints.
1. Set up your directory structure. A possible directory structure could look like this:
```bash
project-root
├── mastra-server
│ ├── src
│ │ └── mastra
│ └── package.json
└── my-copilot-app
└── package.json
```
Bootstrap your Mastra server:
**npm**:
```bash
npx create-mastra@latest
```
**pnpm**:
```bash
pnpm dlx create-mastra@latest
```
**Yarn**:
```bash
yarn dlx create-mastra@latest
```
**Bun**:
```bash
bun x create-mastra@latest
```
This command opens an interactive wizard that scaffolds a new Mastra project. Follow the prompts to create your server project.
Navigate to your newly created Mastra server directory:
```bash
cd mastra-server # Replace with the actual directory name you provided
```
You now have a basic Mastra server project ready.
> **Note:** Ensure that you have set the appropriate environment variables for your LLM provider in the `.env` file.
2. Create a chat route for the CopilotKit frontend by using the `registerCopilotKit()` helper from `@ag-ui/mastra`. Add it to your Mastra project (and its peer dependencies):
**npm**:
```bash
npm install @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**pnpm**:
```bash
pnpm add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**Yarn**:
```bash
yarn add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**Bun**:
```bash
bun add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
In your `src/mastra/index.ts` file, register the chat route:
```typescript
import { Mastra } from '@mastra/core/mastra'
import { registerCopilotKit } from '@ag-ui/mastra/copilotkit'
// Rest of the imports...
export const mastra = new Mastra({
// Rest of the configuration...
server: {
cors: {
origin: '*',
allowMethods: ['*'],
allowHeaders: ['*'],
},
apiRoutes: [
registerCopilotKit({
path: '/copilotkit',
resourceId: 'weatherAgent',
}),
],
},
})
```
This exposes the agents on your Mastra instance at `/copilotkit` in a CopilotKit-compatible format. The frontend selects which agent to talk to with the `agent` prop shown below. Add the CORS configuration so the CopilotKit frontend can access the Mastra server. For production deployments, restrict CORS origins to your frontend domain.
3. Run the Mastra server using the following command:
**npm**:
```bash
npm run dev
```
**pnpm**:
```bash
pnpm run dev
```
**Yarn**:
```bash
yarn dev
```
**Bun**:
```bash
bun run dev
```
By default, the Mastra server runs on `http://localhost:4111`. Keep this server running while you set up the CopilotKit frontend.
4. Go up one directory to your project root.
```bash
cd ..
```
Create a new Next.js project with the name `my-copilot-app`:
**npm**:
```bash
npx create-next-app@latest my-copilot-app
```
**pnpm**:
```bash
pnpm dlx create-next-app@latest my-copilot-app
```
**Yarn**:
```bash
yarn dlx create-next-app@latest my-copilot-app
```
**Bun**:
```bash
bun x create-next-app@latest my-copilot-app
```
Navigate to your newly created Next.js project directory:
```bash
cd my-copilot-app
```
5. Install the CopilotKit UI packages which you'll use to display a chat interface:
**npm**:
```bash
npm install @copilotkit/react-ui @copilotkit/react-core
```
**pnpm**:
```bash
pnpm add @copilotkit/react-ui @copilotkit/react-core
```
**Yarn**:
```bash
yarn add @copilotkit/react-ui @copilotkit/react-core
```
**Bun**:
```bash
bun add @copilotkit/react-ui @copilotkit/react-core
```
Open the home route of the Next.js app (usually `app/page.tsx` or `src/app/page.tsx`) and replace the existing contents with the following code to set up a basic CopilotKit chat interface:
```typescript
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
)
}
```
The `agent` prop names the Mastra agent to route to. It must match a key in your Mastra instance's `agents` map.
6. Ensure both the Mastra server and the CopilotKit frontend are running. Start the Next.js development server:
**npm**:
```bash
npm run dev
```
**pnpm**:
```bash
pnpm run dev
```
**Yarn**:
```bash
yarn dev
```
**Bun**:
```bash
bun run dev
```
Open the app in your browser and chat with your agent.
Your CopilotKit frontend now communicates with a standalone Mastra agent server.
## Chat UI options
`CopilotChat` renders an inline, full-height chat. CopilotKit ships two other drop-in surfaces that share the same props:
- `CopilotSidebar`: a collapsible panel docked to the side of your app.
- `CopilotPopup`: a floating button that opens a chat window.
Swap the component to change the surface. All three connect through the same `CopilotKit` provider:
```typescript
import { CopilotSidebar } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
{/* your app */}
)
}
```
For fully custom chat UIs (bring your own components), see [CopilotKit's headless UI guide](https://docs.copilotkit.ai/).
## App control and interactivity
Beyond rendering agent output as UI (see [generative UI](https://mastra.ai/guides/build-your-ui/copilotkit/generative-ui)), CopilotKit lets the agent act on your application and pause for the user. Both patterns run against the same Mastra setup.
### Frontend tools
Give the agent the ability to act on your app. Register the tool on the frontend with `useFrontendTool`; the `handler` runs in the browser when the agent calls it:
```tsx
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useFrontendTool } from '@copilotkit/react-core'
function Chat() {
useFrontendTool({
name: 'colorChangeTool',
description: 'Changes the background color',
parameters: [
{ name: 'color', type: 'string', description: 'The color to change to', required: true },
],
handler: ({ color }) => {
document.body.style.setProperty('--background', color)
},
})
return
}
export default function Page() {
return (
)
}
```
The matching Mastra agent is a normal agent instructed to call `colorChangeTool` with the requested color.
### Human-in-the-loop
Pause the agent mid-run and wait for the user to approve, edit, or reject before continuing. Use `useHumanInTheLoop`: its `render` function receives a `respond` callback, and the agent's run stays suspended until you call it.
```tsx
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useHumanInTheLoop } from '@copilotkit/react-core'
import { StepsFeedback } from '@/components/steps-feedback'
function Chat() {
useHumanInTheLoop({
name: 'generate_task_steps',
description: 'Generates a list of steps for the user to perform',
parameters: [
{
name: 'steps',
type: 'object[]',
attributes: [
{ name: 'description', type: 'string' },
{ name: 'status', type: 'string', enum: ['enabled', 'disabled', 'executing'] },
],
},
],
available: 'enabled',
// `respond` resumes the agent with the user's edited selection.
render: ({ args, respond, status }) => (
),
})
return
}
export default function Page() {
return (
)
}
```
Inside `StepsFeedback`, let the user toggle steps and then call `respond({ accepted: true, steps })` to resume the agent, or `respond({ accepted: false })` to reject. The agent reads the returned value and continues accordingly. See the full component in the [UI Dojo](https://ui-dojo.mastra.ai/).
The example above uses a client tool: the agent calls `generate_task_steps` and the frontend fulfills it through `respond`. Mastra can also pause on the server, suspending a tool call before it executes so a human approves or supplies input. For that path, see Mastra's [Agent approval](https://mastra.ai/docs/agents/agent-approval) guide for the backend side and CopilotKit's [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/useHumanInTheLoop) reference for the frontend.
## Configuration options
Use these `registerCopilotKit()` options for the common integration points:
| Option | Use it to |
| ---------------- | --------------------------------------------------------------------------------------------- |
| `path` | Set the route path, such as `/copilotkit`. |
| `resourceId` | Scope Mastra memory for conversations. |
| `cors` | Configure per-route CORS in addition to `server.cors`. |
| `setContext` | Populate request context before agents run, such as auth or per-user resource IDs. |
| `agents` | Provide pre-constructed AG-UI agents instead of the agents registered on the Mastra instance. |
| `tracingOptions` | Forward Mastra tracing options to each agent run. |
By default, the endpoint exposes every agent registered on the Mastra instance, and the frontend chooses one with the `agent` prop. Other CopilotKit runtime options are forwarded to the underlying runtime. For example, see [Open-ended generative UI](https://mastra.ai/guides/build-your-ui/copilotkit/generative-ui) for `mcpApps`.
## Deployment
When deploying your Mastra server with CopilotKit, you must exclude `@copilotkit/runtime` from the bundle. This package contains dependencies that aren't compatible with bundling and will cause 500 errors if included.
> **Note:** This issue doesn't occur during development with `mastra dev` since it doesn't require bundling. However, anyone running `mastra build` for deployment will encounter this issue.
Add the `@copilotkit/runtime` package to your bundler externals configuration:
```typescript
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})
```