Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions agentregistry/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
Agent Registry Python Samples

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (blocking): This file is named README.md, but it's written in reStructuredText syntax (.. _Google Cloud Agent Registry:, .. code-block:: bash, double backticks like AgentRegistry). On GitHub, .md files render as Markdown, so those directives and double backticks will show up as raw literal text. Could we convert this to GitHub-flavored Markdown (or rename to README.rst if that's the preferred convention in this repo)?

=============================

Code samples for `Google Cloud Agent Registry`_, using the Agent Development Kit (ADK) and Vertex AI Agent Engine.

.. _Google Cloud Agent Registry: https://cloud.google.com/agent-registry

Quick Start
-----------

1. Select or create a Google Cloud project.
2. Enable billing for your project.
3. Enable the Agent Registry API (`agentregistry.googleapis.com`) and Vertex AI API (`aiplatform.googleapis.com`).
4. Set up `Application Default Credentials`_.
5. Set the required environment variables and install dependencies:

.. code-block:: bash

export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="global"
cd adk
pip install -r requirements.txt

.. _Application Default Credentials: https://googleapis.dev/python/google-api-core/latest/auth.html

Samples
-------

* `adk/compose_multi_agent.py`: Initialize the ``AgentRegistry`` client and compose an ``LlmAgent`` orchestrator with a remote A2A agent and an MCP toolset.
* `adk/clone_remote_agent.py`: Fetch a remote A2A agent once and clone it across multiple orchestrator agents.
* `adk/discover_agents_and_toolsets.py`: Discover agents by skill tag and retrieve remote agents and MCP toolsets.
* `adk/deploy_agent_runtime.py`: Deploy an A2A agent to Vertex AI Agent Engine so it is automatically registered in Agent Registry.

Testing
-------

Tests require a Google Cloud project with ``agentregistry.googleapis.com`` enabled and the following environment variables set:

* ``GOOGLE_CLOUD_PROJECT``: Google Cloud project ID.
* ``GOOGLE_CLOUD_LOCATION``: Agent Registry location (defaults to ``global``).
* ``AGENTREGISTRY_TEST_AGENT_ID``: ID of a pre-registered A2A agent fixture.
* ``AGENTREGISTRY_TEST_MCP_SERVER_ID``: ID of a pre-registered MCP server fixture.
* ``AGENTREGISTRY_TEST_STAGING_BUCKET``: Cloud Storage bucket URI (``gs://...``) for the Agent Engine deployment test.
81 changes: 81 additions & 0 deletions agentregistry/adk/clone_remote_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from collections.abc import Iterator
import os

from google.adk.agents.llm_agent import LlmAgent
from google.adk.integrations.agent_registry import AgentRegistry
import google.auth
from google.auth.transport.requests import Request
import httpx


def clone_remote_agent(
agent_name: str = "projects/PROJECT_ID/locations/LOCATION/agents/AGENT_ID",
model: str = "gemini-2.5-flash",
) -> tuple[LlmAgent, LlmAgent]:
"""Fetches a remote A2A agent once and clones it across orchestrators."""
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

registry = AgentRegistry(
project_id=project_id,
location=location,
)

# [START agentregistry_adk_clone_remote_agent]
class GoogleAuth(httpx.Auth):
def __init__(self) -> None:
self.creds, _ = google.auth.default()

def auth_flow(self, request: httpx.Request) -> Iterator[httpx.Request]:
self.creds.before_request(
Request(),
request.method,
str(request.url),
request.headers,
)
yield request
Comment thread
fatoboist marked this conversation as resolved.
Resolved

httpx_client = httpx.AsyncClient(
auth=GoogleAuth(),
timeout=httpx.Timeout(60.0),
)

base_remote_agent = registry.get_remote_a2a_agent(
agent_name=agent_name,
httpx_client=httpx_client,
)
Comment on lines +55 to +63

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Since clone_remote_agent is a synchronous function, using httpx.AsyncClient is inappropriate and can lead to unclosed client warnings or event loop issues. Use the synchronous httpx.Client instead, and wrap it in a with statement to ensure connections are properly closed.

    with httpx.Client(
        auth=GoogleAuth(),
        timeout=httpx.Timeout(60.0),
    ) as httpx_client:
        base_remote_agent = registry.get_remote_a2a_agent(
            agent_name=agent_name,
            httpx_client=httpx_client,
        )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping httpx.AsyncClient without a with block here: AgentRegistry.get_remote_a2a_agent() expects httpx.AsyncClient | None and passes it to ADK's RemoteA2aAgent, which executes async HTTP calls when the returned LlmAgent is invoked. Using a synchronous httpx.Client would fail at runtime, and a with block inside clone_remote_agent() would close the client before the returned orchestrators run.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 from the docs side — get_remote_a2a_agent() requires httpx.AsyncClient and keeping it open for RemoteA2aAgent matches our documented behavior.


flight_orchestrator = LlmAgent(
model=model,
name="flight_orchestrator",
sub_agents=[base_remote_agent.clone()],
)

hotel_orchestrator = LlmAgent(
model=model,
name="hotel_orchestrator",
sub_agents=[base_remote_agent.clone()],
)
# [END agentregistry_adk_clone_remote_agent]
Comment on lines +41 to +76

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): Similar to the other samples, # [START agentregistry_adk_clone_remote_agent] repeats the GoogleAuth + httpx_client setup, while registry, agent_name, model, and the imports are outside the region tag. It would be more consistent if the region tag either includes the full function (with agent_name / model defaults visible) or stays focused on the get_remote_a2a_agent + .clone() block like resolve-endpoints-and-build-orchestrators.md.

return flight_orchestrator, hotel_orchestrator


if __name__ == "__main__":
clone_remote_agent()
36 changes: 36 additions & 0 deletions agentregistry/adk/clone_remote_agent_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import clone_remote_agent
import pytest


def test_clone_remote_agent(
monkeypatch: pytest.MonkeyPatch,
project_id: str,
location: str,
agent_id: str,
) -> None:
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)

flight_orchestrator, hotel_orchestrator = clone_remote_agent.clone_remote_agent(
agent_name=f"projects/{project_id}/locations/{location}/agents/{agent_id}",
)

assert flight_orchestrator.name == "flight_orchestrator"
assert hotel_orchestrator.name == "hotel_orchestrator"
assert len(flight_orchestrator.sub_agents) == 1
assert len(hotel_orchestrator.sub_agents) == 1
assert flight_orchestrator.sub_agents[0] is not hotel_orchestrator.sub_agents[0]
84 changes: 84 additions & 0 deletions agentregistry/adk/compose_multi_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from collections.abc import Iterator
import os

from google.adk.agents.llm_agent import LlmAgent
from google.adk.integrations.agent_registry import AgentRegistry
import google.auth
from google.auth.transport.requests import Request
import httpx


def compose_multi_agent(
agent_name: str = "agents/AGENT_ID",
mcp_server_name: str = "mcpServers/SERVER_ID",
model: str = "gemini-2.5-flash",
) -> LlmAgent:
"""Initializes AgentRegistry and composes an orchestrator LlmAgent."""
# [START agentregistry_adk_initialize_client]
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

# Initialize the client
registry = AgentRegistry(
project_id=project_id,
location=location,
)
# [END agentregistry_adk_initialize_client]

# [START agentregistry_adk_compose_multi_agent]
class GoogleAuth(httpx.Auth):
def __init__(self) -> None:
self.creds, _ = google.auth.default()

def auth_flow(self, request: httpx.Request) -> Iterator[httpx.Request]:
self.creds.before_request(
Request(),
request.method,
str(request.url),
request.headers,
)
yield request
Comment thread
fatoboist marked this conversation as resolved.
Resolved

httpx_client = httpx.AsyncClient(
auth=GoogleAuth(),
timeout=httpx.Timeout(60.0),
)
my_remote_agent = registry.get_remote_a2a_agent(
agent_name=agent_name,
httpx_client=httpx_client,
)
Comment on lines +59 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Since compose_multi_agent is a synchronous function, using httpx.AsyncClient is inappropriate and can lead to unclosed client warnings or event loop issues. Use the synchronous httpx.Client instead, and wrap it in a with statement to ensure connections are properly closed.

Suggested change
httpx_client = httpx.AsyncClient(
auth=GoogleAuth(),
timeout=httpx.Timeout(60.0),
)
my_remote_agent = registry.get_remote_a2a_agent(
agent_name=agent_name,
httpx_client=httpx_client,
)
with httpx.Client(
auth=GoogleAuth(),
timeout=httpx.Timeout(60.0),
) as httpx_client:
my_remote_agent = registry.get_remote_a2a_agent(
agent_name=agent_name,
httpx_client=httpx_client,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping httpx.AsyncClient without a with block here: AgentRegistry.get_remote_a2a_agent() expects httpx.AsyncClient | None and passes it to ADK's RemoteA2aAgent, which executes async HTTP calls when the returned LlmAgent is invoked. Using a synchronous httpx.Client would fail at runtime, and a with block inside compose_multi_agent() would close the client before the returned orchestrator runs.

my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

main_agent = LlmAgent(
model=model,
name="travel_orchestrator",
instruction=(
"You are a travel coordinator. You can use your subagents to book "
"travel and your tools to query historical travel data."
),
tools=[my_mcp_toolset],
sub_agents=[my_remote_agent],
)
# [END agentregistry_adk_compose_multi_agent]
Comment on lines +45 to +79

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (blocking): Two doc-parity items to align with resolve-endpoints-and-build-orchestrators.md before we switch the page to a GitHub include:

  • ADK CLI commands (adk run / adk web) expect the module-level variable to be named root_agent, and the paragraph right below this snippet in resolve-endpoints-and-build-orchestrators.md explicitly says "After saving root_agent in your ADK project's agent.py file...". Could we rename main_agent to root_agent?
  • Our current doc prose and callout note specifically explain GoogleApiAuth(quota_project_id), the https://www.googleapis.com/auth/cloud-platform scope, and the X-Goog-User-Project header (and the "Replace the following" list defines QUOTA_PROJECT_ID). Using self.creds.before_request(...) is cleaner, so either we keep GoogleApiAuth with quota_project_id / scopes here, or we make a note to update the surrounding doc prose in resolve-endpoints-and-build-orchestrators.md when we swap in the include—let me know which you prefer!
  • Right now # [START agentregistry_adk_compose_multi_agent] (and # [START agentregistry_adk_initialize_client] above) excludes the import statements and the function parameters (agent_name, mcp_server_name, model), so readers on cloud.google.com won't see the imports or the placeholder values ("agents/AGENT_ID", "mcpServers/SERVER_ID", "gemini-2.5-flash") that the doc's "Replace the following" list refers to. Could we include the imports and variable/parameter definitions inside the region tags (or wrap the function signature inside the tags per python-docs-samples conventions)?

return main_agent


if __name__ == "__main__":
compose_multi_agent()
36 changes: 36 additions & 0 deletions agentregistry/adk/compose_multi_agent_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import compose_multi_agent
import pytest


def test_compose_multi_agent(
monkeypatch: pytest.MonkeyPatch,
project_id: str,
location: str,
agent_id: str,
mcp_server_id: str,
) -> None:
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)

orchestrator = compose_multi_agent.compose_multi_agent(
agent_name=f"agents/{agent_id}",
mcp_server_name=f"mcpServers/{mcp_server_id}",
)

assert orchestrator.name == "travel_orchestrator"
assert len(orchestrator.sub_agents) == 1
assert len(orchestrator.tools) == 1
51 changes: 51 additions & 0 deletions agentregistry/adk/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import pytest


@pytest.fixture()
def project_id() -> str:
return os.environ["GOOGLE_CLOUD_PROJECT"]


@pytest.fixture()
def location() -> str:
return os.environ.get("GOOGLE_CLOUD_LOCATION", "global")


@pytest.fixture()
def agent_id() -> str:
value = os.environ.get("AGENTREGISTRY_TEST_AGENT_ID")
if not value:
pytest.skip("AGENTREGISTRY_TEST_AGENT_ID environment variable not set.")
return value


@pytest.fixture()
def mcp_server_id() -> str:
value = os.environ.get("AGENTREGISTRY_TEST_MCP_SERVER_ID")
if not value:
pytest.skip("AGENTREGISTRY_TEST_MCP_SERVER_ID environment variable not set.")
return value


@pytest.fixture()
def staging_bucket() -> str:
value = os.environ.get("AGENTREGISTRY_TEST_STAGING_BUCKET")
if not value:
pytest.skip("AGENTREGISTRY_TEST_STAGING_BUCKET environment variable not set.")
return value
56 changes: 56 additions & 0 deletions agentregistry/adk/deploy_agent_runtime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
from typing import Any

import vertexai
from vertexai.agent_engines.templates.a2a import default_a2a_agent


def deploy_agent_runtime(
staging_bucket: str | None = None,
display_name: str = "my-support-agent",
) -> Any:
"""Deploys an A2A agent to Vertex AI Agent Engine."""
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1")

if not project_id:
raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

client = vertexai.Client(project=project_id, location=location)
my_a2a_agent = default_a2a_agent()

config: dict[str, Any] = {
"display_name": display_name,
"description": "An agent that handles support tickets.",
"requirements": ["google-cloud-aiplatform[agent_engines,a2a]"],
}
if staging_bucket:
config["staging_bucket"] = staging_bucket

# [START agentregistry_deploy_agent_runtime]
# Create and deploy the agent
# This action automatically registers the agent in Agent Registry
remote_agent = client.agent_engines.create(
agent=my_a2a_agent,
config=config,
)
# [END agentregistry_deploy_agent_runtime]
Comment on lines +36 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (blocking): # [START agentregistry_deploy_agent_runtime] currently starts at line 44, after config is defined. That means the rendered snippet in automatic-registration.md will only show client.agent_engines.create(agent=my_a2a_agent, config=config) without showing display_name, description, or requirements. Could we move # [START agentregistry_deploy_agent_runtime] above config (or include the client/agent setup) so readers can still see the config dictionary?

return remote_agent


if __name__ == "__main__":
deploy_agent_runtime()
Loading