Repository navigation
feat(agentregistry): add ADK authentication samples #15003
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 | ||
| 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() | ||
| 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 |
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of importing
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not applying this change: There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. By using the official # [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),
)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not applying this change: |
||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| # 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() | ||||||||||||||||||||||||||||||||
| 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 |
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() | ||
| 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 |
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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:
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() | ||
There was a problem hiding this comment.
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.