# Quickstart

> Run a Claude Agent SDK Python agent behind CopilotKit.

## Start with your coding agent [#start-with-your-coding-agent]

Use this prompt to connect your Claude Agent SDK for Python agent to CopilotKit and verify a working conversation. Your coding agent will follow this guide in your project, or you can work through the manual steps below.

<PageAgentPrompt />

This quickstart gives you two working paths:

- **Start from scratch** to scaffold the Claude Agent SDK Python starter app.
- **Use an existing agent** to expose your own Claude Agent SDK process over AG-UI and connect it to a React app.

## Prerequisites [#prerequisites]

Before you begin, you'll need the following:

- An Anthropic API key
- Python 3.12 or 3.13
- Node.js 20.9+
- `uv` for Python dependency management
- Your favorite JavaScript package manager

## Getting started [#getting-started]

<Steps>
  <Step>
    ### Choose your starting point [#choose-your-starting-point]

    <TailoredContent className="step" id="agent">
      <TailoredContentOption
        id="starter"
        title="Start from scratch"
        description="Scaffold the canonical Claude Agent SDK Python starter."
      >
        <Step>
          ### Run the CLI [#run-the-cli]

          ```bash
          npx copilotkit@latest init --framework claude-sdk-python
          ```

          The starter contains three pieces:

          - `agent/main.py` - the FastAPI server that serves the agent over AG-UI
          - `agent/src/agent.py` - the agent: its backend tools and the `ClaudeAgentAdapter`
          - `src/app/api/copilotkit/[[...slug]]/route.ts` - the CopilotKit runtime route that proxies to the agent
        </Step>

        <Step>
          ### Configure your environment [#configure-your-environment]

          Create a `.env` file in the generated project root:

          ```plaintext title=".env"
          ANTHROPIC_API_KEY=your_anthropic_api_key
          ANTHROPIC_MODEL=claude-opus-4-8
          ```

          The runtime route defaults to `AGENT_URL=http://localhost:8000`, which is where the starter's FastAPI agent server listens.
        </Step>

        <Step>
          ### Install dependencies [#install-dependencies]

          <Tabs groupId="package-manager" items={['npm', 'pnpm', 'yarn', 'bun']}>
            <Tab value="npm">
              ```bash
              npm install
              ```
            </Tab>
            <Tab value="pnpm">
              ```bash
              pnpm install
              ```
            </Tab>
            <Tab value="yarn">
              ```bash
              yarn install
              ```
            </Tab>
            <Tab value="bun">
              ```bash
              bun install
              ```
            </Tab>
          </Tabs>
        </Step>

        <Step>
          ### Start the development server [#start-the-development-server]

          <Tabs groupId="package-manager" items={['npm', 'pnpm', 'yarn', 'bun']}>
            <Tab value="npm">
              ```bash
              npm run dev
              ```
            </Tab>
            <Tab value="pnpm">
              ```bash
              pnpm dev
              ```
            </Tab>
            <Tab value="yarn">
              ```bash
              yarn dev
              ```
            </Tab>
            <Tab value="bun">
              ```bash
              bun dev
              ```
            </Tab>
          </Tabs>

          This starts both the Next.js app and the Python agent server.
        </Step>
      </TailoredContentOption>

      <TailoredContentOption
        id="bring-your-own"
        title="Use an existing agent"
        description="I already have a Claude Agent SDK Python agent and want to add CopilotKit."
      >
        <Step>
          ### Install the required Python packages [#install-the-required-python-packages]

          From your agent project, install the Claude Agent SDK adapter, AG-UI protocol packages, and FastAPI:

          ```bash
          uv add claude-agent-sdk ag-ui-claude-sdk ag-ui-protocol anthropic fastapi uvicorn python-dotenv
          ```
        </Step>

        <Step>
          ### Configure your agent environment [#configure-your-agent-environment]

          Create a `.env` file for the process that runs your Claude agent:

          ```plaintext title=".env"
          ANTHROPIC_API_KEY=your_anthropic_api_key
          ANTHROPIC_MODEL=claude-opus-4-8
          ```
        </Step>

        <Step>
          ### Expose Claude Agent SDK over AG-UI [#expose-claude-agent-sdk-over-ag-ui]

          CopilotKit talks to agents over AG-UI. The small FastAPI server below receives AG-UI run input, passes it to `ClaudeAgentAdapter`, and streams AG-UI events back to the runtime.

          ```python title="main.py"
          import logging
          import os
          from collections.abc import AsyncIterator

          from ag_ui.core import EventType, RunAgentInput, RunErrorEvent
          from ag_ui.encoder import EventEncoder
          from ag_ui_claude_sdk import ClaudeAgentAdapter
          from dotenv import load_dotenv
          from fastapi import FastAPI
          from fastapi.responses import StreamingResponse

          load_dotenv()

          app = FastAPI(title="Claude Agent SDK Agent")
          logger = logging.getLogger("claude_agent")

          # Build the adapter once, at module scope. ClaudeAgentAdapter is a
          # long-lived singleton that caches a worker (and its Claude SDK
          # subprocess) per thread; constructing it per request would leak those
          # workers and their subprocesses.
          adapter = ClaudeAgentAdapter(
              name="claude_agent",
              options={
                  "model": os.getenv("ANTHROPIC_MODEL", "claude-opus-4-8"),
                  "system_prompt": "You are a helpful assistant embedded in a CopilotKit app.",
                  "tools": [],
                  "permission_mode": "dontAsk",
                  "max_turns": 10,
              },
          )

          @app.get("/health")
          async def health() -> dict[str, str]:
              return {"status": "ok"}

          @app.post("/")
          async def run_agent(input_data: RunAgentInput) -> StreamingResponse:
              encoder = EventEncoder()

              async def event_stream() -> AsyncIterator[str]:
                  try:
                      async for event in adapter.run(input_data):
                          yield encoder.encode(event)
                  except Exception as error:
                      # Agent and streaming failures become a graceful RUN_ERROR,
                      # with the full detail logged server-side.
                      logger.exception("Claude agent run failed")
                      yield encoder.encode(
                          RunErrorEvent(
                              type=EventType.RUN_ERROR,
                              message=str(error),
                          )
                      )

              return StreamingResponse(
                  event_stream(),
                  media_type="text/event-stream",
                  headers={
                      "Cache-Control": "no-cache",
                      "X-Accel-Buffering": "no",
                  },
              )
          ```

          Start it and confirm the health check:

          ```bash
          uv run uvicorn main:app --reload --host 0.0.0.0 --port 8000
          curl http://localhost:8000/health
          ```
        </Step>

        <Step>
          ### Create your frontend [#create-your-frontend]

          CopilotKit works with any React app. This example uses Next.js App Router:

          ```bash
          npx create-next-app@latest frontend
          cd frontend
          npm install @copilotkit/runtime @copilotkit/react-core @ag-ui/client@1.0.2
          ```
        </Step>

        <Step>
          ### Add the CopilotKit runtime route [#add-the-copilotkit-runtime-route]

          Create `app/api/copilotkit/route.ts` in your Next.js app. It registers the Python agent server as an AG-UI `HttpAgent`.

          ```ts title="app/api/copilotkit/route.ts"
          import { HttpAgent } from "@ag-ui/client";
          import {
            CopilotRuntime,
            createCopilotRuntimeHandler,
          } from "@copilotkit/runtime/v2";
          import type { NextRequest } from "next/server";

          const runtime = new CopilotRuntime({
            agents: {
              claude_agent: new HttpAgent({
                url: process.env.AGENT_URL ?? "http://localhost:8000",
              }),
            },
          });

          const handler = createCopilotRuntimeHandler({
            runtime,
            basePath: "/api/copilotkit",
            mode: "single-route",
          });

          export const POST = (req: NextRequest) => handler(req);
          ```
        </Step>

        <Step>
          ### Mount CopilotKit in React [#mount-copilotkit-in-react]

          Wrap your app with `CopilotKit` and target the agent name you registered in the runtime route.

          ```tsx title="app/providers.tsx"
          "use client";

          import { CopilotKit } from "@copilotkit/react-core/v2";

          export function Providers({ children }: { children: React.ReactNode }) {
            return (
              <CopilotKit runtimeUrl="/api/copilotkit" agent="claude_agent">
                {children}
              </CopilotKit>
            );
          }
          ```

          Render the provider from `app/layout.tsx`:

          ```tsx title="app/layout.tsx"
          import { Providers } from "./providers";
          import "@copilotkit/react-core/v2/styles.css";
          import "./globals.css";

          export default function RootLayout({ children }: { children: React.ReactNode }) {
            return (
              <html lang="en">
                <body>
                  <Providers>
                    {children}
                  </Providers>
                </body>
              </html>
            );
          }
          ```

          <Callout type="info" title="This relative runtimeUrl assumes Next.js serves the runtime">
            `/api/copilotkit` resolves only because Next.js serves your app and the runtime from the
            same origin. A client-only frontend has no shared origin, so it needs a standalone runtime
            server of its own and an absolute `runtimeUrl` such as
            `http://localhost:8200/api/copilotkit`. The per-frontend guides at `/react-spa`, `/vue`,
            `/angular` and `/react-native` each show that setup.
          </Callout>

          Add a chat surface:

          ```tsx title="app/page.tsx"
          "use client";

          import { CopilotSidebar } from "@copilotkit/react-core/v2";

          export default function Page() {
            return (
              <main>
                <CopilotSidebar />
              </main>
            );
          }
          ```
        </Step>

        <Step>
          ### Start the UI [#start-the-ui]

          Keep the FastAPI agent server running, then start the frontend in a second terminal:

          ```bash
          npm run dev
          ```
        </Step>
      </TailoredContentOption>
    </TailoredContent>
  </Step>

  <Step>
    ### Verify the integration [#verify-the-integration]

    Open `http://localhost:3000` and ask:

    ```plaintext
    Tell me in one sentence what this app can do.
    ```

    If the chat streams a Claude response, CopilotKit is connected to your Claude Agent SDK Python agent.

    <Accordions className="mb-4">
      <Accordion title="Troubleshooting">
        - If the runtime cannot reach the agent, check that the FastAPI server is running on `http://localhost:8000` or set `AGENT_URL` in the frontend.
        - If Claude returns an authentication error, make sure `ANTHROPIC_API_KEY` is available to the Python process.
        - If a custom tool call stalls, add the backend tool bridge shown below instead of leaving `"tools": []`.
      </Accordion>
    </Accordions>
  </Step>

    <Step>
        ### Open Inspector and confirm setup [#open-inspector-and-confirm-setup]

        On localhost, click the Inspector button in the corner of the app.

        1. Open **Inspect**, then **Agent**. Your agent is listed.
        2. Send a chat message. Open **Inspect**, then **AG-UI Events**. Events are moving.
        3. Open **Rich Threads**. The list is unlocked (Intelligence is on), or locked with **Copy setup prompt** (Intelligence is off).

        More detail: [Inspector](/claude-sdk-python/inspector).
    </Step>

</Steps>

## Backend tools and state [#backend-tools-and-state]

The minimal server above is enough for text chat. To support backend tools, shared state snapshots, and richer demos, expose your tool schemas through the Claude SDK MCP bridge and emit AG-UI state events:

<Steps>
  <Step>
    ### Install the Claude Agent SDK packages

    ```bash
    uv add claude-agent-sdk ag-ui-claude-sdk ag-ui-protocol anthropic fastapi uvicorn python-dotenv
    ```
  </Step>

  <Step>
    ### Bridge Claude Agent SDK to AG-UI

    Use `ClaudeAgentAdapter` from `ag_ui_claude_sdk`. The adapter receives the
    AG-UI run input, emits AG-UI events back to CopilotKit, and can expose
    backend tools through an in-process Claude SDK MCP server.

~~~~python title="claude_agent_sdk_adapter.py"
async def run_with_claude_agent_sdk(
    input_data: RunAgentInput,
    *,
    system_prompt: str,
    tools: list[dict[str, Any]],
    state: Any,
    model: str,
    execute_tool: ExecuteTool,
    max_turns: int = 10,
) -> AsyncIterator[str]:
    """Run through the official AG-UI Claude adapter and emit SSE chunks."""

    encoder = EventEncoder()
    state_box = {"state": state}
    pending_state_snapshots: list[Any] = []
    sdk_tools = _build_sdk_tools(
        tools,
        execute_tool=execute_tool,
        get_state=lambda: state_box["state"],
        set_state=lambda next_state: _set_state(
            next_state,
            state_box,
            pending_state_snapshots,
        ),
    )

    options: dict[str, Any] = {
        "model": _normalize_claude_agent_sdk_model(model),
        "system_prompt": system_prompt,
        "tools": [],
        "permission_mode": "dontAsk",
        "max_turns": max_turns,
    }

    if sdk_tools:
        options["mcp_servers"] = {
            COPILOTKIT_MCP_SERVER_NAME: create_sdk_mcp_server(
                COPILOTKIT_MCP_SERVER_NAME,
                "1.0.0",
                tools=sdk_tools,
            )
        }
        options["allowed_tools"] = [
            f"{COPILOTKIT_TOOL_PREFIX}{schema['name']}" for schema in tools
        ]

    adapter = ClaudeAgentAdapter(
        name="claude-sdk-python",
        options=options,
    )
    run_input = _with_initial_state(input_data, state)

    async for event in adapter.run(run_input):
        if event.type == EventType.TOOL_CALL_RESULT and pending_state_snapshots:
            yield encoder.encode(
                StateSnapshotEvent(
                    type=EventType.STATE_SNAPSHOT,
                    snapshot=pending_state_snapshots.pop(0),
                )
            )
        yield encoder.encode(event)


~~~~

  </Step>
</Steps>
