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
33 changes: 30 additions & 3 deletions src/a2a/client/transports/jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,30 @@
from a2a.client.errors import A2AClientError
from a2a.client.transports.base import ClientTransport
from a2a.client.transports.http_helpers import (
get_http_args,
send_http_request,
send_http_stream_request,
)
from a2a.types.a2a_pb2 import (
AgentCard,
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetExtendedAgentCardRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
ListTaskPushNotificationConfigsRequest,
ListTaskPushNotificationConfigsResponse,
ListTasksRequest,
ListTasksResponse,
SendMessageRequest,
SendMessageResponse,
StreamResponse,
SubscribeToTaskRequest,
Task,
TaskPushNotificationConfig,
)
from a2a.utils._httpx_compat import AsyncClient
from a2a.utils._httpx_compat import AsyncClient, HTTPStatusError
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP

Check notice on line 38 in src/a2a/client/transports/jsonrpc.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/client/transports/rest.py (17-39)
from a2a.utils.proto_utils import parse_lenient
from a2a.utils.telemetry import SpanKind, trace_class

Expand Down Expand Up @@ -325,9 +325,36 @@
request = self.httpx_client.build_request(
'POST', self.url, json=payload, **(http_kwargs or {})
)
response_data = await send_http_request(self.httpx_client, request)
response_data = await send_http_request(
self.httpx_client, request, self._handle_http_error
)
return self._check_jsonrpc_response(response_data)

def _handle_http_error(self, e: HTTPStatusError) -> NoReturn:
"""Raises the A2A error carried by a non-2xx JSON-RPC response.

Some servers send a JSON-RPC error object with a non-2xx status. Only
a JSON-RPC 2.0 error with a known A2A code is mapped; any other body,
such as a gateway's own error, raises the generic HTTP error.
"""
try:
body = e.response.json()
except ValueError: # Not JSON, or not valid UTF-8.
body = None
error = (
body.get('error')
if isinstance(body, dict) and body.get('jsonrpc') == '2.0'
else None
)
if isinstance(error, dict):
code = error.get('code')
if (
isinstance(code, int)
and code in _JSON_RPC_ERROR_CODE_TO_A2A_ERROR
):
raise self._create_jsonrpc_error(error) from e
raise A2AClientError(f'HTTP Error {e.response.status_code}: {e}') from e

def _check_jsonrpc_response(self, response_data: Any) -> dict[str, Any]:
"""Returns a JSON-RPC success response, raising for anything else.

Expand Down Expand Up @@ -368,7 +395,7 @@
self.httpx_client,
'POST',
self.url,
None,
self._handle_http_error,
self._handle_sse_error,
json=rpc_request_payload,
**http_kwargs,
Expand Down
121 changes: 120 additions & 1 deletion tests/client/transports/test_jsonrpc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@
TaskState,
)
from a2a.utils._httpx_compat import httpx_lib
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP, TaskNotFoundError
from a2a.utils.errors import (
JSON_RPC_ERROR_CODE_MAP,
InternalError,
TaskNotFoundError,
)
from google.protobuf import json_format


Expand Down Expand Up @@ -978,3 +982,118 @@ async def test_streaming_malformed_event_raises_a2a_error(
create_send_message_request()
):
pass


class TestJsonRpcErrorWithNonSuccessStatus:
"""A JSON-RPC error body maps to its A2A error whatever the HTTP status.

Some servers (e.g. a2a-js for internal errors) send the error object with
a non-2xx status. Bodies that are not JSON-RPC errors keep raising the
generic HTTP error.
"""

@staticmethod
def _error_body(code: int, message: str) -> dict[str, object]:
return {
'jsonrpc': '2.0',
'id': '1',
'error': {'code': code, 'message': message},
}

@pytest.mark.parametrize(
('status_code', 'code', 'expected_error'),
[
pytest.param(500, -32603, InternalError, id='500-internal'),
pytest.param(404, -32001, TaskNotFoundError, id='404-not-found'),
],
)
@pytest.mark.asyncio
async def test_unary_maps_error_body(
self,
agent_card: AgentCard,
status_code: int,
code: int,
expected_error: type[Exception],
) -> None:
body = self._error_body(code, 'server says why')
mock_transport = httpx_lib.MockTransport(
lambda request: httpx_lib.Response(status_code, json=body)
)
async with httpx_lib.AsyncClient(
transport=mock_transport
) as http_client:
transport = JsonRpcTransport(
http_client, agent_card, 'http://agent.example.com'
)
with pytest.raises(expected_error, match='server says why'):
await transport.get_task(GetTaskRequest(id='task-1'))

@pytest.mark.asyncio
async def test_streaming_maps_error_body(
self, agent_card: AgentCard
) -> None:
body = self._error_body(-32001, 'Task not found: task-1')
mock_transport = httpx_lib.MockTransport(
lambda request: httpx_lib.Response(404, json=body)
)
async with httpx_lib.AsyncClient(
transport=mock_transport
) as http_client:
transport = JsonRpcTransport(
http_client, agent_card, 'http://agent.example.com'
)
with pytest.raises(TaskNotFoundError, match='task-1'):
async for _ in transport.send_message_streaming(
create_send_message_request()
):
pass

@pytest.mark.parametrize(
'content',
[
pytest.param(b'<html>Bad Gateway</html>', id='html'),
pytest.param(b'{"detail": "upstream down"}', id='json-not-rpc'),
pytest.param(
json.dumps(
{'error': {'code': 429, 'status': 'RESOURCE_EXHAUSTED'}}
).encode(),
id='gateway-error-not-rpc',
),
pytest.param(
json.dumps(
{
'jsonrpc': '2.0',
'id': '1',
'error': {'code': -32050, 'message': 'overloaded'},
}
).encode(),
id='rpc-unknown-code',
),
pytest.param(
json.dumps({'jsonrpc': '2.0', 'id': '1', 'error': {}}).encode(),
id='rpc-empty-error',
),
],
)
@pytest.mark.parametrize('streaming', [False, True])
@pytest.mark.asyncio
async def test_other_bodies_raise_http_error(
self, agent_card: AgentCard, content: bytes, streaming: bool
) -> None:
mock_transport = httpx_lib.MockTransport(
lambda request: httpx_lib.Response(502, content=content)
)
async with httpx_lib.AsyncClient(
transport=mock_transport
) as http_client:
transport = JsonRpcTransport(
http_client, agent_card, 'http://agent.example.com'
)
with pytest.raises(A2AClientError, match='HTTP Error 502'):
if streaming:
async for _ in transport.send_message_streaming(
create_send_message_request()
):
pass
else:
await transport.get_task(GetTaskRequest(id='task-1'))
Loading