Skip to content

Commit 83f1cf8

Browse files
authored
fix(server): ignore unrecognized request fields and fix parse-error data shape (a2aproject#1273)
Two problems on the same code path. ## Unrecognized fields Spec [5.7](https://a2a-protocol.org/latest/specification/#57-field-presence-and-optionality): "Implementations **SHOULD** ignore unrecognized fields in messages, allowing for forward compatibility as the protocol evolves." Both dispatchers parsed strictly, so `ignore_unknown_fields` defaulted to `False` and a client one minor version ahead was rejected outright over a field this build has never heard of. Four call sites, one flag. The v0.3 compat handler was already lenient, so this brings 1.0 into line with it. ## The flag also covers enum values `ignore_unknown_fields` is not only about field names: protobuf applies the same rule one level down and accepts an unknown enum value, defaulting it to 0. A future `ROLE_SYSTEM` now arrives as `ROLE_UNSPECIFIED` instead of failing the request. That is the same forward-compatibility bargain and arguably what 5.7 is for, but it is a real widening and protobuf offers no way to take the field leniency without it. It is commented at the call site and pinned by a test, so it is a decision on the record rather than something to be rediscovered later. **Reviewers: this is the part worth a second opinion.** ## error.data was a bare string Spec [9.5](https://a2a-protocol.org/latest/specification/#95-json-rpc-error-handling) makes `error.data` an "array of objects, each containing a `@type` key", and every object in it "**MUST** include a `@type` key". Only the `A2AError` path runs `build_error_details`, which produces that array. The parse-failure branch constructed the pydantic JSON-RPC model instead, whose `data` is `Any`, so the raw ProtoJSON diagnostic went out as a bare string. Both parse-failure sites now raise the `A2AError`, and the diagnostic survives in `ErrorInfo.metadata` rather than being dropped. No ACTS test reaches this - the corpus cannot construct a request that fails ProtoJSON parsing and then inspect `data` - so it is a genuine MUST violation that conformance would not have caught either way. ## Three tests moved off payloads that leniency now accepts `{'message': 'should be an object'}` and `{'message': {'text': 'Hello'}}` both parse to an empty `Message` now, so they no longer stop at the parser. All three tests use mock handlers, which is why they saw it: they pin the parser layer with nothing behind it. Against a **real** handler, both payloads still answer `-32602`, from required-field validation one layer down. Verified before changing them: ``` message as string -> error -32602 Validation failed unknown key only -> error -32602 Validation failed valid + unknown -> OK ``` So the end-to-end contract is unchanged; what moved is which layer rejects. The tests now use a value of the wrong shape (`parts` as a string), which leniency does not excuse, and each carries a comment saying why. ## Result Clears `DM-EXTRA-001` (`should`, jsonrpc only), taking jsonrpc to zero failures at every level.
1 parent 83d7f5d commit 83f1cf8

5 files changed

Lines changed: 89 additions & 18 deletions

File tree

‎src/a2a/server/routes/jsonrpc_dispatcher.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@
1515
from a2a.server.events import Event
1616
from a2a.server.jsonrpc_models import (
1717
InternalError,
18-
InvalidParamsError,
19-
InvalidRequestError,
2018
JSONParseError,
2119
JSONRPCError,
2220
MethodNotFoundError,
@@ -45,6 +43,8 @@
4543
from a2a.utils import constants, json_utils, proto_utils
4644
from a2a.utils.errors import (
4745
A2AError,
46+
InvalidParamsError,
47+
InvalidRequestError,
4848
TaskNotFoundError,
4949
UnsupportedOperationError,
5050
)
@@ -256,7 +256,7 @@ async def handle_requests(self, request: Request) -> Response: # noqa: PLR0911,
256256
logger.exception('Failed to validate base JSON-RPC request')
257257
return self._generate_error_response(
258258
request_id,
259-
InvalidRequestError(data=str(e)),
259+
InvalidRequestError(data={'parseError': str(e)}),
260260
)
261261

262262
# 2) Route by method name; unknown -> -32601, known -> validate params (-32602 on failure)
@@ -287,14 +287,18 @@ async def handle_requests(self, request: Request) -> Response: # noqa: PLR0911,
287287
request_id, MethodNotFoundError()
288288
)
289289
try:
290-
# Parse the params field into the proto message type
290+
# Unknown fields are ignored for forward compatibility. The
291+
# flag also defaults unknown enum values to 0, which protobuf
292+
# gives no way to opt out of separately.
291293
params = body.get('params', {})
292-
specific_request = ParseDict(params, model_class())
294+
specific_request = ParseDict(
295+
params, model_class(), ignore_unknown_fields=True
296+
)
293297
except Exception as e:
294298
logger.exception('Failed to parse request params')
295299
return self._generate_error_response(
296300
request_id,
297-
InvalidParamsError(data=str(e)),
301+
InvalidParamsError(data={'parseError': str(e)}),
298302
)
299303

300304
# 3) Build call context and wrap the request for downstream handling

‎src/a2a/server/routes/rest_dispatcher.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ async def _handler(
163163
) -> a2a_pb2.SendMessageResponse:
164164
body = await request.body()
165165
params = a2a_pb2.SendMessageRequest()
166-
Parse(body, params)
166+
Parse(body, params, ignore_unknown_fields=True)
167167
task_or_message = await self.request_handler.on_message_send(
168168
params, context
169169
)
@@ -186,7 +186,7 @@ async def _handler(
186186
) -> AsyncIterator[dict[str, Any]]:
187187
body = await request.body()
188188
params = a2a_pb2.SendMessageRequest()
189-
Parse(body, params)
189+
Parse(body, params, ignore_unknown_fields=True)
190190
async for event in self.request_handler.on_message_send_stream(
191191
params, context
192192
):
@@ -298,7 +298,7 @@ async def _handler(
298298
) -> a2a_pb2.TaskPushNotificationConfig:
299299
body = await request.body()
300300
params = a2a_pb2.TaskPushNotificationConfig()
301-
Parse(body, params)
301+
Parse(body, params, ignore_unknown_fields=True)
302302
params.task_id = request.path_params['id']
303303
return await self.request_handler.on_create_task_push_notification_config(
304304
params, context

‎tests/integration/test_client_server_integration.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,7 +1104,11 @@ async def mock_send(*args, **kwargs):
11041104
'json': {
11051105
'jsonrpc': '2.0',
11061106
'method': 'SendMessage',
1107-
'params': {'message': 'should be an object'},
1107+
# A field of the wrong shape, not merely an unknown
1108+
# one: `{'message': 'a string'}` now parses to an empty
1109+
# Message and is rejected by the handler's required-field
1110+
# validation, which a mock handler does not run.
1111+
'params': {'message': {'parts': 'should be a list'}},
11081112
'id': 1,
11091113
}
11101114
},
@@ -1146,7 +1150,8 @@ async def test_jsonrpc_malformed_payload(
11461150
pytest.param(
11471151
'POST',
11481152
'/message:send',
1149-
{'json': {'message': 'should be an object'}},
1153+
# Wrong shape rather than an unknown name; see the JSON-RPC case.
1154+
{'json': {'message': {'parts': 'should be a list'}}},
11501155
id='wrong-body-type',
11511156
),
11521157
pytest.param(

‎tests/server/routes/test_jsonrpc_dispatcher.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,70 @@ def _make_send_message_request(
9393
}
9494

9595

96+
class TestUnrecognizedFields:
97+
"""Unrecognized fields are ignored, for forward compatibility."""
98+
99+
def test_unknown_field_in_params_is_ignored(self, client):
100+
request = _make_send_message_request()
101+
request['params']['x_custom_field'] = 'test'
102+
103+
body = client.post('/', json=request).json()
104+
105+
assert 'error' not in body
106+
assert 'result' in body
107+
108+
def test_unknown_field_inside_message_is_ignored(self, client):
109+
request = _make_send_message_request()
110+
request['params']['message']['x_custom_field'] = 'test'
111+
112+
body = client.post('/', json=request).json()
113+
114+
assert 'error' not in body
115+
assert 'result' in body
116+
117+
def test_a_structurally_wrong_value_is_still_rejected(self, client):
118+
"""Leniency covers unknown names, not values of the wrong shape."""
119+
request = _make_send_message_request()
120+
request['params']['message']['parts'] = 'not-a-list'
121+
122+
body = client.post('/', json=request).json()
123+
124+
assert body['error']['code'] == -32602
125+
126+
def test_unknown_enum_value_is_accepted_as_unspecified(self, client):
127+
"""A documented side effect of ignore_unknown_fields, pinned here.
128+
129+
protobuf applies the same forward-compatibility rule to enum values
130+
as to field names, and the flag cannot be taken for one and not the
131+
other. A future ROLE_* therefore arrives as ROLE_UNSPECIFIED (0)
132+
rather than failing the request.
133+
"""
134+
request = _make_send_message_request()
135+
request['params']['message']['role'] = 'ROLE_FROM_THE_FUTURE'
136+
137+
body = client.post('/', json=request).json()
138+
139+
assert 'error' not in body
140+
141+
142+
class TestParseErrorDataShape:
143+
"""error.data is an array of objects, each carrying @type."""
144+
145+
@pytest.fixture
146+
def parse_error(self, client) -> dict:
147+
request = _make_send_message_request()
148+
request['params']['message']['parts'] = 'not-a-list'
149+
return client.post('/', json=request).json()['error']
150+
151+
def test_data_is_a_typed_array(self, parse_error):
152+
assert isinstance(parse_error['data'], list)
153+
assert parse_error['data'][0]['@type'].endswith('google.rpc.ErrorInfo')
154+
assert parse_error['data'][0]['reason'] == 'INVALID_PARAMS'
155+
156+
def test_parse_diagnostic_survives_in_metadata(self, parse_error):
157+
assert 'parts' in parse_error['data'][0]['metadata']['parseError']
158+
159+
96160
class TestJsonRpcDispatcherOptionalDependencies:
97161
@pytest.fixture(scope='class')
98162
def mock_app_params(self) -> dict:

‎tests/server/test_integration.py‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -876,19 +876,17 @@ def test_unknown_method(client: TestClient):
876876

877877
def test_validation_error(client: TestClient):
878878
"""Test handling validation error."""
879-
# Missing required fields in the message
879+
# A params the dispatcher cannot parse at all. Merely omitting required
880+
# fields no longer stops here: the unknown names are dropped, leaving an
881+
# empty Message that the handler's required-field validation rejects
882+
# instead -- a layer this mock handler never reaches.
880883
response = client.post(
881884
'/',
882885
json={
883886
'jsonrpc': '2.0',
884887
'id': '123',
885888
'method': 'SendMessage',
886-
'params': {
887-
'message': {
888-
# Missing required fields
889-
'text': 'Hello'
890-
}
891-
},
889+
'params': {'message': {'parts': 'should be a list'}},
892890
},
893891
)
894892
assert response.status_code == 200

0 commit comments

Comments
 (0)