From 0338a01d7a9403b1d8b7e40862762ff2fec9d6ad Mon Sep 17 00:00:00 2001 From: Shivam Sharma <192242476+ShivamSharma43@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:46:27 +0530 Subject: [PATCH 1/2] fix(compat): raise A2A errors for malformed v0.3 JSON-RPC responses CompatJsonRpcTransport parsed every unary response with the json-rpc package's JSONRPC20Response(**response_data). That package validates the envelope with its own exceptions, so an error object with an extra member or without a message, an error that is not an object, a body with neither result nor error, or a body that is not an object reached the caller as TypeError or ValueError instead of the mapped A2A error or A2AClientError. Check the response with a _get_jsonrpc_result helper instead, as JsonRpcTransport does since #1375. Delete still accepts a body with neither result nor error. Co-Authored-By: Claude Opus 5.5 --- src/a2a/compat/v0_3/jsonrpc_transport.py | 91 +++++++++++---------- tests/compat/v0_3/test_jsonrpc_transport.py | 47 ++++++++++- 2 files changed, 92 insertions(+), 46 deletions(-) diff --git a/src/a2a/compat/v0_3/jsonrpc_transport.py b/src/a2a/compat/v0_3/jsonrpc_transport.py index 9e83168a1..376254f37 100644 --- a/src/a2a/compat/v0_3/jsonrpc_transport.py +++ b/src/a2a/compat/v0_3/jsonrpc_transport.py @@ -7,7 +7,7 @@ import httpx -from jsonrpc.jsonrpc2 import JSONRPC20Request, JSONRPC20Response +from jsonrpc.jsonrpc2 import JSONRPC20Request from a2a.client.client import ClientCallContext from a2a.client.errors import A2AClientError @@ -89,11 +89,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 = self._get_jsonrpc_result(response_data) if not isinstance(result_dict, dict): return SendMessageResponse() @@ -164,12 +160,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 = self._get_jsonrpc_result(response_data) + return conversions.to_core_task(types_v03.Task.model_validate(result)) async def list_tasks( self, @@ -203,13 +195,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 = self._get_jsonrpc_result(response_data) - 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, @@ -233,14 +221,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 = self._get_jsonrpc_result(response_data) 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( @@ -265,14 +249,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 = self._get_jsonrpc_result(response_data) 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( @@ -297,11 +277,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 = self._get_jsonrpc_result(response_data) if not isinstance(configs_data, list): return ListTaskPushNotificationConfigsResponse() @@ -338,12 +314,7 @@ async def delete_task_push_notification_config( response_data = await self._send_request( dict(rpc_request.data), context ) - 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) + self._get_jsonrpc_result(response_data, result_required=False) async def subscribe( self, @@ -387,12 +358,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 = self._get_jsonrpc_result(response_data) 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 @@ -424,6 +393,38 @@ def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception: return A2AClientError(message) + def _get_jsonrpc_result( + self, response_data: Any, *, result_required: bool = True + ) -> Any: + """Returns the result of a JSON-RPC success response, raising for anything else. + + An error response raises the A2A error mapped from its code, even when + the error object lacks a ``message`` or carries extra members. A body + that is not a JSON-RPC 2.0 response object (a list, a string, an object + with neither ``result`` nor ``error``, or an ``error`` that is not an + object) raises ``A2AClientError`` instead of leaking a ``TypeError`` or + ``ValueError`` from the ``json-rpc`` package. With + ``result_required=False``, a body with neither member returns ``None``. + """ + 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 result_required and 'result' not in response_data: + raise A2AClientError( + "Invalid JSON-RPC response: it has neither 'result' nor 'error'" + ) + return response_data.get('result') + def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn: """Handles HTTP errors for standard requests.""" raise A2AClientError(f'HTTP Error: {e.response.status_code}') from e diff --git a/tests/compat/v0_3/test_jsonrpc_transport.py b/tests/compat/v0_3/test_jsonrpc_transport.py index 13d91162a..cac1c9f99 100644 --- a/tests/compat/v0_3/test_jsonrpc_transport.py +++ b/tests/compat/v0_3/test_jsonrpc_transport.py @@ -26,7 +26,7 @@ TaskPushNotificationConfig, TaskState, ) -from a2a.utils.errors import InvalidParamsError +from a2a.utils.errors import InvalidParamsError, TaskNotFoundError @pytest.fixture @@ -567,3 +567,48 @@ 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), + (['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 +@patch('a2a.compat.v0_3.jsonrpc_transport.send_http_request') +async def test_compat_jsonrpc_transport_delete_push_config_without_result( + mock_send_http_request, transport +): + mock_send_http_request.return_value = {'jsonrpc': '2.0', 'id': '1'} + + req = DeleteTaskPushNotificationConfigRequest( + task_id='task-123', id='push-123' + ) + assert await transport.delete_task_push_notification_config(req) is None From 21f43e41a63394d7048839f035461ff2c8a70c58 Mon Sep 17 00:00:00 2001 From: Shivam Sharma <192242476+ShivamSharma43@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:11:18 +0530 Subject: [PATCH 2/2] fix(compat): reject null v0.3 JSON-RPC results outside delete Check the response envelope once in _send_request instead of in every method. A missing or null result now raises A2AClientError instead of reaching model_validate, except for tasks/pushNotificationConfig/delete, whose v0.3 success response carries a null result. Co-Authored-By: Claude Opus 5.5 --- src/a2a/compat/v0_3/jsonrpc_transport.py | 53 +++++++++--------- tests/compat/v0_3/test_jsonrpc_transport.py | 62 ++++++++++++++++++++- 2 files changed, 85 insertions(+), 30 deletions(-) diff --git a/src/a2a/compat/v0_3/jsonrpc_transport.py b/src/a2a/compat/v0_3/jsonrpc_transport.py index 0e64e71b3..469f0ae8f 100644 --- a/src/a2a/compat/v0_3/jsonrpc_transport.py +++ b/src/a2a/compat/v0_3/jsonrpc_transport.py @@ -88,7 +88,7 @@ async def send_message( response_data = await self._send_request( dict(rpc_request.data), context ) - result_dict = self._get_jsonrpc_result(response_data) + result_dict = response_data['result'] if not isinstance(result_dict, dict): return SendMessageResponse() @@ -159,7 +159,7 @@ async def get_task( response_data = await self._send_request( dict(rpc_request.data), context ) - result = self._get_jsonrpc_result(response_data) + result = response_data['result'] return conversions.to_core_task(types_v03.Task.model_validate(result)) async def list_tasks( @@ -194,7 +194,7 @@ async def cancel_task( response_data = await self._send_request( dict(rpc_request.data), context ) - result = self._get_jsonrpc_result(response_data) + result = response_data['result'] return conversions.to_core_task(types_v03.Task.model_validate(result)) @@ -220,7 +220,7 @@ async def create_task_push_notification_config( response_data = await self._send_request( dict(rpc_request.data), context ) - result = self._get_jsonrpc_result(response_data) + result = response_data['result'] return conversions.to_core_task_push_notification_config( types_v03.TaskPushNotificationConfig.model_validate(result) @@ -248,7 +248,7 @@ async def get_task_push_notification_config( response_data = await self._send_request( dict(rpc_request.data), context ) - result = self._get_jsonrpc_result(response_data) + result = response_data['result'] return conversions.to_core_task_push_notification_config( types_v03.TaskPushNotificationConfig.model_validate(result) @@ -276,7 +276,7 @@ async def list_task_push_notification_configs( response_data = await self._send_request( dict(rpc_request.data), context ) - configs_data = self._get_jsonrpc_result(response_data) + configs_data = response_data['result'] if not isinstance(configs_data, list): return ListTaskPushNotificationConfigsResponse() @@ -310,10 +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 ) - self._get_jsonrpc_result(response_data, result_required=False) async def subscribe( self, @@ -357,7 +357,7 @@ async def get_extended_agent_card( response_data = await self._send_request( dict(rpc_request.data), context ) - result = self._get_jsonrpc_result(response_data) + result = response_data['result'] card = conversions.to_core_agent_card( types_v03.AgentCard.model_validate(result) @@ -392,18 +392,12 @@ def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception: return A2AClientError(message) - def _get_jsonrpc_result( - self, response_data: Any, *, result_required: bool = True - ) -> Any: - """Returns the result of a JSON-RPC success response, raising for anything else. - - An error response raises the A2A error mapped from its code, even when - the error object lacks a ``message`` or carries extra members. A body - that is not a JSON-RPC 2.0 response object (a list, a string, an object - with neither ``result`` nor ``error``, or an ``error`` that is not an - object) raises ``A2AClientError`` instead of leaking a ``TypeError`` or - ``ValueError`` from the ``json-rpc`` package. With - ``result_required=False``, a body with neither member returns ``None``. + 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( @@ -418,11 +412,11 @@ def _get_jsonrpc_result( f'{error!r}' ) raise self._create_jsonrpc_error(error) - if result_required and 'result' not in response_data: + if response_data.get('result') is None and not allow_null_result: raise A2AClientError( - "Invalid JSON-RPC response: it has neither 'result' nor 'error'" + "Invalid JSON-RPC response: 'result' is missing or null" ) - return response_data.get('result') + return response_data def _handle_http_error(self, e: HTTPStatusError) -> NoReturn: """Handles HTTP errors for standard requests.""" @@ -494,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 @@ -507,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 b3bb3905a..19514c8f2 100644 --- a/tests/compat/v0_3/test_jsonrpc_transport.py +++ b/tests/compat/v0_3/test_jsonrpc_transport.py @@ -590,6 +590,7 @@ async def test_compat_jsonrpc_transport_mirrors_extension_header( ), ({'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), ], ) @@ -605,11 +606,66 @@ async def test_compat_jsonrpc_transport_malformed_response( @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_delete_push_config_without_result( - mock_send_http_request, transport +async def test_compat_jsonrpc_transport_null_result( + mock_send_http_request, transport, call ): - mock_send_http_request.return_value = {'jsonrpc': '2.0', 'id': '1'} + """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'