# Copilotkit

> Build AI-powered agentic applications with CopilotKit. Use when building React apps with AI copilot features, generative UI, chat interfaces, agent integration (LangGraph/Mastra/Agent Spec), human-in-the-loop workflows, shared state, frontend/backend actions, or MCP Apps. Covers setup, hooks, components, styling, and agent backends.

- **Type:** Skill
- **Install:** `agentstack add skill-xuliang2024-agent-skills-copilotkit`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [xuliang2024](https://agentstack.voostack.com/s/xuliang2024)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [xuliang2024](https://github.com/xuliang2024)
- **Source:** https://github.com/xuliang2024/agent-skills/tree/main/skills/copilotkit

## Install

```sh
agentstack add skill-xuliang2024-agent-skills-copilotkit
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# CopilotKit — Agentic Application Framework

Build AI copilot features into React apps: chat UI, generative UI, frontend/backend tools, shared state, human-in-the-loop, and agent framework integration.

## Quick Start

### 1. Install

```bash
npm install @copilotkit/react-ui @copilotkit/react-core
```

For self-hosted runtime:

```bash
npm install @copilotkit/runtime
```

### 2. Provider Setup (layout.tsx)

```tsx
import "@copilotkit/react-ui/styles.css";
import { CopilotKit } from "@copilotkit/react-core";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    
      
        {/* Option A: Copilot Cloud */}
        ">
          {children}
        

        {/* Option B: Self-hosted */}
        {/* {children} */}
      
    
  );
}
```

### 3. Add Chat UI

Pick one of three built-in components:

```tsx
import { CopilotPopup } from "@copilotkit/react-ui";

export function App() {
  return (
    <>
      
      
    
  );
}
```

Alternatives: `CopilotSidebar` (wraps children), `CopilotChat` (inline, any size).

---

## Core Hooks

### useCopilotReadable — Provide context to LLM

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

const [items, setItems] = useState([...]);
useCopilotReadable({ description: "User's todo items", value: items });
```

Supports hierarchical context via `parentId` (return value of parent call).

### useFrontendTool — Frontend executable tool + optional UI

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

useFrontendTool({
  name: "addTodo",
  description: "Add a new todo item",
  parameters: [
    { name: "text", type: "string", description: "Todo content", required: true },
  ],
  handler: async ({ text }) => {
    setTodos(prev => [...prev, text]);
  },
  render: ({ status, args, result }) => {
    if (status === "inProgress") return ;
    return ;
  },
});
```

`render` is optional. When provided, UI appears inline in chat during tool execution.

### useRenderToolCall — Render-only (no handler)

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

useRenderToolCall({
  name: "get_weather",
  render: ({ status, args }) => {
    if (status !== "complete") return Loading weather...;
    return ;
  },
});
```

### useDefaultTool — Fallback renderer for all tools

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

useDefaultTool({
  render: ({ name, args, status, result }) => (
    
      {status === "complete" ? "✓" : "⏳"} {name}
      {status === "complete" && result && {JSON.stringify(result, null, 2)}}
    
  ),
});
```

### useCopilotChat — Headless chat API

```tsx
import { useCopilotChat } from "@copilotkit/react-core";
import { Role, TextMessage } from "@copilotkit/runtime-client-gql";

const { visibleMessages, appendMessage, stopGeneration, isLoading } = useCopilotChat();
appendMessage(new TextMessage({ content: "Hello", role: Role.User }));
```

### useCopilotChatSuggestions — Auto-generate suggestions

```tsx
import { useCopilotChatSuggestions } from "@copilotkit/react-ui";

useCopilotChatSuggestions({
  instructions: "Suggest next actions based on current state.",
  minSuggestions: 1,
  maxSuggestions: 3,
}, [relevantState]);
```

---

## Generative UI — Three Patterns

### Static (AG-UI) — Pre-built components, agent selects + fills data

Use `useFrontendTool` with `render`. Agent chooses which tool/component to show.

### Declarative (A2UI / Open-JSON-UI) — Agent returns structured JSON UI spec

Agent emits JSON describing cards/lists/forms. Frontend renders with its own styling.

### Open-ended (MCP Apps) — Agent returns full HTML/JS in sandboxed iframe

```bash
npm install @ag-ui/mcp-apps-middleware
```

```typescript
import { BuiltInAgent } from "@copilotkit/runtime/v2";
import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful assistant.",
}).use(
  new MCPAppsMiddleware({
    mcpServers: [{ type: "http", url: "http://localhost:3108/mcp", serverId: "my-server" }],
  }),
);
```

---

## Shared State (with LangGraph)

### Backend state definition (Python)

```python
from copilotkit import CopilotKitState

class AgentState(CopilotKitState):
    language: str = "english"
```

### Frontend read/write — useCoAgent

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

const { state, setState } = useCoAgent({
  name: "sample_agent",
  initialState: { language: "english" },
});
```

### Render state in chat — useCoAgentStateRender

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

useCoAgentStateRender({
  name: "sample_agent",
  render: ({ state }) => state.language ? Lang: {state.language} : null,
});
```

---

## Human-in-the-Loop (with LangGraph)

### Backend — interrupt()

```python
from langgraph.types import interrupt

def chat_node(state, config):
    name = state.get("agent_name") or interrupt("What should I call you?")
    # ... continue with name
```

### Frontend — useLangGraphInterrupt

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

useLangGraphInterrupt({
  render: ({ event, resolve }) => (
    
      {event.value}
      
       resolve(document.querySelector('input').value)}>Submit
    
  ),
});
```

Supports `enabled` for conditional routing and `handler` for programmatic pre-processing.

---

## Backend Actions (Self-hosted Runtime)

### API Route (Next.js App Router)

```typescript
import { CopilotRuntime, ExperimentalEmptyAdapter, copilotRuntimeNextJSAppRouterEndpoint } from "@copilotkit/runtime";

const runtime = new CopilotRuntime({
  actions: ({ properties, url }) => [
    {
      name: "fetchUser",
      description: "Fetch user by ID from database",
      parameters: [{ name: "userId", type: "string", description: "User ID", required: true }],
      handler: async ({ userId }) => {
        return await db.users.findById(userId);
      },
    },
  ],
});

const serviceAdapter = new ExperimentalEmptyAdapter();

export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime, serviceAdapter, endpoint: "/api/copilotkit",
  });
  return handleRequest(req);
};
```

`actions` is a factory function receiving `{ properties, url }` — dynamically expose different actions per page.

---

## Styling & Customization

### CSS Variables (simplest)

```tsx

  

```

### CSS Classes

Key classes: `.copilotKitMessages`, `.copilotKitInput`, `.copilotKitUserMessage`, `.copilotKitAssistantMessage`, `.copilotKitHeader`, `.copilotKitButton`, `.copilotKitWindow`.

### Custom Labels & Icons

```tsx
, sendIcon:  }}
/>
```

Available icons: `openIcon`, `closeIcon`, `headerCloseIcon`, `sendIcon`, `activityIcon`, `spinnerIcon`, `stopIcon`, `regenerateIcon`, `pushToTalkIcon`.

---

## CopilotKit Provider — Key Props

| Prop | Type | Description |
|------|------|-------------|
| `publicApiKey` | `string` | Copilot Cloud API key |
| `runtimeUrl` | `string` | Self-hosted runtime endpoint |
| `agent` | `string` | Agent name to use |
| `threadId` | `string` | Conversation thread ID |
| `headers` | `Record` | Custom request headers |
| `properties` | `Record` | Custom props (auth, metadata) |
| `credentials` | `RequestCredentials` | CORS cookie policy, e.g. `"include"` |
| `showDevConsole` | `boolean` | Show dev console |

---

## Decision Guide

| Need | Solution |
|------|----------|
| Add chat to existing app | `CopilotPopup` or `CopilotSidebar` |
| Fully custom chat UI | `useCopilotChat` (headless) |
| LLM reads app state | `useCopilotReadable` |
| LLM modifies app state | `useFrontendTool` with handler |
| Custom UI in chat messages | `useFrontendTool` or `useRenderToolCall` with render |
| Agent framework (LangGraph/Mastra) | `useCoAgent` + `useCoAgentStateRender` |
| User approval flows | `useLangGraphInterrupt` |
| Server-side data/API calls | Backend actions via `CopilotRuntime` |
| External MCP tool UIs | `MCPAppsMiddleware` |

## Additional Resources

- For complete API reference and advanced patterns, see [reference.md](reference.md)
- Official docs: https://docs.copilotkit.ai
- GitHub: https://github.com/CopilotKit/CopilotKit
- Generative UI playground: https://github.com/CopilotKit/generative-ui-playground

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [xuliang2024](https://github.com/xuliang2024)
- **Source:** [xuliang2024/agent-skills](https://github.com/xuliang2024/agent-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-xuliang2024-agent-skills-copilotkit
- Seller: https://agentstack.voostack.com/s/xuliang2024
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
