-
Notifications
You must be signed in to change notification settings - Fork 3.5k
feat: Integrate mTLS support into Agent Registry API calls #5861
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
Open
agrawalradhika-cell
wants to merge
5
commits into
google:main
Choose a base branch
from
agrawalradhika-cell:add-agent-registry-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+249
−95
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b2fbf30
feat: Integrate mTLS support into Agent Registry API calls
agrawalradhika-cell 46218f3
chore: Add unit tests for mTLS support for AgentRegistry
agrawalradhika-cell 3653fb1
Merge branch 'google:main' into add-agent-registry-support
agrawalradhika-cell 8e26ecf
Merge branch 'main' into add-agent-registry-support
rohityan 3146c0a
Merge branch 'google:main' into add-agent-registry-support
agrawalradhika-cell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,6 +19,7 @@ | |
| from collections.abc import Generator | ||
| from enum import Enum | ||
| import logging | ||
| import os | ||
| import re | ||
| from typing import Any | ||
| from typing import Callable | ||
|
|
@@ -39,9 +40,11 @@ | |
| from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams | ||
| from google.adk.tools.mcp_tool.mcp_toolset import McpToolset | ||
| import google.auth | ||
| import google.auth.transport.requests | ||
| from google.auth.transport import mtls | ||
| from google.auth.transport import requests as requests_auth | ||
| import httpx | ||
| from mcp import StdioServerParameters | ||
| import requests | ||
| from typing_extensions import override | ||
|
|
||
| # pylint: disable=g-import-not-at-top | ||
|
|
@@ -61,6 +64,9 @@ | |
| logger = logging.getLogger("google_adk." + __name__) | ||
|
|
||
| AGENT_REGISTRY_BASE_URL = "https://agentregistry.googleapis.com/v1alpha" | ||
| AGENT_REGISTRY_MTLS_BASE_URL = ( | ||
| "https://agentregistry.mtls.googleapis.com/v1alpha" | ||
| ) | ||
|
|
||
| _TRANSPORT_MAPPING = { | ||
| "HTTP_JSON": A2ATransport.http_json, | ||
|
|
@@ -120,6 +126,14 @@ async def get_tools( | |
| return tools | ||
|
|
||
|
|
||
| class _MtlsEndpoint(Enum): | ||
| """The mTLS endpoint setting.""" | ||
|
|
||
| AUTO = "auto" | ||
| ALWAYS = "always" | ||
| NEVER = "never" | ||
|
|
||
|
|
||
| class _ProtocolType(str, Enum): | ||
| """Supported agent protocol types.""" | ||
|
|
||
|
|
@@ -224,23 +238,40 @@ def _make_request( | |
| self, path: str, params: Dict[str, Any] | None = None | ||
| ) -> Dict[str, Any]: | ||
| """Helper function to make GET requests to the Agent Registry API.""" | ||
| # Determine if mTLS should be used | ||
| session = requests_auth.AuthorizedSession(credentials=self._credentials) | ||
|
|
||
| use_client_cert = _use_client_cert_effective() | ||
| client_cert_source = None | ||
|
|
||
| if use_client_cert: | ||
| client_cert_source = ( | ||
| mtls.default_client_cert_source() | ||
| if mtls.has_default_client_cert_source() | ||
| else None | ||
| ) | ||
| session.configure_mtls_channel() | ||
|
|
||
| base_url = _get_agent_registry_base_url(client_cert_source) | ||
|
|
||
| if path.startswith("projects/"): | ||
| url = f"{AGENT_REGISTRY_BASE_URL}/{path}" | ||
| url = f"{base_url}/{path}" | ||
| else: | ||
| url = f"{AGENT_REGISTRY_BASE_URL}/{self._base_path}/{path}" | ||
| url = f"{base_url}/{self._base_path}/{path}" | ||
|
|
||
| try: | ||
| headers = self._get_auth_headers() | ||
| with httpx.Client() as client: | ||
| response = client.get(url, headers=headers, params=params) | ||
| response.raise_for_status() | ||
| return response.json() | ||
| except httpx.HTTPStatusError as e: | ||
| # Using AuthorizedSession for internal API calls to handle mTLS/Auth. | ||
| response = session.get( | ||
| url, headers=self._get_auth_headers(), params=params | ||
|
Collaborator
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. we shouldn't be manually injecting _get_auth_headers() into every request (I think it defeats the point of AuthorizedSession) perhaps we should have something like |
||
| ) | ||
| response.raise_for_status() | ||
| return response.json() | ||
| except requests.exceptions.HTTPError as e: | ||
| raise RuntimeError( | ||
| f"API request failed with status {e.response.status_code}:" | ||
| f" {e.response.text}" | ||
| ) from e | ||
| except httpx.RequestError as e: | ||
| except requests.exceptions.RequestException as e: | ||
| raise RuntimeError(f"API request failed (network error): {e}") from e | ||
| except Exception as e: | ||
| raise RuntimeError(f"API request failed: {e}") from e | ||
|
|
@@ -520,3 +551,33 @@ def get_remote_a2a_agent( | |
| description=description, | ||
| httpx_client=httpx_client, | ||
| ) | ||
|
|
||
|
|
||
| def _use_client_cert_effective() -> bool: | ||
| """Returns whether client certificate should be used for mTLS.""" | ||
| try: | ||
| return bool(mtls.should_use_client_cert()) | ||
| except (ImportError, AttributeError): | ||
| use_client_cert_str = os.getenv( | ||
| "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" | ||
| ).lower() | ||
| return use_client_cert_str == "true" | ||
|
|
||
|
|
||
| def _get_agent_registry_base_url(client_cert_source: Any | None = None) -> str: | ||
| """Returns the base URL based on mTLS configuration and cert availability.""" | ||
| use_mtls_endpoint_str = os.getenv( | ||
| "GOOGLE_API_USE_MTLS_ENDPOINT", _MtlsEndpoint.AUTO.value | ||
| ).lower() | ||
|
|
||
| try: | ||
| use_mtls_endpoint = _MtlsEndpoint(use_mtls_endpoint_str) | ||
| except ValueError: | ||
| use_mtls_endpoint = _MtlsEndpoint.AUTO | ||
|
|
||
| if (use_mtls_endpoint is _MtlsEndpoint.ALWAYS) or ( | ||
| use_mtls_endpoint is _MtlsEndpoint.AUTO and client_cert_source | ||
| ): | ||
| return AGENT_REGISTRY_MTLS_BASE_URL | ||
|
|
||
| return AGENT_REGISTRY_BASE_URL | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
recommended to pass in client_cert_source:
session.configure_mtls_channel(client_cert_source)