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
76 changes: 67 additions & 9 deletions src/google/adk/integrations/api_registry/api_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,51 @@

from __future__ import annotations

import os
from typing import Any
from typing import Callable
from urllib.parse import urlparse

from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.tools.base_toolset import ToolPredicate
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.utils import _mtls_utils
import google.auth
import google.auth.transport.requests
import httpx
from google.auth.transport import mtls
from google.auth.transport import requests as requests_auth
import requests

API_REGISTRY_URL = "https://cloudapiregistry.googleapis.com"
API_REGISTRY_MTLS_URL = "https://cloudapiregistry.mtls.googleapis.com"


def _get_api_registry_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", _mtls_utils.MtlsEndpoint.AUTO.value
).lower()
try:
use_mtls_endpoint = _mtls_utils.MtlsEndpoint(use_mtls_endpoint_str)
except ValueError:
use_mtls_endpoint = _mtls_utils.MtlsEndpoint.AUTO
if (use_mtls_endpoint is _mtls_utils.MtlsEndpoint.ALWAYS) or (
use_mtls_endpoint is _mtls_utils.MtlsEndpoint.AUTO
and client_cert_source is not None
):
return API_REGISTRY_MTLS_URL
return API_REGISTRY_URL


def _is_google_api(url: str) -> bool:
"""Checks if the given URL points to a Google API endpoint over https."""
parsed_url = urlparse(url)
if parsed_url.scheme != "https" or not parsed_url.hostname:
return False
return (
parsed_url.hostname == "googleapis.com"
or parsed_url.hostname.endswith(".googleapis.com")
)


class ApiRegistry:
Expand Down Expand Up @@ -53,19 +86,38 @@ def __init__(
self._mcp_servers: dict[str, dict[str, Any]] = {}
self._header_provider = header_provider

url = f"{API_REGISTRY_URL}/v1beta/projects/{self.api_registry_project_id}/locations/{self.location}/mcpServers"
use_client_cert = _mtls_utils.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
)
base_url = _get_api_registry_url(client_cert_source)

url = f"{base_url}/v1beta/projects/{self.api_registry_project_id}/locations/{self.location}/mcpServers"

try:
headers = self._get_auth_headers()
headers["Content-Type"] = "application/json"
quota_project_id = getattr(self._credentials, "quota_project_id", None)
headers = {
"Content-Type": "application/json",
}
if quota_project_id:
headers["x-goog-user-project"] = quota_project_id

page_token = None
with httpx.Client() as client:
with requests_auth.AuthorizedSession(
credentials=self._credentials
) as session:
if use_client_cert:
session.configure_mtls_channel(client_cert_source)
while True:
params = {}
if page_token:
params["pageToken"] = page_token

response = client.get(url, headers=headers, params=params)
response = session.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
mcp_servers_list = data.get("mcpServers", [])
Expand All @@ -77,7 +129,7 @@ def __init__(
page_token = data.get("nextPageToken")
if not page_token:
break
except (httpx.HTTPError, ValueError) as e:
except (requests.exceptions.RequestException, ValueError) as e:
# Handle error in fetching or parsing tool definitions
raise RuntimeError(
f"Error fetching MCP servers from API Registry: {e}"
Expand Down Expand Up @@ -110,12 +162,18 @@ def get_toolset(
raise ValueError(f"MCP server {mcp_server_name} has no URLs.")

mcp_server_url = server["urls"][0]
headers = self._get_auth_headers()

# Only prepend "https://" if the URL doesn't already have a scheme
if not mcp_server_url.startswith(("http://", "https://")):
mcp_server_url = "https://" + mcp_server_url

# A registry entry can name any host, so the caller's own credentials are
# only attached to Google API endpoints. Other servers get their headers
# from the header_provider.
headers = (
self._get_auth_headers() if _is_google_api(mcp_server_url) else None
)

return McpToolset(
connection_params=StreamableHTTPConnectionParams(
url=mcp_server_url,
Expand Down
41 changes: 41 additions & 0 deletions src/google/adk/utils/_mtls_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# 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.

"""Utilities for mTLS regional endpoint resolution."""

from __future__ import annotations

import enum
import os

from google.auth.transport import mtls


class MtlsEndpoint(enum.Enum):
"""Enum for the mTLS endpoint setting."""

AUTO = "auto"
ALWAYS = "always"
NEVER = "never"


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):
return (
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower()
== "true"
)
Loading
Loading