From 2f566babedb93794529fa100b901d83bc91791f5 Mon Sep 17 00:00:00 2001 From: Ben Clarke Date: Sat, 7 Nov 2026 23:59:05 +0000 Subject: [PATCH 1/5] fix(tools): reject blank RestApiTool path parameters - Raise InputValidationError naming the parameter when a path parameter value is empty or whitespace-only, so the model gets a retryable tool error instead of a request to a path with an empty segment. --- .../openapi_spec_parser/rest_api_tool.py | 11 ++++- .../openapi_spec_parser/test_rest_api_tool.py | 42 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py index 18dbb70b259..c3e69a10190 100644 --- a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py +++ b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py @@ -141,7 +141,11 @@ def _to_param_string(value: object) -> str: def _encode_path_param(*, name: str, value: str) -> str: - """Percent-encode a path parameter, rejecting RFC 3986 dot-segments. + """Percent-encode a path parameter, rejecting blank values and dot-segments. + + A blank value would leave an empty path segment (for example + ``/pets//toys``), which servers answer with a redirect or an error that does + not name the parameter, so it is rejected like a missing one. ``quote(..., safe="")`` encodes reserved characters including ``/``, ``?``, and ``#``, but leaves ``.`` literal because it is unreserved. A value of @@ -163,8 +167,11 @@ def _encode_path_param(*, name: str, value: str) -> str: The percent-encoded parameter value. Raises: - InputValidationError: If any path segment is ``.`` or ``..``. + InputValidationError: If the value is empty or whitespace-only, or any + path segment is ``.`` or ``..``. """ + if not value.strip(): + raise InputValidationError(f"Path parameter {name!r} must not be empty.") for segment in value.replace("\\", "/").split("/"): if segment in (".", ".."): raise InputValidationError( diff --git a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py index 74d6cefd4f4..bb7832e9b2b 100644 --- a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py +++ b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py @@ -226,6 +226,12 @@ def oauth2_credential(): ) +@pytest.mark.parametrize("value", ["", " ", "\t\n"]) +def test_encode_path_param_rejects_blank_values(value): + with pytest.raises(InputValidationError, match="'name' must not be empty"): + _encode_path_param(name="name", value=value) + + @pytest.mark.parametrize( "value", [".", "..", "../../admin/v1/tenants", "foo/../bar", r"..\admin", "./x"], @@ -2435,6 +2441,42 @@ async def test_call_rejects_dot_segment_path_param( assert not mock_request.called assert tool._detect_error_in_response(result) == "HTTP_ERROR" + @patch( + "google.adk.tools.openapi_tool.openapi_spec_parser.rest_api_tool._request" + ) + @pytest.mark.asyncio + async def test_call_rejects_blank_path_param( + self, mock_request, mock_tool_context + ): + """A blank path arg must return a retryable error without a request.""" + tool = RestApiTool( + name="list_toys", + description="List a pet's toys.", + endpoint=OperationEndpoint( + base_url="https://petstore.example.com", + path="/pets/{petId}/toys", + method="GET", + ), + operation=Operation( + operationId="listToys", + parameters=[ + OpenAPIParameter(**{ + "name": "petId", + "in": "path", + "required": True, + "schema": OpenAPISchema(type="string"), + }) + ], + ), + ) + + result = await tool.call( + args={"pet_id": " "}, tool_context=mock_tool_context + ) + + assert "Path parameter 'petId' must not be empty." in result["error"] + assert not mock_request.called + def test_prepare_request_params_header_param( self, sample_endpoint, From e44ffed09d8f7d42739d5fdbcfffbfe428f0c4a4 Mon Sep 17 00:00:00 2001 From: Ben Clarke Date: Sun, 8 Nov 2026 12:28:07 +0000 Subject: [PATCH 2/5] fix(tools): treat a None RestApiTool path parameter as missing - Skip a path parameter whose value is None, so it is reported as a missing required parameter instead of being sent as the string "None". - Cover the None case in the missing path parameter test. Co-authored-by: Aman Agnihotri --- .../tools/openapi_tool/openapi_spec_parser/rest_api_tool.py | 2 ++ .../openapi_tool/openapi_spec_parser/test_rest_api_tool.py | 6 ++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py index c3e69a10190..95267958d5d 100644 --- a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py +++ b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py @@ -504,6 +504,8 @@ def _prepare_request_params( param_location = param_obj.param_location if param_location == "path": + if v is None: + continue # Reported as a missing parameter when the URL is built. # Percent-encode path parameter values (including '/') before they # are substituted into the URL template below. Path parameter # values ultimately originate from the model's tool-call diff --git a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py index bb7832e9b2b..d359876a030 100644 --- a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py +++ b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py @@ -1541,12 +1541,14 @@ async def test_call_with_required_param_defaults( "google.adk.tools.openapi_tool.openapi_spec_parser.rest_api_tool._request" ) @pytest.mark.asyncio + @pytest.mark.parametrize("args", [{}, {"user_id": None}]) async def test_call_missing_required_path_param_returns_error( self, mock_request, mock_tool_context, sample_auth_scheme, sample_auth_credential, + args, ): """A required path param with no default and no value must not crash.""" mock_operation = Operation( @@ -1574,8 +1576,8 @@ async def test_call_missing_required_path_param_returns_error( auth_credential=sample_auth_credential, ) - # Call without providing userId and without a default to fall back on. - result = await tool.call(args={}, tool_context=mock_tool_context) + # Call without a userId value and without a default to fall back on. + result = await tool.call(args=args, tool_context=mock_tool_context) assert not mock_request.called assert "error" in result From 12756fe3f56de37588b14166566ce0986648d8e8 Mon Sep 17 00:00:00 2001 From: Ben Clarke Date: Sun, 8 Nov 2026 12:30:55 +0000 Subject: [PATCH 3/5] fix(tools): name path parameters as the model sees them in errors - Pass the parameter's Python name to _encode_path_param, so the empty and dot-segment errors say 'pet_id' like the missing parameter error does, instead of the spec's 'petId'. --- .../tools/openapi_tool/openapi_spec_parser/rest_api_tool.py | 4 ++-- .../openapi_tool/openapi_spec_parser/test_rest_api_tool.py | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py index 95267958d5d..531e318712c 100644 --- a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py +++ b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py @@ -160,7 +160,7 @@ def _encode_path_param(*, name: str, value: str) -> str: valid. Args: - name: Original OpenAPI parameter name, used in the error message. + name: Parameter name the model sees, used in the error message. value: Raw path parameter value from the tool call. Returns: @@ -516,7 +516,7 @@ def _prepare_request_params( # Reserved characters ('/', '?', '#') are still escaped so a # value cannot introduce a query string or fragment. path_params[original_k] = _encode_path_param( - name=original_k, value=_to_param_string(v) + name=param_k, value=_to_param_string(v) ) elif param_location == "query": if v is not None: diff --git a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py index d359876a030..ae80a3a6d51 100644 --- a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py +++ b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py @@ -2476,7 +2476,8 @@ async def test_call_rejects_blank_path_param( args={"pet_id": " "}, tool_context=mock_tool_context ) - assert "Path parameter 'petId' must not be empty." in result["error"] + assert "Path parameter 'pet_id' must not be empty." in result["error"] + assert "petId" not in result["error"] assert not mock_request.called def test_prepare_request_params_header_param( From 1c79117bfc72880a86ab2a0ad9451ece5d47bece Mon Sep 17 00:00:00 2001 From: Ben Clarke Date: Sun, 8 Nov 2026 12:47:18 +0000 Subject: [PATCH 4/5] fix(tools): allow blank values inside REST path segments - Allow blank substitutions when the segment still contains literal or parameter content. - Keep retryable errors for blank and dot segments using the exposed argument name. - Exercise both rejected segments and permitted filename substitutions. --- .../openapi_spec_parser/rest_api_tool.py | 36 ++++++++----- .../openapi_spec_parser/test_rest_api_tool.py | 51 +++++++++++++------ 2 files changed, 60 insertions(+), 27 deletions(-) diff --git a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py index 531e318712c..9ca96cd4ca4 100644 --- a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py +++ b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py @@ -18,6 +18,7 @@ from dataclasses import dataclass import logging import ssl +from string import Formatter from typing import Any from typing import Callable from typing import Dict @@ -141,11 +142,7 @@ def _to_param_string(value: object) -> str: def _encode_path_param(*, name: str, value: str) -> str: - """Percent-encode a path parameter, rejecting blank values and dot-segments. - - A blank value would leave an empty path segment (for example - ``/pets//toys``), which servers answer with a redirect or an error that does - not name the parameter, so it is rejected like a missing one. + """Percent-encode a path parameter, rejecting dot-segments. ``quote(..., safe="")`` encodes reserved characters including ``/``, ``?``, and ``#``, but leaves ``.`` literal because it is unreserved. A value of @@ -167,11 +164,8 @@ def _encode_path_param(*, name: str, value: str) -> str: The percent-encoded parameter value. Raises: - InputValidationError: If the value is empty or whitespace-only, or any - path segment is ``.`` or ``..``. + InputValidationError: If any path segment is ``.`` or ``..``. """ - if not value.strip(): - raise InputValidationError(f"Path parameter {name!r} must not be empty.") for segment in value.replace("\\", "/").split("/"): if segment in (".", ".."): raise InputValidationError( @@ -474,6 +468,7 @@ def _prepare_request_params( raise ValueError("Operation method not found.") path_params: Dict[str, Any] = {} + blank_path_params: dict[str, str] = {} query_params: Dict[str, Any] = {} spread_query_keys: set[str] = set() header_params: dict[str, str] = {} @@ -515,9 +510,10 @@ def _prepare_request_params( # with this tool's configured auth -- onto an undeclared path. # Reserved characters ('/', '?', '#') are still escaped so a # value cannot introduce a query string or fragment. - path_params[original_k] = _encode_path_param( - name=param_k, value=_to_param_string(v) - ) + value = _to_param_string(v) + if not value.strip(): + blank_path_params[original_k] = param_k + path_params[original_k] = _encode_path_param(name=param_k, value=value) elif param_location == "query": if v is not None: serialized = _serialize_query_param(param_obj, v) @@ -557,6 +553,22 @@ def _prepare_request_params( f"Missing required path parameter '{param.py_name}'." ) from e raise + if blank_path_params: + # Blank substitutions are safe when the segment still has content, + # such as the extension in /exports/{suffix}.csv. + path_template = self.endpoint.path.partition("?")[0].partition("#")[0] + for segment in path_template.split("/"): + parts = list(Formatter().parse(segment)) + fields = [field for _, field, _, _ in parts if field is not None] + if not fields or any( + field not in blank_path_params for field in fields + ): + continue + if "".join(part[0] for part in parts) in ("", ".", ".."): + name = blank_path_params[fields[0]] + raise InputValidationError( + f"Path parameter {name!r} must not be empty." + ) url = f"{base_url}{formatted_path}" # Move query params embedded in the path template itself (now that path diff --git a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py index ae80a3a6d51..f5df85d5295 100644 --- a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py +++ b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py @@ -226,12 +226,6 @@ def oauth2_credential(): ) -@pytest.mark.parametrize("value", ["", " ", "\t\n"]) -def test_encode_path_param_rejects_blank_values(value): - with pytest.raises(InputValidationError, match="'name' must not be empty"): - _encode_path_param(name="name", value=value) - - @pytest.mark.parametrize( "value", [".", "..", "../../admin/v1/tenants", "foo/../bar", r"..\admin", "./x"], @@ -2447,16 +2441,32 @@ async def test_call_rejects_dot_segment_path_param( "google.adk.tools.openapi_tool.openapi_spec_parser.rest_api_tool._request" ) @pytest.mark.asyncio - async def test_call_rejects_blank_path_param( - self, mock_request, mock_tool_context - ): - """A blank path arg must return a retryable error without a request.""" + @pytest.mark.parametrize( + ("path", "value", "expected_path"), + [ + ("/pets/{petId}/toys", "", None), + ("/pets/{petId}/toys", " ", None), + ("/pets/{petId}/toys", "\t\n", None), + ("/pets/.{petId}/toys", "", None), + ("/exports/{petId}.csv", "", "/exports/.csv"), + ("/exports/{petId}.csv", " ", "/exports/%20.csv"), + ], + ) + async def test_call_with_blank_path_param( + self, + mock_request: AsyncMock, + mock_tool_context: MagicMock, + path: str, + value: str, + expected_path: str | None, + ) -> None: + """Reject blank segments while allowing blank values inside a segment.""" tool = RestApiTool( name="list_toys", description="List a pet's toys.", endpoint=OperationEndpoint( base_url="https://petstore.example.com", - path="/pets/{petId}/toys", + path=path, method="GET", ), operation=Operation( @@ -2472,13 +2482,24 @@ async def test_call_rejects_blank_path_param( ), ) + mock_request.return_value = httpx.Response( + 200, + json={}, + request=httpx.Request("GET", "https://petstore.example.com"), + ) result = await tool.call( - args={"pet_id": " "}, tool_context=mock_tool_context + args={"pet_id": value}, tool_context=mock_tool_context ) - assert "Path parameter 'pet_id' must not be empty." in result["error"] - assert "petId" not in result["error"] - assert not mock_request.called + if expected_path is None: + assert "Path parameter 'pet_id' must not be empty." in result["error"] + assert "petId" not in result["error"] + mock_request.assert_not_called() + else: + assert result == {} + assert mock_request.call_args.kwargs["url"] == ( + f"https://petstore.example.com{expected_path}" + ) def test_prepare_request_params_header_param( self, From 53a3a327c095c865447555cce939897cb1ee2719 Mon Sep 17 00:00:00 2001 From: Ben Clarke Date: Mon, 16 Nov 2026 16:42:41 +0000 Subject: [PATCH 5/5] fix(tools): apply RestApiTool defaults to None arguments - Fill a required parameter's schema default when its argument is None, not only when it is absent, so an explicit null uses the default instead of returning a missing path parameter error. - Cover a None argument in the required parameter defaults test. - Note what blank_path_params maps. --- .../tools/openapi_tool/openapi_spec_parser/rest_api_tool.py | 5 +++-- .../openapi_tool/openapi_spec_parser/test_rest_api_tool.py | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py index 9ca96cd4ca4..b090d49e8f7 100644 --- a/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py +++ b/src/google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py @@ -468,6 +468,7 @@ def _prepare_request_params( raise ValueError("Operation method not found.") path_params: Dict[str, Any] = {} + # Original name -> name the model sees, for blank path params. blank_path_params: dict[str, str] = {} query_params: Dict[str, Any] = {} spread_query_keys: set[str] = set() @@ -696,9 +697,9 @@ async def call( api_params = self._operation_parser.get_parameters().copy() api_args = args.copy() - # Add any required arguments that are missing and have defaults: + # Add any required arguments that are missing or None and have defaults: for api_param in api_params: - if api_param.py_name not in api_args: + if api_args.get(api_param.py_name) is None: if ( api_param.required and isinstance(api_param.param_schema, Schema) diff --git a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py index f5df85d5295..940f528d15a 100644 --- a/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py +++ b/tests/unittests/tools/openapi_tool/openapi_spec_parser/test_rest_api_tool.py @@ -1483,6 +1483,7 @@ async def test_call_401_without_a_tool_context_returns_error( "google.adk.tools.openapi_tool.openapi_spec_parser.rest_api_tool._request" ) @pytest.mark.asyncio + @pytest.mark.parametrize("args", [{}, {"user_id": None}]) async def test_call_with_required_param_defaults( self, mock_request, @@ -1490,6 +1491,7 @@ async def test_call_with_required_param_defaults( sample_endpoint, sample_auth_scheme, sample_auth_credential, + args, ): """Test that required parameters with defaults are auto-filled.""" mock_response = MagicMock() @@ -1522,8 +1524,8 @@ async def test_call_with_required_param_defaults( auth_credential=sample_auth_credential, ) - # Call without providing userId - should use default "me" - result = await tool.call(args={}, tool_context=mock_tool_context) + # Call without a userId value - should use default "me" + result = await tool.call(args=args, tool_context=mock_tool_context) # Verify the default was applied assert mock_request.called