Skip to content

Commit 486f0f6

Browse files
fix(client): normalize malformed agent card parsing errors (a2aproject#1307)
## Description When an agent-card endpoint returns HTTP 200 with valid JSON such as `null`, an array, a string, a number, or a boolean, the compatibility helpers raise `AttributeError` or `TypeError`. Malformed nested legacy fields can raise the same exceptions even when the root is an object. These exceptions escape `A2ACardResolver.get_agent_card()` instead of the documented `AgentCardResolutionError`. Validate that the decoded value is a JSON object at the parser boundary. Convert `TypeError` and `AttributeError` from the three compatibility helpers into `ParseError`, retaining their original cause. The resolver already wraps `ParseError` into `AgentCardResolutionError`; protobuf parsing and signature verification retain their existing exception handling. Regression tests use `httpx.MockTransport` with real JSON decoding: eight non-object roots and all six malformed nested cases from the review (null/list capabilities, a null additional interface, null skills/a null skill, and string security). Every new case failed before its corresponding fix. The nested-field tests also verify the full exception cause chain. ## Validation - The Windows equivalents of `scripts/lint.sh` (`uv run --locked ruff check --fix`, `ruff format`, and `ty check`) passed. `ty` exits successfully with three existing unused-ignore warnings. - `uv run --locked pytest tests/client/test_card_resolver.py -q`: **46 passed**. - `uv run --locked pytest --ignore=tests/integration --cov=src --cov-report=term-missing -q`: **1,788 passed, 169 skipped, 3 xfailed; 91% coverage**. `card_resolver.py` has **100% statement and branch coverage**. - With `PYTHONIOENCODING=utf-8`, sample integration smoke tests: **3 passed**. - Full pytest was attempted on Windows and timed out in scenario integration tests. A coverage run excluding only the scenario and sample modules completed with **2,095 passed, 183 skipped, 3 xfailed and 8 fixture errors; 93% coverage**. The errors are in the previously problematic cross-version server fixtures (startup / unavailable `os.killpg`) and push-notification fixtures (a FastAPI local callable cannot be pickled under Windows multiprocessing). These platform limitations are outside this change. - Updated GitHub Actions checks all passed, including the full Python 3.10–3.14 matrix, ACTS, ITK, lint and install checks. The same matrix also passed before this follow-up. AI assistance: OpenAI Codex (GPT-6) was used to implement, reproduce, and test this change under the account owner's explicit authorization. The follow-up implements the human maintainer's review request and received another independent review before submission. - [x] Followed the contributing guide and conventional-commit title format. - [x] Added failing regression cases and ran lint, formatting, type and coverage checks. --------- Co-authored-by: mykytanetipa <mykytanetipa@google.com>
1 parent 5653daf commit 486f0f6

2 files changed

Lines changed: 81 additions & 3 deletions

File tree

‎src/a2a/client/card_resolver.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,14 @@
2020

2121
def parse_agent_card(agent_card_data: dict[str, Any]) -> AgentCard:
2222
"""Parse AgentCard JSON dictionary and handle backward compatibility."""
23-
_handle_extended_card_compatibility(agent_card_data)
24-
_handle_connection_fields_compatibility(agent_card_data)
25-
_handle_security_compatibility(agent_card_data)
23+
if not isinstance(agent_card_data, dict):
24+
raise ParseError('Agent card must be a JSON object')
25+
try:
26+
_handle_extended_card_compatibility(agent_card_data)
27+
_handle_connection_fields_compatibility(agent_card_data)
28+
_handle_security_compatibility(agent_card_data)
29+
except (TypeError, AttributeError) as e:
30+
raise ParseError(f'Invalid agent card structure: {e}') from e
2631

2732
return ParseDict(agent_card_data, AgentCard(), ignore_unknown_fields=True)
2833

‎tests/client/test_card_resolver.py‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
StringList,
3131
)
3232
from a2a.utils import AGENT_CARD_WELL_KNOWN_PATH
33+
from google.protobuf.json_format import ParseError
3334

3435

3536
@pytest.fixture
@@ -310,6 +311,78 @@ async def test_get_agent_card_validation_error(
310311
f'{base_url}/{AGENT_CARD_WELL_KNOWN_PATH[1:]}',
311312
)
312313

314+
@pytest.mark.parametrize(
315+
'response_body',
316+
[
317+
'null',
318+
'[]',
319+
'[{"name":"TestAgent"}]',
320+
'"TestAgent"',
321+
'42',
322+
'1.5',
323+
'true',
324+
'false',
325+
],
326+
)
327+
@pytest.mark.asyncio
328+
async def test_get_agent_card_non_object_json(
329+
self, response_body: str
330+
) -> None:
331+
"""Non-object JSON responses use the documented resolution error."""
332+
transport = httpx.MockTransport(
333+
lambda _request: httpx.Response(200, content=response_body)
334+
)
335+
async with httpx.AsyncClient(transport=transport) as client:
336+
resolver = A2ACardResolver(client, 'https://example.com')
337+
with pytest.raises(AgentCardResolutionError) as exc_info:
338+
await resolver.get_agent_card()
339+
340+
assert 'Failed to validate agent card structure' in str(exc_info.value)
341+
assert isinstance(exc_info.value.__cause__, ParseError)
342+
343+
@pytest.mark.parametrize(
344+
('response_body', 'original_error'),
345+
[
346+
pytest.param(
347+
'{"supportsAuthenticatedExtendedCard":true,"capabilities":null}',
348+
TypeError,
349+
id='null-capabilities',
350+
),
351+
pytest.param(
352+
'{"supportsAuthenticatedExtendedCard":true,"capabilities":[]}',
353+
TypeError,
354+
id='list-capabilities',
355+
),
356+
pytest.param(
357+
'{"url":"https://example.com","additionalInterfaces":[null]}',
358+
AttributeError,
359+
id='null-interface',
360+
),
361+
pytest.param('{"skills":null}', TypeError, id='null-skills'),
362+
pytest.param('{"skills":[null]}', AttributeError, id='null-skill'),
363+
pytest.param(
364+
'{"security":"invalid"}', AttributeError, id='string-security'
365+
),
366+
],
367+
)
368+
@pytest.mark.asyncio
369+
async def test_get_agent_card_malformed_nested_fields(
370+
self, response_body: str, original_error: type[Exception]
371+
) -> None:
372+
"""Malformed legacy fields preserve the documented error chain."""
373+
transport = httpx.MockTransport(
374+
lambda _request: httpx.Response(200, content=response_body)
375+
)
376+
async with httpx.AsyncClient(transport=transport) as client:
377+
resolver = A2ACardResolver(client, 'https://example.com')
378+
with pytest.raises(AgentCardResolutionError) as exc_info:
379+
await resolver.get_agent_card()
380+
381+
assert 'Failed to validate agent card structure' in str(exc_info.value)
382+
parse_error = exc_info.value.__cause__
383+
assert isinstance(parse_error, ParseError)
384+
assert isinstance(parse_error.__cause__, original_error)
385+
313386
@pytest.mark.asyncio
314387
async def test_get_agent_card_logs_success( # noqa: PLR0913
315388
self,

0 commit comments

Comments
 (0)