
Copilotkit Setup
- 466 installs
- 35 repo stars
- Updated June 3, 2026
- copilotkit/skills
copilotkit-setup is a CopilotKit agent skill that bootstraps packages, providers, copilot runtime, and minimum project structure for developers adding first CopilotKit agent features to new or existing apps.
About
copilotkit-setup is a copilotkit/skills agent skill that bootstraps CopilotKit into a new or existing application by installing required packages, configuring React or Next.js providers, wiring the CopilotKit runtime, and establishing the minimum folder and hook structure for first agent-powered UI features. Developers reach for copilotkit-setup when starting a CopilotKit integration from scratch, adding copilot chat or action hooks to an existing React codebase, or validating that runtime endpoints and provider wrappers are correctly placed before building custom agents. The skill reduces setup errors around missing providers, uninitialized runtime routes, and incomplete SDK installation steps common in first CopilotKit PRs.
- Package and provider installation
- Runtime and env configuration
- Project scaffold conventions
- First copilot entry component
- Baseline agent-ready app structure
Copilotkit Setup by the numbers
- 466 all-time installs (skills.sh)
- Ranked #1,851 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/copilotkit/skills --skill copilotkit-setupAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 466 |
|---|---|
| repo stars | ★ 35 |
| Last updated | June 3, 2026 |
| Repository | copilotkit/skills ↗ |
How do you set up CopilotKit in a Next.js app?
Bootstrap a new or existing app with CopilotKit: install packages, configure providers, add the copilot runtime, and establish the minimum project structure for first agent features.
Who is it for?
Developers integrating CopilotKit agents into a new or existing React or Next.js app who need end-to-end SDK bootstrap guidance.
Skip if: Teams already running CopilotKit who only need version bumps and breaking-change migrations should use copilotkit-upgrade instead.
When should I use this skill?
User asks to add CopilotKit, set up copilot runtime, install CopilotKit packages, or bootstrap first agent features in an app.
What you get
Installed CopilotKit packages, configured providers, copilot runtime route, and starter project structure for agent UI hooks
- CopilotKit provider setup
- Copilot runtime route
- Starter agent hook structure
Files
CopilotKit Setup
Prerequisites
Live Documentation (MCP)
This plugin includes an MCP server (copilotkit-docs) that provides search-docs and search-code tools for querying live CopilotKit documentation and source code.
- Claude Code: Auto-configured by the plugin's
.mcp.json-- no setup needed. - Codex: Requires manual configuration. See the copilotkit-debug skill for setup instructions.
Environment
Before starting setup, verify:
1. Node.js >= 18 (required for fetch globals used by the runtime) 2. An AI provider API key (one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY) 3. A React-based frontend (Next.js App Router, Next.js Pages Router, Vite + React, or Angular) 4. A backend capable of running the runtime (same Next.js app via API routes, or a standalone Express/Hono server)
Framework Detection
Before generating any code, detect the project's framework by checking files in the project root. See references/framework-detection.md for the full decision tree.
Quick summary:
| Signal File | Framework |
|---|---|
next.config.{js,ts,mjs} + app/ directory | Next.js App Router |
next.config.{js,ts,mjs} + pages/ directory | Next.js Pages Router |
angular.json | Angular |
vite.config.{js,ts} + React deps in package.json | Vite + React |
Setup Workflow
Step 1: Install packages
All packages use the @copilotkit namespace.
Frontend (React) packages:
npm install @copilotkit/react @copilotkit/coreRuntime packages (backend):
npm install @copilotkit/runtime @copilotkit/agentIf the runtime runs in the same Next.js app as the frontend, install all four packages together.
For standalone Express backends, also install Express adapter dependencies:
npm install express cors
npm install -D @types/express @types/corsStep 2: Configure the runtime
The runtime is the server-side component that manages agent execution. See references/runtime-architecture.md for details.
There are two endpoint styles:
1. Multi-route (Hono) -- uses createCopilotEndpoint. Requires a catch-all route ([[...slug]] in Next.js). Each operation (run, connect, stop, info, transcribe, threads) gets its own HTTP path. 2. Single-route (Hono or Express) -- uses createCopilotEndpointSingleRoute or createCopilotEndpointSingleRouteExpress. All operations go through a single POST endpoint with method multiplexing.
Next.js App Router (recommended: multi-route with Hono)
Create src/app/api/copilotkit/[[...slug]]/route.ts:
import {
CopilotRuntime,
createCopilotEndpoint,
InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";
const agent = new BuiltInAgent({
model: "openai/gpt-4o",
prompt: "You are a helpful AI assistant.",
});
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
runner: new InMemoryAgentRunner(),
});
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
});
export const GET = handle(app);
export const POST = handle(app);This requires hono as a dependency:
npm install honoNext.js App Router (alternative: single-route)
Create src/app/api/copilotkit/route.ts:
import {
CopilotRuntime,
createCopilotEndpointSingleRoute,
InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";
const agent = new BuiltInAgent({
model: "openai/gpt-4o",
prompt: "You are a helpful AI assistant.",
});
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
runner: new InMemoryAgentRunner(),
});
const app = createCopilotEndpointSingleRoute({
runtime,
basePath: "/api/copilotkit",
});
export const POST = handle(app);When using single-route, the frontend must set useSingleEndpoint on the provider (see Step 3).
Standalone Express Server
Create src/index.ts:
import express from "express";
import { CopilotRuntime } from "@copilotkit/runtime";
import { createCopilotEndpointSingleRouteExpress } from "@copilotkit/runtime/express";
import { BuiltInAgent, defineTool } from "@copilotkit/agent";
import { z } from "zod";
const agent = new BuiltInAgent({
model: "openai/gpt-4o",
});
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
});
const app = express();
app.use(
"/api/copilotkit",
createCopilotEndpointSingleRouteExpress({
runtime,
basePath: "/",
}),
);
const port = Number(process.env.PORT ?? 4000);
app.listen(port, () => {
console.log(`CopilotKit runtime listening at http://localhost:${port}/api/copilotkit`);
});For multi-route Express, use createCopilotEndpointExpress instead (imported from @copilotkit/runtime/express).
Standalone Hono Server (non-Vercel)
import { CopilotRuntime, createCopilotEndpoint } from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { serve } from "@hono/node-server";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-4o" }),
},
});
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
});
serve({ fetch: app.fetch, port: 8787 });Requires @hono/node-server:
npm install hono @hono/node-serverStep 3: Set up the frontend provider
Wrap your application with CopilotKitProvider from @copilotkit/react.
Important: Import the stylesheet in your root layout:
import "@copilotkit/react/styles.css";Next.js App Router
In src/app/page.tsx (or a client component):
"use client";
import { CopilotKitProvider, CopilotChat } from "@copilotkit/react";
export default function Home() {
return (
<CopilotKitProvider runtimeUrl="/api/copilotkit">
<div style={{ height: "100vh" }}>
<CopilotChat />
</div>
</CopilotKitProvider>
);
}Connecting to an external runtime
When the runtime runs on a separate server (e.g., Express on port 4000):
<CopilotKitProvider
runtimeUrl="http://localhost:4000/api/copilotkit"
useSingleEndpoint
>
{children}
</CopilotKitProvider>Set useSingleEndpoint when the backend uses single-route endpoints (createCopilotEndpointSingleRoute or createCopilotEndpointSingleRouteExpress).
CopilotKitProvider key props
| Prop | Type | Description |
|---|---|---|
runtimeUrl | string | URL of the CopilotKit runtime endpoint |
useSingleEndpoint | boolean | Set to true when using single-route endpoints |
headers | Record<string, string> | Custom headers sent with every request |
credentials | RequestCredentials | Fetch credentials mode (e.g., "include" for cookies) |
publicApiKey | string | Copilot Cloud public API key (if using hosted runtime) |
showDevConsole | `boolean \ | "auto"` |
renderToolCalls | ReactToolCallRenderer[] | Custom renderers for tool call UI |
frontendTools | ReactFrontendTool[] | Frontend-defined tools (declarative alternative to useFrontendTool) |
onError | (event) => void | Global error handler |
Step 4: Add a chat UI component
CopilotKit provides three pre-built chat layouts:
| Component | Usage |
|---|---|
CopilotChat | Inline chat, fills its container |
CopilotSidebar | Collapsible sidebar panel |
CopilotPopup | Floating popup widget |
Example with sidebar:
<CopilotKitProvider runtimeUrl="/api/copilotkit" showDevConsole="auto">
<YourApp />
<CopilotSidebar
defaultOpen
width="420px"
labels={{
modalHeaderTitle: "AI Assistant",
chatInputPlaceholder: "Ask me anything...",
}}
/>
</CopilotKitProvider>Step 5: Set environment variables
Create a .env.local (Next.js) or .env file:
OPENAI_API_KEY=sk-...The BuiltInAgent automatically resolves API keys from environment variables based on the model prefix:
openai/*models readOPENAI_API_KEYanthropic/*models readANTHROPIC_API_KEYgoogle/*models readGOOGLE_API_KEY
You can also pass apiKey directly to BuiltInAgent if needed.
Step 6: Connect to the cloud platform (telemetry)
CopilotKit uses telemetry to understand adoption, improve the product, and provide better support. Connecting to the CopilotKit cloud platform gives you access to analytics and optional premium features.
1. Ask the user if they'd like to connect to the CopilotKit cloud platform (default: yes). 2. If yes, run the CopilotKit CLI authentication flow (verify the exact command with npx copilotkit --help as it may vary by version):
npx copilotkit auth3. Guide the user through the browser-based authentication that opens. 4. Once authentication completes, the CLI outputs a license key (format: ck_...). 5. Add the license key to the CopilotKitProvider:
<CopilotKitProvider
runtimeUrl="/api/copilotkit"
licenseKey="ck_..."
>Alternatively, store it as an environment variable (COPILOTKIT_LICENSE_KEY in .env.local or .env) and reference it:
<CopilotKitProvider
runtimeUrl="/api/copilotkit"
licenseKey={process.env.NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY}
>See references/telemetry-setup.md for full details on what the license key enables and how to opt out.
Step 7: Verify the setup
1. Start the dev server 2. Open the app in a browser 3. The chat UI should render and connect to the runtime 4. Send a test message -- you should receive an AI response 5. Check the runtime's /info endpoint (GET) to confirm it reports available agents
Quick Reference
Package map
| Package | Purpose |
|---|---|
@copilotkit/react | React components, hooks, provider |
@copilotkit/core | Core types, agent abstraction, state management |
@copilotkit/runtime | Server-side runtime, endpoint factories, agent runners |
@copilotkit/agent | BuiltInAgent, defineTool, model resolution |
@copilotkit/shared | Shared utilities, logger, types |
Endpoint factory functions
| Function | Import | Protocol | Framework |
|---|---|---|---|
createCopilotEndpoint | @copilotkit/runtime | Multi-route (Hono) | Next.js App Router, Hono standalone |
createCopilotEndpointSingleRoute | @copilotkit/runtime | Single-route (Hono) | Next.js App Router |
createCopilotEndpointExpress | @copilotkit/runtime/express | Multi-route (Express) | Express standalone |
createCopilotEndpointSingleRouteExpress | @copilotkit/runtime/express | Single-route (Express) | Express standalone |
Runtime classes
| Class | Use case |
|---|---|
CopilotRuntime | Compatibility shim; auto-selects SSE or Intelligence mode |
CopilotSseRuntime | Explicit SSE mode (default, in-memory threads) |
CopilotIntelligenceRuntime | Intelligence mode (durable threads, realtime events) |
Agent runners
| Runner | Description |
|---|---|
InMemoryAgentRunner | Default. Stores thread state in process memory. Suitable for development and single-instance deployments. |
IntelligenceAgentRunner | Used automatically with CopilotIntelligenceRuntime. Connects to CopilotKit Intelligence Platform via WebSocket. |
Supported models (BuiltInAgent)
Format: "provider/model-name" string or a Vercel AI SDK LanguageModel instance.
OpenAI: openai/gpt-5, openai/gpt-5-mini, openai/gpt-4.1, openai/gpt-4.1-mini, openai/gpt-4.1-nano, openai/gpt-4o, openai/gpt-4o-mini, openai/o3, openai/o3-mini, openai/o4-mini
Anthropic: anthropic/claude-sonnet-4.5, anthropic/claude-sonnet-4, anthropic/claude-3.7-sonnet, anthropic/claude-opus-4.1, anthropic/claude-opus-4, anthropic/claude-3.5-haiku
Google: google/gemini-2.5-pro, google/gemini-2.5-flash, google/gemini-2.5-flash-lite
Any string is accepted (for custom/unlisted models); the provider is parsed from the prefix before /.
// File: src/index.ts
// Standalone Express server with CopilotKit runtime (single-route)
//
// Prerequisites:
// npm install @copilotkit/runtime @copilotkit/agent express dotenv zod
// npm install -D @types/express tsx typescript
//
// Environment variables:
// OPENAI_API_KEY=sk-... (or ANTHROPIC_API_KEY / GOOGLE_API_KEY)
// PORT=4000 (optional, defaults to 4000)
//
// Run:
// npx tsx watch src/index.ts
import express from "express";
import dotenv from "dotenv";
import { z } from "zod";
import { CopilotRuntime } from "@copilotkit/runtime";
import { createCopilotEndpointSingleRouteExpress } from "@copilotkit/runtime/express";
import { BuiltInAgent, defineTool } from "@copilotkit/agent";
import type { ToolDefinition } from "@copilotkit/agent";
dotenv.config();
// Example server-side tool
const weatherTool = defineTool({
name: "getWeather",
description: "Get the current weather for a city",
parameters: z.object({
city: z.string().describe("The city name"),
}),
execute: async ({ city }) => {
// Replace with real weather API call
return { city, temperature: 72, condition: "sunny" };
},
}) as unknown as ToolDefinition;
const agent = new BuiltInAgent({
model: "openai/gpt-4o",
prompt: "You are a helpful AI assistant.",
tools: [weatherTool],
});
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
});
const app = express();
app.use(
"/api/copilotkit",
createCopilotEndpointSingleRouteExpress({
runtime,
basePath: "/",
}),
);
const port = Number(process.env.PORT ?? 4000);
app.listen(port, () => {
console.log(
`CopilotKit runtime listening at http://localhost:${port}/api/copilotkit`,
);
});
// File: src/app/page.tsx
// Next.js App Router frontend with CopilotKit provider and chat UI
//
// Prerequisites:
// npm install @copilotkit/react @copilotkit/core
//
// Also add to layout.tsx:
// import "@copilotkit/react/styles.css";
"use client";
import { CopilotKitProvider, CopilotChat } from "@copilotkit/react";
export default function Home() {
return (
<CopilotKitProvider runtimeUrl="/api/copilotkit" showDevConsole="auto">
<div style={{ height: "100vh", margin: 0, padding: 0, overflow: "hidden" }}>
<CopilotChat />
</div>
</CopilotKitProvider>
);
}
// File: src/app/api/copilotkit/[[...slug]]/route.ts
// Next.js App Router + Hono multi-route endpoint
//
// Prerequisites:
// npm install @copilotkit/runtime @copilotkit/agent hono
//
// Environment variables:
// OPENAI_API_KEY=sk-... (or ANTHROPIC_API_KEY / GOOGLE_API_KEY)
import {
CopilotRuntime,
createCopilotEndpoint,
InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";
const agent = new BuiltInAgent({
model: "openai/gpt-4o",
prompt: "You are a helpful AI assistant.",
});
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
runner: new InMemoryAgentRunner(),
});
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
});
export const GET = handle(app);
export const POST = handle(app);
version: "1"
defaults:
agent: claude
provider: docker
trials: 3
timeout: 300
threshold: 0.8
docker:
base: node:20-slim
setup: |
apt-get update && apt-get install -y git jq
tasks:
- name: nextjs-app-router-setup
instruction: |
Create a new Next.js App Router project and add CopilotKit with a basic chat
interface using BuiltInAgent. The project should have:
- CopilotKit frontend packages (@copilotkit/react, @copilotkit/core)
- CopilotKit runtime packages (@copilotkit/runtime, @copilotkit/agent)
- A runtime API route at src/app/api/copilotkit/[[...slug]]/route.ts using
createCopilotEndpoint with a BuiltInAgent
- A page component with CopilotKitProvider wrapping CopilotChat
- The @copilotkit/react stylesheet imported
graders:
- type: deterministic
run: |
cd /workspace
PROJECT_DIR=$(find . -maxdepth 1 -type d ! -name '.' | head -1)
if [ -z "$PROJECT_DIR" ]; then
echo '{"score": 0.0, "details": "No project directory found"}'
exit 0
fi
cd "$PROJECT_DIR"
CHECKS='[]'
add_check() {
CHECKS=$(echo "$CHECKS" | jq --arg name "$1" --argjson passed "$2" --arg msg "$3" '. + [{"name": $name, "passed": $passed, "message": $msg}]')
}
# Check frontend packages
if jq -e '.dependencies["@copilotkit/react"]' package.json > /dev/null 2>&1; then
add_check "@copilotkit/react installed" true "Found in dependencies"
else
add_check "@copilotkit/react installed" false "Not found in package.json dependencies"
fi
if jq -e '.dependencies["@copilotkit/core"]' package.json > /dev/null 2>&1; then
add_check "@copilotkit/core installed" true "Found in dependencies"
else
add_check "@copilotkit/core installed" false "Not found in package.json dependencies"
fi
# Check runtime packages
if jq -e '.dependencies["@copilotkit/runtime"]' package.json > /dev/null 2>&1; then
add_check "@copilotkit/runtime installed" true "Found in dependencies"
else
add_check "@copilotkit/runtime installed" false "Not found in package.json dependencies"
fi
if jq -e '.dependencies["@copilotkit/agent"]' package.json > /dev/null 2>&1; then
add_check "@copilotkit/agent installed" true "Found in dependencies"
else
add_check "@copilotkit/agent installed" false "Not found in package.json dependencies"
fi
# Check runtime route exists
ROUTE_FILE=$(find . -path '*/api/copilotkit/*/route.ts' -o -path '*/api/copilotkit/*/route.js' 2>/dev/null | head -1)
if [ -n "$ROUTE_FILE" ]; then
add_check "Runtime route file exists" true "Found at $ROUTE_FILE"
else
add_check "Runtime route file exists" false "No copilotkit API route found"
fi
# Check for CopilotKitProvider usage
if grep -r "CopilotKitProvider" --include='*.tsx' --include='*.ts' --include='*.jsx' . > /dev/null 2>&1; then
add_check "CopilotKitProvider used" true "Found in source files"
else
add_check "CopilotKitProvider used" false "CopilotKitProvider not found in any source file"
fi
# Check for CopilotChat usage
if grep -r "CopilotChat\|CopilotSidebar\|CopilotPopup" --include='*.tsx' --include='*.ts' --include='*.jsx' . > /dev/null 2>&1; then
add_check "Chat component used" true "Found chat component in source files"
else
add_check "Chat component used" false "No CopilotChat/CopilotSidebar/CopilotPopup found"
fi
PASSED=$(echo "$CHECKS" | jq '[.[] | select(.passed == true)] | length')
TOTAL=$(echo "$CHECKS" | jq 'length')
SCORE=$(echo "scale=2; $PASSED / $TOTAL" | bc)
echo "{\"score\": $SCORE, \"details\": \"$PASSED/$TOTAL checks passed\", \"checks\": $CHECKS}"
weight: 0.7
- type: llm_rubric
rubric: |
Evaluate whether this project has a complete, working CopilotKit setup:
1. Does it have a CopilotKitProvider wrapping a CopilotChat (or CopilotSidebar/CopilotPopup) component?
2. Does the runtime route use createCopilotEndpoint or createCopilotEndpointSingleRoute with a BuiltInAgent?
3. Is the @copilotkit/react stylesheet imported (styles.css)?
4. Does the provider's runtimeUrl point to the correct API route?
5. Is the project structured correctly for Next.js App Router (app/ directory, "use client" directives where needed)?
weight: 0.3
- name: vite-react-setup
instruction: |
Add CopilotKit to this existing Vite+React project with a chat sidebar and a
BuiltInAgent backend. The setup should include:
- CopilotKit frontend packages (@copilotkit/react, @copilotkit/core)
- CopilotKit runtime packages (@copilotkit/runtime, @copilotkit/agent)
- A backend server (Express or Hono) running the CopilotRuntime with a BuiltInAgent
- CopilotKitProvider in the React app pointing to the backend URL
- A CopilotSidebar component for the chat UI
- The @copilotkit/react stylesheet imported
workspace:
- src: workspace/vite-react
dest: /workspace
graders:
- type: deterministic
run: |
cd /workspace
CHECKS='[]'
add_check() {
CHECKS=$(echo "$CHECKS" | jq --arg name "$1" --argjson passed "$2" --arg msg "$3" '. + [{"name": $name, "passed": $passed, "message": $msg}]')
}
# Check frontend packages
if jq -e '.dependencies["@copilotkit/react"]' package.json > /dev/null 2>&1; then
add_check "@copilotkit/react installed" true "Found in dependencies"
else
add_check "@copilotkit/react installed" false "Not found in package.json dependencies"
fi
# Check runtime packages (may be in a separate server directory)
RUNTIME_FOUND=false
for PKG_FILE in $(find . -name 'package.json' -not -path '*/node_modules/*' 2>/dev/null); do
if jq -e '.dependencies["@copilotkit/runtime"]' "$PKG_FILE" > /dev/null 2>&1; then
RUNTIME_FOUND=true
break
fi
done
if [ "$RUNTIME_FOUND" = true ]; then
add_check "@copilotkit/runtime installed" true "Found in dependencies"
else
add_check "@copilotkit/runtime installed" false "Not found in any package.json"
fi
# Check for CopilotKitProvider
if grep -r "CopilotKitProvider" --include='*.tsx' --include='*.ts' --include='*.jsx' . > /dev/null 2>&1; then
add_check "CopilotKitProvider used" true "Found in source files"
else
add_check "CopilotKitProvider used" false "CopilotKitProvider not found"
fi
# Check for CopilotSidebar or other chat component
if grep -r "CopilotSidebar\|CopilotChat\|CopilotPopup" --include='*.tsx' --include='*.ts' --include='*.jsx' . > /dev/null 2>&1; then
add_check "Chat UI component used" true "Found sidebar/chat/popup component"
else
add_check "Chat UI component used" false "No chat UI component found"
fi
# Check for BuiltInAgent in backend
if grep -r "BuiltInAgent" --include='*.ts' --include='*.js' . > /dev/null 2>&1; then
add_check "BuiltInAgent configured" true "Found in backend source"
else
add_check "BuiltInAgent configured" false "BuiltInAgent not found in any source file"
fi
# Check for stylesheet import
if grep -r "styles\.css\|@copilotkit/react/styles" --include='*.tsx' --include='*.ts' --include='*.jsx' --include='*.css' . > /dev/null 2>&1; then
add_check "Stylesheet imported" true "Found styles.css import"
else
add_check "Stylesheet imported" false "No @copilotkit/react/styles.css import found"
fi
PASSED=$(echo "$CHECKS" | jq '[.[] | select(.passed == true)] | length')
TOTAL=$(echo "$CHECKS" | jq 'length')
SCORE=$(echo "scale=2; $PASSED / $TOTAL" | bc)
echo "{\"score\": $SCORE, \"details\": \"$PASSED/$TOTAL checks passed\", \"checks\": $CHECKS}"
weight: 0.7
- type: llm_rubric
rubric: |
Evaluate whether CopilotKit is properly integrated into this Vite+React project:
1. Is CopilotKitProvider set up with a runtimeUrl pointing to the backend server?
2. Is there a CopilotSidebar (or equivalent chat component) rendered in the app?
3. Does the backend use CopilotRuntime with a BuiltInAgent and an appropriate endpoint factory?
4. Is the @copilotkit/react stylesheet imported?
5. If the backend is a separate server, does the frontend URL account for the correct port and CORS is handled?
weight: 0.3
Framework Detection
Detect the project's framework before generating any setup code. The detection order matters -- check more specific signals first.
Detection Decision Tree
1. Does `angular.json` exist?
YES -> Angular
NO -> continue
2. Does `next.config.{js,ts,mjs}` exist?
YES -> Next.js (go to step 3)
NO -> continue to step 4
3. Does an `app/` directory exist at the project root or under `src/`?
YES -> Next.js App Router
NO -> Does a `pages/` directory exist at the project root or under `src/`?
YES -> Next.js Pages Router
NO -> Next.js App Router (assume App Router for new projects)
4. Does `vite.config.{js,ts}` exist AND does `package.json` list `react` as a dependency?
YES -> Vite + React
NO -> Unknown / standalone backend onlyWhat Differs Per Framework
Next.js App Router
- Runtime location:
src/app/api/copilotkit/[[...slug]]/route.ts(multi-route) orsrc/app/api/copilotkit/route.ts(single-route) - Provider placement: In a
"use client"page or layout component - Route handler style: Named exports
GETandPOSTusinghandle(app)fromhono/vercel - Stylesheet import: In
layout.tsx:import "@copilotkit/react/styles.css" - Env file:
.env.local - Extra deps:
hono(for Hono adapter)
Next.js Pages Router
- Runtime location: Typically runs as a separate Express server (not in API routes). The Pages Router examples in the CopilotKit repo use an external Express runtime.
- Provider placement: In
pages/_app.tsxor a page component. Must be a client component (default in Pages Router). - Frontend connects to external URL:
runtimeUrlpoints to the Express server (e.g.,http://localhost:4000/api/copilotkit) - Stylesheet import: In
pages/_app.tsxorstyles/globals.css:import "@copilotkit/react/styles.css" - Env file:
.env.local - Key prop:
useSingleEndpointmust be set on the provider when using single-route Express endpoints
Angular
- Runtime location: Separate backend server (Express or Hono standalone)
- Provider placement: Uses Angular-specific components from
@copilotkit/angular(separate package) - Not React-based: Does NOT use
CopilotKitProvideror React hooks - Stylesheet import: Via Angular styles configuration in
angular.json - Package:
@copilotkit/angularinstead of@copilotkit/react
Vite + React
- Runtime location: Separate backend server (Express or Hono standalone). Vite dev server only serves the frontend.
- Provider placement: In the root
App.tsxcomponent - Frontend connects to external URL:
runtimeUrlpoints to the backend server - Stylesheet import: In
main.tsxorApp.tsx:import "@copilotkit/react/styles.css" - Env file:
.env(Vite exposes vars prefixed withVITE_) - Note: API keys should NOT be prefixed with
VITE_-- they belong on the backend server, not exposed to the browser
Standalone Backend (Express)
- No framework detection needed -- this is a backend-only setup
- Uses:
@copilotkit/runtimeand@copilotkit/agent - Does NOT need:
@copilotkit/reactor@copilotkit/core - Endpoint factories:
createCopilotEndpointExpress(multi-route) orcreateCopilotEndpointSingleRouteExpress(single-route), both from@copilotkit/runtime/express - Env file:
.env(loaded viadotenv)
Standalone Backend (Hono)
- Same as Express but uses
createCopilotEndpointorcreateCopilotEndpointSingleRoutefrom@copilotkit/runtime - Served via:
@hono/node-serverwithserve({ fetch: app.fetch, port })
File-Level Detection Commands
When implementing framework detection in a skill, check these files:
# Next.js
ls next.config.{js,ts,mjs} 2>/dev/null
# App Router vs Pages Router
ls -d app src/app 2>/dev/null # App Router
ls -d pages src/pages 2>/dev/null # Pages Router
# Angular
ls angular.json 2>/dev/null
# Vite + React
ls vite.config.{js,ts} 2>/dev/null
grep -q '"react"' package.json 2>/dev/null
# Package manager
ls pnpm-lock.yaml 2>/dev/null && echo "pnpm"
ls yarn.lock 2>/dev/null && echo "yarn"
ls package-lock.json 2>/dev/null && echo "npm"
ls bun.lockb 2>/dev/null && echo "bun"Runtime Architecture
The CopilotKit v2 runtime (@copilotkit/runtime) is the server-side component that manages agent execution, thread state, and communication with the frontend via the AG-UI protocol (SSE-based events).
Core Concepts
CopilotRuntime
CopilotRuntime is the main entry point. It is a compatibility shim that delegates to either CopilotSseRuntime (default) or CopilotIntelligenceRuntime depending on configuration.
import { CopilotRuntime } from "@copilotkit/runtime";
// SSE mode (default) -- in-memory thread state
const runtime = new CopilotRuntime({
agents: { default: myAgent },
runner: new InMemoryAgentRunner(), // optional, this is the default
});
// Intelligence mode -- durable threads via CopilotKit Intelligence Platform
const runtime = new CopilotRuntime({
agents: { default: myAgent },
intelligence: new CopilotKitIntelligence({ ... }),
identifyUser: (request) => ({ id: "user-123" }),
});Constructor options (`CopilotRuntimeOptions`):
| Option | Type | Description |
|---|---|---|
agents | Record<string, AbstractAgent> | Map of named agents. Must have at least one entry. |
runner | AgentRunner | Agent execution strategy. Defaults to InMemoryAgentRunner. |
intelligence | CopilotKitIntelligence | Enables Intelligence mode with durable threads. |
identifyUser | (request: Request) => CopilotRuntimeUser | Required with Intelligence mode. Resolves authenticated user. |
generateThreadNames | boolean | Auto-generate thread names (Intelligence mode only, default: true). |
transcriptionService | TranscriptionService | Optional audio transcription (e.g., TranscriptionServiceOpenAI). |
beforeRequestMiddleware | BeforeRequestMiddleware | Callback or webhook URL invoked before each request. |
afterRequestMiddleware | AfterRequestMiddleware | Callback or webhook URL invoked after each request. |
a2ui | { agents?: string[] } & A2UIMiddlewareConfig | Auto-apply A2UI (Agent-to-UI) middleware to agents. |
mcpApps | { servers: McpAppsServerConfig[] } | Auto-apply MCP Apps middleware with MCP server configs. |
Agents
Agents implement the AbstractAgent interface from @ag-ui/client. CopilotKit provides BuiltInAgent (from @copilotkit/agent) as a ready-to-use implementation backed by the Vercel AI SDK.
import { BuiltInAgent, defineTool } from "@copilotkit/agent";
import { z } from "zod";
const agent = new BuiltInAgent({
model: "openai/gpt-4o", // "provider/model" string or LanguageModel instance
prompt: "You are helpful.", // System prompt
temperature: 0.7, // Sampling temperature
maxSteps: 5, // Max tool-calling iterations (default: 1)
tools: [ // Server-side tools
defineTool({
name: "getWeather",
description: "Get current weather for a city",
parameters: z.object({
city: z.string(),
}),
execute: async ({ city }) => {
return { temp: 72, condition: "sunny" };
},
}),
],
});BasicAgent is an alias for BuiltInAgent (same class, exported for convenience).
BuiltInAgent configuration:
| Option | Type | Description |
|---|---|---|
model | `string \ | LanguageModel` |
apiKey | string | Provider API key (falls back to env vars) |
prompt | string | System prompt |
temperature | number | Sampling temperature |
maxSteps | number | Max tool-calling iterations (default: 1) |
maxOutputTokens | number | Max tokens to generate |
toolChoice | ToolChoice | How tools are selected ("auto", "required", "none", or specific) |
tools | ToolDefinition[] | Server-side tools available to the agent |
mcpServers | MCPClientConfig[] | MCP server connections for dynamic tool discovery |
providerOptions | Record<string, any> | Provider-specific options (e.g., { openai: { reasoningEffort: "high" } }) |
overridableProperties | OverridableProperty[] | Properties the frontend can override via forwarded props |
forwardSystemMessages | boolean | Forward system-role messages from input (default: false) |
forwardDeveloperMessages | boolean | Forward developer-role messages as system messages (default: false) |
AgentRunner
The AgentRunner abstract class controls how agent execution is managed. It has four methods:
abstract class AgentRunner {
abstract run(request: AgentRunnerRunRequest): Observable<BaseEvent>;
abstract connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;
abstract isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;
abstract stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;
}Built-in runners:
- `InMemoryAgentRunner` -- Default. Stores thread state (events, runs) in process memory using a global
Mapkeyed by thread ID. Survives hot reloads viaSymbol.foronglobalThis. Suitable for development and single-instance deployments. - `IntelligenceAgentRunner` -- Used automatically when
CopilotIntelligenceRuntimeis configured. Connects to the Intelligence Platform via WebSocket for durable, distributed thread management.
Endpoint Factories
Endpoint factories create HTTP handlers that expose the runtime's functionality. There are four variants across two HTTP frameworks (Hono, Express) and two routing styles (multi-route, single-route).
Multi-Route Endpoints
Each operation gets its own HTTP path under the base path:
| Method | Path | Handler |
|---|---|---|
| POST | /agent/:agentId/run | Start an agent run |
| POST | /agent/:agentId/connect | Connect to an existing thread |
| POST | /agent/:agentId/stop/:threadId | Stop a running agent |
| GET | /info | Runtime info (version, available agents) |
| POST | /transcribe | Audio transcription |
| GET | /threads | List threads (Intelligence mode) |
| POST | /threads/subscribe | Subscribe to thread updates |
| PATCH | /threads/:threadId | Update thread metadata |
| POST | /threads/:threadId/archive | Archive a thread |
| DELETE | /threads/:threadId | Delete a thread |
Hono (`createCopilotEndpoint`):
import { CopilotRuntime, createCopilotEndpoint } from "@copilotkit/runtime";
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
cors: { // optional CORS config
origin: "https://myapp.com", // string, string[], or function
credentials: true, // enable for HTTP-only cookies
},
});Express (`createCopilotEndpointExpress`):
import { createCopilotEndpointExpress } from "@copilotkit/runtime/express";
const router = createCopilotEndpointExpress({
runtime,
basePath: "/api/copilotkit",
});
app.use(router);Single-Route Endpoints
All operations go through a single POST endpoint. The operation is identified by a method field in the JSON body. This is simpler to deploy (one route, no catch-all needed).
Hono (`createCopilotEndpointSingleRoute`):
import { CopilotRuntime, createCopilotEndpointSingleRoute } from "@copilotkit/runtime";
const app = createCopilotEndpointSingleRoute({
runtime,
basePath: "/api/copilotkit",
});Express (`createCopilotEndpointSingleRouteExpress`):
import { createCopilotEndpointSingleRouteExpress } from "@copilotkit/runtime/express";
const router = createCopilotEndpointSingleRouteExpress({
runtime,
basePath: "/", // relative to where it's mounted
});
app.use("/api/copilotkit", router);When to Use Which
| Scenario | Recommended |
|---|---|
| Next.js App Router | Multi-route Hono (createCopilotEndpoint) via [[...slug]] catch-all |
| Next.js App Router (no catch-all desired) | Single-route Hono (createCopilotEndpointSingleRoute) |
| Standalone Express server | Single-route Express (createCopilotEndpointSingleRouteExpress) |
| Standalone Hono/Node server | Multi-route Hono (createCopilotEndpoint) |
| Need thread management (Intelligence mode) | Multi-route only (thread endpoints not available in single-route) |
Middleware
The runtime supports before/after request middleware for cross-cutting concerns (auth, logging, rate limiting).
const runtime = new CopilotRuntime({
agents: { default: agent },
beforeRequestMiddleware: async ({ request, path }) => {
// Validate auth, return modified request or void
const token = request.headers.get("Authorization");
if (!token) {
throw new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
return request; // or return void to pass through unchanged
},
afterRequestMiddleware: async ({ response, path, messages, threadId }) => {
// Log, audit, etc. Non-blocking (errors are caught and logged).
console.log(`Completed request to ${path}, thread: ${threadId}`);
},
});afterRequestMiddleware receives reconstructed messages from the SSE stream and the threadId/runId extracted from the RUN_STARTED event.
CORS
All endpoint factories enable CORS by default with origin: "*". For production with credentials (cookies), configure explicit origins:
Hono endpoints:
createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
cors: {
origin: "https://myapp.com",
credentials: true,
},
});Express endpoints: CORS is handled internally via the cors middleware with permissive defaults. Customize by wrapping the router or adding your own CORS middleware upstream.
Frontend side: Set credentials: "include" on CopilotKitProvider to send cookies:
<CopilotKitProvider runtimeUrl="/api/copilotkit" credentials="include">CopilotCloud Telemetry Setup
What is CopilotCloud?
CopilotCloud is CopilotKit's hosted platform that provides:
- Usage analytics -- see how users interact with your AI features (message volume, tool usage, session duration)
- Error monitoring -- surface runtime errors and failed agent interactions
- Premium features -- access to hosted runtimes, advanced agent orchestration, and priority support (requires a paid plan)
The license key is a lightweight identifier that connects your local CopilotKit instance to CopilotCloud. It does not gate any open-source functionality -- CopilotKit works fully without it.
The npx copilotkit auth flow
Running the CLI command starts an interactive authentication (verify the exact command with npx copilotkit --help as it may vary by version):
npx copilotkit auth1. The CLI opens your default browser to the CopilotCloud login/signup page. 2. Sign in with GitHub, Google, or email. 3. Select or create a project in the CopilotCloud dashboard. 4. The CLI receives the license key and prints it to stdout:
Successfully authenticated!
Your license key: ck_abc123...If the browser does not open automatically, the CLI prints a URL you can copy-paste manually.
Where to put the license key
Option A: Inline in CopilotKitProvider
Pass the key directly as a prop:
<CopilotKitProvider
runtimeUrl="/api/copilotkit"
licenseKey="ck_abc123..."
>
{children}
</CopilotKitProvider>This is the simplest approach for quick prototyping but exposes the key in source code.
Option B: Environment variable (recommended)
Add the key to your environment file:
Next.js (.env.local):
NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY=ck_abc123...Vite (.env):
VITE_COPILOTKIT_LICENSE_KEY=ck_abc123...Then reference it in the provider:
// Next.js
<CopilotKitProvider
runtimeUrl="/api/copilotkit"
licenseKey={process.env.NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY}
>
// Vite
<CopilotKitProvider
runtimeUrl="/api/copilotkit"
licenseKey={import.meta.env.VITE_COPILOTKIT_LICENSE_KEY}
>The NEXT_PUBLIC_ or VITE_ prefix is required because the license key is used on the client side. It is safe to expose -- the key is a project identifier, not a secret.
Opting out
To disconnect from CopilotCloud, simply remove the licenseKey prop from CopilotKitProvider (and delete the environment variable if you set one). No other changes are needed -- CopilotKit will continue to function normally without it.
Sources
Files and directories read from CopilotKit/CopilotKit to generate this skill's references. Generated: 2026-03-28
framework-detection.md
- examples/v2/ (Angular, React, Node, Node-Express, Next Pages Router directory structures)
- examples/integrations/ (integration example directory structures for framework patterns)
- packages/v2/runtime/src/ (endpoint factories: createCopilotEndpoint, createCopilotEndpointExpress, createCopilotEndpointSingleRoute)
- packages/v2/react/src/ (CopilotKitProvider props, stylesheet imports)
- packages/v2/angular/src/ (Angular component package structure)
runtime-architecture.md
- packages/v2/runtime/src/ (CopilotRuntime, CopilotRuntimeOptions, AgentRunner, InMemoryAgentRunner, IntelligenceAgentRunner)
- packages/v2/runtime/src/endpoints/ (createCopilotEndpoint, createCopilotEndpointExpress, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, CORS config, route definitions)
- packages/v2/runtime/src/intelligence-platform/ (CopilotKitIntelligence, CopilotSseRuntime, CopilotIntelligenceRuntime)
- packages/v2/agent/src/ (BuiltInAgent, BasicAgent, defineTool, ToolDefinition, resolveModel, MCPClientConfig)
- packages/v2/shared/src/ (TranscriptionService, BeforeRequestMiddleware, AfterRequestMiddleware)
assets/express-runtime.ts
- packages/v2/runtime/src/ (CopilotRuntime constructor, createCopilotEndpointSingleRouteExpress)
- packages/v2/agent/src/ (BuiltInAgent, defineTool, ToolDefinition)
- examples/v2/node-express/ (Express server setup patterns)
assets/nextjs-app-router-route.ts
- packages/v2/runtime/src/ (CopilotRuntime, createCopilotEndpoint, InMemoryAgentRunner)
- packages/v2/agent/src/ (BuiltInAgent)
- examples/v2/react/ (Next.js App Router route handler patterns)
assets/nextjs-app-router-page.tsx
- packages/v2/react/src/ (CopilotKitProvider, CopilotChat component exports)
- examples/v2/react/ (Next.js App Router page component patterns)
Related skills
FAQ
What does copilotkit-setup configure?
copilotkit-setup installs CopilotKit packages, configures providers, adds the copilot runtime, and creates the minimum project structure needed for first agent chat or action hooks in React or Next.js apps.
When should you use copilotkit-setup?
Use copilotkit-setup when adding CopilotKit to a greenfield app or integrating agents into an existing React or Next.js codebase that lacks CopilotKit runtime wiring.
Does copilotkit-setup handle SDK version upgrades?
copilotkit-setup focuses on initial bootstrap; use copilotkit-upgrade for bumping CopilotKit package versions and migrating breaking API changes in active repos.