diff --git a/src/a2a/compat/v0_3/jsonrpc_transport.py b/src/a2a/compat/v0_3/jsonrpc_transport.py index ddeeb3f89..469f0ae8f 100644 --- a/src/a2a/compat/v0_3/jsonrpc_transport.py +++ b/src/a2a/compat/v0_3/jsonrpc_transport.py @@ -5,7 +5,7 @@ from typing import Any, NoReturn from uuid import uuid4 -from jsonrpc.jsonrpc2 import JSONRPC20Request, JSONRPC20Response +from jsonrpc.jsonrpc2 import JSONRPC20Request from a2a.client.client import ClientCallContext from a2a.client.errors import A2AClientError @@ -88,11 +88,7 @@ async def send_message( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) - - result_dict = json_rpc_response.result + result_dict = response_data['result'] if not isinstance(result_dict, dict): return SendMessageResponse() @@ -163,12 +159,8 @@ async def get_task( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) - return conversions.to_core_task( - types_v03.Task.model_validate(json_rpc_response.result) - ) + result = response_data['result'] + return conversions.to_core_task(types_v03.Task.model_validate(result)) async def list_tasks( self, @@ -202,13 +194,9 @@ async def cancel_task( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) + result = response_data['result'] - return conversions.to_core_task( - types_v03.Task.model_validate(json_rpc_response.result) - ) + return conversions.to_core_task(types_v03.Task.model_validate(result)) async def create_task_push_notification_config( self, @@ -232,14 +220,10 @@ async def create_task_push_notification_config( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) + result = response_data['result'] return conversions.to_core_task_push_notification_config( - types_v03.TaskPushNotificationConfig.model_validate( - json_rpc_response.result - ) + types_v03.TaskPushNotificationConfig.model_validate(result) ) async def get_task_push_notification_config( @@ -264,14 +248,10 @@ async def get_task_push_notification_config( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) + result = response_data['result'] return conversions.to_core_task_push_notification_config( - types_v03.TaskPushNotificationConfig.model_validate( - json_rpc_response.result - ) + types_v03.TaskPushNotificationConfig.model_validate(result) ) async def list_task_push_notification_configs( @@ -296,11 +276,7 @@ async def list_task_push_notification_configs( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) - - configs_data = json_rpc_response.result + configs_data = response_data['result'] if not isinstance(configs_data, list): return ListTaskPushNotificationConfigsResponse() @@ -334,15 +310,10 @@ async def delete_task_push_notification_config( ), _id=str(uuid4()), ) - response_data = await self._send_request( - dict(rpc_request.data), context + # A v0.3 server answers a successful delete with a null result. + await self._send_request( + dict(rpc_request.data), context, allow_null_result=True ) - if 'result' not in response_data and 'error' not in response_data: - response_data['result'] = None - - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) async def subscribe( self, @@ -386,12 +357,10 @@ async def get_extended_agent_card( response_data = await self._send_request( dict(rpc_request.data), context ) - json_rpc_response = JSONRPC20Response(**response_data) - if json_rpc_response.error: - raise self._create_jsonrpc_error(json_rpc_response.error) + result = response_data['result'] card = conversions.to_core_agent_card( - types_v03.AgentCard.model_validate(json_rpc_response.result) + types_v03.AgentCard.model_validate(result) ) self.agent_card = card return card @@ -423,6 +392,32 @@ def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception: return A2AClientError(message) + def _check_jsonrpc_response( + self, response_data: Any, *, allow_null_result: bool = False + ) -> dict[str, Any]: + """Returns a JSON-RPC success response, raising A2A errors otherwise. + + A missing or null ``result`` is accepted only with ``allow_null_result``. + """ + if not isinstance(response_data, dict): + raise A2AClientError( + 'Invalid JSON-RPC response: expected an object, got ' + f'{type(response_data).__name__}' + ) + error = response_data.get('error') + if error: + if not isinstance(error, dict): + raise A2AClientError( + f'Invalid JSON-RPC response: error is not an object: ' + f'{error!r}' + ) + raise self._create_jsonrpc_error(error) + if response_data.get('result') is None and not allow_null_result: + raise A2AClientError( + "Invalid JSON-RPC response: 'result' is missing or null" + ) + return response_data + def _handle_http_error(self, e: HTTPStatusError) -> NoReturn: """Handles HTTP errors for standard requests.""" raise A2AClientError(f'HTTP Error: {e.response.status_code}') from e @@ -493,8 +488,10 @@ async def _send_request( self, json_data: dict[str, Any], context: ClientCallContext | None = None, + *, + allow_null_result: bool = False, ) -> dict[str, Any]: - """Sends an HTTP request.""" + """Sends a JSON-RPC request and returns the checked success response.""" http_kwargs = get_http_args(context) http_kwargs.setdefault('headers', {}) http_kwargs['headers'][VERSION_HEADER.lower()] = PROTOCOL_VERSION_0_3 @@ -506,6 +503,9 @@ async def _send_request( json=json_data, **http_kwargs, ) - return await send_http_request( + response_data = await send_http_request( self.httpx_client, request, self._handle_http_error ) + return self._check_jsonrpc_response( + response_data, allow_null_result=allow_null_result + ) diff --git a/tests/compat/v0_3/test_jsonrpc_transport.py b/tests/compat/v0_3/test_jsonrpc_transport.py index 56a17e084..19514c8f2 100644 --- a/tests/compat/v0_3/test_jsonrpc_transport.py +++ b/tests/compat/v0_3/test_jsonrpc_transport.py @@ -26,7 +26,7 @@ TaskState, ) from a2a.utils._httpx_compat import httpx_lib -from a2a.utils.errors import InvalidParamsError +from a2a.utils.errors import InvalidParamsError, TaskNotFoundError pytestmark = pytest.mark.httpx2 @@ -570,3 +570,104 @@ async def test_compat_jsonrpc_transport_mirrors_extension_header( headers = kwargs['headers'] assert headers['A2A-Extensions'] == 'foo,bar' assert headers['X-A2A-Extensions'] == 'foo,bar' + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('response_data', 'expected_error'), + [ + ( + { + 'jsonrpc': '2.0', + 'id': '1', + 'error': {'code': -32001, 'message': 'No task', 'reason': 'x'}, + }, + TaskNotFoundError, + ), + ( + {'jsonrpc': '2.0', 'id': '1', 'error': {'code': -32001}}, + TaskNotFoundError, + ), + ({'jsonrpc': '2.0', 'id': '1', 'error': 'boom'}, A2AClientError), + ({'jsonrpc': '2.0', 'id': '1'}, A2AClientError), + ({'jsonrpc': '2.0', 'id': '1', 'result': None}, A2AClientError), + (['not', 'a', 'response'], A2AClientError), + ], +) +@patch('a2a.compat.v0_3.jsonrpc_transport.send_http_request') +async def test_compat_jsonrpc_transport_malformed_response( + mock_send_http_request, transport, response_data, expected_error +): + """Bodies the json-rpc package rejects raise A2A errors, not TypeError.""" + mock_send_http_request.return_value = response_data + + with pytest.raises(expected_error): + await transport.get_task(GetTaskRequest(id='task-123')) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'call', + [ + lambda t: t.send_message( + SendMessageRequest( + message=Message(message_id='msg-1', role=Role.ROLE_USER) + ) + ), + lambda t: t.cancel_task(CancelTaskRequest(id='task-123')), + lambda t: t.create_task_push_notification_config( + TaskPushNotificationConfig(task_id='task-123', id='push-123') + ), + lambda t: t.get_task_push_notification_config( + GetTaskPushNotificationConfigRequest( + task_id='task-123', id='push-123' + ) + ), + lambda t: t.list_task_push_notification_configs( + ListTaskPushNotificationConfigsRequest(task_id='task-123') + ), + lambda t: t.get_extended_agent_card(GetExtendedAgentCardRequest()), + ], + ids=[ + 'send_message', + 'cancel_task', + 'create_push_config', + 'get_push_config', + 'list_push_configs', + 'get_extended_agent_card', + ], +) +@patch('a2a.compat.v0_3.jsonrpc_transport.send_http_request') +async def test_compat_jsonrpc_transport_null_result( + mock_send_http_request, transport, call +): + """A null result is only valid for delete, so other methods reject it.""" + mock_send_http_request.return_value = { + 'jsonrpc': '2.0', + 'id': '1', + 'result': None, + } + + with pytest.raises(A2AClientError, match="'result' is missing or null"): + await call(transport) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'response_data', + [ + {'jsonrpc': '2.0', 'id': '1', 'result': None}, + {'jsonrpc': '2.0', 'id': '1'}, + ], + ids=['null_result', 'no_result'], +) +@patch('a2a.compat.v0_3.jsonrpc_transport.send_http_request') +async def test_compat_jsonrpc_transport_delete_push_config_null_result( + mock_send_http_request, transport, response_data +): + mock_send_http_request.return_value = response_data + + req = DeleteTaskPushNotificationConfigRequest( + task_id='task-123', id='push-123' + ) + assert await transport.delete_task_push_notification_config(req) is None