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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -141,7 +142,7 @@ 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 dot-segments.

``quote(..., safe="")`` encodes reserved characters including ``/``, ``?``,
and ``#``, but leaves ``.`` literal because it is unreserved. A value of
Expand All @@ -156,7 +157,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:
Expand Down Expand Up @@ -467,6 +468,8 @@ 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()
header_params: dict[str, str] = {}
Expand Down Expand Up @@ -497,6 +500,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
Expand All @@ -506,9 +511,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=original_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)
Expand Down Expand Up @@ -548,6 +554,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
Expand Down Expand Up @@ -675,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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1483,13 +1483,15 @@ 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,
mock_tool_context,
sample_endpoint,
sample_auth_scheme,
sample_auth_credential,
args,
):
"""Test that required parameters with defaults are auto-filled."""
mock_response = MagicMock()
Expand Down Expand Up @@ -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
Expand All @@ -1535,12 +1537,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(
Expand Down Expand Up @@ -1568,8 +1572,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
Expand Down Expand Up @@ -2435,6 +2439,70 @@ 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
@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=path,
method="GET",
),
operation=Operation(
operationId="listToys",
parameters=[
OpenAPIParameter(**{
"name": "petId",
"in": "path",
"required": True,
"schema": OpenAPISchema(type="string"),
})
],
),
)

mock_request.return_value = httpx.Response(
200,
json={},
request=httpx.Request("GET", "https://petstore.example.com"),
)
result = await tool.call(
args={"pet_id": value}, tool_context=mock_tool_context
)

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,
sample_endpoint,
Expand Down
Loading