Skip to content

Commit c25022f

Browse files
authored
fix(server): reject a message whose contextId disagrees with its task (a2aproject#1270)
## What Spec [3.4.3](https://a2a-protocol.org/latest/specification/#343-multi-turn-conversation-patterns): "Agents **MUST** reject messages containing mismatching `contextId` and `taskId` (i.e., the provided `contextId` is different from that of the referenced `Task`)." A follow-up carrying a real `taskId` with someone else's `contextId` was accepted with HTTP 200, and the client's `contextId` was then written into the task's history while the `Task` kept its own - two disagreeing context ids inside one task. ## This guard already existed `RequestContext` has carried it all along (`agent_execution/context.py:77-78`). It only fires when a non-`None` `task` reaches `build()`, and v2 passes `task=None` on purpose: ```python # We will get the task when we have to process the request to avoid concurrent read/write issues. task=None, ``` So the check went dead when V2 became the default. The legacy handler passes the task and still rejects. Rather than undo that deliberate `task=None`, the comparison goes where v2 already fetches the task to prove it exists, one line after the `TaskNotFoundError` it raises there. No extra read, and the task is not retained. ## Scoped to requests that name a task The check only runs under `if original_task_id:`. A `contextId` with no `taskId` is a new task in an existing context, which stays legal - `test_scenario_context_id_visibility` depends on it, and there is a test here pinning it. ## A test that passed for the wrong reason Worth flagging for review. `TaskManager` already rejects this mismatch *once the agent emits an event*, with `Context in event doesn't match TaskManager wrong-context : real-context`. That message happens to contain both context ids, so the obvious assertion - `pytest.raises(InvalidParamsError)` plus both ids in the message - passes with or without this change. It did, and mutation testing is what caught it. The test now asserts the executor was never awaited. That is the actual behavioural difference: the request is refused before any agent work starts, instead of after the agent has already been handed a request whose ids contradict each other. ## Result Clears `CORE-MULTI-006` (`must`) on all three bindings.
1 parent 8037b24 commit c25022f

2 files changed

Lines changed: 105 additions & 0 deletions

File tree

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,15 @@ async def _setup_active_task(
237237
task = await self.task_store.get(original_task_id, call_context)
238238
if not task:
239239
raise TaskNotFoundError(f'Task {original_task_id} not found')
240+
# Agents must reject a message whose contextId differs from that
241+
# of the task it names.
242+
if original_context_id and task.context_id != original_context_id:
243+
raise InvalidParamsError(
244+
message=(
245+
f'Context {original_context_id} does not match '
246+
f'context {task.context_id} of task {original_task_id}'
247+
)
248+
)
240249

241250
# Build context to resolve or generate missing IDs
242251
request_context = await self._request_context_builder.build(

‎tests/server/request_handlers/test_default_request_handler_v2.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,102 @@ async def test_on_message_send_stream_task_in_terminal_state(terminal_state):
11301130
)
11311131

11321132

1133+
@pytest.mark.asyncio
1134+
async def test_on_message_send_rejects_context_id_not_matching_task():
1135+
"""A contextId disagreeing with the named task's is rejected.
1136+
1137+
Asserted on the executor never running, not merely on the error type.
1138+
TaskManager already rejects this mismatch once the agent emits an event
1139+
(`Context in event doesn't match TaskManager`), so an assertion on
1140+
InvalidParamsError alone passes with or without the handler's guard.
1141+
What the guard changes is that the request is refused before any agent
1142+
work starts.
1143+
"""
1144+
task = create_sample_task(task_id='task-1', context_id='real-context')
1145+
mock_task_store = AsyncMock(spec=TaskStore)
1146+
mock_task_store.get.return_value = task
1147+
executor = HelloAgentExecutor()
1148+
executor.execute = AsyncMock(wraps=executor.execute)
1149+
request_handler = DefaultRequestHandlerV2(
1150+
agent_executor=executor,
1151+
task_store=mock_task_store,
1152+
agent_card=create_default_agent_card(),
1153+
)
1154+
params = SendMessageRequest(
1155+
message=Message(
1156+
role=Role.ROLE_USER,
1157+
message_id='msg-mismatch',
1158+
parts=[Part(text='hello')],
1159+
task_id='task-1',
1160+
context_id='wrong-context',
1161+
)
1162+
)
1163+
1164+
with pytest.raises(InvalidParamsError) as exc_info:
1165+
await request_handler.on_message_send(
1166+
params, create_server_call_context()
1167+
)
1168+
1169+
assert (
1170+
'Context wrong-context does not match context real-context'
1171+
in exc_info.value.message
1172+
)
1173+
executor.execute.assert_not_awaited()
1174+
1175+
1176+
@pytest.mark.asyncio
1177+
async def test_on_message_send_accepts_context_id_matching_task():
1178+
task = create_sample_task(task_id='task-1', context_id='real-context')
1179+
mock_task_store = AsyncMock(spec=TaskStore)
1180+
mock_task_store.get.return_value = task
1181+
request_handler = DefaultRequestHandlerV2(
1182+
agent_executor=HelloAgentExecutor(),
1183+
task_store=mock_task_store,
1184+
agent_card=create_default_agent_card(),
1185+
)
1186+
params = SendMessageRequest(
1187+
message=Message(
1188+
role=Role.ROLE_USER,
1189+
message_id='msg-match',
1190+
parts=[Part(text='hello')],
1191+
task_id='task-1',
1192+
context_id='real-context',
1193+
)
1194+
)
1195+
1196+
assert (
1197+
await request_handler.on_message_send(
1198+
params, create_server_call_context()
1199+
)
1200+
is not None
1201+
)
1202+
1203+
1204+
@pytest.mark.asyncio
1205+
async def test_on_message_send_accepts_context_id_without_task_id():
1206+
"""A contextId alone starts a new task in that context, so it is not checked."""
1207+
request_handler = DefaultRequestHandlerV2(
1208+
agent_executor=HelloAgentExecutor(),
1209+
task_store=InMemoryTaskStore(),
1210+
agent_card=create_default_agent_card(),
1211+
)
1212+
params = SendMessageRequest(
1213+
message=Message(
1214+
role=Role.ROLE_USER,
1215+
message_id='msg-context-only',
1216+
parts=[Part(text='hello')],
1217+
context_id='client-chosen-context',
1218+
)
1219+
)
1220+
1221+
assert (
1222+
await request_handler.on_message_send(
1223+
params, create_server_call_context()
1224+
)
1225+
is not None
1226+
)
1227+
1228+
11331229
@pytest.mark.asyncio
11341230
@pytest.mark.parametrize('terminal_state', TERMINAL_TASK_STATES)
11351231
async def test_on_subscribe_to_task_in_terminal_state(terminal_state):

0 commit comments

Comments
 (0)