Skip to content
Merged
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
47 changes: 47 additions & 0 deletions agentregistry/adk/auth_mcp_toolset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 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.

# [START agentregistry_adk_auth_mcp_toolset]
import os

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


# mcp_server_name accepts short ("mcpServers/SERVER_ID") or full
# ("projects/{project_id}/locations/{location}/mcpServers/SERVER_ID") format.
def auth_mcp_toolset(
mcp_server_name: str = "mcpServers/SERVER_ID",
) -> McpToolset:
"""Retrieves an MCP toolset authenticated with Application Default Credentials."""
# Initialize the registry client
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

@NimJay NimJay Dec 1, 2026 •

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.

Nit: Location and Project ID should come in through the sample function params.
See: https://googlecloudsamples.github.io/catalog/docs/effective-samples/author-samples/#minimal-arguments

This applies to all samples in this PR.


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
Comment thread
fatoboist marked this conversation as resolved.
Resolved
my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)
return my_mcp_toolset
# [END agentregistry_adk_auth_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
73 changes: 73 additions & 0 deletions agentregistry/adk/auth_remote_a2a_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# 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.

# [START agentregistry_adk_auth_remote_a2a_agent]
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 thread
fatoboist marked this conversation as resolved.
Resolved


# agent_name accepts short ("agents/AGENT_ID") or full
# ("projects/{project_id}/locations/{location}/agents/AGENT_ID") format.
def auth_remote_a2a_agent(
agent_name: str = "agents/AGENT_ID",
) -> RemoteA2aAgent:
"""Authenticates a remote A2A agent with Application Default Credentials."""
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),
)

# 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,
)
return my_remote_agent
# [END agentregistry_adk_auth_remote_a2a_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.

# [START agentregistry_adk_mcp_custom_headers]
import os
from typing import Any

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


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)
return external_mcp_toolset
# [END agentregistry_adk_mcp_custom_headers]


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.

# [START agentregistry_adk_resolve_auth_bindings]
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",

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.

Suggestion: Gemini 2.5 reached end-of-life today. Under the hood, I believe Gemini Flash 3+ would be used here. Consider changing the model.

) -> LlmAgent:
"""Fetches an authenticated MCP toolset with resolved auth provider bindings."""
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],
)
return maps_agent
# [END agentregistry_adk_resolve_auth_bindings]


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