Skip to content

Commit 70eb4b4

Browse files
committed
fix(client): map JSON-RPC error bodies sent with a non-2xx HTTP status
JsonRpcTransport passed no status error handler to the shared HTTP helpers, so a JSON-RPC error object sent with a non-2xx status (a2a-js does this for internal errors) raised a generic "HTTP Error 500" A2AClientError and dropped the error code and message. Add JsonRpcTransport._handle_http_error, used by unary and streaming requests. A JSON-RPC 2.0 error with a known A2A code now raises the mapped error, as it already does with HTTP 200. Any other body keeps raising the same generic HTTP error as before. Signed-off-by: ArnabDutta01 <rickkdutta@gmail.com>
1 parent c76e640 commit 70eb4b4

2 files changed

Lines changed: 150 additions & 4 deletions

File tree

‎src/a2a/client/transports/jsonrpc.py‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
Task,
3535
TaskPushNotificationConfig,
3636
)
37-
from a2a.utils._httpx_compat import AsyncClient
37+
from a2a.utils._httpx_compat import AsyncClient, HTTPStatusError
3838
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP
3939
from a2a.utils.proto_utils import parse_lenient
4040
from a2a.utils.telemetry import SpanKind, trace_class
@@ -325,9 +325,36 @@ async def _send_request(
325325
request = self.httpx_client.build_request(
326326
'POST', self.url, json=payload, **(http_kwargs or {})
327327
)
328-
response_data = await send_http_request(self.httpx_client, request)
328+
response_data = await send_http_request(
329+
self.httpx_client, request, self._handle_http_error
330+
)
329331
return self._check_jsonrpc_response(response_data)
330332

333+
def _handle_http_error(self, e: HTTPStatusError) -> NoReturn:
334+
"""Raises the A2A error carried by a non-2xx JSON-RPC response.
335+
336+
Some servers send a JSON-RPC error object with a non-2xx status. Only
337+
a JSON-RPC 2.0 error with a known A2A code is mapped; any other body,
338+
such as a gateway's own error, raises the generic HTTP error.
339+
"""
340+
try:
341+
body = e.response.json()
342+
except ValueError: # Not JSON, or not valid UTF-8.
343+
body = None
344+
error = (
345+
body.get('error')
346+
if isinstance(body, dict) and body.get('jsonrpc') == '2.0'
347+
else None
348+
)
349+
if isinstance(error, dict):
350+
code = error.get('code')
351+
if (
352+
isinstance(code, int)
353+
and code in _JSON_RPC_ERROR_CODE_TO_A2A_ERROR
354+
):
355+
raise self._create_jsonrpc_error(error) from e
356+
raise A2AClientError(f'HTTP Error {e.response.status_code}: {e}') from e
357+
331358
def _check_jsonrpc_response(self, response_data: Any) -> dict[str, Any]:
332359
"""Returns a JSON-RPC success response, raising for anything else.
333360
@@ -368,7 +395,7 @@ async def _send_stream_request(
368395
self.httpx_client,
369396
'POST',
370397
self.url,
371-
None,
398+
self._handle_http_error,
372399
self._handle_sse_error,
373400
json=rpc_request_payload,
374401
**http_kwargs,

‎tests/client/transports/test_jsonrpc_client.py‎

Lines changed: 120 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@
3030
TaskState,
3131
)
3232
from a2a.utils._httpx_compat import httpx_lib
33-
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP, TaskNotFoundError
33+
from a2a.utils.errors import (
34+
JSON_RPC_ERROR_CODE_MAP,
35+
InternalError,
36+
TaskNotFoundError,
37+
)
3438
from google.protobuf import json_format
3539

3640

@@ -978,3 +982,118 @@ async def test_streaming_malformed_event_raises_a2a_error(
978982
create_send_message_request()
979983
):
980984
pass
985+
986+
987+
class TestJsonRpcErrorWithNonSuccessStatus:
988+
"""A JSON-RPC error body maps to its A2A error whatever the HTTP status.
989+
990+
Some servers (e.g. a2a-js for internal errors) send the error object with
991+
a non-2xx status. Bodies that are not JSON-RPC errors keep raising the
992+
generic HTTP error.
993+
"""
994+
995+
@staticmethod
996+
def _error_body(code: int, message: str) -> dict[str, object]:
997+
return {
998+
'jsonrpc': '2.0',
999+
'id': '1',
1000+
'error': {'code': code, 'message': message},
1001+
}
1002+
1003+
@pytest.mark.parametrize(
1004+
('status_code', 'code', 'expected_error'),
1005+
[
1006+
pytest.param(500, -32603, InternalError, id='500-internal'),
1007+
pytest.param(404, -32001, TaskNotFoundError, id='404-not-found'),
1008+
],
1009+
)
1010+
@pytest.mark.asyncio
1011+
async def test_unary_maps_error_body(
1012+
self,
1013+
agent_card: AgentCard,
1014+
status_code: int,
1015+
code: int,
1016+
expected_error: type[Exception],
1017+
) -> None:
1018+
body = self._error_body(code, 'server says why')
1019+
mock_transport = httpx_lib.MockTransport(
1020+
lambda request: httpx_lib.Response(status_code, json=body)
1021+
)
1022+
async with httpx_lib.AsyncClient(
1023+
transport=mock_transport
1024+
) as http_client:
1025+
transport = JsonRpcTransport(
1026+
http_client, agent_card, 'http://agent.example.com'
1027+
)
1028+
with pytest.raises(expected_error, match='server says why'):
1029+
await transport.get_task(GetTaskRequest(id='task-1'))
1030+
1031+
@pytest.mark.asyncio
1032+
async def test_streaming_maps_error_body(
1033+
self, agent_card: AgentCard
1034+
) -> None:
1035+
body = self._error_body(-32001, 'Task not found: task-1')
1036+
mock_transport = httpx_lib.MockTransport(
1037+
lambda request: httpx_lib.Response(404, json=body)
1038+
)
1039+
async with httpx_lib.AsyncClient(
1040+
transport=mock_transport
1041+
) as http_client:
1042+
transport = JsonRpcTransport(
1043+
http_client, agent_card, 'http://agent.example.com'
1044+
)
1045+
with pytest.raises(TaskNotFoundError, match='task-1'):
1046+
async for _ in transport.send_message_streaming(
1047+
create_send_message_request()
1048+
):
1049+
pass
1050+
1051+
@pytest.mark.parametrize(
1052+
'content',
1053+
[
1054+
pytest.param(b'<html>Bad Gateway</html>', id='html'),
1055+
pytest.param(b'{"detail": "upstream down"}', id='json-not-rpc'),
1056+
pytest.param(
1057+
json.dumps(
1058+
{'error': {'code': 429, 'status': 'RESOURCE_EXHAUSTED'}}
1059+
).encode(),
1060+
id='gateway-error-not-rpc',
1061+
),
1062+
pytest.param(
1063+
json.dumps(
1064+
{
1065+
'jsonrpc': '2.0',
1066+
'id': '1',
1067+
'error': {'code': -32050, 'message': 'overloaded'},
1068+
}
1069+
).encode(),
1070+
id='rpc-unknown-code',
1071+
),
1072+
pytest.param(
1073+
json.dumps({'jsonrpc': '2.0', 'id': '1', 'error': {}}).encode(),
1074+
id='rpc-empty-error',
1075+
),
1076+
],
1077+
)
1078+
@pytest.mark.parametrize('streaming', [False, True])
1079+
@pytest.mark.asyncio
1080+
async def test_other_bodies_raise_http_error(
1081+
self, agent_card: AgentCard, content: bytes, streaming: bool
1082+
) -> None:
1083+
mock_transport = httpx_lib.MockTransport(
1084+
lambda request: httpx_lib.Response(502, content=content)
1085+
)
1086+
async with httpx_lib.AsyncClient(
1087+
transport=mock_transport
1088+
) as http_client:
1089+
transport = JsonRpcTransport(
1090+
http_client, agent_card, 'http://agent.example.com'
1091+
)
1092+
with pytest.raises(A2AClientError, match='HTTP Error 502'):
1093+
if streaming:
1094+
async for _ in transport.send_message_streaming(
1095+
create_send_message_request()
1096+
):
1097+
pass
1098+
else:
1099+
await transport.get_task(GetTaskRequest(id='task-1'))

0 commit comments

Comments
 (0)