Skip to main content

Overview

CopilotKitProvider is the root provider component that initializes CopilotKit in your React application. It manages the connection to your runtime, registers agents and tools, and provides configuration for error handling, rendering, and more.

Usage

import { CopilotKitProvider } from "@copilotkit/react";

function App() {
  return (
    <CopilotKitProvider
      runtimeUrl="https://your-runtime.com/api/copilotkit"
      headers={{ "Authorization": "Bearer token" }}
    >
      <YourApp />
    </CopilotKitProvider>
  );
}

Props

runtimeUrl
string
URL of your CopilotKit runtime endpoint. Required unless using publicApiKey or local agents only.
runtimeUrl="https://api.example.com/copilotkit"
publicApiKey
string
Your Copilot Cloud public API key. When provided, connects to CopilotKit Cloud.
publicApiKey="ck_pub_..."
publicLicenseKey
string
Alias for publicApiKey. Use either this or publicApiKey.
headers
Record<string, string>
default:"{}"
Custom headers to include in requests to the runtime.
headers={{ 
  "Authorization": "Bearer token",
  "X-Custom-Header": "value"
}}
credentials
RequestCredentials
Credentials mode for fetch requests. Use "include" for HTTP-only cookies in cross-origin requests.
credentials="include"
properties
Record<string, unknown>
default:"{}"
Additional properties to pass to the runtime for context or configuration.
properties={{ 
  userId: "123",
  workspace: "production"
}}
useSingleEndpoint
boolean
default:"false"
Use single endpoint mode instead of REST mode for runtime transport.
selfManagedAgents
Record<string, AbstractAgent>
Self-managed agents to register. These agents are managed by your application code.
selfManagedAgents={{
  "research-agent": myResearchAgent
}}
frontendTools
ReactFrontendTool[]
Array of frontend tools to register. Must be a stable array reference.
This must be a stable array. For dynamic tools, use the useFrontendTool hook instead.
const tools = useMemo(() => [
  {
    name: "getWeather",
    description: "Get weather for a city",
    parameters: z.object({ city: z.string() }),
    handler: async ({ city }) => {
      // Implementation
      return weatherData;
    }
  }
], []);

<CopilotKitProvider frontendTools={tools}>
renderToolCalls
ReactToolCallRenderer[]
Array of tool call renderers for custom UI. Must be a stable array reference.
const renderers = useMemo(() => [
  {
    name: "searchDocs",
    args: z.object({ query: z.string() }),
    render: ({ args, status }) => (
      <div>Searching: {args.query}</div>
    )
  }
], []);
renderActivityMessages
ReactActivityMessageRenderer[]
Array of activity message renderers. Must be a stable array reference.
renderCustomMessages
ReactCustomMessageRenderer[]
Array of custom message renderers. Must be a stable array reference.
humanInTheLoop
ReactHumanInTheLoop[]
Array of human-in-the-loop tools. Must be a stable array reference.
For dynamic human-in-the-loop tools, use the useHumanInTheLoop hook instead.
showDevConsole
boolean | 'auto'
default:"false"
Show the CopilotKit development console.
  • true: Always show the dev console
  • false: Never show the dev console
  • "auto": Show only on localhost/127.0.0.1
showDevConsole="auto"
onError
(event: ErrorEvent) => void | Promise<void>
Error handler called when CopilotKit encounters an error. Receives all error types including runtime connection failures, agent errors, and tool errors.
onError={({ error, code, context }) => {
  console.error(`CopilotKit error [${code}]:`, error);
  // Handle error based on code
}}
ErrorEvent Interface:
error
Error
The error object
code
CopilotKitCoreErrorCode
Error code indicating the type of error
context
Record<string, any>
Additional context about the error

Context Value

The provider exposes a context value that can be accessed via useCopilotKit():
copilotkit
CopilotKitCoreReact
The core CopilotKit instance
executingToolCallIds
ReadonlySet<string>
Set of tool call IDs currently being executed. Tracked at provider level for reconnection handling.

Hook: useCopilotKit

Access the CopilotKit context value:
import { useCopilotKit } from "@copilotkit/react";

function MyComponent() {
  const { copilotkit, executingToolCallIds } = useCopilotKit();
  
  // Check if a specific tool is executing
  const isExecuting = executingToolCallIds.has(toolCallId);
  
  return <div>...</div>;
}

Examples

Basic Setup with Runtime URL

import { CopilotKitProvider } from "@copilotkit/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      <YourApp />
    </CopilotKitProvider>
  );
}

CopilotKit Cloud Setup

import { CopilotKitProvider } from "@copilotkit/react";

function App() {
  return (
    <CopilotKitProvider publicApiKey={process.env.COPILOT_CLOUD_API_KEY}>
      <YourApp />
    </CopilotKitProvider>
  );
}

With Error Handling

import { CopilotKitProvider } from "@copilotkit/react";
import * as Sentry from "@sentry/react";

function App() {
  return (
    <CopilotKitProvider 
      runtimeUrl="/api/copilotkit"
      onError={({ error, code, context }) => {
        // Log to monitoring service
        Sentry.captureException(error, {
          tags: { copilotkit_error: code },
          extra: context,
        });
        
        // Show user-friendly message
        if (code === "RUNTIME_CONNECTION_FAILED") {
          toast.error("Unable to connect to AI service");
        }
      }}
    >
      <YourApp />
    </CopilotKitProvider>
  );
}

With Frontend Tools

import { CopilotKitProvider } from "@copilotkit/react";
import { z } from "zod";
import { useMemo } from "react";

function App() {
  const tools = useMemo(() => [
    {
      name: "searchDatabase",
      description: "Search the product database",
      parameters: z.object({
        query: z.string().describe("Search query"),
      }),
      handler: async ({ query }) => {
        const results = await searchProducts(query);
        return results;
      },
    },
  ], []);

  return (
    <CopilotKitProvider 
      runtimeUrl="/api/copilotkit"
      frontendTools={tools}
    >
      <YourApp />
    </CopilotKitProvider>
  );
}

With Custom Headers and Properties

import { CopilotKitProvider } from "@copilotkit/react";

function App({ userId, sessionToken }) {
  return (
    <CopilotKitProvider 
      runtimeUrl="/api/copilotkit"
      headers={{
        "Authorization": `Bearer ${sessionToken}`,
      }}
      properties={{
        userId,
        timestamp: Date.now(),
      }}
    >
      <YourApp />
    </CopilotKitProvider>
  );
}

Notes

Array props (frontendTools, renderToolCalls, renderActivityMessages, renderCustomMessages, humanInTheLoop) must be stable array references. If you need to dynamically add or remove items, use the corresponding hooks instead:
  • useFrontendTool for dynamic tools
  • useRenderTool for dynamic renderers
  • useHumanInTheLoop for dynamic human-in-the-loop tools
The CopilotKit instance is stable for the lifetime of the provider. Updates to props are applied via setters rather than recreating the instance.