Skip to content

Commit 8037b24

Browse files
authored
feat(server): add opt-in validation of message media types against the agent card (a2aproject#1269)
## What Spec [3.3.2](https://a2a-protocol.org/latest/specification/#332-error-types) defines `ContentTypeNotSupportedError` for "A Media Type provided in the request's message parts ... is not supported by the agent". `ContentTypeNotSupportedError` was fully wired already - `-32005`, `INVALID_ARGUMENT`, HTTP 400, gRPC `INVALID_ARGUMENT` - but nothing ever read `AgentCard.default_input_modes`, so an undeclared `mediaType` was always accepted. This is the same change a2a-js made in [a2aproject/a2a-js#745](a2aproject/a2a-js#745), and it lands in the same place: a shared helper called from the one setup path that both `send_message` and `send_message_stream` go through, in each handler. ## Why opt-in Always-on would start refusing traffic these agents accept today. Four cards in this repo declare input modes their clients contradict: | card | declares | | --- | --- | | `samples/hello_world_agent.py:156` | `['text']` | | `samples/agent_card_signing.py:146` | `['text']` | | `itk/main.py:720` | `['text/plain']` | | `itk/acts_client_parse.py:123` | `['text/plain']` | `'text'` is not a media type, so a client sending `text/plain` against it would be rejected. a2a-js hit exactly this and reached the same conclusion. The ITK fixture opts in, since its card states its modes accurately. ## Two carve-outs A card declaring **no** input modes accepts everything - an empty `default_input_modes` is an absent declaration, not an empty allowlist. A part with **no** `media_type` is not checked. It is a proto3 string, so an absent one arrives as `''`; only a media type the client actually stated can contradict the card. ## Tests Six unit tests on the validator, three on the handler wiring, two on the legacy handler. The handler tests matter more than they look: a flag that is stored but never read is the failure mode here, so both states are asserted and both were mutation-checked - forcing the branch off fails the two rejection tests, forcing it on fails the opt-out test. ## Result Clears `CORE-SEND-004` (`must`) on all three bindings.
1 parent 6cce91b commit 8037b24

7 files changed

Lines changed: 294 additions & 1 deletion

File tree

‎itk/main.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -717,7 +717,13 @@ async def main_async(http_port: int, grpc_port: int) -> None:
717717
# ACTS `authentication` precondition reads both of these.
718718
security_schemes=_security_schemes(),
719719
security_requirements=_security_requirements(),
720-
default_input_modes=['text/plain'],
720+
# application/x-protobuf because the ITK instruction envelope is a
721+
# binary Part: wrap_instruction_to_request() builds one and
722+
# extract_instruction() reads it. The agent has always accepted
723+
# those; declaring text/plain alone was a card that understated
724+
# what it takes, which went unnoticed until validate_input_modes
725+
# below started holding the agent to it.
726+
default_input_modes=['text/plain', 'application/x-protobuf'],
721727
default_output_modes=['text/plain'],
722728
supported_interfaces=interfaces,
723729
skills=[
@@ -752,6 +758,11 @@ async def main_async(http_port: int, grpc_port: int) -> None:
752758
push_config_store=push_config_store,
753759
push_sender=push_sender,
754760
extended_agent_card=agent_card,
761+
# CORE-SEND-004 sends a part whose mediaType the card does not
762+
# declare and expects ContentTypeNotSupportedError. Off by default in
763+
# the SDK; this card states its input modes accurately, so the
764+
# fixture can hold the SDK to them.
765+
validate_input_modes=True,
755766
)
756767

757768
agent_card_routes = create_agent_card_routes(

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
TaskNotFoundError,
6060
UnsupportedOperationError,
6161
)
62+
from a2a.utils.input_mode_validator import validate_input_modes
6263
from a2a.utils.task import (
6364
apply_history_length,
6465
validate_history_length,
@@ -104,6 +105,7 @@ def __init__( # noqa: PLR0913
104105
]
105106
| None = None,
106107
push_url_validator: Callable[[str], Awaitable[bool]] | None = None,
108+
validate_input_modes: bool = False,
107109
) -> None:
108110
"""Initializes the DefaultRequestHandler.
109111
@@ -123,6 +125,13 @@ def __init__( # noqa: PLR0913
123125
library screening). The spec lists these checks as SHOULD,
124126
so deployments that want the built-in policy should pass
125127
``validate_push_notification_url``.
128+
validate_input_modes: Reject message parts whose ``media_type``
129+
the card declares nowhere -- neither in
130+
``default_input_modes`` nor in any skill's ``input_modes`` --
131+
with ``ContentTypeNotSupportedError``. Defaults to False,
132+
because an agent whose declared modes do not spell the media
133+
types its clients really send would start refusing traffic it
134+
previously accepted.
126135
"""
127136
self.agent_executor = agent_executor
128137
self.task_store = task_store
@@ -131,6 +140,7 @@ def __init__( # noqa: PLR0913
131140
self._push_config_store = push_config_store
132141
self._push_sender = push_sender
133142
self._push_url_validator = push_url_validator
143+
self._validate_input_modes = validate_input_modes
134144
self.extended_agent_card = extended_agent_card
135145
self.extended_card_modifier = extended_card_modifier
136146
self._request_context_builder = (
@@ -277,6 +287,9 @@ async def _setup_message_execution(
277287
Returns:
278288
A tuple of (task_manager, task_id, queue, result_aggregator, producer_task)
279289
"""
290+
if self._validate_input_modes:
291+
validate_input_modes(params.message, self._agent_card)
292+
280293
# Create task manager and validate existing task
281294
# Proto empty strings should be treated as None
282295
task_id = params.message.task_id or None

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
TaskNotFoundError,
5050
UnsupportedOperationError,
5151
)
52+
from a2a.utils.input_mode_validator import validate_input_modes
5253
from a2a.utils.task import (
5354
apply_history_length,
5455
validate_history_length,
@@ -101,6 +102,7 @@ def __init__( # noqa: PLR0913
101102
]
102103
| None = None,
103104
push_url_validator: Callable[[str], Awaitable[bool]] | None = None,
105+
validate_input_modes: bool = False,
104106
) -> None:
105107
if queue_manager is not None:
106108
message = (
@@ -119,6 +121,7 @@ def __init__( # noqa: PLR0913
119121
self._push_config_store = push_config_store
120122
self._push_sender = push_sender
121123
self._push_url_validator = push_url_validator
124+
self._validate_input_modes = validate_input_modes
122125
self.extended_agent_card = extended_agent_card
123126
self.extended_card_modifier = extended_card_modifier
124127
self._request_context_builder = (
@@ -224,6 +227,8 @@ async def _setup_active_task(
224227
call_context: ServerCallContext,
225228
) -> tuple[ActiveTask, RequestContext]:
226229
validate_history_length(params.configuration)
230+
if self._validate_input_modes:
231+
validate_input_modes(params.message, self._agent_card)
227232

228233
original_task_id = params.message.task_id or None
229234
original_context_id = params.message.context_id or None
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""Shared policy for checking message parts against an agent's declared input modes."""
2+
3+
from a2a.types.a2a_pb2 import AgentCard, Message
4+
from a2a.utils.errors import ContentTypeNotSupportedError
5+
6+
7+
def validate_input_modes(message: Message, agent_card: AgentCard) -> None:
8+
"""Rejects parts whose media type the agent card does not declare.
9+
10+
The allowed set is the union of `default_input_modes` and every skill's
11+
`input_modes`, which may widen it: a skill's `input_modes` overrides the
12+
card default for that skill. A request does not name the skill that will
13+
serve it, so the union is the most that can be decided here -- anything
14+
outside it is supported by no skill and cannot be served, while a media
15+
type inside it may still reach a skill that does not take it, which only
16+
that skill can answer.
17+
18+
A card declaring no input modes anywhere accepts everything: an empty
19+
union is an absent declaration, not an empty allowlist. `media_type` is
20+
a proto3 string, so a part that omits it arrives as `''` and is likewise
21+
not checked -- only a media type the client actually stated can
22+
contradict the card.
23+
"""
24+
declared = set(agent_card.default_input_modes)
25+
for skill in agent_card.skills:
26+
declared.update(skill.input_modes)
27+
if not declared:
28+
return
29+
30+
for part in message.parts:
31+
if part.media_type and part.media_type not in declared:
32+
raise ContentTypeNotSupportedError(
33+
message=(
34+
f'Media type {part.media_type} is not supported. '
35+
f'Supported input modes: {", ".join(sorted(declared))}'
36+
)
37+
)

‎tests/server/request_handlers/test_default_request_handler.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
TaskUpdater,
4646
)
4747
from a2a.types import (
48+
ContentTypeNotSupportedError,
4849
InternalError,
4950
InvalidParamsError,
5051
PushNotificationNotSupportedError,
@@ -986,6 +987,47 @@ async def cancel(self, context: RequestContext, event_queue: EventQueue):
986987
pass
987988

988989

990+
@pytest.mark.asyncio
991+
@pytest.mark.parametrize(
992+
('validate_input_modes', 'expect_rejection'), [(True, True), (False, False)]
993+
)
994+
async def test_on_message_send_input_mode_validation_is_opt_in(
995+
validate_input_modes, expect_rejection
996+
):
997+
"""The legacy handler gates the same check behind the same flag."""
998+
request_handler = DefaultRequestHandler(
999+
agent_executor=HelloAgentExecutor(),
1000+
task_store=InMemoryTaskStore(),
1001+
agent_card=AgentCard(
1002+
name='test_agent',
1003+
version='1.0',
1004+
capabilities=AgentCapabilities(streaming=True),
1005+
default_input_modes=['text/plain'],
1006+
),
1007+
validate_input_modes=validate_input_modes,
1008+
)
1009+
params = SendMessageRequest(
1010+
message=Message(
1011+
role=Role.ROLE_USER,
1012+
message_id='msg_bad_media_type',
1013+
parts=[Part(text='hello', media_type='application/x-nope')],
1014+
)
1015+
)
1016+
1017+
if expect_rejection:
1018+
with pytest.raises(ContentTypeNotSupportedError):
1019+
await request_handler.on_message_send(
1020+
params, create_server_call_context()
1021+
)
1022+
else:
1023+
assert (
1024+
await request_handler.on_message_send(
1025+
params, create_server_call_context()
1026+
)
1027+
is not None
1028+
)
1029+
1030+
9891031
@pytest.mark.asyncio
9901032
async def test_on_message_send_non_blocking(agent_card):
9911033
task_store = InMemoryTaskStore()

‎tests/server/request_handlers/test_default_request_handler_v2.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
)
3535
from a2a.server.tasks.task_manager import TaskManager
3636
from a2a.types import (
37+
ContentTypeNotSupportedError,
3738
InternalError,
3839
InvalidAgentResponseError,
3940
InvalidParamsError,
@@ -987,6 +988,69 @@ async def test_delete_task_push_notification_config_info_with_config_and_no_id()
987988
}
988989

989990

991+
def create_input_mode_handler(*, validate_input_modes: bool):
992+
"""A handler whose card declares text/plain as its only input mode."""
993+
return DefaultRequestHandlerV2(
994+
# HelloAgentExecutor reaches a terminal state; MockAgentExecutor
995+
# streams forever, so a blocking send against it never returns.
996+
agent_executor=HelloAgentExecutor(),
997+
task_store=InMemoryTaskStore(),
998+
agent_card=AgentCard(
999+
name='test_agent',
1000+
version='1.0',
1001+
capabilities=AgentCapabilities(streaming=True),
1002+
default_input_modes=['text/plain'],
1003+
),
1004+
validate_input_modes=validate_input_modes,
1005+
)
1006+
1007+
1008+
def create_undeclared_media_type_request():
1009+
return SendMessageRequest(
1010+
message=Message(
1011+
role=Role.ROLE_USER,
1012+
message_id='msg_bad_media_type',
1013+
parts=[Part(text='hello', media_type='application/x-nope')],
1014+
)
1015+
)
1016+
1017+
1018+
@pytest.mark.asyncio
1019+
async def test_on_message_send_rejects_undeclared_media_type_when_enabled():
1020+
handler = create_input_mode_handler(validate_input_modes=True)
1021+
1022+
with pytest.raises(ContentTypeNotSupportedError):
1023+
await handler.on_message_send(
1024+
create_undeclared_media_type_request(),
1025+
create_server_call_context(),
1026+
)
1027+
1028+
1029+
@pytest.mark.asyncio
1030+
async def test_on_message_send_allows_undeclared_media_type_by_default():
1031+
"""The check is opt-in, so an unflagged handler keeps accepting the part."""
1032+
handler = create_input_mode_handler(validate_input_modes=False)
1033+
1034+
result = await handler.on_message_send(
1035+
create_undeclared_media_type_request(), create_server_call_context()
1036+
)
1037+
1038+
assert result is not None
1039+
1040+
1041+
@pytest.mark.asyncio
1042+
async def test_on_message_send_stream_rejects_undeclared_media_type():
1043+
"""Streaming shares _setup_active_task, so it is gated by the same flag."""
1044+
handler = create_input_mode_handler(validate_input_modes=True)
1045+
1046+
with pytest.raises(ContentTypeNotSupportedError):
1047+
async for _ in handler.on_message_send_stream(
1048+
create_undeclared_media_type_request(),
1049+
create_server_call_context(),
1050+
):
1051+
pass
1052+
1053+
9901054
@pytest.mark.asyncio
9911055
@pytest.mark.parametrize('terminal_state', TERMINAL_TASK_STATES)
9921056
async def test_on_message_send_task_in_terminal_state(terminal_state):

0 commit comments

Comments
 (0)