Skip to content

Commit 3ce65c5

Browse files
authored
fix(errors): emit JSON-RPC error.data as typed-details array per A2A 1.0 spec hot-fix (a2aproject#1058)
# Description Aligns the JSON-RPC and REST transports with the A2A 1.0 spec hot-fix which makes `error.data` (JSON-RPC) and `error.details` (REST) carry an array of typed-detail objects using the ProtoJSON `Any` representation. ## Server side `build_error_response` and `build_rest_error_payload` now emit a leading `google.rpc.ErrorInfo` carrying the canonical A2A reason and `error.data` as `metadata`. For `InvalidParamsError` with validation details, both transports also append a `google.rpc.BadRequest` ## Client side The JSON-RPC client now extracts `ErrorInfo.metadata` from the array onto `A2AError.data`. Also adds the missing `JSONParseError(-32700)` exception class so JSON-RPC clients receive a typed exception for the standard parse-error code instead of falling back to a generic `A2AClientError`. Fixes a2aproject#1027. 🦕
1 parent 03699a8 commit 3ce65c5

8 files changed

Lines changed: 330 additions & 49 deletions

File tree

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
_JSON_RPC_ERROR_CODE_TO_A2A_ERROR = {
4545
code: error_type for error_type, code in JSON_RPC_ERROR_CODE_MAP.items()
4646
}
47+
_ERROR_INFO_TYPE = 'type.googleapis.com/google.rpc.ErrorInfo'
4748

4849

4950
@trace_class(kind=SpanKind.CLIENT)
@@ -318,10 +319,19 @@ def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception:
318319
"""Creates the appropriate A2AError from a JSON-RPC error dictionary."""
319320
code = error_dict.get('code')
320321
message = error_dict.get('message', str(error_dict))
321-
data = error_dict.get('data')
322+
raw_data = error_dict.get('data')
323+
324+
a2a_data: dict[str, Any] | None = None
325+
if isinstance(raw_data, list):
326+
for d in raw_data:
327+
if isinstance(d, dict) and d.get('@type') == _ERROR_INFO_TYPE:
328+
a2a_data = d.get('metadata') or None
329+
break
322330

323331
if isinstance(code, int) and code in _JSON_RPC_ERROR_CODE_TO_A2A_ERROR:
324-
return _JSON_RPC_ERROR_CODE_TO_A2A_ERROR[code](message, data=data)
332+
return _JSON_RPC_ERROR_CODE_TO_A2A_ERROR[code](
333+
message, data=a2a_data
334+
)
325335

326336
# Fallback to general A2AClientError
327337
return A2AClientError(f'JSON-RPC Error {code}: {message}')

‎src/a2a/server/request_handlers/response_helpers.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from a2a.types.a2a_pb2 import (
2727
SendMessageResponse as SendMessageResponseProto,
2828
)
29+
from a2a.utils.error_handlers import build_error_details
2930
from a2a.utils.errors import (
3031
JSON_RPC_ERROR_CODE_MAP,
3132
A2AError,
@@ -135,7 +136,7 @@ def build_error_response(
135136
jsonrpc_error = model_class(
136137
code=code,
137138
message=str(error),
138-
data=error.data,
139+
data=build_error_details(error),
139140
)
140141
else:
141142
jsonrpc_error = JSONRPCInternalError(message=str(error))

‎src/a2a/utils/error_handlers.py‎

Lines changed: 65 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,41 +16,85 @@
1616
Response = Any
1717

1818

19-
from google.protobuf.json_format import ParseError
19+
from google.protobuf.json_format import MessageToDict, ParseError
2020

2121
from a2a.utils.errors import (
22-
A2A_REST_ERROR_MAPPING,
22+
A2A_ERROR_MAPPING,
23+
A2A_ERROR_REASONS,
2324
A2AError,
25+
ErrorMapping,
2426
InternalError,
25-
RestErrorMap,
27+
InvalidParamsError,
2628
)
29+
from a2a.utils.proto_utils import validation_errors_to_bad_request
2730

2831

2932
logger = logging.getLogger(__name__)
3033

3134

35+
ERROR_INFO_TYPE = 'type.googleapis.com/google.rpc.ErrorInfo'
36+
BAD_REQUEST_TYPE = 'type.googleapis.com/google.rpc.BadRequest'
37+
A2A_DOMAIN = 'a2a-protocol.org'
38+
39+
40+
def _error_info(
41+
reason: str, metadata: dict[str, Any] | None = None
42+
) -> dict[str, Any]:
43+
"""Build a single ``google.rpc.ErrorInfo`` typed-detail object."""
44+
return {
45+
'@type': ERROR_INFO_TYPE,
46+
'reason': reason,
47+
'domain': A2A_DOMAIN,
48+
'metadata': metadata if metadata is not None else {},
49+
}
50+
51+
52+
def build_error_details(error: A2AError) -> list[dict[str, Any]]:
53+
"""Build the typed-details array for an :class:`A2AError`.
54+
55+
Always emits a leading ``google.rpc.ErrorInfo`` carrying the A2A reason
56+
and ``error.data`` as ``metadata``. For `InvalidParamsError` whose ``data``
57+
contains an ``errors`` list of validation details, also appends
58+
a ``google.rpc.BadRequest`` so all transports surface field-level
59+
violations identically.
60+
"""
61+
reason = A2A_ERROR_REASONS.get(type(error), 'UNKNOWN_ERROR')
62+
metadata = error.data if isinstance(error.data, dict) else {}
63+
details: list[dict[str, Any]] = [_error_info(reason, metadata)]
64+
65+
if (
66+
isinstance(error, InvalidParamsError)
67+
and isinstance(error.data, dict)
68+
and error.data.get('errors')
69+
):
70+
bad_request_dict = MessageToDict(
71+
validation_errors_to_bad_request(error.data['errors']),
72+
preserving_proto_field_name=False,
73+
)
74+
details.append(
75+
{
76+
'@type': BAD_REQUEST_TYPE,
77+
'fieldViolations': bad_request_dict.get('fieldViolations', []),
78+
}
79+
)
80+
81+
return details
82+
83+
3284
def _build_error_payload(
3385
code: int,
3486
status: str,
3587
message: str,
36-
reason: str | None = None,
37-
metadata: dict[str, Any] | None = None,
88+
details: list[dict[str, Any]] | None = None,
3889
) -> dict[str, Any]:
3990
"""Helper function to build the JSON error payload."""
4091
payload: dict[str, Any] = {
4192
'code': code,
4293
'status': status,
4394
'message': message,
4495
}
45-
if reason:
46-
payload['details'] = [
47-
{
48-
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
49-
'reason': reason,
50-
'domain': 'a2a-protocol.org',
51-
'metadata': metadata if metadata is not None else {},
52-
}
53-
]
96+
if details:
97+
payload['details'] = details
5498
return {'error': payload}
5599

56100

@@ -61,25 +105,24 @@ def build_rest_error_payload(error: Exception) -> dict[str, Any]:
61105
A dict with the error payload in the standard REST error format.
62106
"""
63107
if isinstance(error, A2AError):
64-
mapping = A2A_REST_ERROR_MAPPING.get(
65-
type(error), RestErrorMap(500, 'INTERNAL', 'INTERNAL_ERROR')
108+
mapping = A2A_ERROR_MAPPING.get(
109+
type(error), ErrorMapping(500, 'INTERNAL', 'INTERNAL_ERROR')
66110
)
67-
# SECURITY WARNING: Data attached to A2AError.data is serialized unaltered and exposed publicly to the client in the REST API response.
68-
metadata = getattr(error, 'data', None) or {}
111+
# SECURITY WARNING: Data attached to A2AError.data is serialized
112+
# unaltered and exposed publicly to the client in the REST API
113+
# response (as ErrorInfo.metadata).
69114
return _build_error_payload(
70115
code=mapping.http_code,
71116
status=mapping.grpc_status,
72117
message=getattr(error, 'message', str(error)),
73-
reason=mapping.reason,
74-
metadata=metadata,
118+
details=build_error_details(error),
75119
)
76120
if isinstance(error, ParseError):
77121
return _build_error_payload(
78122
code=400,
79123
status='INVALID_ARGUMENT',
80124
message=str(error),
81-
reason='INVALID_REQUEST',
82-
metadata={},
125+
details=[_error_info('INVALID_REQUEST')],
83126
)
84127
return _build_error_payload(
85128
code=500,

‎src/a2a/utils/errors.py‎

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from typing import NamedTuple
88

99

10-
class RestErrorMap(NamedTuple):
10+
class ErrorMapping(NamedTuple):
1111
"""Named tuple mapping HTTP status, gRPC status, and reason strings."""
1212

1313
http_code: int
@@ -94,6 +94,12 @@ class MethodNotFoundError(A2AError):
9494
message = 'Method not found'
9595

9696

97+
class JSONParseError(A2AError):
98+
"""Exception raised when invalid JSON was received by the server."""
99+
100+
message = 'Invalid JSON payload'
101+
102+
97103
class ExtensionSupportRequiredError(A2AError):
98104
"""Exception raised when extension support is required but not present."""
99105

@@ -106,22 +112,21 @@ class VersionNotSupportedError(A2AError):
106112
message = 'Version not supported'
107113

108114

109-
# For backward compatibility if needed, or just aliases for clean refactor
110-
# We remove the Pydantic models here.
111-
112115
__all__ = [
116+
'A2A_ERROR_MAPPING',
113117
'A2A_ERROR_REASONS',
114118
'A2A_REASON_TO_ERROR',
115119
'A2A_REST_ERROR_MAPPING',
116120
'JSON_RPC_ERROR_CODE_MAP',
121+
'ErrorMapping',
117122
'ExtensionSupportRequiredError',
118123
'InternalError',
119124
'InvalidAgentResponseError',
120125
'InvalidParamsError',
121126
'InvalidRequestError',
127+
'JSONParseError',
122128
'MethodNotFoundError',
123129
'PushNotificationNotSupportedError',
124-
'RestErrorMap',
125130
'TaskNotCancelableError',
126131
'TaskNotFoundError',
127132
'UnsupportedOperationError',
@@ -143,56 +148,62 @@ class VersionNotSupportedError(A2AError):
143148
InvalidRequestError: -32600,
144149
MethodNotFoundError: -32601,
145150
InternalError: -32603,
151+
JSONParseError: -32700,
146152
}
147153

148154

149-
A2A_REST_ERROR_MAPPING: dict[type[A2AError], RestErrorMap] = {
150-
TaskNotFoundError: RestErrorMap(404, 'NOT_FOUND', 'TASK_NOT_FOUND'),
151-
TaskNotCancelableError: RestErrorMap(
155+
A2A_ERROR_MAPPING: dict[type[A2AError], ErrorMapping] = {
156+
TaskNotFoundError: ErrorMapping(404, 'NOT_FOUND', 'TASK_NOT_FOUND'),
157+
TaskNotCancelableError: ErrorMapping(
152158
400, 'FAILED_PRECONDITION', 'TASK_NOT_CANCELABLE'
153159
),
154-
PushNotificationNotSupportedError: RestErrorMap(
160+
PushNotificationNotSupportedError: ErrorMapping(
155161
400,
156162
'FAILED_PRECONDITION',
157163
'PUSH_NOTIFICATION_NOT_SUPPORTED',
158164
),
159-
UnsupportedOperationError: RestErrorMap(
165+
UnsupportedOperationError: ErrorMapping(
160166
400, 'FAILED_PRECONDITION', 'UNSUPPORTED_OPERATION'
161167
),
162-
ContentTypeNotSupportedError: RestErrorMap(
168+
ContentTypeNotSupportedError: ErrorMapping(
163169
400,
164170
'INVALID_ARGUMENT',
165171
'CONTENT_TYPE_NOT_SUPPORTED',
166172
),
167-
InvalidAgentResponseError: RestErrorMap(
173+
InvalidAgentResponseError: ErrorMapping(
168174
500, 'INTERNAL', 'INVALID_AGENT_RESPONSE'
169175
),
170-
ExtendedAgentCardNotConfiguredError: RestErrorMap(
176+
ExtendedAgentCardNotConfiguredError: ErrorMapping(
171177
400,
172178
'FAILED_PRECONDITION',
173179
'EXTENDED_AGENT_CARD_NOT_CONFIGURED',
174180
),
175-
ExtensionSupportRequiredError: RestErrorMap(
181+
ExtensionSupportRequiredError: ErrorMapping(
176182
400,
177183
'FAILED_PRECONDITION',
178184
'EXTENSION_SUPPORT_REQUIRED',
179185
),
180-
VersionNotSupportedError: RestErrorMap(
186+
VersionNotSupportedError: ErrorMapping(
181187
400, 'FAILED_PRECONDITION', 'VERSION_NOT_SUPPORTED'
182188
),
183-
InvalidParamsError: RestErrorMap(400, 'INVALID_ARGUMENT', 'INVALID_PARAMS'),
184-
InvalidRequestError: RestErrorMap(
189+
InvalidParamsError: ErrorMapping(400, 'INVALID_ARGUMENT', 'INVALID_PARAMS'),
190+
InvalidRequestError: ErrorMapping(
185191
400, 'INVALID_ARGUMENT', 'INVALID_REQUEST'
186192
),
187-
MethodNotFoundError: RestErrorMap(404, 'NOT_FOUND', 'METHOD_NOT_FOUND'),
188-
InternalError: RestErrorMap(500, 'INTERNAL', 'INTERNAL_ERROR'),
193+
MethodNotFoundError: ErrorMapping(404, 'NOT_FOUND', 'METHOD_NOT_FOUND'),
194+
InternalError: ErrorMapping(500, 'INTERNAL', 'INTERNAL_ERROR'),
189195
}
190196

191197

198+
# Deprecated alias kept for backwards compatibility; remove in the next
199+
# major version.
200+
A2A_REST_ERROR_MAPPING = A2A_ERROR_MAPPING
201+
202+
192203
A2A_ERROR_REASONS = {
193-
cls: mapping.reason for cls, mapping in A2A_REST_ERROR_MAPPING.items()
204+
cls: mapping.reason for cls, mapping in A2A_ERROR_MAPPING.items()
194205
}
195206

196207
A2A_REASON_TO_ERROR = {
197-
mapping.reason: cls for cls, mapping in A2A_REST_ERROR_MAPPING.items()
208+
mapping.reason: cls for cls, mapping in A2A_ERROR_MAPPING.items()
198209
}

‎tests/client/transports/test_jsonrpc_client.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,3 +684,87 @@ async def test_get_card_with_extended_card_support_with_extensions(
684684
assert mock_kwargs.service_parameters == {
685685
HTTP_EXTENSION_HEADER: extensions_header_val
686686
}
687+
688+
689+
class TestCreateJsonRpcError:
690+
"""Unit tests for JsonRpcTransport._create_jsonrpc_error."""
691+
692+
@pytest.fixture
693+
def transport(self, mock_httpx_client, agent_card):
694+
return JsonRpcTransport(
695+
httpx_client=mock_httpx_client,
696+
agent_card=agent_card,
697+
url='http://test-agent.example.com',
698+
)
699+
700+
def test_lifts_error_info_metadata_onto_a2a_error_data(
701+
self, transport
702+
) -> None:
703+
"""New spec format: ErrorInfo.metadata is exposed as A2AError.data."""
704+
from a2a.utils.errors import TaskNotFoundError
705+
706+
exc = transport._create_jsonrpc_error(
707+
{
708+
'code': -32001,
709+
'message': 'Task not found',
710+
'data': [
711+
{
712+
'@type': ('type.googleapis.com/google.rpc.ErrorInfo'),
713+
'reason': 'TASK_NOT_FOUND',
714+
'domain': 'a2a-protocol.org',
715+
'metadata': {'taskId': 'abc-123'},
716+
}
717+
],
718+
}
719+
)
720+
assert isinstance(exc, TaskNotFoundError)
721+
assert exc.message == 'Task not found'
722+
assert exc.data == {'taskId': 'abc-123'}
723+
724+
def test_no_data_field_yields_none_data(self, transport) -> None:
725+
from a2a.utils.errors import InternalError
726+
727+
exc = transport._create_jsonrpc_error(
728+
{'code': -32603, 'message': 'oops'}
729+
)
730+
assert isinstance(exc, InternalError)
731+
assert exc.data is None
732+
733+
def test_array_without_error_info_yields_none_data(self, transport) -> None:
734+
"""A details array carrying only BadRequest (no ErrorInfo) yields None."""
735+
from a2a.utils.errors import InvalidParamsError
736+
737+
exc = transport._create_jsonrpc_error(
738+
{
739+
'code': -32602,
740+
'message': 'bad params',
741+
'data': [
742+
{
743+
'@type': ('type.googleapis.com/google.rpc.BadRequest'),
744+
'fieldViolations': [],
745+
}
746+
],
747+
}
748+
)
749+
assert isinstance(exc, InvalidParamsError)
750+
assert exc.data is None
751+
752+
def test_unknown_code_falls_back_to_a2a_client_error(
753+
self, transport
754+
) -> None:
755+
exc = transport._create_jsonrpc_error(
756+
{'code': -42, 'message': 'who knows'}
757+
)
758+
assert isinstance(exc, A2AClientError)
759+
assert 'JSON-RPC Error -42' in str(exc)
760+
761+
def test_json_parse_error_is_typed(self, transport) -> None:
762+
"""JSON-RPC -32700 must map to a typed JSONParseError exception (not
763+
the generic A2AClientError fallback)."""
764+
from a2a.utils.errors import JSONParseError
765+
766+
exc = transport._create_jsonrpc_error(
767+
{'code': -32700, 'message': 'Invalid JSON payload'}
768+
)
769+
assert isinstance(exc, JSONParseError)
770+
assert exc.message == 'Invalid JSON payload'

0 commit comments

Comments
 (0)