examples/v2/docs/reference/copilotkit-core.mdx
CopilotKitCore is the client-side cross-framework orchestration layer that coordinates communication between your
application's UI, agents abd the remote Copilot runtime.
graph TB
subgraph Framework["Framework Layer"]
React["**CopilotKit React**
Components & Hooks"]
Angular["**CopilotKit Angular**
Directives & Services"]
Vue["**CopilotKit ...**
Future frameworks"]
end
subgraph CoreLayer["Core Layer"]
Core["**CopilotKitCore**
Cross-framework Orchestration
State Management & Agent Coordination"]
end
subgraph RuntimeLayer["Runtime Layer"]
Runtime["**CopilotRuntime**
AI Agent Execution
Backend Services"]
end
React --> Core
Angular --> Core
Vue -.-> Core
Core <--> Runtime
CopilotKitCore solves several complex challenges in building AI-powered applications:
CopilotRuntime.At its heart, CopilotKitCore maintains the authoritative state for these critical elements:
Instantiate CopilotKitCore to initialize the client that manages runtime connections, agents, and tools.
new CopilotKitCore(config?: CopilotKitCoreConfig)
interface CopilotKitCoreConfig {
runtimeUrl?: string; // The endpoint where your CopilotRuntime server is hosted
headers?: Record<string, string>; // Custom HTTP headers to include with every request
properties?: Record<string, unknown>; // Application-specific data forwarded to agents as context
agents__unsafe_dev_only?: Record<string, AbstractAgent>; // Local agents for development only - production requires CopilotRuntime
tools?: FrontendTool<any>[]; // Frontend functions that agents can invoke
}
Configuration details:
runtimeUrl: When provided, CopilotKitCore will automatically connect and discover available remote agents.headers: Headers to include with every request.properties: Properties forwarded to agents as forwardedProps.tools: Frontend tools that agents can invoke.agents__unsafe_dev_only: Development only - This property is intended solely for rapid prototyping during
development. Production deployments require the security, reliability, and performance guarantees that only the
CopilotRuntime can provide. The key becomes the agent's identifier.Once initialized, CopilotKitCore exposes several properties that provide insight into its current state:
runtimeUrl: string | undefined The current runtime endpoint. Changing this property triggers a connection attempt
to the new runtime. Setting it to undefined gracefully disconnects from the current runtime.
runtimeVersion: string | undefined The version of the connected runtime, helpful for compatibility checks and
debugging.
runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus Tracks the current connection state, allowing you
to respond to connection changes in your UI.
headers: Readonly<Record<string, string>> The current request headers sent with every request.
properties: Readonly<Record<string, unknown>> The application properties being forwarded to agents.
agents: Readonly<Record<string, AbstractAgent>> A combined view of all available agents, merging local development
agents with those discovered from the runtime.
tools: Readonly<FrontendTool<any>[]> The list of registered frontend tools available to agents.
context: Readonly<Record<string, Context>> Contextual information that agents can use to make more informed
decisions.
When you provide a runtimeUrl, CopilotKitCore initiates a connection to your CopilotRuntime server. Here's what
happens behind the scenes:
{runtimeUrl}/infoCopilotKitCore creates a ProxiedCopilotRuntimeAgent instanceThe connection to your runtime can be in one of four states:
Disconnected: No runtime URL is configured, or the connection was intentionally closedConnecting: Actively attempting to establish a connection with the runtimeConnected: Successfully connected and remote agents are availableError: The connection attempt failed, but CopilotKitCore will continue with local agents onlyCopilotKitCore implements a robust event system that allows you to react to state changes and agent activities:
Registers a subscriber to receive events. Returns a subscription object with an unsubscribe() method, keeping
unsubscription localized to the subscription object.
subscribe(subscriber: CopilotKitCoreSubscriber): { unsubscribe(): void }
The event subscription system allows you to build reactive UIs that respond to CopilotKitCore's state changes. Each event provides both the CopilotKitCore instance and relevant data:
Notified whenever the connection to the runtime changes state. Use this to show connection indicators in your UI.
onRuntimeConnectionStatusChanged?: (event: {
copilotkit: CopilotKitCore;
status: CopilotKitCoreRuntimeConnectionStatus;
}) => void | Promise<void>
Fired when an agent begins executing a tool. Useful for showing loading states or activity indicators.
onToolExecutionStart?: (event: {
copilotkit: CopilotKitCore;
toolCallId: string;
agentId: string;
toolName: string;
args: unknown;
}) => void | Promise<void>
Fired when tool execution completes, whether successfully or with an error. Use this to update your UI based on the results.
onToolExecutionEnd?: (event: {
copilotkit: CopilotKitCore;
toolCallId: string;
agentId: string;
toolName: string;
result: string;
error?: string;
}) => void | Promise<void>
Notified when agents are added, removed, or updated. This includes both local changes and runtime discovery.
onAgentsChanged?: (event: {
copilotkit: CopilotKitCore;
agents: Readonly<Record<string, AbstractAgent>>;
}) => void | Promise<void>
Fired when context items are added or removed. Use this to keep UI elements in sync with available context.
onContextChanged?: (event: {
copilotkit: CopilotKitCore;
context: Readonly<Record<string, Context>>;
}) => void | Promise<void>
Notified when application properties are updated. Useful for debugging or showing current configuration.
onPropertiesChanged?: (event: {
copilotkit: CopilotKitCore;
properties: Readonly<Record<string, unknown>>;
}) => void | Promise<void>
Fired when HTTP headers are modified. Important for tracking authentication state changes.
onHeadersChanged?: (event: {
copilotkit: CopilotKitCore;
headers: Readonly<Record<string, string>>;
}) => void | Promise<void>
The central error handler for all CopilotKitCore operations. Every error includes a code and contextual information to help with debugging.
onError?: (event: {
copilotkit: CopilotKitCore;
error: Error;
code: CopilotKitCoreErrorCode;
context: Record<string, any>;
}) => void | Promise<void>
CopilotKitCore provides detailed error information through typed error codes, making it easier to handle different failure scenarios appropriately:
Each error is categorized with a specific code that indicates what went wrong:
RUNTIME_INFO_FETCH_FAILED: The attempt to fetch runtime information failed. This might indicate network issues or an
incorrect runtime URL.
AGENT_CONNECT_FAILED: Failed to establish a connection with an agent. Check that the agent is properly configured.
AGENT_RUN_FAILED: The agent execution failed. This could be due to invalid messages or agent-side errors.
AGENT_RUN_FAILED_EVENT: The agent reported a failure through its event stream.
AGENT_RUN_ERROR_EVENT: The agent emitted an error event during execution.
TOOL_ARGUMENT_PARSE_FAILED: The arguments provided to a tool couldn't be parsed. This usually indicates a mismatch
between expected and actual parameters.
TOOL_HANDLER_FAILED: A tool's handler function threw an error during execution.
CopilotKitCore provides two primary methods for executing agents: runAgent for immediate execution with message
handling, and connectAgent for establishing live connections to existing agent sessions.
Executes an agent and intelligently handles the complete request-response cycle, including automatic tool execution and follow-up runs.
The execution flow:
followUp enabled (default), the agent is automatically re-run with the tool resultsKey behaviors:
runAgent(params: CopilotKitCoreRunAgentParams): Promise<RunAgentResult>
interface CopilotKitCoreRunAgentParams {
agent: AbstractAgent; // The agent to execute
}
Establishes a live connection with an agent, restoring any existing conversation history and subscribing to real-time events. This method is particularly useful when:
The connection process:
connectAgent(params: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult>
interface CopilotKitCoreConnectAgentParams {
agent: AbstractAgent; // The agent to connect
agentId?: string; // Override the agent's default identifier
}
Retrieves an agent by its identifier. Returns undefined if the agent doesn't exist or if the runtime is still
connecting.
getAgent(id: string): AbstractAgent | undefined
Context provides agents with additional information about the current state of your application:
Adds contextual information that agents can reference. Returns a unique identifier for later removal.
addContext(context: Context): string
interface Context {
description: string; // A human-readable description of what this context represents
value: any; // The actual context data
}
Removes previously added context using its identifier.
removeContext(id: string): void
Tools are functions that agents can call to interact with your application:
Registers a new frontend tool. If a tool with the same name and agent scope already exists, the registration is skipped to prevent duplicates.
addTool<T>(tool: FrontendTool<T>): void
Removes a tool from the registry. You can remove tools globally or for specific agents:
agentId is provided, removes the tool only for that agentagentId is omitted, removes only global tools with the matching nameremoveTool(id: string, agentId?: string): void
Retrieves a tool by name, with intelligent fallback behavior:
getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined
interface CopilotKitCoreGetToolParams {
toolName: string; // The tool's name
agentId?: string; // Look for agent-specific tools first
}
Replaces all tools at once. Useful for completely reconfiguring available tools.
setTools(tools: FrontendTool<any>[]): void
Understanding how CopilotKitCore handles tool execution is crucial for building responsive AI applications. Here's the complete lifecycle:
When an agent needs to interact with your application, it returns a tool call request with:
CopilotKitCore uses a two-tier resolution strategy:
*) can handle any unmatched tool requestsThe tool handler is invoked with parsed arguments:
By default, after tool execution completes:
followUp: false on specific toolsThese methods allow you to dynamically update CopilotKitCore's configuration after initialization:
Changes the runtime endpoint and manages the connection lifecycle. This is useful when switching between different environments or disconnecting from the runtime entirely.
setRuntimeUrl(runtimeUrl: string | undefined): void
Replaces all HTTP headers. Subscribers are notified so they can react to authentication changes or other header updates.
setHeaders(headers: Record<string, string>): void
Updates the properties forwarded to agents. Use this when your application state changes in ways that might affect agent behavior.
setProperties(properties: Record<string, unknown>): void
Agents are the AI-powered components that process requests and generate responses. CopilotKitCore provides several methods to manage them locally during development:
Replaces all local development agents while preserving remote agents from the runtime.
setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void
Adds a single agent for development testing.
addAgent__unsafe_dev_only(params: CopilotKitCoreAddAgentParams): void
interface CopilotKitCoreAddAgentParams {
id: string; // A unique identifier for the agent
agent: AbstractAgent; // The agent instance to add
}
Removes a local development agent by its identifier. Remote agents from the runtime cannot be removed this way.
removeAgent__unsafe_dev_only(id: string): void