Skip to content

Commit 0fc0d3a

Browse files
Shay-DengclaudeIwaniukooo11
authored
fix(rest): serve HTTP+JSON error responses as application/a2a+json (#1446)
# Description #1274 made 1.0 HTTP+JSON success responses `application/a2a+json` and deliberately left the error path on `application/json`, since `rest_error_handler` is shared with the v0.3 REST adapter, calling it worth a follow-up. This is that follow-up. Spec [11.1](https://a2a-protocol.org/latest/specification/#111-protocol-requirements) says `application/a2a+json` SHOULD be used for responses, and the error example in [11.6](https://a2a-protocol.org/latest/specification/#116-error-handling) is served as `Content-Type: application/a2a+json`. The spec's own examples in 6.4 and 6.5 still show `application/problem+json`; a2aproject/A2A#1689 updates them. Changes: - `rest_error_handler` and `rest_stream_error_handler` take a keyword-only `media_type`, defaulting to `application/json`, so every existing caller is unchanged. - `RestDispatcher` (1.0) decorates its handlers with `functools.partial(..., media_type=constants.A2A_JSON_MEDIA_TYPE)`. - The v0.3 adapter keeps `application/json`; `test_v03_message_stream_malformed_json_returns_400` already pins that. - The client side does not look at the error `Content-Type`, so SDK clients are unaffected. Testing: - `./scripts/lint.sh` passes (ruff check, ruff format, ty). - `uv run pytest --cov=src`: 2562 passed, 207 skipped; total coverage 94%. - Two new tests in `tests/server/routes/test_rest_routes.py` cover a handler error (404) and an error raised before the first stream event (400 for an unsupported `A2A-Version`). Both fail on `main` and pass with this change. - Ran the a2a-tck reference SUT built from this branch: `HTTP_JSON-SVC-001` (error Content-Type SHOULD be `application/a2a+json`) now passes. One thing to know: a2a-tck `main` currently has a check under `HTTP_JSON-ERR-001` that rejects any error Content-Type other than `application/json`, which contradicts its own `HTTP_JSON-SVC-001` and the 11.6 example. Open a2a-tck PR a2aproject/a2a-tck#238 relaxes it. Until that lands, a TCK run from a2a-tck `main` reports `HTTP_JSON-ERR-001` instead of `HTTP_JSON-SVC-001` for this SDK. This repo's `run-tck.yaml` pins TCK `0.3.0.beta3` on JSON-RPC, so CI here is unaffected. - [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) AI assistance: developed with help from Claude Code. I reviewed the change, and the checks listed under Testing were run locally. Follow-up to #1274 🦕 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Mateusz Iwaniuk <45974414+Iwaniukooo11@users.noreply.github.com>
1 parent af9437f commit 0fc0d3a

3 files changed

Lines changed: 83 additions & 21 deletions

File tree

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

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ async def event_generator() -> AsyncIterator[ServerSentEvent]:
170170
shutdown_grace_period=self._shutdown_grace_period,
171171
)
172172

173-
@rest_error_handler
173+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
174174
async def on_message_send(self, request: Request) -> Response:
175175
"""Handles the 'message/send' REST method."""
176176

@@ -191,7 +191,7 @@ async def _handler(
191191
response = await self._handle_non_streaming(request, _handler)
192192
return A2AJSONResponse(content=MessageToDict(response))
193193

194-
@rest_stream_error_handler
194+
@rest_stream_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
195195
async def on_message_send_stream(
196196
self, request: Request
197197
) -> EventSourceResponse:
@@ -212,7 +212,7 @@ async def _handler(
212212

213213
return await self._handle_streaming(request, _handler)
214214

215-
@rest_error_handler
215+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
216216
async def on_cancel_task(self, request: Request) -> Response:
217217
"""Handles the 'tasks/cancel' REST method."""
218218

@@ -231,7 +231,7 @@ async def _handler(context: ServerCallContext) -> a2a_pb2.Task:
231231
response = await self._handle_non_streaming(request, _handler)
232232
return A2AJSONResponse(content=MessageToDict(response))
233233

234-
@rest_stream_error_handler
234+
@rest_stream_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
235235
async def on_subscribe_to_task(
236236
self, request: Request
237237
) -> EventSourceResponse:
@@ -250,7 +250,7 @@ async def _handler(
250250

251251
return await self._handle_streaming(request, _handler)
252252

253-
@rest_error_handler
253+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
254254
async def on_get_task(self, request: Request) -> Response:
255255
"""Handles the 'tasks/{id}' REST method."""
256256

@@ -267,7 +267,7 @@ async def _handler(context: ServerCallContext) -> a2a_pb2.Task:
267267
response = await self._handle_non_streaming(request, _handler)
268268
return A2AJSONResponse(content=MessageToDict(response))
269269

270-
@rest_error_handler
270+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
271271
async def get_push_notification(self, request: Request) -> Response:
272272
"""Handles the 'tasks/pushNotificationConfig/get' REST method."""
273273

@@ -289,7 +289,7 @@ async def _handler(
289289
response = await self._handle_non_streaming(request, _handler)
290290
return A2AJSONResponse(content=MessageToDict(response))
291291

292-
@rest_error_handler
292+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
293293
async def delete_push_notification(self, request: Request) -> Response:
294294
"""Handles the 'tasks/pushNotificationConfig/delete' REST method."""
295295

@@ -307,7 +307,7 @@ async def _handler(context: ServerCallContext) -> None:
307307
await self._handle_non_streaming(request, _handler)
308308
return A2AJSONResponse(content={})
309309

310-
@rest_error_handler
310+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
311311
async def set_push_notification(self, request: Request) -> Response:
312312
"""Handles the 'tasks/pushNotificationConfig/set' REST method."""
313313

@@ -326,7 +326,7 @@ async def _handler(
326326
response = await self._handle_non_streaming(request, _handler)
327327
return A2AJSONResponse(content=MessageToDict(response))
328328

329-
@rest_error_handler
329+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
330330
async def list_push_notifications(self, request: Request) -> Response:
331331
"""Handles the 'tasks/pushNotificationConfig/list' REST method."""
332332

@@ -344,7 +344,7 @@ async def _handler(
344344
response = await self._handle_non_streaming(request, _handler)
345345
return A2AJSONResponse(content=MessageToDict(response))
346346

347-
@rest_error_handler
347+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
348348
async def list_tasks(self, request: Request) -> Response:
349349
"""Handles the 'tasks/list' REST method."""
350350
params = a2a_pb2.ListTasksRequest()
@@ -363,7 +363,7 @@ async def _handler(
363363
)
364364
)
365365

366-
@rest_error_handler
366+
@rest_error_handler(media_type=constants.A2A_JSON_MEDIA_TYPE)
367367
async def handle_authenticated_agent_card(
368368
self, request: Request
369369
) -> Response:

‎src/a2a/utils/error_handlers.py‎

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
ERROR_INFO_TYPE = 'type.googleapis.com/google.rpc.ErrorInfo'
3636
BAD_REQUEST_TYPE = 'type.googleapis.com/google.rpc.BadRequest'
3737
A2A_DOMAIN = 'a2a-protocol.org'
38+
JSON_MEDIA_TYPE = 'application/json'
3839

3940

4041
def _error_info(
@@ -131,7 +132,9 @@ def build_rest_error_payload(error: Exception) -> dict[str, Any]:
131132
)
132133

133134

134-
def _create_error_response(error: Exception) -> Response:
135+
def _create_error_response(
136+
error: Exception, media_type: str = JSON_MEDIA_TYPE
137+
) -> Response:
135138
"""Helper function to create a JSONResponse for an error."""
136139
if isinstance(error, A2AError):
137140
log_level = (
@@ -157,29 +160,62 @@ def _create_error_response(error: Exception) -> Response:
157160
return JSONResponse(
158161
content=payload,
159162
status_code=http_code,
160-
media_type='application/json',
163+
media_type=media_type,
161164
)
162165

163166

164167
def rest_error_handler(
165-
func: Callable[..., Awaitable[Response]],
166-
) -> Callable[..., Awaitable[Response]]:
167-
"""Decorator to catch A2AError and map it to an appropriate JSONResponse."""
168+
func: Callable[..., Awaitable[Response]] | None = None,
169+
*,
170+
media_type: str = JSON_MEDIA_TYPE,
171+
) -> Callable:
172+
"""Decorator to catch A2AError and map it to an appropriate JSONResponse.
173+
174+
Use it as ``@rest_error_handler``, or as
175+
``@rest_error_handler(media_type=...)`` to set the error Content-Type.
176+
177+
Args:
178+
func: The handler to wrap. None when called with arguments only.
179+
media_type: The Content-Type of the error response.
180+
181+
Returns:
182+
The wrapped handler, or a partial decorator if ``func`` is None.
183+
"""
184+
if func is None:
185+
return functools.partial(rest_error_handler, media_type=media_type)
168186

169187
@functools.wraps(func)
170188
async def wrapper(*args: Any, **kwargs: Any) -> Response:
171189
try:
172190
return await func(*args, **kwargs)
173191
except Exception as error: # noqa: BLE001
174-
return _create_error_response(error)
192+
return _create_error_response(error, media_type)
175193

176194
return wrapper
177195

178196

179197
def rest_stream_error_handler(
180-
func: Callable[..., Coroutine[Any, Any, Any]],
181-
) -> Callable[..., Coroutine[Any, Any, Any]]:
182-
"""Decorator to catch A2AError for a streaming method. Maps synchronous errors to JSONResponse and logs streaming errors."""
198+
func: Callable[..., Coroutine[Any, Any, Any]] | None = None,
199+
*,
200+
media_type: str = JSON_MEDIA_TYPE,
201+
) -> Callable:
202+
"""Decorator to catch A2AError for a streaming method. Maps synchronous errors to JSONResponse and logs streaming errors.
203+
204+
Use it as ``@rest_stream_error_handler``, or as
205+
``@rest_stream_error_handler(media_type=...)`` to set the error
206+
Content-Type.
207+
208+
Args:
209+
func: The handler to wrap. None when called with arguments only.
210+
media_type: The Content-Type of a synchronous error response.
211+
212+
Returns:
213+
The wrapped handler, or a partial decorator if ``func`` is None.
214+
"""
215+
if func is None:
216+
return functools.partial(
217+
rest_stream_error_handler, media_type=media_type
218+
)
183219

184220
def _log_error(error: Exception) -> None:
185221
if isinstance(error, A2AError):
@@ -223,7 +259,7 @@ async def error_catching_iterator() -> AsyncGenerator[
223259
response.body_iterator = error_catching_iterator()
224260

225261
except Exception as e: # noqa: BLE001
226-
return _create_error_response(e)
262+
return _create_error_response(e, media_type)
227263
else:
228264
return response
229265

‎tests/server/routes/test_rest_routes.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from a2a.server.request_handlers.request_handler import RequestHandler
66
from a2a.server.routes.rest_routes import create_rest_routes
77
from a2a.types.a2a_pb2 import AgentCard, ListTasksResponse, Task
8+
from a2a.utils.errors import TaskNotFoundError
89
from starlette.applications import Starlette
910
from starlette.routing import BaseRoute
1011
from starlette.testclient import TestClient
@@ -182,3 +183,28 @@ def test_list_tasks_response_uses_the_a2a_media_type(agent_card, mock_handler):
182183
response = client.get('/tasks', headers={'A2A-Version': '1.0'})
183184

184185
assert response.headers['content-type'].startswith('application/a2a+json')
186+
187+
188+
def test_error_response_uses_the_a2a_media_type(agent_card, mock_handler):
189+
"""Error responses are labelled application/a2a+json too (spec 11.1)."""
190+
mock_handler.on_get_task.side_effect = TaskNotFoundError()
191+
client = TestClient(Starlette(routes=create_rest_routes(mock_handler)))
192+
193+
response = client.get('/tasks/missing', headers={'A2A-Version': '1.0'})
194+
195+
assert response.status_code == 404
196+
assert response.headers['content-type'].startswith('application/a2a+json')
197+
198+
199+
def test_stream_error_response_uses_the_a2a_media_type(
200+
agent_card, mock_handler
201+
):
202+
"""An error raised before the first stream event is labelled the same way."""
203+
client = TestClient(Starlette(routes=create_rest_routes(mock_handler)))
204+
205+
response = client.post(
206+
'/message:stream', json={}, headers={'A2A-Version': '9.9'}
207+
)
208+
209+
assert response.status_code == 400
210+
assert response.headers['content-type'].startswith('application/a2a+json')

0 commit comments

Comments
 (0)