|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from typing import Any |
| 18 | +from typing import Callable |
| 19 | + |
| 20 | +from google.adk.agents.readonly_context import ReadonlyContext |
| 21 | +from google.adk.tools.base_toolset import ToolPredicate |
| 22 | +from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams |
| 23 | +from google.adk.tools.mcp_tool.mcp_toolset import McpToolset |
| 24 | +import google.auth |
| 25 | +import google.auth.transport.requests |
| 26 | +import httpx |
| 27 | + |
| 28 | +API_REGISTRY_URL = "https://cloudapiregistry.googleapis.com" |
| 29 | + |
| 30 | + |
| 31 | +class ApiRegistry: |
| 32 | + """Registry that provides McpToolsets for MCP servers registered in API Registry.""" |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + api_registry_project_id: str, |
| 37 | + location: str = "global", |
| 38 | + header_provider: ( |
| 39 | + Callable[[ReadonlyContext], dict[str, str]] | None |
| 40 | + ) = None, |
| 41 | + ): |
| 42 | + """Initialize the API Registry. |
| 43 | +
|
| 44 | + Args: |
| 45 | + api_registry_project_id: The project ID for the Google Cloud API Registry. |
| 46 | + location: The location of the API Registry resources. |
| 47 | + header_provider: Optional function to provide additional headers for MCP |
| 48 | + server calls. |
| 49 | + """ |
| 50 | + self.api_registry_project_id = api_registry_project_id |
| 51 | + self.location = location |
| 52 | + self._credentials, _ = google.auth.default() |
| 53 | + self._mcp_servers: dict[str, dict[str, Any]] = {} |
| 54 | + self._header_provider = header_provider |
| 55 | + |
| 56 | + url = f"{API_REGISTRY_URL}/v1beta/projects/{self.api_registry_project_id}/locations/{self.location}/mcpServers" |
| 57 | + |
| 58 | + try: |
| 59 | + headers = self._get_auth_headers() |
| 60 | + headers["Content-Type"] = "application/json" |
| 61 | + page_token = None |
| 62 | + with httpx.Client() as client: |
| 63 | + while True: |
| 64 | + params = {} |
| 65 | + if page_token: |
| 66 | + params["pageToken"] = page_token |
| 67 | + |
| 68 | + response = client.get(url, headers=headers, params=params) |
| 69 | + response.raise_for_status() |
| 70 | + data = response.json() |
| 71 | + mcp_servers_list = data.get("mcpServers", []) |
| 72 | + for server in mcp_servers_list: |
| 73 | + server_name = server.get("name", "") |
| 74 | + if server_name: |
| 75 | + self._mcp_servers[server_name] = server |
| 76 | + |
| 77 | + page_token = data.get("nextPageToken") |
| 78 | + if not page_token: |
| 79 | + break |
| 80 | + except (httpx.HTTPError, ValueError) as e: |
| 81 | + # Handle error in fetching or parsing tool definitions |
| 82 | + raise RuntimeError( |
| 83 | + f"Error fetching MCP servers from API Registry: {e}" |
| 84 | + ) from e |
| 85 | + |
| 86 | + def get_toolset( |
| 87 | + self, |
| 88 | + mcp_server_name: str, |
| 89 | + tool_filter: ToolPredicate | list[str] | None = None, |
| 90 | + tool_name_prefix: str | None = None, |
| 91 | + ) -> McpToolset: |
| 92 | + """Return the MCP Toolset based on the params. |
| 93 | +
|
| 94 | + Args: |
| 95 | + mcp_server_name: Filter to select the MCP server name to get tools from. |
| 96 | + tool_filter: Optional filter to select specific tools. Can be a list of |
| 97 | + tool names or a ToolPredicate function. |
| 98 | + tool_name_prefix: Optional prefix to prepend to the names of the tools |
| 99 | + returned by the toolset. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + McpToolset: A toolset for the MCP server specified. |
| 103 | + """ |
| 104 | + server = self._mcp_servers.get(mcp_server_name) |
| 105 | + if not server: |
| 106 | + raise ValueError( |
| 107 | + f"MCP server {mcp_server_name} not found in API Registry." |
| 108 | + ) |
| 109 | + if not server.get("urls"): |
| 110 | + raise ValueError(f"MCP server {mcp_server_name} has no URLs.") |
| 111 | + |
| 112 | + mcp_server_url = server["urls"][0] |
| 113 | + headers = self._get_auth_headers() |
| 114 | + |
| 115 | + # Only prepend "https://" if the URL doesn't already have a scheme |
| 116 | + if not mcp_server_url.startswith(("http://", "https://")): |
| 117 | + mcp_server_url = "https://" + mcp_server_url |
| 118 | + |
| 119 | + return McpToolset( |
| 120 | + connection_params=StreamableHTTPConnectionParams( |
| 121 | + url=mcp_server_url, |
| 122 | + headers=headers, |
| 123 | + ), |
| 124 | + tool_filter=tool_filter, |
| 125 | + tool_name_prefix=tool_name_prefix, |
| 126 | + header_provider=self._header_provider, |
| 127 | + ) |
| 128 | + |
| 129 | + def _get_auth_headers(self) -> dict[str, str]: |
| 130 | + """Refreshes credentials and returns authorization headers.""" |
| 131 | + request = google.auth.transport.requests.Request() |
| 132 | + self._credentials.refresh(request) |
| 133 | + headers = { |
| 134 | + "Authorization": f"Bearer {self._credentials.token}", |
| 135 | + } |
| 136 | + # Add quota project header if available in ADC |
| 137 | + quota_project_id = getattr(self._credentials, "quota_project_id", None) |
| 138 | + if quota_project_id: |
| 139 | + headers["x-goog-user-project"] = quota_project_id |
| 140 | + return headers |
0 commit comments