Skip to main content

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:

  1. Integrate CopilotKit in your Mastra server with a separate React frontend.
  2. Integrate CopilotKit in your Next.js app
  1. In your React frontend, install the required CopilotKit packages:

    npm install @copilotkit/react-core @copilotkit/react-ui
  2. Create a CopilotKit component in your React frontend:

    components/copilotkit-component.tsx
    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>
    );
    }
  3. 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 install @copilotkit/runtime @ag-ui/mastra
  4. Configure your Mastra instance to include CopilotKit's runtime endpoint:

    src/mastra/index.ts
    import { Mastra } from "@mastra/core/mastra";
    import { registerCopilotKit } from "@ag-ui/mastra/copilotkit";
    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");
    },
    }),
    ],
    },
    });
  5. Use the component in your React app with your Mastra server URL:

    App.tsx
    import { CopilotKitComponent } from "./components/copilotkit-component";

    function App() {
    return <CopilotKitComponent runtimeUrl="http://localhost:4111/copilotkit" />;
    }

    export default App;

    Now start both the Mastra server and your frontend.

Start building the future!


CopilotKit output

Next Steps​

On this page