# A2A

> Bring your A2A agents to your users through AG-UI and CopilotKit.

## What is the A2A Protocol? [#what-is-the-a2a-protocol]

You have agents that talk over [A2A](https://a2a-protocol.org/latest/), the Agent2Agent protocol, and you want users to reach them from your app's chat.

Your A2A agents need no changes. An AG-UI orchestrator agent, wrapped in the A2A middleware, sends messages to them, and CopilotKit talks to the orchestrator.

<Image
  src="/images/any-agentic-backend-light.png"
  alt="CopilotKit with Agentic Protocols"
  width={4096}
  height={2304}
  className="block dark:hidden w-full mx-auto"
/>
<Image
  src="/images/any-agentic-backend-dark.png"
  alt="CopilotKit with Agentic Protocols"
  width={4096}
  height={2304}
  className="hidden dark:block w-full mx-auto"
/>
<div className="text-center text-sm text-muted-foreground mt-2 mb-8 w-3/5 mx-auto">
  A2A is one of three prominent [agentic protocols](/agentic-protocols)
  CopilotKit supports to connect agents to user-facing frontends
</div>

## How CopilotKit uses A2A agents [#how-copilotkit-uses-a2a-agents]

CopilotKit uses a middleware to expose A2A agents to an AG-UI orchestrator agent. This lets you expose your A2A agents to your users through the AG-UI protocol.

- **Flexibility and Interoperability**: By making a2a agents available over the AG-UI standard, any A2A agent can work with CopilotKit components.
- **Unified Communication**: While A2A agents are enabled to communicate with each other over the A2A protocol, AG-UI adds the missing tooling to expose them cleanly to the front end.

To learn more, check out the [A2A](https://a2a-protocol.org/latest/) website.

## How to use A2A agents with CopilotKit [#how-to-use-a2a-agents-with-copilotkit]

To use A2A agents with CopilotKit, you need to first install the CopilotKit middleware.

<Steps>
  <Step>
    ### Run and Connect Your Agent to CopilotKit [#run-and-connect-your-agent-to-copilotkit]

    You'll need to run your agent and connect it to CopilotKit before proceeding.

    If you already have an AG-UI agent to act as the orchestrator, go to the next step.

    #### I want to start from scratch [#i-want-to-start-from-scratch]

    Run the following command to create a brand new project with a pre-configured AG-UI agent and some A2A agents:

    ```bash
    npx copilotkit@latest create -f a2a
    ```

    This will create a new project with a pre-configured ADK AG-UI agent, but you can use any AG-UI agent you want.

  </Step>

  <Step>
    ### Install the A2A middleware [#install-the-a2a-middleware]

    This is already installed for you in the project, but if you're adding the middleware to an existing agent, you can install it with the following command:

    ```bash
    npm install @ag-ui/a2a-middleware@0.0.2
    ```

    This version speaks the A2A protocol before v1.0, so your A2A agents must use a pre-1.0 A2A SDK.

  </Step>

  <Step>
    ### Configure the A2A middleware [#configure-the-a2a-middleware]
    ```tsx title="app/api/copilotkit/[[...slug]]/route.ts" doctest="component"
    import {
      CopilotRuntime,
      createCopilotRuntimeHandler,
      InMemoryAgentRunner,
    } from "@copilotkit/runtime/v2";
    import { HttpAgent } from "@ag-ui/client";
    import { A2AMiddlewareAgent } from "@ag-ui/a2a-middleware";

    // These first two are the urls to the a2a agents
    const researchAgentUrl = process.env.RESEARCH_AGENT_URL || "http://localhost:9001";
    const analysisAgentUrl = process.env.ANALYSIS_AGENT_URL || "http://localhost:9002";

    // And this is the url to the orchestrator agent that will be wrapped in the middleware
    const orchestratorUrl = process.env.ORCHESTRATOR_URL || "http://localhost:9000";

    // the orchestrator agent we pass to the middleware needs to be an instance of a derivative of an ag-ui `AbstractAgent`
    // In this case, we have access to the agent via url, so we can gain an instance using the `HttpAgent` class
    const orchestrationAgent = new HttpAgent({
      url: orchestratorUrl,
    });

    // A2A Middleware: Wraps orchestrator and injects send_message_to_a2a_agent tool
    // This allows orchestrator to communicate with A2A agents transparently
    const a2aMiddlewareAgent = new A2AMiddlewareAgent({
      description:
        "Research assistant with 2 specialized agents: Research (LangGraph) and Analysis (ADK)",
      // We pass the urls to the a2a agents, the middleware will handle the connections
      agentUrls: [
        researchAgentUrl,
        analysisAgentUrl,
      ],
      // Pass the agent instance
      orchestrationAgent,
      // These are domain specific instructions for the agent. They will be added to the generic instructions on how to
      // connect to a2a agents that will be automatically generated by the middleware
      instructions: `
        You are a research assistant that orchestrates between 2 specialized agents.

        AVAILABLE AGENTS:

        - Research Agent (LangGraph): Gathers and summarizes information about a topic
        - Analysis Agent (ADK): Analyzes research findings and provides insights

        WORKFLOW STRATEGY (SEQUENTIAL - ONE AT A TIME):

        When the user asks to research a topic:

        1. Research Agent - First, gather information about the topic
          - Pass: The user's research query or topic
          - The agent will return structured JSON with research findings

        2. Analysis Agent - Then, analyze the research results
          - Pass: The research results from step 1
          - The agent will return structured JSON with analysis and insights

        3. Present the complete research and analysis to the user

        CRITICAL RULES:
        - Call agents ONE AT A TIME, wait for results before making next call
        - Pass information from earlier agents to later agents
        - Synthesize all gathered information in final response
      `,
    });

    // CopilotKit runtime connects frontend to agent system
    const runtime = new CopilotRuntime({
      agents: {
        a2a_chat: a2aMiddlewareAgent, // Use this same id in the frontend.
      },
      runner: new InMemoryAgentRunner(),
    });

    // Standard Next.js App Router handler that hands requests to the runtime.

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

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

  </Step>

  <Step>
    ### Add a `useFrontendTool` to your Frontend [#add-a-usefrontendtool-to-your-frontend]
    Inside the chat component, we'll display the messages between the orchestrator and the a2a agents using the `useFrontendTool` hook.
    The tool the middleware provides for communication is called `send_message_to_a2a_agent`.

    ```tsx title="components/chat.tsx"
    import { useFrontendTool } from "@copilotkit/react-core/v2";
    import { z } from "zod";
    import { MessageToA2A } from "./a2a/MessageToA2A";
    import { MessageFromA2A } from "./a2a/MessageFromA2A";

    function YourMainContent() {
      // ...

      useFrontendTool({
        name: "send_message_to_a2a_agent",
        description: "Sends a message to an A2A agent",
        available: true,
        parameters: z.object({
          agentName: z
            .string()
            .describe("The name of the A2A agent to send the message to"),
          task: z.string().describe("The message to send to the A2A agent"),
        }),
        render: (actionRenderProps) => {
          return (
            <>
              <MessageToA2A {...actionRenderProps} />
              <MessageFromA2A {...actionRenderProps} />
            </>
          );
        },
      });


      // ...
    }
    ```

    Both renderers use two small helpers. Save them next to the renderers. The starter's
    [`agent-styles.ts`](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/a2a-middleware/components/a2a/agent-styles.ts)
    also gives each agent its own colors.

    ```ts title="components/a2a/agent-styles.ts"
    export function getAgentStyle(_agentName: string) {
      return {
        bgColor: "bg-gray-100",
        textColor: "text-gray-700",
        borderColor: "border-gray-300",
        icon: "🤖",
        framework: "",
      };
    }

    export function truncateTask(text: string, maxLength: number = 50): string {
      if (text.length <= maxLength) return text;
      return text.substring(0, maxLength) + "...";
    }
    ```

    Now we define the rendering for a message sent from the orchestrator to the A2A agents. The renderer handles each status:

    - `inProgress`: the arguments are still streaming. Render nothing.
    - `executing`: the orchestrator sent the message and waits for an answer. Render the message.
    - `complete`: the A2A agent answered. Render the message.

    ```tsx title="components/a2a/MessageToA2A.tsx"
    import { getAgentStyle, truncateTask } from "./agent-styles";

    type MessageActionRenderProps = {
      status: string;
      args: {
        agentName?: string;
        task?: string;
      };
    };

    export const MessageToA2A: React.FC<MessageActionRenderProps> = ({ status, args }) => {
      switch (status) {
        case "executing":
        case "complete":
          break;
        default:
          return null;
      }

      if (!args.agentName || !args.task) {
        return null;
      }

      const agentStyle = getAgentStyle(args.agentName);

      return (
        <div className="bg-green-50 border border-green-200 rounded-lg px-4 py-3 my-2 a2a-message-enter">
          <div className="flex items-start gap-3">
            <div className="flex items-center gap-2 flex-shrink-0">
              <div className="flex flex-col items-center">
                <span className="px-3 py-1 rounded-full text-xs font-semibold bg-gray-700 text-white">
                  Orchestrator
                </span>
                <span className="text-[9px] text-gray-500 mt-0.5">ADK</span>
              </div>

              <span className="text-gray-400 text-sm">→</span>

              <div className="flex flex-col items-center">
                <span
                  className={`px-3 py-1 rounded-full text-xs font-semibold border-2 ${agentStyle.bgColor} ${agentStyle.textColor} ${agentStyle.borderColor} flex items-center gap-1`}
                >
                  <span>{agentStyle.icon}</span>
                  <span>{args.agentName}</span>
                </span>
                {agentStyle.framework && (
                  <span className="text-[9px] text-gray-500 mt-0.5">{agentStyle.framework}</span>
                )}
              </div>
            </div>

            <span className="text-gray-700 text-sm flex-1 min-w-0 break-words" title={args.task}>
              {truncateTask(args.task)}
            </span>
          </div>
        </div>
      );
    };
    ```

    Last, we define the rendering for a response from the A2A agent to the orchestrator. The renderer handles each status:

    - `inProgress`: the message is not sent yet. Render nothing.
    - `executing`: the orchestrator waits for an answer. Render nothing, or a loading state.
    - `complete`: the A2A agent answered. Render the response.

    ```tsx title="components/a2a/MessageFromA2A.tsx"
    import { getAgentStyle } from "./agent-styles";

    type MessageActionRenderProps = {
      status: string;
      args: {
        agentName?: string;
      };
    };

    export const MessageFromA2A: React.FC<MessageActionRenderProps> = ({ status, args }) => {
      switch (status) {
        case "complete":
          break;
        default:
          return null;
      }

      if (!args.agentName) {
        return null;
      }

      const agentStyle = getAgentStyle(args.agentName);

      return (
        <div className="my-2">
          <div className="bg-blue-50 border border-blue-200 rounded-lg px-4 py-3">
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2 min-w-[200px] flex-shrink-0">
                <div className="flex flex-col items-center">
                  <span
                    className={`px-3 py-1 rounded-full text-xs font-semibold border-2 ${agentStyle.bgColor} ${agentStyle.textColor} ${agentStyle.borderColor} flex items-center gap-1`}
                  >
                    <span>{agentStyle.icon}</span>
                    <span>{args.agentName}</span>
                  </span>
                  {agentStyle.framework && (
                    <span className="text-[9px] text-gray-500 mt-0.5">{agentStyle.framework}</span>
                  )}
                </div>

                <span className="text-gray-400 text-sm">→</span>

                <div className="flex flex-col items-center">
                  <span className="px-3 py-1 rounded-full text-xs font-semibold bg-gray-700 text-white">
                    Orchestrator
                  </span>
                  <span className="text-[9px] text-gray-500 mt-0.5">ADK</span>
                </div>
              </div>

              <span className="text-xs text-gray-600">✓ Response received</span>
            </div>
          </div>
        </div>
      );
    };
    ```

  </Step>

  <Step>
    ### Give it a try [#give-it-a-try]
    Try asking your agent to research a topic, like "Please research quantum computing". You'll see that it will send messages to the research agent and the analysis agent.
    Then, it will present the complete research and analysis to the user.
  </Step>
</Steps>
