The Agent-to-Agent (A2A) protocol is an open messaging standard
that enables autonomous AI agents to communicate and coordinate tasks
across disparate systems.

In CX Agent Studio, A2A Protocol tools allow your agent application
to delegate tasks to external remote agents,
or allow external applications and orchestrators
to invoke your CX Agent Studio agents using standardized messaging.

## How A2A works

The A2A protocol in CX Agent Studio supports two execution models between a primary
agent and a remote agent:

- **Delegation model**: The primary agent retains session control, invokes the remote agent as a tool, and summarizes the returned result.
- **Pass-through model** (Preview): The primary application transfers conversation control directly to a remote A2A agent (`Agent.RemoteA2aAgent`) and returns its responses without an intermediate model call. For configuration steps, see [Call a remote A2A agent in pass-through mode](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/tool/a2a-protocol.md.txt#pass-through-mode).

### Delegation model

In the delegation model,
the initiating CX Agent Studio agent acts as the primary orchestrator
and retains overall session control:

- **Session ownership:** The primary agent maintains the user conversation session. When a specialized sub-task is required, the primary agent invokes the remote agent as a tool.
- **Control flow:** The remote agent processes the request and returns structured response data. Control immediately returns to the primary agent, which summarizes or incorporates the results for the end user.
- **Context transfer:** The primary agent transmits only the parameters and conversational context necessary for the delegated task.

![A2A delegation sequence diagram](https://docs.cloud.google.com/static/gemini-enterprise-cx/cx-agent-studio/images/a2a-delegation-flow.png)

### Text-based communication

All inter-agent communication in the A2A protocol is text-based:

- If an end user interacts with a primary agent over a voice channel (such as telephony or WebRTC), the speech is first converted to text.
- The primary agent sends the text transcript and parameters to the remote sub-agent in an HTTP request payload.
- Raw audio streams and embeddings are not transmitted across the A2A network interface.

### Modality support

Modality (text versus voice) support for the A2A protocol depends on the
direction of communication:

- **Remote agent to CX Agent Studio:** Supports the text modality only.
- **CX Agent Studio to remote agent:** Modality-agnostic for CX Agent Studio, meaning the CX Agent Studio session can use any supported modality such as voice or text, but the remote agent only receives text.

## Billing

If both the primary and remote sessions are in
CX Agent Studio and are in the same project, you will be billed for 1 session.

Otherwise, for primary and remote sessions across multiple projects
or third-party systems,
you will be billed for 2 sessions.

## Authentication and access control

Authentication requirements depend on the direction of communication
and the target service.

| Direction | Target destination | Authentication mechanism | Required IAM role | Description |
|---|---|---|---|---|
| **Inbound** (External to CX Agent Studio) | CX Agent Studio agent application | OAuth 2.0 access token | `roles/ces.client` | Required for external callers to invoke the CX Agent Studio inbound endpoint. |
| **Outbound** (CX Agent Studio to CX Agent Studio) | CX Agent Studio agent in another project | Service agent | `roles/ces.client` | Granted to the calling project's service agent on the target project. |
| **Outbound** (CX Agent Studio to Cloud Run) | Cloud Run service | Service agent ID token | `roles/run.invoker` | Granted to the calling project's service agent on the Cloud Run service. |
| **Outbound** (CX Agent Studio to Vertex AI) | Vertex AI Agent Engine | Service agent OAuth | `roles/aiplatform.user` | Granted to the calling project's service agent on the target project. |
| **Outbound** (CX Agent Studio to third-party) | External endpoint (such as ServiceNow or Salesforce) | API Key or OAuth | Managed using Secret Manager | Stored credentials injected during tool execution. |

### Service agent identity

Outbound requests from CX Agent Studio use the CX Agent Studio service agent:

    service-PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com

Replace `PROJECT_NUMBER` with your Google Cloud project number.

### Inbound authentication

When an external application, custom agent, or orchestrator calls into CX Agent Studio,
it must pass a valid Google-issued OAuth 2.0 access token in the `Authorization` header:

- **Testing:** Generate a temporary access token for your active account:

  ```bash
  gcloud auth print-access-token
  ```
- **Programmatic clients:** Use Application Default Credentials (ADC):

  ```bash
  gcloud auth application-default print-access-token
  ```
- **Production:** Use a dedicated Google service account with the
  `roles/ces.client` (`Customer Engagement Suite Client`) role.

## Prerequisites

Before configuring A2A Protocol tools:

1. Enable the Gemini Enterprise for Customer Experience API (`ces.googleapis.com`) on your project:

   ```bash
   gcloud services enable ces.googleapis.com --project=PROJECT_ID
   ```
2. Ensure the calling principal or service account has been granted
   the `Customer Engagement Suite Client` role (`roles/ces.client`).

## Configure an A2A Protocol tool

To connect your primary agent to an external remote agent:

1. Open the [CX Agent Studio console](https://ces.cloud.google.com).
2. Select your project and open your agent application.
3. In the agent builder, click the **Tools** icon.
4. Click the **+** (Add) button to create a new tool.
5. Select the **A2A Protocol** tool card.
6. Configure your agent card using either the **UI Form** or the **JSON** editor.
7. In the **URL** field, enter the remote agent's base endpoint URL (for example, `https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID` or your Cloud Run service URL). Don't append `/message:send` to the URL; CX Agent Studio automatically appends `/message:send` at runtime.
8. Select the appropriate authentication type for the endpoint.
9. Click **Create**.

### Agent card example

The following sample JSON defines an agent card for a remote weather agent:

```json
{
  "name": "weather_agent",
  "description": "Agent capable of querying weather conditions and local time for given locations.",
  "version": "0.1.0",
  "supportedInterfaces": [
    {
      "url": "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID",
      "protocolBinding": "HTTP+JSON",
      "protocolVersion": "1.0"
    }
  ],
  "skills": [
    {
      "id": "get_weather",
      "name": "get_weather",
      "description": "Retrieves weather conditions for a specified location.",
      "tags": [
        "weather",
        "forecast"
      ],
      "examples": [],
      "inputModes": [],
      "outputModes": []
    },
    {
      "id": "get_current_time",
      "name": "get_current_time",
      "description": "Retrieves current local time for a specified city or timezone.",
      "tags": [
        "time",
        "clock"
      ],
      "examples": [],
      "inputModes": [],
      "outputModes": []
    }
  ]
}
```

### Add routing instructions

Instruct your primary agent when to delegate to the A2A tool.
For example:

    If the user asks for weather information or local time, use {@TOOL: weather_agent}.
    Pass the city or location specified by the user.
    If the tool returns an error, inform the user that weather details are temporarily unavailable.

## Call a remote A2A agent in pass-through mode

> [!WARNING]
>
> **Preview**
>
>
> This feature is
>
> subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the
> [Service Specific
> Terms](https://docs.cloud.google.com/terms/service-terms#1).
>
> Pre-GA features are available "as is" and might have limited support.
>
> For more information, see the
> [launch stage descriptions](https://cloud.google.com/products/#product-launch-stages).

By default, an A2A Protocol tool (`RemoteAgentTool`) invokes a remote agent as
an LLM function call: your primary CX Agent Studio agent retains session control,
sends a unary `SendMessage` request, and uses its own model to summarize the
tool result.

When your remote chat agent---such as an agent built with the
[Agent Development Kit (ADK)](https://docs.cloud.google.com/agent-builder/agent-development-kit/overview)---manages
its own conversation wording, configure an
[`Agent.RemoteA2aAgent`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.agents.md.txt#Agent.Agent.RemoteA2aAgent)
resource to run in pass-through mode. While a `RemoteA2aAgent` is active,
CX Agent Studio forwards each user message directly to the remote A2A agent and
returns its response directly to the caller without an intermediate CX Agent Studio
model call. This reduces turn latency and preserves the remote agent's exact
response wording.

### Pass-through topologies

You can attach a `RemoteA2aAgent` in either of the following topologies:

- **Full-session pass-through (`rootAgent`)** : Set the `RemoteA2aAgent` as your agent application's `rootAgent`, or specify it in `SessionConfig.entryAgent`, to route all chat turns directly to the remote agent from the first turn while CX Agent Studio handles channels, authentication, DLP redaction, and conversation logging.
- **Sub-agent transfer (`childAgents`)** : Add the `RemoteA2aAgent` to a parent agent's `childAgents` list and transfer to it using `{@AGENT: ...}` [instructions](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/instruction.md.txt) or a `PARENT_TO_CHILD` `transferRules` [handoff rule](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/handoff.md.txt). Subsequent user turns route directly to the remote agent until it returns control to the parent agent.

### Configure a remote A2A agent

Because `agent_type` is immutable on an existing `Agent` resource, you can't
convert an `LlmAgent` in place. Instead, create a `RemoteA2aAgent` resource
using the REST API, and then attach it as `rootAgent` or in `childAgents`:

1. Create the `Agent` resource with `remoteA2aAgent`:

   ```bash
   curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "X-Goog-User-Project: PROJECT_ID" \
     -H "Content-Type: application/json" \
     -d '{
       "displayName": "adk_chat_agent",
       "description": "Handles customer support chat conversations using ADK.",
       "remoteA2aAgent": {
         "a2aConfig": {
           "streamingEnabled": true,
           "apiAuthentication": {
             "serviceAgentIdTokenAuthConfig": {}
           },
           "inputVariableMapping": {
             "customer_tier": "session_customer_tier"
           },
           "outputVariableMapping": {
             "ticket_id": "session_ticket_id"
           },
           "agentCard": {
             "name": "adk_chat_agent",
             "description": "Customer support ADK chat agent.",
             "version": "1.0.0",
             "supportedInterfaces": [
               {
                 "url": "REMOTE_AGENT_URL",
                 "protocolBinding": "JSONRPC",
                 "protocolVersion": "1.0"
               }
             ],
             "skills": [
               {
                 "id": "customer_support",
                 "name": "Customer Support",
                 "description": "Answers account and billing questions.",
                 "tags": ["support", "chat"]
               }
             ]
           }
         }
       }
     }' \
     "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/agents?agentId=adk_chat_agent"
   ```
2. Attach the `RemoteA2aAgent` as your application's `rootAgent` for
   full-session pass-through:

   ```bash
   curl -X PATCH \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "X-Goog-User-Project: PROJECT_ID" \
     -H "Content-Type: application/json" \
     -d '{
       "rootAgent": "projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/agents/adk_chat_agent"
     }' \
     "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID?updateMask=rootAgent"
   ```

   Alternatively, attach the `RemoteA2aAgent` to a parent agent's `childAgents`
   list for sub-agent pass-through:

   ```bash
   curl -X PATCH \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "X-Goog-User-Project: PROJECT_ID" \
     -H "Content-Type: application/json" \
     -d '{
       "childAgents": [
         "projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/agents/adk_chat_agent"
       ]
     }' \
     "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/agents/PARENT_AGENT_ID?updateMask=childAgents"
   ```

Replace the following:

- `PROJECT_ID`: Your Google Cloud project ID.
- `REMOTE_AGENT_URL`: The base HTTPS URL of your remote A2A agent, such as `https://my-adk-agent-12345-uc.a.run.app`.
- `LOCATION`: The multi-region hosting your CX Agent Studio agent application, such as `us` or `eu`.
- `APP_ID`: The ID of your CX Agent Studio agent application.
- `PARENT_AGENT_ID`: The ID of the parent CX Agent Studio agent when attaching a sub-agent.

> [!NOTE]
> **Note:** After you create a `RemoteA2aAgent` resource, the node appears in the [CX Agent Studio console](https://ces.cloud.google.com) graph, where you can edit its agent card, `contextId`, and authentication by clicking **Modify agent card** . Configure `rootAgent`, `streamingEnabled`, and variable mappings using the REST API or [application export and import](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/export.md.txt).

### Return control to a parent agent

When a `RemoteA2aAgent` runs as a sub-agent, `CHILD_TO_PARENT` handoff rules on
native `LlmAgent` nodes aren't evaluated during `RemoteA2aAgent` turns. To
return control to the parent CX Agent Studio agent within the same turn, emit a
`Part` containing `gecx_a2a_agent_signal.handoff` in the remote agent's
`Message` or `TaskStatus` update:

```json
{
  "data": {
    "gecx_a2a_agent_signal": {
      "handoff": {}
    }
  },
  "mediaType": "application/json"
}
```

CX Agent Studio strips the signal part before returning response text to the user
and invokes the parent agent in the same turn. In ADK `A2aAgentExecutor`, you
can attach this `Part` to `final_event.status.message` inside an
`ExecuteInterceptor` `after_agent` hook when your agent triggers a return
handoff.

### Pass-through behaviors and limitations

Keep the following behaviors and limitations in mind when using
`RemoteA2aAgent`:

- **Stateful `contextId` and delta history** : `RemoteA2aAgent` caches the remote agent's `contextId` across turns automatically unless you override `a2aConfig.contextId`---for example, `$context.variables.order_session_id`---or the remote agent sets `session_metadata.closed` to `true`. Each outbound request includes only the delta conversation history since `RemoteA2aAgent` last responded in `message.metadata["gecx_a2a_agent_context"]`.
- **Chat turn APIs only** : `RemoteA2aAgent` supports [`runSession`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.sessions/runSession.md.txt) and [`streamRunSession`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.sessions/streamRunSession.md.txt). Bidirectional voice streaming with [`BidiRunSession`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rpc/google.cloud.ces.v1.md.txt#google.cloud.ces.v1.SessionService.BidiRunSession) isn't supported on `RemoteA2aAgent`; use `RemoteAgentTool` for voice orchestrators.
- **Inline `agentCard` and bypassed LLM fields** : Provide an inline `agentCard` with `supportedInterfaces`; `agentRegistry` resolution on `RemoteA2aConfig` isn't supported. Agent-level `instruction`, `modelSettings`, `tools`, `guardrails`, and model or tool `callbacks` on the `RemoteA2aAgent` node are bypassed.

## Stream responses from a remote A2A agent

Setting `"streamingEnabled": true` on
[`RemoteA2aConfig`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.agents.md.txt#Agent.RemoteA2aConfig)
instructs CX Agent Studio to open a Server-Sent Events (SSE) stream to the remote
A2A agent and forward incremental response chunks in real time. Outbound
streaming is supported only on `Agent.RemoteA2aAgent` (Preview);
`RemoteAgentTool` executes unary `SendMessage` calls.

### Transport and endpoint mapping

Specify only the base HTTPS URL in `agentCard.supportedInterfaces[].url`, and
don't append `/message:stream`. CX Agent Studio resolves the streaming endpoint or
JSON-RPC method from `protocolBinding` and `protocolVersion`, as shown in the
following table.

| Protocol binding | Protocol version | `streamingEnabled: false` | `streamingEnabled: true` (SSE) |
|---|---|---|---|
| `HTTP+JSON` | `1.0` | `POST BASE_URL/message:send` | `POST BASE_URL/message:stream` |
| `HTTP+JSON` | `0.3` | `POST BASE_URL/v1/message:send` | `POST BASE_URL/v1/message:stream` |
| `JSONRPC` | `1.0` | `"method": "SendMessage"` | `"method": "SendStreamingMessage"` |
| `JSONRPC` | `0.3` | `"method": "message/send"` | `"method": "message/stream"` |
| `GRPC` | `1.0` or `0.3` | Unary `A2AService/SendMessage` | Falls back to unary `SendMessage` |

### Receive streamed chunks with `streamRunSession`

To receive incremental SSE chunks from CX Agent Studio, call
[`streamRunSession`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.sessions/streamRunSession.md.txt)
with `?alt=sse`, and set `"enableTextStreaming": true` if native `LlmAgent`
nodes share the session. Concatenate consecutive `outputs[].text` chunks until
the final event with `"turnCompleted": true`. Callers using unary `runSession`
remain compatible and receive a buffered response.

Send a streaming session request using `curl`:

```bash
curl -N -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "X-Goog-User-Project: PROJECT_ID" \
  -H "Accept: text/event-stream" \
  -H "Content-Type: application/json" \
  -d '{
    "config": {
      "session": "projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/sessions/SESSION_ID",
      "enableTextStreaming": true
    },
    "inputs": [
      {
        "text": "Explain my mobile plan upgrade options."
      }
    ]
  }' \
  "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/sessions/SESSION_ID:streamRunSession?alt=sse"
```

Replace `SESSION_ID` with a unique conversation session
identifier, along with `PROJECT_ID`,
`LOCATION`, and `APP_ID`.

### Configure an ADK remote agent for token streaming

When exposing a Python
[ADK](https://docs.cloud.google.com/agent-builder/agent-development-kit/overview) agent using `to_a2a()`:

1. Set `"protocolBinding": "JSONRPC"` in your CX Agent Studio `AgentCard` because `to_a2a()` mounts JSON-RPC routes by default. Set `"protocolVersion": "1.0"` when using `a2a-sdk` version 1.0 or later, or `"0.3"` for `a2a-sdk` 0.3.x. Use `"HTTP+JSON"` if mounting REST routes, and set `capabilities.streaming=True` if providing a custom `AgentCard`.
2. Enable `StreamingMode.SSE` on `RunConfig`, pass `force_new_version=True` to
   `A2aAgentExecutor`, and attach an `after_event` `ExecuteInterceptor` to drop
   ADK's final non-partial aggregated `TaskArtifactUpdateEvent` snapshot after
   `partial=True` token chunks have streamed, preventing duplicate text at the
   end of a turn:

   ```python
   from a2a.types import TaskArtifactUpdateEvent
   from google.adk.a2a.converters.request_converter import (
       convert_a2a_request_to_agent_run_request,
   )
   from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor
   from google.adk.a2a.executor.config import (
       A2aAgentExecutorConfig,
       ExecuteInterceptor,
   )
   from google.adk.a2a.utils.agent_to_a2a import to_a2a
   from google.adk.agents import LlmAgent
   from google.adk.agents.run_config import RunConfig, StreamingMode

   def create_streaming_executor(runner):
     streamed_ids: set[str] = set()

     def request_converter(req, part_converter):
       run_req = convert_a2a_request_to_agent_run_request(req, part_converter)
       run_req.run_config = run_req.run_config or RunConfig()
       run_req.run_config.streaming_mode = StreamingMode.SSE
       return run_req

     async def dedupe_final_snapshot(ctx, a2a_event, adk_event):
       if isinstance(a2a_event, TaskArtifactUpdateEvent):
         aid = a2a_event.artifact.artifact_id
         if adk_event.partial:
           streamed_ids.add(aid)
         elif aid in streamed_ids:
           streamed_ids.discard(aid)
           return None
       return a2a_event

     return A2aAgentExecutor(
         runner=runner,
         force_new_version=True,
         config=A2aAgentExecutorConfig(
             request_converter=request_converter,
             execute_interceptors=[
                 ExecuteInterceptor(after_event=dedupe_final_snapshot)
             ],
         ),
     )

   app = to_a2a(
       LlmAgent(
           name="support_agent",
           model="gemini-2.5-flash",
           instruction="Help the user.",
       ),
       host="0.0.0.0",
       port=8080,
       protocol="https",
       agent_executor_factory=create_streaming_executor,
   )
   ```

## Inbound messaging

External systems can send messages directly to a CX Agent Studio agent application
using the inbound A2A messaging endpoint.

> [!NOTE]
> **Note:** Remote agents built with the ADK can return either a normalized Task wrapper object (with artifacts) or direct Message payloads.

### Inbound endpoint URL

Send HTTP POST requests to the following endpoint:

    https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/message:send

Replace the following:

- `PROJECT_ID`: Your Google Cloud project ID.
- `LOCATION`: The region hosting your agent application (such as `us-central1`).
- `APP_ID`: The unique identifier of your CX Agent Studio agent application.

### Request payload schema

The JSON payload structure for sending an inbound message:

```json
{
  "message": {
    "messageId": "msg-MY_UNIQUE_MESSAGE_UUID",
    "role": "ROLE_USER",
    "content": [
      {
        "text": "Hello! I would like help checking my account balance."
      }
    ],
    "metadata": {
      "gecx_a2a_agent_context": "MY_SERIALIZED_AGENT_CONTEXT_STRING"
    }
  }
}
```

> [!NOTE]
> **Note:** In CX Agent Studio, the message payload uses the `content` field to contain message text parts.

### Example request using curl

You can test inbound messaging using `curl`:

```bash
curl -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "X-Goog-User-Project: PROJECT_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "messageId": "msg-'"$(uuidgen)"'",
      "role": "ROLE_USER",
      "content": [
        {
          "text": "Hello!"
        }
      ]
    }
  }' \
  "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/apps/APP_ID/message:send"
```

## Context and state management

The A2A protocol uses the `AgentContext` message
to manage variables and session states between agents.
Context is passed in the metadata of the `SendMessageRequest`
using the `gecx_a2a_agent_context` key.

### Variable mapping

When delegating a task,
you can map variables between the primary and remote agents:

- **Outbound mapping:** `RemoteAgentTool.input_variable_mapping` computes the `AgentContext.variables` sent to the remote agent.
- **Inbound mapping:** `RemoteAgentTool.output_variable_mapping` updates the primary agent's variables when the remote agent responds.

For inbound requests (external client to CX Agent Studio),
the application deserializes the `gecx_a2a_agent_context` metadata
and writes the `AgentContext.variables` directly into the current session.
The updated variables are written back to `AgentContext.variables`
when responding to the client.

### Session closure

The primary agent monitors `AgentContext.session_metadata.closed`
to determine when a remote session ends:

- Outbound requests always set `closed` to `false`. If the remote agent's response sets `closed` to `true`, the A2A connection is terminated.
- For inbound responses back to the client, the CX Agent Studio app sets `closed` to `true` if the session has ended.

### Stateful mode

Remote sessions with CXAS apps are always stateful. Primary and remote CXAS sessions will share the same session ID and remote sessions will keep the conversation history between the primary and the remote agents.

For remote sessions with third-party systems, the remote sessions will be stateless by default and remote agent will receive each message from the primary agent as a new session (aka a new context ID).

You can enable the `RemoteAgentTool.stateful_agent` field
to automatically cache and reuse the first context ID
returned by the remote agent.

This cached context ID is used for the remainder of the session
unless the remote agent responds with
`AgentContext.session_metadata.closed == true`.
If the session is closed,
the cache is reset and a new context ID will be cached on the next tool call.

## Deploy a remote sub-agent

You can deploy custom remote agents on Google Cloud services
to act as sub-agents for CX Agent Studio.

### Deploy to Cloud Run

To host an agent built with the
[Agent Development Kit (ADK)](https://docs.cloud.google.com/agent-builder/agent-development-kit/overview) on Cloud Run:

1. Create a `Dockerfile` in your agent project directory:

   ```docker
   FROM python:3.11-slim

   WORKDIR /app

   COPY pyproject.toml requirements.txt ./
   RUN pip install --no-cache-dir -r requirements.txt
   RUN pip install --no-cache-dir "google-adk[a2a]==1.32.0" "a2a-sdk[all]==0.3.26"

   COPY . .

   ENV PORT=8080
   ENV PYTHONUNBUFFERED=1

   EXPOSE 8080

   CMD ["python", "-m", "app.a2a_rest_server"]
   ```
2. Deploy the container to Cloud Run:

   ```bash
   gcloud run deploy my-adk-agent \
     --project=PROJECT_ID \
     --region=us-central1 \
     --source=. \
     --memory=4Gi \
     --no-cpu-throttling
   ```
3. Grant the `roles/run.invoker` role on the Cloud Run service
   to your calling project's CX Agent Studio service agent.

4. Follow the steps in [Configure an A2A Protocol tool](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/tool/a2a-protocol.md.txt#configure-the-a2a-tool)
   to attach the Cloud Run service URL to CX Agent Studio.

### Deploy to Vertex AI Agent Engine

To deploy an ADK agent onto
[Vertex AI Agent Engine](https://docs.cloud.google.com/agent-builder/agent-engine/overview):

1. Define your dependencies in `requirements.txt`:

       a2a-sdk==0.3.26
       google-adk[a2a]>=1.15.0,<2.0.0

2. Deploy the engine using the Vertex AI SDK:

   ```python
   import os
   import sys
   from google.protobuf import json_format
   import vertexai
   from vertexai.agent_engines import _agent_engines

   sys.path.append("./")
   from app.agent_runtime_app import agent_runtime

   client = vertexai.Client(project="PROJECT_ID", location="us-central1")

   ops = agent_runtime.register_operations()
   class_methods_proto = _agent_engines._generate_class_methods_spec_or_raise(
       agent_engine=agent_runtime,
       operations=ops
   )
   class_methods_list = [
       json_format.MessageToDict(cm, preserving_proto_field_name=True)
       for cm in class_methods_proto
   ]

   agent_config = {
       "entrypoint_module": "app.agent_runtime_app",
       "entrypoint_object": "agent_runtime",
       "source_packages": ["app", "requirements.txt"],
       "requirements_file": "requirements.txt",
       "class_methods": class_methods_list,
       "agent_framework": "google-adk",
       "env_vars": {
           "GOOGLE_CLOUD_LOCATION": "us-central1",
       },
       "min_instances": 1,
       "max_instances": 10,
       "resource_limits": {"cpu": "4", "memory": "8Gi"},
   }

   engine = client.agent_engines.create(config=agent_config)
   print(f"Deployed Engine Resource Name: {engine.api_resource.name}")
   ```
3. Grant the `roles/aiplatform.user` role on the target project
   to your calling project's CX Agent Studio service agent.

4. Follow the steps in [Configure an A2A Protocol tool](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/tool/a2a-protocol.md.txt#configure-the-a2a-tool)
   to attach the Agent Engine endpoint to CX Agent Studio.

### Connect to third-party endpoints

CX Agent Studio can delegate tasks to external third-party endpoints,
such as ServiceNow or Salesforce.

When configuring the tool in the console:

1. Follow the steps in [Configure an A2A Protocol tool](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/tool/a2a-protocol.md.txt#configure-the-a2a-tool).
2. Select the authentication method required by the third-party endpoint (such as API key or OAuth).
3. Store credentials securely using Secret Manager.

## A2A Protocol tools compared to Agent as a tool

CX Agent Studio provides multiple methods for coordinating multi-agent workflows.

| Feature | Agent as a tool | A2A Protocol tool |
|---|---|---|
| **Scope** | Intra-application (agents within the same CX Agent Studio app). | Inter-application (external agents, remote services, or third-party platforms). |
| **Communication** | Direct in-memory / internal execution. | Network HTTP requests using the A2A messaging standard. |
| **Use cases** | Reusing internal sub-agents without handing off the session. | Calling custom ADK agents on Cloud Run, Vertex AI, or external APIs. |
| **Protocol** | Platform-internal tool execution. | Standardized A2A JSON payload over REST. |

## LLM tool execution

Under the hood, A2A protocol calls operate through standard LLM tool calling:

1. When an A2A tool is assigned to an agent, the tool description and skill definitions are provided to the model as function declarations.
2. When the model decides to delegate a sub-task, it generates a function call event.
3. The CX Agent Studio runtime intercepts the function call, translates the parameters into an A2A HTTP request, and sends it to the configured remote endpoint.
4. The response returned by the remote agent is passed back to the model to continue generating the conversation response.

To learn more about how agents are encapsulated as callable tools,
see the [ADK AgentTool implementation](https://github.com/google/adk-python/blob/main/src/google/adk/tools/agent_tool.py)
on GitHub.