diff --git a/src/google/adk/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.py b/src/google/adk/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.py index 1745698e410..1d0ee1677f3 100644 --- a/src/google/adk/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.py +++ b/src/google/adk/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.py @@ -15,6 +15,7 @@ from __future__ import annotations import copy +import re from typing import Any from typing import Dict from typing import List @@ -46,6 +47,28 @@ _SCHEMA_CONTAINER_KEYS: Set[str] = frozenset({"schema", "schemas"}) +_SERVER_URL_VARIABLE_PATTERN = re.compile(r"\{([^{}]+)\}") + + +def _substitute_server_url_variables( + url: str, variables: Optional[Dict[str, Any]] +) -> str: + """Replaces declared ``{name}`` placeholders in ``url`` with their defaults. + + Placeholders that are undeclared, or declared without a ``default`` value, + are left verbatim so partially specified server URLs stay usable. + """ + if not variables: + return url + + def replace(match: re.Match[str]) -> str: + variable = variables.get(match.group(1)) + if not isinstance(variable, dict) or "default" not in variable: + return match.group(0) + return str(variable["default"]) + + return _SERVER_URL_VARIABLE_PATTERN.sub(replace, url) + class OperationEndpoint(BaseModel): base_url: str @@ -180,7 +203,10 @@ def _collect_operations( # Taking first server url, or default to empty string if not present base_url = "" if openapi_spec.get("servers"): - base_url = openapi_spec["servers"][0].get("url", "") + server = openapi_spec["servers"][0] + base_url = _substitute_server_url_variables( + server.get("url", ""), server.get("variables") + ) # Get global security scheme (if any). global_scheme_name = _required_scheme_name(openapi_spec.get("security")) diff --git a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_openapi_spec_parser.py b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_openapi_spec_parser.py index f8f29d1a968..bcb1e735eff 100644 --- a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_openapi_spec_parser.py +++ b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_openapi_spec_parser.py @@ -16,6 +16,8 @@ from typing import Dict from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_spec_parser import OpenApiSpecParser +from google.adk.tools.openapi_tool.openapi_spec_parser.rest_api_tool import RestApiTool +import httpx import pytest @@ -306,6 +308,83 @@ def test_parse_spec_with_no_servers(openapi_spec_generator): assert parsed_operations[0].endpoint.base_url == "" +def _spec_with_templated_server( + url: str, variables: Dict[str, Any] | None +) -> Dict[str, Any]: + """Builds a minimal spec whose only server uses the given templated URL.""" + server: Dict[str, Any] = {"url": url} + if variables is not None: + server["variables"] = variables + return { + "openapi": "3.0.0", + "info": {"title": "Templated API", "version": "1.0.0"}, + "servers": [server], + "paths": { + "/pets": { + "get": { + "operationId": "listPets", + "responses": {"200": {"description": "OK"}}, + } + } + }, + } + + +@pytest.mark.asyncio +async def test_server_url_variables_are_substituted(openapi_spec_generator): + """Declared server URL variables are replaced with their defaults.""" + openapi_spec = _spec_with_templated_server( + "https://{region}.api.example.com/{basePath}", + {"region": {"default": "us"}, "basePath": {"default": "v2"}}, + ) + + parsed_operations = openapi_spec_generator.parse(openapi_spec) + assert len(parsed_operations) == 1 + assert ( + parsed_operations[0].endpoint.base_url == "https://us.api.example.com/v2" + ) + + recorded_requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + recorded_requests.append(request) + return httpx.Response(200, json={"result": "ok"}) + + tool = RestApiTool.from_parsed_operation( + parsed_operations[0], + httpx_client_factory=lambda: httpx.AsyncClient( + transport=httpx.MockTransport(handler) + ), + allow_private_network_access=True, + ) + response = await tool.call(args={}, tool_context=None) + + assert response == {"result": "ok"} + assert len(recorded_requests) == 1 + assert str(recorded_requests[0].url) == "https://us.api.example.com/v2/pets" + + +def test_server_url_placeholders_without_defaults_are_unchanged( + openapi_spec_generator, +): + """Undeclared or default-less placeholders stay verbatim.""" + openapi_spec = _spec_with_templated_server( + "https://{region}.api.example.com/{basePath}/{unknown}", + { + "region": {"default": "us"}, + "basePath": {"description": "no default declared"}, + }, + ) + + parsed_operations = openapi_spec_generator.parse(openapi_spec) + + assert len(parsed_operations) == 1 + assert ( + parsed_operations[0].endpoint.base_url + == "https://us.api.example.com/{basePath}/{unknown}" + ) + + def test_parse_spec_with_description(openapi_spec_generator): openapi_spec = create_minimal_openapi_spec() expected_description = "This is a test description."