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
45 changes: 45 additions & 0 deletions agentregistry/adk/auth_mcp_toolset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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 google.adk.integrations.agent_registry import AgentRegistry
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset


def auth_mcp_toolset(
mcp_server_name: str = "mcpServers/SERVER_ID",
) -> McpToolset:
"""Retrieves an MCP toolset authenticated with Application Default Credentials."""
# [START agentregistry_adk_auth_mcp_toolset]
# Initialize the registry 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.")

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

# Retrieve an MCP toolset using its resource name

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit (non-blocking): In authenticate-toolsets.md, both auth_remote_a2a_agent and auth_mcp_toolset include a brief inline comment explaining that agent_name / mcp_server_name accept either short ("mcpServers/SERVER_ID") or full resource name format. Keeping that comment (or leaving it in the doc prose) is nice for readers.

my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)
# [END agentregistry_adk_auth_mcp_toolset]
return my_mcp_toolset


if __name__ == "__main__":
auth_mcp_toolset()
37 changes: 37 additions & 0 deletions agentregistry/adk/auth_mcp_toolset_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 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 auth_mcp_toolset
import pytest


def test_auth_mcp_toolset(monkeypatch: pytest.MonkeyPatch) -> None:
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
mcp_server_id = os.environ.get("AGENTREGISTRY_TEST_MCP_SERVER_ID")
if not project_id or not mcp_server_id:
pytest.skip(
"GOOGLE_CLOUD_PROJECT and AGENTREGISTRY_TEST_MCP_SERVER_ID must be set."
)

monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv(
"GOOGLE_CLOUD_LOCATION", os.environ.get("GOOGLE_CLOUD_LOCATION", "global")
)

toolset = auth_mcp_toolset.auth_mcp_toolset(
mcp_server_name=f"mcpServers/{mcp_server_id}",
)
assert toolset is not None
71 changes: 71 additions & 0 deletions agentregistry/adk/auth_remote_a2a_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# 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.remote_a2a_agent import RemoteA2aAgent
from google.adk.integrations.agent_registry import AgentRegistry
import google.auth
from google.auth.transport.requests import Request
import httpx
Comment on lines +15 to +22

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.

medium

Instead of importing collections.abc.Iterator and google.auth.transport.requests.Request to build a custom authentication flow, you can use the official google.auth.transport.httpx.Auth class. This simplifies the imports and avoids pulling in requests transport dependencies when using httpx.

Suggested change
from collections.abc import Iterator
import os
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
from google.adk.integrations.agent_registry import AgentRegistry
import google.auth
from google.auth.transport.requests import Request
import httpx
import os
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
from google.adk.integrations.agent_registry import AgentRegistry
import google.auth
import google.auth.transport.httpx
import httpx

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.

Not applying this change: google.auth.transport.httpx does not exist in google-auth (the available transports are requests, urllib3, grpc, and _aiohttp_requests), so importing it would fail with ModuleNotFoundError. The custom GoogleAuth(httpx.Auth) subclass using self.creds.before_request(Request(), ...) is required for httpx.

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, agreed — google.auth.transport.httpx doesn't exist, and using self.creds.before_request(Request(), ...) here is actually a nice improvement over the manual token refresh in our current doc



def auth_remote_a2a_agent(
agent_name: str = "agents/AGENT_ID",
) -> RemoteA2aAgent:
"""Authenticates a remote A2A agent with Application Default Credentials."""
# [START agentregistry_adk_auth_remote_a2a_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

# Initialize the registry 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.")

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

# Configure the HTTP client with GoogleAuth and a 60-second timeout
httpx_client = httpx.AsyncClient(
auth=GoogleAuth(),
timeout=httpx.Timeout(60.0),
)
Comment on lines +29 to +59

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.

medium

By using the official google.auth.transport.httpx.Auth helper, you can completely remove the custom GoogleAuth class boilerplate. This makes the code cleaner, more robust, and easier to maintain.

    # [START agentregistry_adk_auth_remote_a2a_agent]
    # Initialize the registry 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.")

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

    # Configure the HTTP client with Google credentials and a 60-second timeout
    credentials, _ = google.auth.default()
    httpx_client = httpx.AsyncClient(
        auth=google.auth.transport.httpx.Auth(credentials),
        timeout=httpx.Timeout(60.0),
    )

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.

Not applying this change: google.auth.transport.httpx does not exist in google-auth (the available transports are requests, urllib3, grpc, and _aiohttp_requests), so importing it would fail with ModuleNotFoundError. The custom GoogleAuth(httpx.Auth) subclass using self.creds.before_request(Request(), ...) is required for httpx.


# Connect to a remote A2A agent using its resource name
my_remote_agent = registry.get_remote_a2a_agent(
agent_name=agent_name,
httpx_client=httpx_client,
)
# [END agentregistry_adk_auth_remote_a2a_agent]
return my_remote_agent


if __name__ == "__main__":
auth_remote_a2a_agent()
37 changes: 37 additions & 0 deletions agentregistry/adk/auth_remote_a2a_agent_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 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 auth_remote_a2a_agent
import pytest


def test_auth_remote_a2a_agent(monkeypatch: pytest.MonkeyPatch) -> None:
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
agent_id = os.environ.get("AGENTREGISTRY_TEST_AGENT_ID")
if not project_id or not agent_id:
pytest.skip(
"GOOGLE_CLOUD_PROJECT and AGENTREGISTRY_TEST_AGENT_ID must be set."
)

monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv(
"GOOGLE_CLOUD_LOCATION", os.environ.get("GOOGLE_CLOUD_LOCATION", "global")
)

remote_agent = auth_remote_a2a_agent.auth_remote_a2a_agent(
agent_name=f"agents/{agent_id}",
)
assert remote_agent is not None
59 changes: 59 additions & 0 deletions agentregistry/adk/mcp_custom_headers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# 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

from google.adk.integrations.agent_registry import AgentRegistry
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset


# [START agentregistry_adk_mcp_custom_headers]
Comment on lines +15 to +22

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): Nice job including def my_auth_headers and def get_external_mcp_toolset inside the region tag here so EXTERNAL_SERVER_ID is visible! Could we also move # [START agentregistry_adk_mcp_custom_headers] above the imports so AgentRegistry / os / Any are shown in the doc snippet too?

def my_auth_headers(context: Any) -> dict[str, str]:
"""Returns custom headers injected into MCP toolset requests."""
external_api_key = os.environ.get("API_KEY", "")
return {
"Authorization": f"Bearer {external_api_key}",
"X-Custom-Context": "orchestrator-request",
}


def get_external_mcp_toolset(
mcp_server_name: str = (
"projects/PROJECT_ID/locations/LOCATION/mcpServers/EXTERNAL_SERVER_ID"
),
) -> McpToolset:
"""Initializes AgentRegistry with header_provider and fetches an MCP toolset."""
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 registry client.
# The header_provider is sent to the target MCP server during invocation,
# not to authenticate against the Agent Registry API (which uses ADC).
registry = AgentRegistry(
project_id=project_id,
location=location,
header_provider=my_auth_headers,
)

external_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)
# [END agentregistry_adk_mcp_custom_headers]
return external_mcp_toolset


if __name__ == "__main__":
get_external_mcp_toolset()
50 changes: 50 additions & 0 deletions agentregistry/adk/mcp_custom_headers_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 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 mcp_custom_headers
import pytest


def test_my_auth_headers(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("API_KEY", "test-api-key")
headers = mcp_custom_headers.my_auth_headers(context=None)
assert headers == {
"Authorization": "Bearer test-api-key",
"X-Custom-Context": "orchestrator-request",
}


def test_get_external_mcp_toolset(monkeypatch: pytest.MonkeyPatch) -> None:
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
external_server_id = os.environ.get("AGENTREGISTRY_TEST_EXTERNAL_MCP_SERVER_ID")
if not project_id or not external_server_id:
pytest.skip(
"GOOGLE_CLOUD_PROJECT and AGENTREGISTRY_TEST_EXTERNAL_MCP_SERVER_ID "
"must be set."
)

location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
monkeypatch.setenv("API_KEY", "test-api-key")

toolset = mcp_custom_headers.get_external_mcp_toolset(
mcp_server_name=(
f"projects/{project_id}/locations/{location}"
f"/mcpServers/{external_server_id}"
),
)
assert toolset is not None
63 changes: 63 additions & 0 deletions agentregistry/adk/resolve_auth_bindings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# 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 google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider
from google.adk.integrations.agent_registry import AgentRegistry


def resolve_auth_bindings(
mcp_server_name: str = "mcpServers/SERVER_ID",
model: str = "gemini-2.5-flash",
) -> LlmAgent:
"""Fetches an authenticated MCP toolset with resolved auth provider bindings."""
# [START agentregistry_adk_resolve_auth_bindings]
Comment on lines +23 to +28

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): Across four of the five samples in this PR (auth_mcp_toolset.py, auth_remote_a2a_agent.py, resolve_auth_bindings.py, and resolve_auth_bindings_3lo.py), # [START ...] starts inside the function body, which hides:

  • Critical imports like CredentialManager, GcpAuthProvider, AgentRegistry, and LlmAgent.
  • All default placeholder arguments ("mcpServers/SERVER_ID", "agents/AGENT_ID", "https://REDIRECT_URI", and "gemini-2.5-flash"), so the rendered snippets in authenticate-toolsets.md will reference undefined variables (mcp_server_name=mcp_server_name, continue_uri=continue_uri, model=model) and won't match the "Replace the following:" bullet lists in the doc.

Could we expand the region tags (or define the placeholder variables inside the tags, similar to how mcp_custom_headers.py includes def get_external_mcp_toolset(...)) so readers see the imports and placeholders on public docs?

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.")

# Register the auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Initialize the registry client
registry = AgentRegistry(
project_id=project_id,
location=location,
)

# Fetch the registered MCP toolset.
# The ADK applies the bindings configured in Agent Registry.
my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

# Compose the agent
maps_agent = LlmAgent(
name="maps_agent",
model=model,
instruction=(
"You are a local guide and navigation expert. Your goal is to "
"provide accurate location information and directions."
),
tools=[my_mcp_toolset],
)
# [END agentregistry_adk_resolve_auth_bindings]
return maps_agent


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