Integrate CopilotKit with Mastra
CopilotKit 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.
Visit the CopilotKit documentation  to learn more about CopilotKit concepts, components, and advanced usage patterns.
This guide shows two distinct integration approaches:
- Integrate CopilotKit in your Mastra server with a separate React frontend.
- Integrate CopilotKit in your Next.js app
Mastra Server
Install React Dependencies
In your React frontend, install the required CopilotKit packages:
npm
npm install @copilotkit/react-core @copilotkit/react-ui
Create CopilotKit Component
Create a CopilotKit component in your React frontend:
import { CopilotChat } from "@copilotkit/react-ui";
import { CopilotKit } from "@copilotkit/react-core";
import "@copilotkit/react-ui/styles.css";
export function CopilotKitComponent({ runtimeUrl }: { runtimeUrl: string}) {
return (
<CopilotKit
runtimeUrl={runtimeUrl}
agent="weatherAgent"
>
<CopilotChat
labels={{
title: "Your Assistant",
initial: "Hi! 👋 How can I assist you today?",
}}
/>
</CopilotKit>
);
}
Install Dependencies
If you have not yet set up your Mastra server, follow the getting started guide to set up a new Mastra project.
In your Mastra server, install additional packages for CopilotKit integration:
npm
npm install @copilotkit/runtime @ag-ui/mastra
Configure Mastra Server
Configure your Mastra instance to include CopilotKit’s runtime endpoint:
import { Mastra } from "@mastra/core/mastra";
import { registerCopilotKit } from "@ag-ui/mastra";
import { weatherAgent } from "./agents/weather-agent";
type WeatherRuntimeContext = {
"user-id": string;
"temperature-scale": "celsius" | "fahrenheit";
};
export const mastra = new Mastra({
agents: { weatherAgent },
server: {
cors: {
origin: "*",
allowMethods: ["*"],
allowHeaders: ["*"]
},
apiRoutes: [
registerCopilotKit<WeatherRuntimeContext>({
path: "/copilotkit",
resourceId: "weatherAgent",
setContext: (c, runtimeContext) => {
runtimeContext.set("user-id", c.req.header("X-User-ID") || "anonymous");
runtimeContext.set("temperature-scale", "celsius");
}
})
]
}
});
Usage in your React App
Use the component in your React app with your Mastra server URL:
import { CopilotKitComponent } from "./components/copilotkit-component";
function App() {
return (
<CopilotKitComponent runtimeUrl="http://localhost:4111/copilotkit" />
);
}
export default App;
Start building the future!

Next Steps
- CopilotKit Documentation  - Complete CopilotKit reference
- React Hooks with CopilotKit  - Advanced React integration patterns
- Next.js Integration with Mastra - Full-stack Next.js setup guide