Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/a2a/server/request_handlers/default_request_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,24 +56,25 @@
from a2a.utils.constants import TERMINAL_TASK_STATES
from a2a.utils.errors import (
ExtendedAgentCardNotConfiguredError,
InternalError,
InvalidParamsError,
PushNotificationNotSupportedError,
TaskNotCancelableError,
TaskNotFoundError,
UnsupportedOperationError,
)
from a2a.utils.extension_validator import validate_required_extensions
from a2a.utils.input_mode_validator import validate_input_modes
from a2a.utils.proto_utils import warn_on_missing_required_fields
from a2a.utils.task import (
apply_history_length,
validate_history_length,
validate_page_size,
)
from a2a.utils.telemetry import SpanKind, trace_class


logger = logging.getLogger(__name__)

Check notice on line 77 in src/a2a/server/request_handlers/default_request_handler.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/server/request_handlers/default_request_handler_v2.py (66-84)


@trace_class(kind=SpanKind.SERVER)
Expand All @@ -94,16 +95,17 @@
task_store: TaskStore,
agent_card: AgentCard,
queue_manager: QueueManager | None = None,
push_config_store: PushNotificationConfigStore | None = None,
push_sender: PushNotificationSender | None = None,
request_context_builder: RequestContextBuilder | None = None,
extended_agent_card: AgentCard | None = None,
extended_card_modifier: Callable[
[AgentCard, ServerCallContext], Awaitable[AgentCard]
]
| None = None,
push_url_validator: Callable[[str], Awaitable[bool]] | None = None,
validate_input_modes: bool = False,
validate_required_extensions: bool = False,

Check notice on line 108 in src/a2a/server/request_handlers/default_request_handler.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/server/request_handlers/default_request_handler_v2.py (131-141)
) -> None:
"""Initializes the DefaultRequestHandler.

Expand All @@ -130,6 +132,12 @@
because an agent whose declared modes do not spell the media
types its clients really send would start refusing traffic it
previously accepted.
validate_required_extensions: Reject a message whose request
does not declare every extension the card marks ``required``
with ``ExtensionSupportRequiredError``. Defaults to False,
because a card that marks an extension required its clients
do not yet send would start refusing traffic it previously
accepted.
"""
self.agent_executor = agent_executor
self.task_store = task_store
Expand All @@ -139,6 +147,7 @@
self._push_sender = push_sender
self._push_url_validator = push_url_validator
self._validate_input_modes = validate_input_modes
self._validate_required_extensions = validate_required_extensions
self.extended_agent_card = extended_agent_card
self.extended_card_modifier = extended_card_modifier
warn_on_missing_required_fields(
Expand Down Expand Up @@ -295,6 +304,10 @@
"""
if self._validate_input_modes:
validate_input_modes(params.message, self._agent_card)
if self._validate_required_extensions:
validate_required_extensions(
context.requested_extensions, self._agent_card
)

# Create task manager and validate existing task
# Proto empty strings should be treated as None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,24 +63,25 @@
from a2a.utils.errors import (
ExtendedAgentCardNotConfiguredError,
InternalError,
InvalidAgentResponseError,
InvalidParamsError,
PushNotificationNotSupportedError,
TaskNotCancelableError,
TaskNotFoundError,
UnsupportedOperationError,
)
from a2a.utils.extension_validator import validate_required_extensions
from a2a.utils.input_mode_validator import validate_input_modes
from a2a.utils.proto_utils import warn_on_missing_required_fields
from a2a.utils.task import (
apply_history_length,
validate_history_length,
validate_page_size,
)
from a2a.utils.telemetry import SpanKind, trace_class


if TYPE_CHECKING:

Check notice on line 84 in src/a2a/server/request_handlers/default_request_handler_v2.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/server/request_handlers/default_request_handler.py (59-77)
from collections.abc import AsyncGenerator, Awaitable, Callable

from a2a.plugins.manager import PluginManager
Expand Down Expand Up @@ -127,19 +128,20 @@
agent_card: AgentCard,
queue_manager: Any
| None = None, # Accepted for signature compat; ignored in v2 (warns)
push_config_store: PushNotificationConfigStore | None = None,
push_sender: PushNotificationSender | None = None,
request_context_builder: RequestContextBuilder | None = None,
extended_agent_card: AgentCard | None = None,
extended_card_modifier: Callable[
[AgentCard, ServerCallContext], Awaitable[AgentCard]
]
| None = None,
push_url_validator: Callable[[str], Awaitable[bool]] | None = None,
validate_input_modes: bool = False,
event_stream: TaskEventStream | None = None,

Check notice on line 141 in src/a2a/server/request_handlers/default_request_handler_v2.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/server/request_handlers/default_request_handler.py (98-108)
interrupted_task_timeout: float | None = None,
plugins: PluginManager | None = None,
validate_required_extensions: bool = False,
) -> None:
if (
interrupted_task_timeout is not None
Expand Down Expand Up @@ -172,6 +174,7 @@
self._push_sender = push_sender
self._push_url_validator = push_url_validator
self._validate_input_modes = validate_input_modes
self._validate_required_extensions = validate_required_extensions
self.extended_agent_card = extended_agent_card
self.extended_card_modifier = extended_card_modifier
self._event_stream = event_stream
Expand Down Expand Up @@ -408,6 +411,10 @@
validate_history_length(params.configuration)
if self._validate_input_modes:
validate_input_modes(params.message, self._agent_card)
if self._validate_required_extensions:
validate_required_extensions(
call_context.requested_extensions, self._agent_card
)

original_task_id = params.message.task_id or None
original_context_id = params.message.context_id or None
Expand Down
25 changes: 25 additions & 0 deletions src/a2a/utils/extension_validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Shared policy for checking a request against an agent's required extensions."""

from a2a.types.a2a_pb2 import AgentCard
from a2a.utils.errors import ExtensionSupportRequiredError


def validate_required_extensions(
requested_extensions: set[str], agent_card: AgentCard
) -> None:
"""Rejects a request that does not declare every required extension.

An extension the card marks `required` must appear in the URIs the
client sent in the `A2A-Extensions` header, or the agent MUST answer
with `ExtensionSupportRequiredError` (spec section 3.3.4). URIs are
compared exactly.
"""
missing = [
extension.uri
for extension in agent_card.capabilities.extensions
if extension.required and extension.uri not in requested_extensions
]
if missing:
raise ExtensionSupportRequiredError(
message=(f'Required extensions not requested: {", ".join(missing)}')
)
53 changes: 53 additions & 0 deletions tests/server/request_handlers/test_default_request_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
)
from a2a.types import (
ContentTypeNotSupportedError,
ExtensionSupportRequiredError,
InternalError,
InvalidParamsError,
PushNotificationNotSupportedError,
Expand All @@ -56,6 +57,7 @@
from a2a.types.a2a_pb2 import (
AgentCapabilities,
AgentCard,
AgentExtension,
AgentInterface,
AgentSkill,
Artifact,
Expand Down Expand Up @@ -1063,6 +1065,57 @@ async def test_on_message_send_input_mode_validation_is_opt_in(
)


@pytest.mark.asyncio
@pytest.mark.parametrize(
('validate_required_extensions', 'requested', 'expect_rejection'),
[
(True, set(), True),
(True, {'https://example.com/ext/required/v1'}, False),
(False, set(), False),
],
)
async def test_on_message_send_required_extension_validation_is_opt_in(
validate_required_extensions, requested, expect_rejection
):
"""The legacy handler gates the same check behind the same flag."""
request_handler = DefaultRequestHandler(
agent_executor=HelloAgentExecutor(),
task_store=InMemoryTaskStore(),
agent_card=AgentCard(
name='test_agent',
version='1.0',
capabilities=AgentCapabilities(
streaming=True,
extensions=[
AgentExtension(
uri='https://example.com/ext/required/v1',
required=True,
)
],
),
),
validate_required_extensions=validate_required_extensions,
)
params = SendMessageRequest(
message=Message(
role=Role.ROLE_USER,
message_id='msg_hello',
parts=[Part(text='hello')],
)
)
context = ServerCallContext(
user=UnauthenticatedUser(), requested_extensions=requested
)

if expect_rejection:
with pytest.raises(ExtensionSupportRequiredError):
await request_handler.on_message_send(params, context)
else:
assert (
await request_handler.on_message_send(params, context) is not None
)


@pytest.mark.asyncio
async def test_on_message_send_non_blocking(agent_card):
task_store = InMemoryTaskStore()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
from a2a.server.tasks.task_manager import TaskManager
from a2a.types import (
ContentTypeNotSupportedError,
ExtensionSupportRequiredError,
InternalError,
InvalidAgentResponseError,
InvalidParamsError,
Expand All @@ -51,6 +52,7 @@
from a2a.types.a2a_pb2 import (
AgentCapabilities,
AgentCard,
AgentExtension,
AgentInterface,
AgentSkill,
Artifact,
Expand Down Expand Up @@ -1325,6 +1327,92 @@ async def test_on_message_send_stream_rejects_undeclared_media_type():
pass


REQUIRED_EXTENSION = 'https://example.com/ext/required/v1'


def create_required_extension_handler(*, validate_required_extensions: bool):
"""A handler whose card marks one extension as required."""
return DefaultRequestHandlerV2(
agent_executor=HelloAgentExecutor(),
task_store=InMemoryTaskStore(),
agent_card=AgentCard(
name='test_agent',
version='1.0',
capabilities=AgentCapabilities(
streaming=True,
extensions=[
AgentExtension(uri=REQUIRED_EXTENSION, required=True)
],
),
),
validate_required_extensions=validate_required_extensions,
)


def create_hello_request():
return SendMessageRequest(
message=Message(
role=Role.ROLE_USER,
message_id='msg_hello',
parts=[Part(text='hello')],
)
)


@pytest.mark.asyncio
async def test_on_message_send_rejects_missing_required_extension():
handler = create_required_extension_handler(
validate_required_extensions=True
)

with pytest.raises(ExtensionSupportRequiredError):
await handler.on_message_send(
create_hello_request(), create_server_call_context()
)


@pytest.mark.asyncio
async def test_on_message_send_accepts_requested_required_extension():
handler = create_required_extension_handler(
validate_required_extensions=True
)
context = ServerCallContext(
user=UnauthenticatedUser(),
requested_extensions={REQUIRED_EXTENSION},
)

result = await handler.on_message_send(create_hello_request(), context)

assert result is not None


@pytest.mark.asyncio
async def test_on_message_send_skips_required_extensions_by_default():
"""The check is opt-in, so an unflagged handler keeps accepting it."""
handler = create_required_extension_handler(
validate_required_extensions=False
)

result = await handler.on_message_send(
create_hello_request(), create_server_call_context()
)

assert result is not None


@pytest.mark.asyncio
async def test_on_message_send_stream_rejects_missing_required_extension():
handler = create_required_extension_handler(
validate_required_extensions=True
)

with pytest.raises(ExtensionSupportRequiredError):
async for _ in handler.on_message_send_stream(
create_hello_request(), create_server_call_context()
):
pass


@pytest.mark.asyncio
@pytest.mark.parametrize('terminal_state', TERMINAL_TASK_STATES)
async def test_on_message_send_task_in_terminal_state(terminal_state):
Expand Down
52 changes: 52 additions & 0 deletions tests/utils/test_extension_validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import pytest

from a2a.types.a2a_pb2 import AgentCapabilities, AgentCard, AgentExtension
from a2a.utils.errors import ExtensionSupportRequiredError
from a2a.utils.extension_validator import validate_required_extensions


REQUIRED = 'https://example.com/ext/required/v1'
OPTIONAL = 'https://example.com/ext/optional/v1'


def _card(*extensions: AgentExtension) -> AgentCard:
return AgentCard(capabilities=AgentCapabilities(extensions=extensions))


def test_rejects_missing_required_extension():
card = _card(AgentExtension(uri=REQUIRED, required=True))

with pytest.raises(ExtensionSupportRequiredError) as excinfo:
validate_required_extensions(set(), card)

assert REQUIRED in excinfo.value.message


def test_accepts_requested_required_extension():
card = _card(AgentExtension(uri=REQUIRED, required=True))

validate_required_extensions({REQUIRED}, card)


def test_optional_extension_is_not_enforced():
card = _card(AgentExtension(uri=OPTIONAL))

validate_required_extensions(set(), card)


def test_names_every_missing_required_extension():
other = 'https://example.com/ext/other/v1'
card = _card(
AgentExtension(uri=REQUIRED, required=True),
AgentExtension(uri=other, required=True),
)

with pytest.raises(ExtensionSupportRequiredError) as excinfo:
validate_required_extensions({OPTIONAL}, card)

assert REQUIRED in excinfo.value.message
assert other in excinfo.value.message


def test_card_without_extensions_accepts_anything():
validate_required_extensions({OPTIONAL}, AgentCard())
Loading