# AWS AgentCore

> Add a frontend to your AWS AgentCore agents with CopilotKit.

[AWS Bedrock AgentCore](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html)
gives you a secure, serverless runtime for deploying AG-UI agents at scale. It handles auth, session
isolation, and infrastructure. CopilotKit gives those agents a chat UI, shared state, and generative UI in your React or Angular app.

## How it works [#how-it-works]

The two connect through **CopilotKit Runtime**, a lightweight server-side layer that sits between
your browser and AgentCore. This is the same runtime that every CopilotKit agent uses. For
AgentCore, it must run on the server. Browsers cannot sign AgentCore requests with SigV4 or OAuth2.

```
Browser → CopilotKit Runtime → AgentCore Runtime → your agent
```

## What you get [#what-you-get]

- **Chat UI**: prebuilt chat interface, or headless APIs to build your own
- **[Shared state](/shared-state)**: bidirectional sync between agent state and your application UI
- **[Generative UI](/generative-ui/tool-rendering)**: render custom components from tool calls in real time
- **Human-in-the-loop**: let users review, approve, or redirect agent actions
- **AgentCore memory**: conversation history persists across sessions via AgentCore's memory layer

## Quickstart [#quickstart]

<Callout type="info" title="AWS CLI required">
  Both paths below require AWS credentials configured locally. If you haven't done this yet,
  follow the [AWS CLI getting started guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)
  before continuing.
</Callout>

<Steps>
  <TailoredContent
    className="step"
    id="starting-point"
    header={
      <div>
        <p className="text-xl font-semibold">Choose your starting point</p>
        <p className="text-base">
          Start fresh with our CLI, or connect CopilotKit to an agent you've already deployed on AgentCore.
        </p>
      </div>
    }
  >
    <TailoredContentOption
      id="scratch"
      title="Start from scratch"
      description="Scaffold a complete AgentCore + CopilotKit application with one command."
    >

      <Step>
        ### Run the CLI [#run-the-cli]

        <AgentCoreCommandTabs
          lgCommand="npx copilotkit@latest create -f agentcore-langgraph"
          stCommand="npx copilotkit@latest create -f agentcore-strands"
        />

        The CLI downloads the full AgentCore template and sets up `config.yaml` for you.
      </Step>

      <Step>
        ### Configure [#configure]

        Open `config.yaml` and set your details:

        ```yaml title="config.yaml"
        stack_name_base: my-agentcore-app   # prefix for all AWS resources (max 35 chars)
        admin_user_email: you@example.com   # where your Cognito invite will be sent
        ```

        Then create the `.env` file in the project root:

        ```bash
        cp .env.example .env
        ```

        In `.env`, set `CPK_INTELLIGENCE_API_KEY` to the API key of your CopilotKit Intelligence project.
        The deploy script stops if this key is not set. It stores the key in AWS Secrets Manager.
      </Step>

      <Step>
        ### Deploy [#deploy]

        One command deploys the CDK infrastructure, AgentCore Runtime, and the frontend:

        <AgentCoreCommandTabs
          lgCommand="./deploy-langgraph.sh"
          stCommand="./deploy-strands.sh"
        />
      </Step>

      <Step>
        ### 🎉 Open your app [#-open-your-app]

        The deploy script prints an Amplify URL when it finishes. Open it and sign in with your `admin_user_email`.
      </Step>

      <Step>
        ### Run locally [#run-locally]

        After you deploy, you can run the agent, the CopilotKit runtime, and the frontend locally.
        The local stack still uses the Cognito user pool and the AgentCore memory of the deployed stack:

        ```bash
        cd docker
        cp .env.example .env
        # Fill in AWS credentials and STACK_NAME
        ./up.sh --build
        ```

        | Service | Port | Description |
        |---|---|---|
        | `agent` | 8080 | Your agent, hot-reloads on `.py` changes |
        | `runtime` | 3001 | CopilotKit Runtime |
        | `frontend` | 3000 | Vite dev server |
      </Step>

      <Step>
        ### Tear down [#tear-down]

        When done, delete all AWS resources to stop charges:

        ```bash
        cd infra-cdk && npx cdk destroy --all
        ```
      </Step>
    </TailoredContentOption>

    <TailoredContentOption
      id="existing"
      title="I already have an agent"
      description="I've followed the AWS guide and have an AG-UI agent deployed on AgentCore Runtime."
    >
      <Step>
        ### Install CopilotKit [#install-copilotkit]

        <Callout type="info" title="Deploying your AG-UI agent on AgentCore">
          This path assumes you already have an AG-UI-compatible agent deployed on AgentCore Runtime.
          If not, follow AWS's [Deploy an AG-UI agent to AgentCore Runtime](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-agui.html)
          guide first, then return here.
        </Callout>

      </Step>

      <Step>
        ### Set up CopilotKit Runtime [#set-up-copilotkit-runtime]

        CopilotKit Runtime is the server-side layer that connects your frontend to AgentCore. It handles
        the communication protocol, middleware, and (with AgentCore specifically) the server-side
        authentication that browsers can't perform directly.

        Create an API route:

        ```typescript title="app/api/copilotkit/[[...slug]]/route.ts"
        import {
          CopilotRuntime,
          createCopilotRuntimeHandler,
          InMemoryAgentRunner,
        } from "@copilotkit/runtime/v2";
        import { HttpAgent } from "@ag-ui/client";
        import { AgentCoreRunner } from "../agent-core-runner";

        const runtime = new CopilotRuntime({
          agents: {
            my_agent: new HttpAgent({
              url: process.env.AGENTCORE_ENDPOINT_URL!, // your /invocations URL
              headers: {
                Authorization: `Bearer ${process.env.AGENTCORE_ACCESS_TOKEN}`,
              },
            }),
          },
          runner: new AgentCoreRunner(),
        });

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

        export const GET = handler;
        export const POST = handler;
        ```

        <Callout type="info" title="What is AGENTCORE_ENDPOINT_URL?">
          This is the invocation URL for your deployed AgentCore Runtime. You call this URL to reach
          your agent. It takes the form:
          `https://bedrock-agentcore.{region}.amazonaws.com/runtimes/{encoded-arn}/invocations`
        </Callout>

        <Callout type="info" title="Auth in production">
          The example above uses a static token for simplicity. In production you'll want to pass the
          user's Cognito JWT from the frontend through to AgentCore. See the
          [AgentCore template](https://github.com/CopilotKit/CopilotKit/tree/main/examples/integrations/agentcore) for a complete Cognito OIDC implementation.
          To validate the frontend session at the runtime before you forward identity to AgentCore, see
          [Authentication](/auth).
        </Callout>
      </Step>

      <Step>
        ### Add the AgentCoreRunner [#add-the-agentcorerunner]

        AgentCore's memory layer stores conversation history server-side. When CopilotKit reconnects
        to an existing thread (e.g. on page refresh), two issues arise that require a custom runner:

        1. **Unknown threads**: CopilotKit may call `connect()` before any `run()` has happened.
           Without handling this, you'll get an error on first load.
        2. **Missing tool-call results**: AgentCore's replayed history includes assistant messages
           with tool calls, but omits the corresponding results. CopilotKit needs those to reconcile
           its message state, so the runner synthesises empty results for each past tool call.

        Create the runner file alongside your API route:

        ```typescript title="app/api/copilotkit/agent-core-runner.ts"
        import {
          EventType,
          type BaseEvent,
          type Message,
          type MessagesSnapshotEvent,
          type ToolCall,
          type ToolCallResultEvent,
        } from "@ag-ui/client";
        import { InMemoryAgentRunner } from "@copilotkit/runtime/v2";
        import { concatMap, of } from "rxjs";
        import { randomUUID } from "node:crypto";

        export class AgentCoreRunner extends InMemoryAgentRunner {
          private readonly knownThreadIds = new Set<string>();

          override run(request: Parameters<InMemoryAgentRunner["run"]>[0]) {
            if (request.threadId) this.knownThreadIds.add(request.threadId);
            return super.run(request);
          }

          override connect(request: Parameters<InMemoryAgentRunner["connect"]>[0]) {
            if (!request.threadId || !this.knownThreadIds.has(request.threadId)) {
              const threadId = request.threadId ?? randomUUID();
              const runId = randomUUID();
              return of<BaseEvent>(
                { type: EventType.RUN_STARTED, threadId, runId },
                { type: EventType.MESSAGES_SNAPSHOT, messages: [] },
                { type: EventType.RUN_FINISHED, threadId, runId },
              );
            }

            return super.connect(request).pipe(
              concatMap((event: BaseEvent) => {
                if (event.type !== EventType.MESSAGES_SNAPSHOT) return of(event);
                const snapshot = event as MessagesSnapshotEvent;
                const replayedResults: ToolCallResultEvent[] = snapshot.messages.flatMap(
                  (message: Message) => {
                    if (message.role !== "assistant" || !message.toolCalls?.length) return [];
                    return message.toolCalls.map<ToolCallResultEvent>((toolCall: ToolCall) => ({
                      type: EventType.TOOL_CALL_RESULT,
                      toolCallId: toolCall.id,
                      messageId: `${toolCall.id}-result`,
                      content: "",
                      role: "tool",
                    }));
                  },
                );
                return of<BaseEvent>(...replayedResults, snapshot);
              }),
            );
          }
        }
        ```
      </Step>

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

      </Step>

      <Step>
        ### Add the chat interface [#add-the-chat-interface]

      </Step>

      <Step>
        ### 🎉 Run it [#-run-it]

        Point the CopilotKit Runtime server at the AgentCore runtime you deployed via AWS's
        [Deploy an AG-UI agent to AgentCore Runtime](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-agui.html)
        guide. Configure its environment:

        ```bash title=".env"
        AGENTCORE_ENDPOINT_URL=https://bedrock-agentcore.{region}.amazonaws.com/runtimes/{encoded-arn}/invocations
        AGENTCORE_ACCESS_TOKEN=<your-bearer-token>
        ```

        Start the runtime and your frontend application using their normal
        development commands. The frontend calls CopilotKit Runtime; the runtime
        forwards each request to the AgentCore invocation URL using the
        server-held token.

      </Step>
    </TailoredContentOption>
  </TailoredContent>
</Steps>

## Troubleshooting [#troubleshooting]

### HTTP 401: `Missing Authentication Token` [#http-401-missing-authentication-token]

```
Agent execution failed: Error: HTTP 401:
{"jsonrpc":"2.0","error":{"code":-32001,"message":"Missing Authentication Token"},"id":"null"}
```

`Missing Authentication Token` is AWS's own error, not a CopilotKit or agent error. AWS returns it
when a request reaches an AgentCore or API Gateway endpoint with no credentials, or when the request
path matches no deployed route. Check the following, in order:

- **The runtime is actually sending a token.** Set `AGENTCORE_ACCESS_TOKEN` in the environment of the
  CopilotKit Runtime **server**, not the frontend. If the variable is unset, the `Authorization` header
  interpolates to `Bearer undefined`, which AWS rejects exactly like a missing header.
- **The token has not expired.** Cognito access tokens are short-lived. Mint a fresh one and retry
  before you debug anything else.
- **`AGENTCORE_ENDPOINT_URL` is the full invocation URL**, ending in `/invocations`, with the agent
  ARN URL-encoded:
  `https://bedrock-agentcore.{region}.amazonaws.com/runtimes/{encoded-arn}/invocations`. A URL that
  stops short of `/invocations` matches no route, and AWS reports that as
  `Missing Authentication Token` rather than as a 404.
- **The browser is not calling AgentCore directly.** AgentCore requires SigV4 or OAuth2 signing,
  which a browser cannot perform. Point the frontend at your CopilotKit Runtime endpoint and let the
  runtime make the AgentCore call server-side.

<Callout type="warn" title="This error does not apply to the local quickstart">
  The framework quickstarts run the agent locally on `http://localhost:8000`, and a local agent
  server never returns `Missing Authentication Token`. If you see this error, the runtime is pointed
  at a deployed AWS endpoint.
</Callout>
