Skip to content

Commit 4f4101c

Browse files
fix(server): warn when an AgentCard is missing required fields (a2aproject#1279)
# Description `AgentCard` marks eight fields `REQUIRED`, but nothing in the SDK checks them, so an empty `AgentCard()` is served as `{}` with HTTP 200. Following the "suggested first step" in a2aproject#1267, this logs a warning instead of raising, so existing non-compliant cards keep working while the problem becomes visible. **Changes** - `a2a.utils.proto_utils.warn_on_missing_required_fields(msg, source) -> bool`: runs the existing required-field check (`_validate_proto_required_fields_internal`) and logs one `WARNING` listing the fields that are missing or empty, including nested paths such as `skills[0].tags`. It never raises and returns whether the message was complete. Objects that are not Protobuf messages are skipped: an existing test in `test_default_request_handler.py` passes a non-card object as `agent_card`, and user code does the same with test doubles, so a warning helper must not turn that into an `AttributeError`. - Called where a card enters or leaves the SDK: - `create_agent_card_routes(agent_card=...)` - `DefaultRequestHandler.__init__` and `DefaultRequestHandlerV2.__init__` for `agent_card` and, when given, `extended_agent_card` - `agent_card_to_dict`, which serializes every served card (including cards from `card_modifier` / `extended_card_modifier`), so this one logs per request; it can be silenced through the `a2a.utils.proto_utils` logger - `signing._canonicalize_agent_card`, used when signing and verifying a card For an empty card the log reads: ``` agent_card passed to create_agent_card_routes: AgentCard is not spec-compliant - REQUIRED fields missing or empty: name, description, supported_interfaces, version, capabilities, default_input_modes, default_output_modes, skills. This is allowed and does not raise, but it may not verify or interoperate across SDKs and could be rejected in a future major release. See https://a2a-protocol.org/latest/specification/#57-field-presence-and-optionality ``` Enforcement (raising) is left for a major version, as the issue suggests. **Tests** (`uv run pytest`) - `tests/utils/test_proto_utils.py`: complete message returns `True` with no log; empty message returns `False` and logs the exact message instead of raising; an empty repeated field is reported; nested paths are reported. - `tests/server/routes/test_agent_card_routes.py`: an incomplete card logs a warning and is still served with 200; a complete card logs nothing. - `tests/server/request_handlers/test_default_request_handler.py` and `..._v2.py`: incomplete `agent_card` and `extended_agent_card` each log one warning; complete cards log nothing. - `tests/server/request_handlers/test_response_helpers.py`: `agent_card_to_dict` warns for an incomplete card and stays silent for a complete one. - `tests/utils/test_signing.py`: `_canonicalize_agent_card` warns for an incomplete card. - The warning-asserting tests fail on `main` and pass with this change. - `bash scripts/lint.sh` (ruff check, ruff format, ty) passes. - `uv run pytest --ignore=tests/integration`: 1829 passed, 169 skipped, 3 xfailed. - On Windows, some `tests/integration` tests that spawn server subprocesses fail identically on `main`, so I relied on CI for those. --- - [x] Follow the [`CONTRIBUTING` Guide](https://github.com/a2aproject/a2a-python/blob/main/CONTRIBUTING.md). - [x] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification. - [x] Ensure the tests and linter pass (Run `bash scripts/format.sh` from the repository root to format) - [x] Appropriate docs were updated (if necessary) Fixes a2aproject#1267 🦕
1 parent cbb2d84 commit 4f4101c

12 files changed

Lines changed: 380 additions & 1 deletion

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
UnsupportedOperationError,
6464
)
6565
from a2a.utils.input_mode_validator import validate_input_modes
66+
from a2a.utils.proto_utils import warn_on_missing_required_fields
6667
from a2a.utils.task import (
6768
apply_history_length,
6869
validate_history_length,
@@ -146,6 +147,14 @@ def __init__( # noqa: PLR0913
146147
self._validate_input_modes = validate_input_modes
147148
self.extended_agent_card = extended_agent_card
148149
self.extended_card_modifier = extended_card_modifier
150+
warn_on_missing_required_fields(
151+
agent_card, 'agent_card passed to DefaultRequestHandler:'
152+
)
153+
if extended_agent_card is not None:
154+
warn_on_missing_required_fields(
155+
extended_agent_card,
156+
'extended_agent_card passed to DefaultRequestHandler:',
157+
)
149158
self._request_context_builder = (
150159
request_context_builder
151160
or SimpleRequestContextBuilder(

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
UnsupportedOperationError,
6262
)
6363
from a2a.utils.input_mode_validator import validate_input_modes
64+
from a2a.utils.proto_utils import warn_on_missing_required_fields
6465
from a2a.utils.task import (
6566
apply_history_length,
6667
validate_history_length,
@@ -151,6 +152,14 @@ def __init__( # noqa: PLR0913
151152
)
152153
warnings.warn(message, stacklevel=2)
153154
logger.warning(message)
155+
warn_on_missing_required_fields(
156+
agent_card, 'agent_card passed to DefaultRequestHandlerV2:'
157+
)
158+
if extended_agent_card is not None:
159+
warn_on_missing_required_fields(
160+
extended_agent_card,
161+
'extended_agent_card passed to DefaultRequestHandlerV2:',
162+
)
154163
self._request_context_builder = (
155164
request_context_builder
156165
or SimpleRequestContextBuilder(

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
UnsupportedOperationError,
4545
VersionNotSupportedError,
4646
)
47+
from a2a.utils.proto_utils import warn_on_missing_required_fields
4748

4849

4950
EXCEPTION_MAP: dict[type[A2AError], type[JSONRPCError]] = {
@@ -86,6 +87,9 @@
8687

8788
def agent_card_to_dict(card: AgentCard) -> dict[str, Any]:
8889
"""Convert AgentCard to dict and inject backward compatibility fields."""
90+
warn_on_missing_required_fields(
91+
card, 'agent_card passed to agent_card_to_dict:'
92+
)
8993
result = MessageToDict(card)
9094

9195
try:

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from a2a.server.request_handlers.response_helpers import agent_card_to_dict
3030
from a2a.types.a2a_pb2 import AgentCard
3131
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
32+
from a2a.utils.proto_utils import warn_on_missing_required_fields
3233

3334

3435
def _etag_for(card_dict: dict[str, Any]) -> str:
@@ -96,6 +97,10 @@ def create_agent_card_routes(
9697
'It can be installed as part of `a2a-sdk` optional dependencies, `a2a-sdk[http-server]`.'
9798
)
9899

100+
warn_on_missing_required_fields(
101+
agent_card, 'agent_card passed to create_agent_card_routes:'
102+
)
103+
99104
async def _get_agent_card(request: Request) -> Response:
100105
"""Returns the public AgentCard describing this agent's capabilities, supported transports, and skills."""
101106
card_to_serve = agent_card

‎src/a2a/utils/proto_utils.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
This module provides helper functions for common proto type operations.
1818
"""
1919

20+
import logging
21+
2022
from typing import TYPE_CHECKING, Any, TypedDict, cast
2123

2224
from google.api.field_behavior_pb2 import FieldBehavior, field_behavior
@@ -45,6 +47,9 @@
4547
)
4648

4749

50+
logger = logging.getLogger(__name__)
51+
52+
4853
# Define Event type locally to avoid circular imports
4954
Event = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
5055

@@ -316,6 +321,45 @@ def validate_proto_required_fields(msg: ProtobufMessage) -> None:
316321
)
317322

318323

324+
_SPEC_FIELD_PRESENCE_URL = (
325+
'https://a2a-protocol.org/latest/specification/'
326+
'#57-field-presence-and-optionality'
327+
)
328+
329+
330+
def warn_on_missing_required_fields(msg: ProtobufMessage, source: str) -> bool:
331+
"""Log a warning if fields marked as REQUIRED are missing or empty.
332+
333+
Unlike `validate_proto_required_fields`, this never raises, so it can
334+
surface spec violations without breaking callers that currently rely on
335+
non-compliant messages.
336+
337+
Args:
338+
msg: The Protobuf message to check.
339+
source: Where the message was passed in, used in the log message.
340+
341+
Returns:
342+
True if every REQUIRED field is set, False otherwise. Objects that
343+
are not Protobuf messages (for example test doubles) are not checked.
344+
"""
345+
if not isinstance(msg, ProtobufMessage):
346+
return True
347+
errors = _validate_proto_required_fields_internal(msg)
348+
if not errors:
349+
return True
350+
logger.warning(
351+
'%s %s is not spec-compliant - REQUIRED fields missing or empty: '
352+
'%s. This is allowed and does not raise, but it may not verify or '
353+
'interoperate across SDKs and could be rejected in a future major '
354+
'release. See %s',
355+
source,
356+
msg.DESCRIPTOR.name,
357+
', '.join(err['field'] for err in errors),
358+
_SPEC_FIELD_PRESENCE_URL,
359+
)
360+
return False
361+
362+
319363
def validation_errors_to_bad_request(
320364
errors: list[ValidationDetail],
321365
) -> error_details_pb2.BadRequest:

‎src/a2a/utils/signing.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
from a2a.types import AgentCard, AgentCardSignature
2424
from a2a.utils._jcs import MAX_DEPTH, CanonicalizationError, canonicalize
25+
from a2a.utils.proto_utils import warn_on_missing_required_fields
2526

2627

2728
class SignatureVerificationError(Exception):
@@ -198,6 +199,9 @@ def _clean_empty(d: Any, depth: int = 1) -> Any:
198199

199200
def _canonicalize_agent_card(agent_card: AgentCard) -> str:
200201
"""Canonicalizes the Agent Card JSON according to RFC 8785 (JCS)."""
202+
warn_on_missing_required_fields(
203+
agent_card, 'agent_card passed to _canonicalize_agent_card:'
204+
)
201205
card_dict = MessageToDict(
202206
agent_card,
203207
)

‎tests/server/request_handlers/test_default_request_handler.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@
5656
from a2a.types.a2a_pb2 import (
5757
AgentCapabilities,
5858
AgentCard,
59+
AgentInterface,
60+
AgentSkill,
5961
Artifact,
6062
CancelTaskRequest,
6163
DeleteTaskPushNotificationConfigRequest,
@@ -3389,3 +3391,63 @@ async def test_on_message_send_rejects_invalid_push_url(agent_card):
33893391
InvalidParamsError, match='Invalid push notification URL'
33903392
):
33913393
await request_handler.on_message_send(params, context)
3394+
3395+
3396+
def _complete_agent_card() -> AgentCard:
3397+
"""Returns an AgentCard with every field the A2A spec marks REQUIRED."""
3398+
return AgentCard(
3399+
name='complete_agent',
3400+
description='An agent card with all required fields.',
3401+
supported_interfaces=[
3402+
AgentInterface(
3403+
url='http://localhost:8000',
3404+
protocol_binding='JSONRPC',
3405+
protocol_version='1.0',
3406+
)
3407+
],
3408+
version='1.0',
3409+
capabilities=AgentCapabilities(),
3410+
default_input_modes=['text/plain'],
3411+
default_output_modes=['text/plain'],
3412+
skills=[
3413+
AgentSkill(
3414+
id='echo',
3415+
name='Echo',
3416+
description='Echoes the input.',
3417+
tags=['test'],
3418+
)
3419+
],
3420+
)
3421+
3422+
3423+
def test_init_warns_about_incomplete_agent_cards(
3424+
agent_card: AgentCard,
3425+
caplog: pytest.LogCaptureFixture,
3426+
) -> None:
3427+
"""Cards missing REQUIRED fields are accepted, but each one is logged."""
3428+
with caplog.at_level(logging.WARNING, logger='a2a.utils.proto_utils'):
3429+
DefaultRequestHandler(
3430+
agent_executor=MockAgentExecutor(),
3431+
task_store=InMemoryTaskStore(),
3432+
agent_card=agent_card,
3433+
extended_agent_card=AgentCard(),
3434+
)
3435+
messages = [record.getMessage() for record in caplog.records]
3436+
assert len(messages) == 2
3437+
assert messages[0].startswith('agent_card passed to DefaultRequestHandler:')
3438+
assert messages[1].startswith(
3439+
'extended_agent_card passed to DefaultRequestHandler:'
3440+
)
3441+
3442+
3443+
def test_init_does_not_warn_for_complete_agent_cards(
3444+
caplog: pytest.LogCaptureFixture,
3445+
) -> None:
3446+
with caplog.at_level(logging.WARNING, logger='a2a.utils.proto_utils'):
3447+
DefaultRequestHandler(
3448+
agent_executor=MockAgentExecutor(),
3449+
task_store=InMemoryTaskStore(),
3450+
agent_card=_complete_agent_card(),
3451+
extended_agent_card=_complete_agent_card(),
3452+
)
3453+
assert caplog.records == []

‎tests/server/request_handlers/test_default_request_handler_v2.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@
4646
from a2a.types.a2a_pb2 import (
4747
AgentCapabilities,
4848
AgentCard,
49+
AgentInterface,
50+
AgentSkill,
4951
Artifact,
5052
CancelTaskRequest,
5153
DeleteTaskPushNotificationConfigRequest,
@@ -2528,3 +2530,64 @@ async def send(tag: str, message: Message) -> None:
25282530

25292531
assert agent.seen_tags == ['request-1', 'request-2']
25302532
await handler.aclose()
2533+
2534+
2535+
def _complete_agent_card() -> AgentCard:
2536+
"""Returns an AgentCard with every field the A2A spec marks REQUIRED."""
2537+
return AgentCard(
2538+
name='complete_agent',
2539+
description='An agent card with all required fields.',
2540+
supported_interfaces=[
2541+
AgentInterface(
2542+
url='http://localhost:8000',
2543+
protocol_binding='JSONRPC',
2544+
protocol_version='1.0',
2545+
)
2546+
],
2547+
version='1.0',
2548+
capabilities=AgentCapabilities(),
2549+
default_input_modes=['text/plain'],
2550+
default_output_modes=['text/plain'],
2551+
skills=[
2552+
AgentSkill(
2553+
id='echo',
2554+
name='Echo',
2555+
description='Echoes the input.',
2556+
tags=['test'],
2557+
)
2558+
],
2559+
)
2560+
2561+
2562+
def test_init_warns_about_incomplete_agent_cards(
2563+
caplog: pytest.LogCaptureFixture,
2564+
) -> None:
2565+
"""Cards missing REQUIRED fields are accepted, but each one is logged."""
2566+
with caplog.at_level(logging.WARNING, logger='a2a.utils.proto_utils'):
2567+
DefaultRequestHandlerV2(
2568+
agent_executor=MockAgentExecutor(),
2569+
task_store=InMemoryTaskStore(),
2570+
agent_card=create_default_agent_card(),
2571+
extended_agent_card=AgentCard(),
2572+
)
2573+
messages = [record.getMessage() for record in caplog.records]
2574+
assert len(messages) == 2
2575+
assert messages[0].startswith(
2576+
'agent_card passed to DefaultRequestHandlerV2:'
2577+
)
2578+
assert messages[1].startswith(
2579+
'extended_agent_card passed to DefaultRequestHandlerV2:'
2580+
)
2581+
2582+
2583+
def test_init_does_not_warn_for_complete_agent_cards(
2584+
caplog: pytest.LogCaptureFixture,
2585+
) -> None:
2586+
with caplog.at_level(logging.WARNING, logger='a2a.utils.proto_utils'):
2587+
DefaultRequestHandlerV2(
2588+
agent_executor=MockAgentExecutor(),
2589+
task_store=InMemoryTaskStore(),
2590+
agent_card=_complete_agent_card(),
2591+
extended_agent_card=_complete_agent_card(),
2592+
)
2593+
assert caplog.records == []

‎tests/server/request_handlers/test_response_helpers.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import unittest
23

34
from a2a.server.request_handlers.response_helpers import (
@@ -13,6 +14,7 @@
1314
AgentCapabilities,
1415
AgentCard,
1516
AgentInterface,
17+
AgentSkill,
1618
Task,
1719
TaskState,
1820
TaskStatus,
@@ -420,3 +422,40 @@ def test_prepare_response_object_with_invalid_response(self) -> None:
420422

421423
if __name__ == '__main__':
422424
unittest.main()
425+
426+
427+
class TestAgentCardToDictRequiredFields(unittest.TestCase):
428+
def test_warns_when_required_fields_are_missing(self) -> None:
429+
with self.assertLogs('a2a.utils.proto_utils', logging.WARNING) as logs:
430+
result = agent_card_to_dict(AgentCard(name='partial'))
431+
self.assertEqual(result['name'], 'partial')
432+
[message] = logs.output
433+
self.assertIn('agent_card passed to agent_card_to_dict:', message)
434+
self.assertIn('description', message)
435+
436+
def test_complete_card_does_not_warn(self) -> None:
437+
card = AgentCard(
438+
name='complete_agent',
439+
description='An agent card with all required fields.',
440+
supported_interfaces=[
441+
AgentInterface(
442+
url='http://localhost:8000',
443+
protocol_binding='JSONRPC',
444+
protocol_version='1.0',
445+
)
446+
],
447+
version='1.0',
448+
capabilities=AgentCapabilities(),
449+
default_input_modes=['text/plain'],
450+
default_output_modes=['text/plain'],
451+
skills=[
452+
AgentSkill(
453+
id='echo',
454+
name='Echo',
455+
description='Echoes the input.',
456+
tags=['test'],
457+
)
458+
],
459+
)
460+
with self.assertNoLogs('a2a.utils.proto_utils', logging.WARNING):
461+
agent_card_to_dict(card)

0 commit comments

Comments
 (0)