# API Reference

> API Reference for the CopilotKit v2 React API.

The v2 React API (`@copilotkit/react-core/v2`) gives you hooks and components for apps that talk to agents over the [AG-UI](https://docs.ag-ui.com) protocol.

## Provider Setup [#provider-setup]

Wrap your application with `<CopilotKitProvider>` to configure the v2 runtime connection:

```tsx
import { CopilotKitProvider } from "@copilotkit/react-core/v2";

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

The [`<CopilotKit>`](/reference/components/CopilotKit) export is the v1 compatibility wrapper, not an alias for `<CopilotKitProvider>`. Use `agentId` on the v2 provider; the compatibility wrapper uses `agent` and retains the v1 error-handler contract.

<Accordions>
<Accordion title="CopilotKitProvider props">

### Props [#props]

<PropertyReference name="agentId" type="string" default='"default"'>
  Default agent for chats and hooks under this provider. An explicit hook or
  chat `agentId`, or a surrounding chat configuration, takes precedence.
</PropertyReference>

<PropertyReference name="licenseToken" type="string">
  Signed license token for offline verification of CopilotKit Intelligence features.
</PropertyReference>

<PropertyReference name="selfManagedAgents" type="Record<string, AbstractAgent>">
  AG-UI agents managed by your app and registered directly with CopilotKit.
  Use this when you connect to agents without routing through a Copilot Runtime.
</PropertyReference>

<PropertyReference name="openGenerativeUI" type="{ sandboxFunctions?: SandboxFunction[]; designSkill?: string }">
  Configuration for Open Generative UI. Use `sandboxFunctions` to expose host
  functions to generated sandboxed iframes, and `designSkill` to override the
  design guidance injected as agent context for `generateSandboxedUi`.
</PropertyReference>

<PropertyReference name="defaultThrottleMs" type="number">
  Default throttle interval, in milliseconds, for `useAgent` re-renders caused
  by message and state updates. Individual `useAgent` calls and prebuilt chat
  components can override it with their own `throttleMs`.
</PropertyReference>

<PropertyReference name="debug" type="DebugConfig">
  Enable client-side debug logging for the AG-UI transport and event pipeline.
  Pass `true` for event and lifecycle summaries, or a config object with
  `verbose: true` to include full event payloads.
</PropertyReference>

<PropertyReference name="runtimeUrl" type="string">
  URL of the CopilotKit runtime endpoint. Lazily forwarded to the core after
  mount.
</PropertyReference>

<PropertyReference name="headers" type="Record<string, string> | (() => Record<string, string>) | (() => Promise<Record<string, string>>)" default="{}">
  Request headers forwarded with runtime calls. Pass an object for static
  headers, or a function (sync or async) to build them fresh. A builder runs
  when each request is sent, so a refreshed token is always used. An inline
  arrow is fine.

  Cache inside the builder. Clerk's and Auth0's `getToken()` already cache. A
  builder that calls the network every time adds one call per request.

  If the builder throws or rejects, that request is not sent and `onError`
  gets `header_resolution_failed`.

  Re-passing the same builder function is a no-op. On a user switch, remount
  the provider (e.g. `key={userId}`), so Inspector metadata and thread lists
  reload for the new user. This does not refetch the runtime's `/info`.

  `copilotkit.headers` is the last resolved value. Use
  `await copilotkit.resolveHeaders()` for your own requests.

  Core headers are also sent to any `selfManagedAgents` /
  `agents__unsafe_dev_only` agent, including ones on other origins. Don't put
  a bearer token in core headers if those agents point at a third party.

  ```tsx
  const { getToken } = useAuth();

  <CopilotKitProvider
    runtimeUrl="/api/copilotkit"
    headers={async () => ({ Authorization: `Bearer ${await getToken()}` })}
  >
  ```
</PropertyReference>

<PropertyReference name="credentials" type="RequestCredentials">
  Credentials mode for fetch requests (e.g. `"include"` for HTTP-only cookies in
  cross-origin requests).
</PropertyReference>

<PropertyReference name="publicApiKey" type="string">
  Copilot Cloud public API key.
</PropertyReference>

<PropertyReference name="publicLicenseKey" type="string">
  Alias for `publicApiKey`.
</PropertyReference>

<PropertyReference
  name="properties"
  type="Record<string, unknown>"
  default="{}"
>
  Runtime metadata payload.
</PropertyReference>

<PropertyReference name="useSingleEndpoint" type="boolean">
  When omitted, transport is negotiated from the runtime info response. Set
  `true` to use a single endpoint or `false` to use separate routes.
</PropertyReference>

<PropertyReference
  name="agents__unsafe_dev_only"
  type="Record<string, AbstractAgent>"
>
  Preinstantiated agents for development/testing. **Not intended for production
  use.**
</PropertyReference>

<PropertyReference name="renderToolCalls" type="ReactToolCallRenderer[]">
  Static set of tool call renderers. The array should be stable across renders.
</PropertyReference>

<PropertyReference
  name="renderActivityMessages"
  type="ReactActivityMessageRenderer[]"
>
  Static set of activity message renderers.
</PropertyReference>

<PropertyReference
  name="renderCustomMessages"
  type="ReactCustomMessageRenderer[]"
>
  Static set of custom message renderers.
</PropertyReference>

<PropertyReference name="frontendTools" type="ReactFrontendTool[]">
  Static tool handlers defined at the provider level. The array should be stable
  across renders.
</PropertyReference>

<PropertyReference name="humanInTheLoop" type="ReactHumanInTheLoop[]">
  Declarative human-in-the-loop tool definitions. Each becomes both a tool
  handler and a tool call renderer.
</PropertyReference>

<PropertyReference name="messageFilter" type="(messages: Message[], context: { agentId: string }) => Message[]">
  Rewrites the message list sent to runtime agents on every run. Return the
  messages to send. The transcript that the UI renders does not change.
  Intelligence runs and suggestion runs are not filtered. Pass a stable
  reference (`useCallback`).
</PropertyReference>

<PropertyReference name="showIntelligenceIndicator" type="boolean" default="true">
  Whether to mount the Intelligence indicator in chat automatically.
</PropertyReference>

<PropertyReference name="a2ui" type="{ theme?: A2UITheme; catalog?: any; loadingComponent?: React.ComponentType; includeSchema?: boolean; recovery?: A2UIRecoveryRendererOptions }">
  Options for the A2UI renderer. The renderer turns on when `a2ui` is
  configured in `CopilotRuntime`. Use this prop to override the theme, the
  component catalog, or the loading component. `includeSchema` (default
  `true`) sends the component schemas of the catalog to the agent as context.
</PropertyReference>

<PropertyReference name="generativeUI" type="GenerativeUIConfig">
  Experimental. Native generative UI: pass `{ ui }`, where `ui` comes from
  `createGenerativeUI`. The agent renders your React components into chat or
  into `<GenerativeUISurface id>` mounts.
</PropertyReference>

<PropertyReference name="mcpApps" type="{ allowSameOriginFallback?: boolean }">
  Options for the built-in MCP Apps renderer. `allowSameOriginFallback`
  (default `false`) restores `allow-same-origin` on the MCP App sandbox. The
  widget then runs with the origin of your page, so set it only for widgets
  that you wrote and trust.
</PropertyReference>

<PropertyReference name="learning" type="boolean | LearningProp">
  Turns on interaction capture (`@copilotkit/learning`). Pass `true` for the
  default options, or an object for options such as `autoStart` and
  `trajectoryId`. Omit the prop or pass `false` to turn capture off. Capture
  starts after mount and stops on unmount.
</PropertyReference>

<PropertyReference name="enableInspector" type="boolean">
  Controls the CopilotKit Inspector in development browser builds on localhost
  or loopback hosts. It is shown by default unless set to `false`, and is never
  loaded on remote hosts, in production, or during SSR, even when explicitly
  set to `true`.
</PropertyReference>

<PropertyReference name="showDevConsole" type='boolean | "auto"'>
  **Deprecated for Inspector control:** this prop does not change Inspector
  visibility. Use `enableInspector` instead.
</PropertyReference>

<PropertyReference name="onError" type="(event: { error: Error; code: CopilotKitCoreErrorCode; context: Record<string, any> }) => void | Promise<void>">
  Error handler called when CopilotKit encounters an error. Fires for all error types: runtime connection failures, agent errors, and tool errors.

`onError` works with any configuration. It does not need a `publicApiKey`.

```tsx
<CopilotKitProvider
  runtimeUrl="/api/copilotkit"
  onError={(event) => {
    console.error(`[${event.code}]`, event.error.message, event.context);
  }}
>
  <App />
</CopilotKitProvider>
```

</PropertyReference>

</Accordion>
</Accordions>

## Import Surfaces [#import-surfaces]

Use the main v2 entry when your app renders CopilotKit's web UI components or A2UI surfaces:

```tsx
import {
  CopilotKitProvider,
  CopilotChat,
  useAgent,
} from "@copilotkit/react-core/v2";
```

Use the headless entry when you build a fully custom chat surface and only need platform-agnostic hooks. This avoids the built-in chat rendering stack and its CSS:

```tsx
import {
  useAgent,
  useCopilotKit,
  useFrontendTool,
  useRenderToolCall,
} from "@copilotkit/react-core/v2/headless";
```

The headless entry exports the provider context, chat configuration provider, `useAgent`, tool hooks, suggestions, threads, capabilities, and shared types. It does not export `CopilotKitProvider`, `CopilotKit`, `CopilotChat`, `CopilotPopup`, `CopilotSidebar`, `useDefaultRenderTool`, or A2UI render helpers.

## Styling [#styling]

When using v2 UI components, import the stylesheet once at your app boundary:

```tsx
import "@copilotkit/react-core/v2/styles.css";
```

## API Reference [#api-reference]

<Callout type="info">
  Looking for tool rendering hooks? Start with
  [`useComponent`](/reference/hooks/useComponent),
  [`useRenderTool`](/reference/hooks/useRenderTool), and
  [`useDefaultRenderTool`](/reference/hooks/useDefaultRenderTool).
</Callout>

<Cards>
  <Card
    title="Hooks"
    description="React hooks for agents, tools, context, and chat configuration."
    href="/reference/hooks/useAgent"
  />
  <Card
    title="UI Components"
    description="Pre-built chat components: CopilotChat, CopilotPopup, CopilotSidebar, and more."
    href="/reference/components/CopilotChat"
  />
</Cards>
