diff --git a/a2a/docs/features/server-core.md b/a2a/docs/features/server-core.md index 36b728f5..620d83d3 100644 --- a/a2a/docs/features/server-core.md +++ b/a2a/docs/features/server-core.md @@ -25,6 +25,26 @@ description: "Server-core spec: factory, execution router, task state machine, a Core server machinery: factory that wires everything together, router that dispatches A2A messages to apcore Executor, task manager with the state machine, and transport that serves JSON-RPC + REST endpoints. +## JSON-RPC compatibility + +Use `A2A-Version: 1.0` for the standard JSON-RPC methods `SendMessage`, +`GetTask`, `CancelTask`, and `ListTasks`. `SendMessage` wraps its Task in +`result.task`. An omitted or empty version header preserves the legacy +`message/send` and `tasks/*` client flow. An unsupported explicit version +returns `-32009` with the request ID and does not dispatch the operation. + +`ListTasks` scopes results to the authenticated caller before applying +filters and pagination. The last page includes an empty `nextPageToken`. + +The Rust A2A 1.0 interface advertises its implemented capabilities in the +Agent Card. The modern streaming and push operations return their respective +unsupported-operation errors. Rust `SendMessage` starts a new task. +A continuation request for an existing visible task returns +`UnsupportedOperationError`. Existing Rust legacy streaming remains available +through the legacy JSON-RPC methods. + +[A2A versioning and JSON-RPC binding](https://a2a-protocol.org/v1.0.0/specification/#36-versioning) + ## Components ### 1. `A2AServerFactory` — `server/factory.py` diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index d600c574..c588be42 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -17,7 +17,9 @@ from a2a.server.context import ServerCallContext from a2a.server.request_handlers import DefaultRequestHandler -from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes, create_rest_routes +from a2a.server.request_handlers.response_helpers import build_error_response +from a2a.server.routes import create_agent_card_routes, create_rest_routes +from a2a.server.routes.jsonrpc_dispatcher import JsonRpcDispatcher from a2a.server.tasks.inmemory_push_notification_config_store import ( InMemoryPushNotificationConfigStore, ) @@ -34,15 +36,15 @@ TaskState, TaskStatusUpdateEvent, ) -from a2a.utils.constants import DEFAULT_LIST_TASKS_PAGE_SIZE -from a2a.utils.errors import InvalidParamsError, TaskNotCancelableError, TaskNotFoundError +from a2a.utils.constants import DEFAULT_LIST_TASKS_PAGE_SIZE, PROTOCOL_VERSION_0_3, VERSION_HEADER +from a2a.utils.errors import InvalidParamsError, TaskNotCancelableError, TaskNotFoundError, VersionNotSupportedError from apcore.error_formatter import ErrorFormatterRegistry from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.cors import CORSMiddleware from starlette.requests import Request -from starlette.responses import JSONResponse +from starlette.responses import JSONResponse, Response from starlette.routing import Route from apcore_a2a._config import register_a2a_namespace @@ -423,6 +425,37 @@ def _warn_on_unprotected_control_surface(executor: Any) -> None: ) +def _jsonrpc_route( + handler: DefaultRequestHandler, context_builder: AuthIdentityServerCallContextBuilder, card: AgentCard +) -> Route: + dispatcher = JsonRpcDispatcher( + request_handler=handler, context_builder=context_builder, enable_v0_3_compat=True + ) + supported = { + interface.protocol_version for interface in card.supported_interfaces if interface.protocol_binding == "JSONRPC" + } + supported.add(PROTOCOL_VERSION_0_3) + + async def dispatch(request: Request) -> Response: + version = request.headers.get(VERSION_HEADER) + if not version or version in supported: + return await dispatcher.handle_requests(request) + + # The SDK dispatches legacy method names before it validates the + # version, then maps their version exception to an internal error. + try: + body = await request.json() + except (json.JSONDecodeError, UnicodeDecodeError): + return await dispatcher.handle_requests(request) + request_id = body.get("id") if isinstance(body, dict) else None + if type(request_id) not in (str, int): + request_id = None + error = VersionNotSupportedError(message="The requested A2A protocol version is not supported") + return JSONResponse(build_error_response(request_id, error)) + + return Route("/", dispatch, methods=["POST"]) + + class A2AServerFactory: def __init__(self) -> None: self._schema_converter = SchemaConverter() @@ -745,17 +778,11 @@ async def extended_card_modifier( # type: ignore[misc] # bucket and ListTasks returns every caller's tasks. context_builder = AuthIdentityServerCallContextBuilder() rest_routes = create_rest_routes(request_handler=handler, context_builder=context_builder) - # enable_v0_3_compat: support legacy 0.3.x method names (message/send, tasks/get, etc.) - jsonrpc_routes = create_jsonrpc_routes( - request_handler=handler, - rpc_url="/", - context_builder=context_builder, - enable_v0_3_compat=True, - ) + jsonrpc_route = _jsonrpc_route(handler, context_builder, agent_card) # custom_routes first: REST routes include Mount /{tenant} which catches all paths # including /explorer, /health etc. if placed before them. - all_routes = custom_routes + agent_card_routes + agent_card_routes_legacy + list(rest_routes) + jsonrpc_routes + all_routes = custom_routes + agent_card_routes + agent_card_routes_legacy + list(rest_routes) + [jsonrpc_route] app = Starlette(routes=all_routes, middleware=middleware) diff --git a/a2a/python/tests/server/test_jsonrpc_interop.py b/a2a/python/tests/server/test_jsonrpc_interop.py new file mode 100644 index 00000000..f2723e0b --- /dev/null +++ b/a2a/python/tests/server/test_jsonrpc_interop.py @@ -0,0 +1,153 @@ +"""Real A2A JSON-RPC factory requests with both supported protocol dialects.""" + +import asyncio + +import httpx +import pytest +from apcore import APCore, Identity + +from apcore_a2a.server.factory import A2AServerFactory + +SKILL = "wire.echo" + + +class _BearerAuthenticator: + def authenticate(self, headers: dict[str, str]) -> Identity | None: + token = headers.get("authorization", "").removeprefix("Bearer ") + return Identity(id=token) if token else None + + def security_schemes(self) -> dict: + return {"bearerAuth": {"type": "http", "scheme": "bearer"}} + + +def _app(): + core = APCore() + calls: list[bool] = [] + waiting = asyncio.Event() + + @core.module(SKILL, tags=["wire"]) + async def echo(wait: bool = False) -> dict: + calls.append(wait) + if wait: + waiting.set() + await asyncio.Future() + return {"echo": True} + + app, _ = A2AServerFactory().create( + core.registry, + core.executor, + name="Interop", + description="A2A echo", + version="1", + url="http://wire.test/", + auth=_BearerAuthenticator(), + ) + return app, calls, waiting + + +def _message(message_id: str, *, legacy: bool = False, wait: bool = False) -> dict: + if legacy: + role, part = "user", {"kind": "text", "text": "{}"} + else: + role, part = "ROLE_USER", {"data": {"wait": wait}} + return {"messageId": message_id, "role": role, "parts": [part], "metadata": {"skillId": SKILL}} + + +async def _rpc(client, method, params, *, version="1.0", request_id=0, owner="alice"): + headers = {"Authorization": f"Bearer {owner}"} + if version is not None: + headers["A2A-Version"] = version + response = await client.post( + "/", + headers=headers, + json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}, + ) + assert response.status_code == 200 + return response.json() + + +@pytest.mark.parametrize("method", ["SendMessage", "message/send"]) +@pytest.mark.parametrize("request_id", [0, "version-check"]) +async def test_unsupported_version_keeps_id_without_execution_or_storage(method, request_id): + app, calls, _ = _app() + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://wire.test") as client: + response = await _rpc( + client, + method, + {"message": _message("rejected", legacy=method == "message/send")}, + version="99.0", + request_id=request_id, + ) + assert response["id"] == request_id + assert response["error"]["code"] == -32009 + listing = await _rpc(client, "ListTasks", {}) + assert listing["result"] == {"tasks": [], "pageSize": 50, "totalSize": 0, "nextPageToken": ""} + assert calls == [] + + +async def test_live_card_and_versioned_lifecycle_preserve_legacy_and_owner_isolation(): + app, calls, waiting = _app() + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://wire.test") as client: + card_response = await client.get("/.well-known/agent-card.json") + assert card_response.status_code == 200 + card = card_response.json() + assert {"protocolBinding": "JSONRPC", "protocolVersion": "1.0", "url": "http://wire.test/"} in ( + card["supportedInterfaces"] + ) + assert card["capabilities"]["streaming"] + assert card["capabilities"]["extendedAgentCard"] + extended = await _rpc(client, "GetExtendedAgentCard", {}) + assert extended["result"]["name"] == card["name"] + + completed = [] + for index, version in enumerate((None, "")): + legacy = await _rpc( + client, + "message/send", + {"message": _message(f"legacy-{index}", legacy=True)}, + version=version, + ) + assert legacy["result"]["status"]["state"] == "completed" + completed.append(legacy["result"]["id"]) + read_legacy = await _rpc(client, "tasks/get", {"id": completed[-1]}, version=version) + assert read_legacy["result"]["id"] == completed[-1] + + response = await _rpc(client, "SendMessage", {"message": _message("v1-complete")}) + finished = response["result"]["task"] + assert finished["status"]["state"] == "TASK_STATE_COMPLETED" + completed.append(finished["id"]) + read = await _rpc(client, "GetTask", {"id": finished["id"]}) + assert read["result"]["id"] == finished["id"] + await _rpc(client, "SendMessage", {"message": _message("bob-task")}, owner="bob") + + running = await _rpc( + client, + "SendMessage", + {"message": _message("v1-running", wait=True), "configuration": {"returnImmediately": True}}, + ) + running_id = running["result"]["task"]["id"] + await asyncio.wait_for(waiting.wait(), timeout=2) + cancelled = await _rpc(client, "CancelTask", {"id": running_id}) + assert cancelled["result"]["status"]["state"] == "TASK_STATE_CANCELED" + queried = await _rpc(client, "GetTask", {"id": running_id}) + assert queried["result"]["status"]["state"] == "TASK_STATE_CANCELED" + + first = (await _rpc(client, "ListTasks", {"pageSize": 2}))["result"] + assert first["totalSize"] == 4 + assert len(first["tasks"]) == 2 + assert all("artifacts" not in task for task in first["tasks"]) + second = (await _rpc(client, "ListTasks", {"pageSize": 2, "pageToken": first["nextPageToken"]}))["result"] + assert second["nextPageToken"] == "" + assert {task["id"] for task in first["tasks"] + second["tasks"]} == {*completed, running_id} + + filtered = ( + await _rpc( + client, + "ListTasks", + {"status": "TASK_STATE_COMPLETED", "contextId": finished["contextId"]}, + ) + )["result"] + assert [task["id"] for task in filtered["tasks"]] == [finished["id"]] + assert filtered["nextPageToken"] == "" + assert filtered["pageSize"] == 50 + assert calls == [False, False, False, False, True] diff --git a/a2a/rust/src/server/factory.rs b/a2a/rust/src/server/factory.rs index 5d71cbf0..9521dee7 100644 --- a/a2a/rust/src/server/factory.rs +++ b/a2a/rust/src/server/factory.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use axum::{ extract::State, - http::StatusCode, + http::{header, HeaderMap, StatusCode}, response::{IntoResponse, Response}, routing::{get, post}, Json, Router, @@ -24,6 +24,7 @@ use crate::server::handlers::{ self, explorer_card as explorer_card_handler, explorer_html, jsonrpc_handler, AppState, AuthIdentity, FilteredCard, }; +use crate::server::wire::{WireVersion, VERSION_HEADER, VERSION_NOT_SUPPORTED}; use crate::storage::{InMemoryPushConfigStore, InMemoryTaskStore, PushConfigStore, TaskStore}; /// Everything [`A2AServerFactory::create`] needs to build a server. @@ -155,7 +156,7 @@ impl A2AServerFactory { extended_agent_card: auth.is_some(), }; - let agent_card = self.agent_card_builder.build( + let mut agent_card = self.agent_card_builder.build( registry, &name, &description, @@ -279,6 +280,8 @@ impl A2AServerFactory { router = router.layer(AuthMiddlewareLayer::new(authenticator, exempt)); } + // The public factory API also describes the 1.0 binding. + agent_card.capabilities.streaming = false; (router, agent_card) } } @@ -287,8 +290,25 @@ async fn health() -> Json { Json(json!({ "status": "healthy" })) } -async fn serve_card(State(state): State) -> Json { - handlers::public_agent_card(State(state)).await +async fn serve_card(State(state): State, headers: HeaderMap) -> Response { + card_response(&headers, || Some(state.agent_card.as_ref().clone())) +} + +fn card_response(headers: &HeaderMap, card: impl FnOnce() -> Option) -> Response { + let result = match WireVersion::negotiate(headers, WireVersion::V1) { + Ok(version) => match card() { + Some(card) => Json(version.project_card(card)).into_response(), + None => ( + StatusCode::NOT_FOUND, + Json(json!({ "error": "Extended agent card is not configured" })), + ).into_response(), + }, + Err(()) => ( + StatusCode::BAD_REQUEST, + Json(json!({ "error": { "code": VERSION_NOT_SUPPORTED, "message": "Version not supported" } })), + ).into_response(), + }; + ([(header::VARY, VERSION_HEADER)], result).into_response() } /// `GET /agent/authenticatedExtendedCard` (srs FR-AGC-004). @@ -298,15 +318,11 @@ async fn serve_card(State(state): State) -> Json { async fn serve_extended_card( State(state): State, AuthIdentity(identity): AuthIdentity, + headers: HeaderMap, ) -> Response { - match handlers::extended_agent_card(&state, identity.as_ref()) { - Some(card) => Json(card).into_response(), - None => ( - StatusCode::NOT_FOUND, - Json(json!({ "error": "Extended agent card is not configured" })), - ) - .into_response(), - } + card_response(&headers, || { + handlers::extended_agent_card(&state, identity.as_ref()) + }) } /// Register the `apcore-a2a` config namespace. Idempotent, and shared with the diff --git a/a2a/rust/src/server/handlers.rs b/a2a/rust/src/server/handlers.rs index f0b1bb87..b2909013 100644 --- a/a2a/rust/src/server/handlers.rs +++ b/a2a/rust/src/server/handlers.rs @@ -30,6 +30,10 @@ use uuid::Uuid; use crate::adapters::errors::{carries_caller_detail, sanitize_message, ErrorMapper}; use crate::server::executor::ApCoreAgentExecutor; +use crate::server::wire::{ + self, ListOptions, RpcFailure, WireVersion, INVALID_PARAMS as CODE_INVALID_PARAMS, + PUSH_NOT_SUPPORTED, UNSUPPORTED_OPERATION, VERSION_NOT_SUPPORTED, +}; use crate::storage::{CallContext, ListParams, OwnerId, PushConfigStore, StoreError, TaskStore}; use crate::types::{ Artifact, Message, StreamEvent, Task, TaskArtifactUpdateEvent, TaskState, TaskStatus, @@ -84,7 +88,7 @@ pub async fn explorer_html() -> Html<&'static str> { /// Already filtered for the anonymous principal at build time, so this is a /// memory read — no `ACL::check`, no audit write, no per-caller cache lookup. pub async fn public_agent_card(State(state): State) -> Json { - Json(state.agent_card.as_ref().clone()) + Json(WireVersion::V1.project_card(state.agent_card.as_ref().clone())) } /// Serve the extended Agent Card for the authenticated caller (srs FR-AGC-004). @@ -412,7 +416,6 @@ fn sse_event(id: &Value, event: &StreamEvent) -> Event { const CODE_PARSE_ERROR: i32 = -32700; const CODE_INVALID_REQUEST: i32 = -32600; const CODE_METHOD_NOT_FOUND: i32 = -32601; -const CODE_INVALID_PARAMS: i32 = -32602; const CODE_TASK_NOT_FOUND: i32 = -32001; const CODE_TASK_NOT_CANCELABLE: i32 = -32002; const CODE_INTERNAL_ERROR: i32 = -32603; @@ -594,57 +597,80 @@ pub async fn jsonrpc_handler( } let id = req.get("id").cloned().unwrap_or(Value::Null); + let Ok(version) = WireVersion::negotiate(&headers, WireVersion::Legacy) else { + return Json(rpc_error( + &id, + VERSION_NOT_SUPPORTED, + "Version not supported", + )) + .into_response(); + }; let method = req.get("method").and_then(Value::as_str).unwrap_or(""); - let params = req.get("params").cloned().unwrap_or(Value::Null); + let params = req.get("params").unwrap_or(&Value::Null); let ctx = CallContext::from_identity(identity.as_ref()); - match method { - "message/send" => match handle_send(&state, identity, &ctx, ¶ms).await { - Ok(task) => Json(rpc_result(&id, task)).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), - }, - "message/stream" => handle_stream(&state, identity, &ctx, ¶ms, id).await, - "tasks/get" => match handle_get(&state, &ctx, ¶ms).await { - Ok(task) => Json(rpc_result(&id, task)).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), - }, - "tasks/cancel" => match handle_cancel(&state, &ctx, ¶ms).await { - Ok(task) => Json(rpc_result(&id, task)).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), - }, - "ListTasks" => match handle_list(&state, &ctx).await { - Ok(tasks) => Json(rpc_result(&id, json!({ "tasks": tasks }))).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), - }, - // srs FR-AGC-004 / FR-AGC-006. Previously this crate advertised - // `capabilities.extendedAgentCard` and dispatched nothing, so a client - // that read the flag and called the method — which A2A §3.2.x entitles - // it to do — got method-not-found. - "GetExtendedAgentCard" => match extended_agent_card(&state, identity.as_ref()) { - Some(card) => Json(rpc_result(&id, card)).into_response(), - None => Json(rpc_error( - &id, - CODE_EXTENDED_CARD_NOT_CONFIGURED, - "Extended agent card is not configured", - )) - .into_response(), - }, - "tasks/pushNotificationConfig/set" => match handle_push_set(&state, &ctx, ¶ms).await { - Ok(v) => Json(rpc_result(&id, v)).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), + use WireVersion::{Legacy, V1}; + let result = match (version, method) { + (Legacy, "message/send") | (V1, "SendMessage") => { + dispatch_send(&state, identity, &ctx, params, version).await + } + (Legacy, "message/stream") => { + return handle_stream(&state, identity, &ctx, params, id).await + } + (Legacy, "tasks/get") | (V1, "GetTask") => { + dispatch_get(&state, &ctx, params, version).await + } + (Legacy, "tasks/cancel") | (V1, "CancelTask") => handle_cancel(&state, &ctx, params).await, + (_, "ListTasks") => match version { + Legacy => handle_list(&state, &ctx) + .await + .map(|tasks| json!({ "tasks": tasks })), + V1 => match ListOptions::parse(params) { + Ok(options) => handle_list(&state, &ctx) + .await + .and_then(|tasks| options.project(tasks)), + Err(error) => Err(error), + }, }, - "tasks/pushNotificationConfig/get" => match handle_push_get(&state, &ctx, ¶ms).await { - Ok(v) => Json(rpc_result(&id, v)).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), + (_, "GetExtendedAgentCard") => match extended_agent_card(&state, identity.as_ref()) { + Some(card) if version == V1 => Ok(version.project_card(card)), + Some(card) => Ok(card), + None => Err(( + if version == V1 { + UNSUPPORTED_OPERATION + } else { + CODE_EXTENDED_CARD_NOT_CONFIGURED + }, + "Extended agent card is not configured".to_string(), + )), }, - "tasks/pushNotificationConfig/delete" => { - match handle_push_delete(&state, &ctx, ¶ms).await { - Ok(v) => Json(rpc_result(&id, v)).into_response(), - Err((code, msg)) => Json(rpc_error(&id, code, &msg)).into_response(), - } + (Legacy, "tasks/pushNotificationConfig/set") => handle_push_set(&state, &ctx, params).await, + (Legacy, "tasks/pushNotificationConfig/get") => handle_push_get(&state, &ctx, params).await, + (Legacy, "tasks/pushNotificationConfig/delete") => { + handle_push_delete(&state, &ctx, params).await } - _ => Json(rpc_error(&id, CODE_METHOD_NOT_FOUND, "Method not found")).into_response(), - } + (V1, "SendStreamingMessage" | "SubscribeToTask") => Err(( + UNSUPPORTED_OPERATION, + "Streaming is not supported".to_string(), + )), + ( + V1, + "CreateTaskPushNotificationConfig" + | "GetTaskPushNotificationConfig" + | "ListTaskPushNotificationConfigs" + | "DeleteTaskPushNotificationConfig", + ) => Err(( + PUSH_NOT_SUPPORTED, + "Push notification is not supported".to_string(), + )), + _ => Err((CODE_METHOD_NOT_FOUND, "Method not found".to_string())), + }; + + Json(match result { + Ok(value) => rpc_result(&id, value), + Err((code, message)) => rpc_error(&id, code, &message), + }) + .into_response() } /// Outcome of a failed request parse. @@ -817,12 +843,58 @@ fn submitted_task(task_id: &str, context_id: &str) -> Task { } /// `message/send` — run to completion, return the final Task. +async fn dispatch_send( + state: &AppState, + identity: Option, + ctx: &CallContext, + params: &Value, + version: WireVersion, +) -> Result { + if version == WireVersion::Legacy { + return handle_send(state, identity, ctx, params, false).await; + } + + let options = wire::send_options(params)?; + if let Some(task_id) = params["message"]["taskId"] + .as_str() + .filter(|id| !id.is_empty()) + { + if read_task(state, task_id, ctx).await?.is_none() { + return Err((CODE_TASK_NOT_FOUND, "Task not found".to_string())); + } + return Err(( + UNSUPPORTED_OPERATION, + "Task continuation is not supported".to_string(), + )); + } + let mut task = handle_send(state, identity, ctx, params, options.return_immediately).await?; + wire::project_history(&mut task, options.history_length); + Ok(json!({ "task": task })) +} + +async fn dispatch_get( + state: &AppState, + ctx: &CallContext, + params: &Value, + version: WireVersion, +) -> Result { + let history = if version == WireVersion::V1 { + wire::get_history_length(params)? + } else { + None + }; + let mut task = handle_get(state, ctx, params).await?; + wire::project_history(&mut task, history); + Ok(task) +} + async fn handle_send( state: &AppState, identity: Option, ctx: &CallContext, params: &Value, -) -> Result { + return_immediately: bool, +) -> Result { let (skill_id, task_id, context_id, inputs) = match parse_request(state, params) { Ok(v) => v, Err(ParseFailure::Rpc(code, msg)) => return Err((code, msg)), @@ -846,62 +918,97 @@ async fn handle_send( .await; } - let mut task = submitted_task(&task_id, &context_id); + let task = submitted_task(&task_id, &context_id); + let submitted = serde_json::to_value(&task).unwrap(); let running = state.running_tasks.register(&task_id, ctx); - let execution = &running.execution; - - save_task( - state, - &task_id, - serde_json::to_value(&task).unwrap(), - ctx, - Some(&skill_id), - ) - .await?; - let result = state - .executor - .call(&skill_id, inputs, identity, execution.token.clone()) - .await; + save_task(state, &task_id, submitted.clone(), ctx, Some(&skill_id)).await?; - let terminal = execution.terminal.lock().await; - if execution.canceled_status().is_some() { - return read_task(state, &task_id, ctx) - .await? - .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string())); + let submission = SubmittedSend { + task, + running, + skill_id, + inputs, + }; + if return_immediately { + let state = state.clone(); + let ctx = ctx.clone(); + tokio::spawn(async move { + // Store failures are logged by the common save/read path. + let _ = submission.complete(&state, identity, &ctx).await; + }); + Ok(submitted) + } else { + submission.complete(state, identity, ctx).await } +} + +struct SubmittedSend { + task: Task, + running: RunningTask, + skill_id: String, + inputs: Value, +} - match result { - Ok(output) => { - let artifact = state - .executor - .part_converter() - .output_to_parts(&output, &task_id); - task.artifacts = vec![artifact]; - task.status = TaskStatus::new(TaskState::Completed); +impl SubmittedSend { + async fn complete( + self, + state: &AppState, + identity: Option, + ctx: &CallContext, + ) -> Result { + let SubmittedSend { + mut task, + running, + skill_id, + inputs, + } = self; + let task_id = &task.id; + let execution = &running.execution; + let result = state + .executor + .call(&skill_id, inputs, identity, execution.token.clone()) + .await; + + let terminal = execution.terminal.lock().await; + if execution.canceled_status().is_some() { + return read_task(state, task_id, ctx) + .await? + .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string())); } - Err(err) => { - task.status = error_to_status(&err, state.executor.disclose_refusal_reason()); + + match result { + Ok(output) => { + let artifact = state + .executor + .part_converter() + .output_to_parts(&output, task_id); + task.artifacts = vec![artifact]; + task.status = TaskStatus::new(TaskState::Completed); + } + Err(err) => { + task.status = error_to_status(&err, state.executor.disclose_refusal_reason()); + } } - } - let task_json = serde_json::to_value(&task).unwrap(); - save_task(state, &task_id, task_json.clone(), ctx, Some(&skill_id)).await?; - drop(terminal); + let task_json = serde_json::to_value(&task).unwrap(); + save_task(state, task_id, task_json.clone(), ctx, Some(&skill_id)).await?; + drop(terminal); - // Deliver the terminal status to any registered webhook. - notify_push( - state, - &task_id, - ctx, - &StreamEvent::StatusUpdate(TaskStatusUpdateEvent { - task_id: task_id.clone(), - context_id: context_id.clone(), - status: task.status.clone(), - }), - ) - .await; - Ok(task_json) + // Deliver the terminal status to any registered webhook. + notify_push( + state, + task_id, + ctx, + &StreamEvent::StatusUpdate(TaskStatusUpdateEvent { + task_id: task_id.clone(), + context_id: task.context_id.clone(), + status: task.status.clone(), + }), + ) + .await; + Ok(task_json) + } } /// `message/stream` — SSE stream of A2A 1.0 events. diff --git a/a2a/rust/src/server/mod.rs b/a2a/rust/src/server/mod.rs index 022dd78b..f37bd946 100644 --- a/a2a/rust/src/server/mod.rs +++ b/a2a/rust/src/server/mod.rs @@ -3,3 +3,4 @@ pub mod executor; pub mod factory; pub mod handlers; +mod wire; diff --git a/a2a/rust/src/server/wire.rs b/a2a/rust/src/server/wire.rs new file mode 100644 index 00000000..e0611c14 --- /dev/null +++ b/a2a/rust/src/server/wire.rs @@ -0,0 +1,266 @@ +//! A2A version negotiation and wire projections at the transport boundary. + +use axum::http::HeaderMap; +use chrono::{DateTime, FixedOffset}; +use serde::Deserialize; +use serde_json::{json, Value}; + +pub(crate) const VERSION_HEADER: &str = "a2a-version"; +pub(crate) const VERSION_NOT_SUPPORTED: i32 = -32009; +pub(crate) const INVALID_PARAMS: i32 = -32602; +pub(crate) const PUSH_NOT_SUPPORTED: i32 = -32003; +pub(crate) const UNSUPPORTED_OPERATION: i32 = -32004; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum WireVersion { + Legacy, + V1, +} + +impl WireVersion { + pub(crate) fn negotiate(headers: &HeaderMap, default: Self) -> Result { + let versions = headers.get_all(VERSION_HEADER); + let mut versions = versions.iter(); + match (versions.next(), versions.next()) { + (None, _) => Ok(default), + (Some(value), None) => match value.to_str().map(str::trim) { + Ok("") => Ok(default), + Ok("0.3") => Ok(Self::Legacy), + Ok("1.0") => Ok(Self::V1), + _ => Err(()), + }, + (Some(_), Some(_)) => Err(()), + } + } + + pub(crate) fn project_card(self, mut card: Value) -> Value { + match self { + Self::V1 => { + card["capabilities"]["streaming"] = json!(false); + card["capabilities"]["pushNotifications"] = json!(false); + } + Self::Legacy => { + card["url"] = card["supportedInterfaces"][0]["url"].take(); + card["preferredTransport"] = + card["supportedInterfaces"][0]["protocolBinding"].take(); + card["protocolVersion"] = json!("0.3"); + card["supportsAuthenticatedExtendedCard"] = + card["capabilities"]["extendedAgentCard"].take(); + if let Some(capabilities) = card["capabilities"].as_object_mut() { + capabilities.remove("extendedAgentCard"); + } + if let Some(schemes) = card["securitySchemes"].as_object_mut() { + for scheme in schemes.values_mut() { + if let Some(mut http) = scheme + .get("httpAuthSecurityScheme") + .and_then(Value::as_object) + .cloned() + { + http.insert("type".into(), json!("http")); + *scheme = Value::Object(http); + } + } + } + if let Some(fields) = card.as_object_mut() { + fields.remove("supportedInterfaces"); + if let Some(Value::Array(requirements)) = fields.remove("securityRequirements") + { + fields.insert( + "security".into(), + Value::Array( + requirements + .into_iter() + .filter_map(|mut requirement| { + requirement.as_object_mut()?.remove("schemes") + }) + .collect(), + ), + ); + } + } + } + } + card + } +} + +pub(crate) type RpcFailure = (i32, String); + +fn params_error(message: &str) -> RpcFailure { + (INVALID_PARAMS, message.to_owned()) +} + +fn request_params(params: &Value) -> Result +where + T: for<'de> Deserialize<'de> + Default, +{ + if params.is_null() { + return Ok(T::default()); + } + if !params.is_object() { + return Err(params_error("Invalid parameters")); + } + serde_json::from_value(params.clone()).map_err(|_| params_error("Invalid parameters")) +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct SendOptions { + #[serde(default)] + pub(crate) return_immediately: bool, + pub(crate) history_length: Option, +} + +pub(crate) fn send_options(params: &Value) -> Result { + let configuration = ¶ms["configuration"]; + let options = request_params(configuration)?; + if !configuration["taskPushNotificationConfig"].is_null() { + return Err(( + PUSH_NOT_SUPPORTED, + "Push notification is not supported".to_string(), + )); + } + Ok(options) +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct GetOptions { + history_length: Option, +} + +pub(crate) fn get_history_length(params: &Value) -> Result, RpcFailure> { + request_params::(params).map(|opts| opts.history_length) +} + +pub(crate) fn project_history(task: &mut Value, limit: Option) { + let Some(limit) = limit else { return }; + let Some(fields) = task.as_object_mut() else { + return; + }; + if limit == 0 { + fields.remove("history"); + } else if let Some(history) = fields.get_mut("history").and_then(Value::as_array_mut) { + history.drain(..history.len().saturating_sub(limit)); + } +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ListOptions { + context_id: Option, + status: Option, + status_timestamp_after: Option>, + page_size: Option, + page_token: Option, + history_length: Option, + #[serde(default)] + include_artifacts: bool, +} + +impl ListOptions { + pub(crate) fn parse(params: &Value) -> Result { + let mut options: Self = request_params(params)?; + if matches!(options.status.as_deref(), Some("TASK_STATE_UNSPECIFIED")) { + options.status = None; + } + if let Some(status) = options.status.as_deref() { + if !matches!( + status, + "TASK_STATE_SUBMITTED" + | "TASK_STATE_WORKING" + | "TASK_STATE_COMPLETED" + | "TASK_STATE_FAILED" + | "TASK_STATE_CANCELED" + | "TASK_STATE_INPUT_REQUIRED" + | "TASK_STATE_REJECTED" + | "TASK_STATE_AUTH_REQUIRED" + ) { + return Err(params_error("Invalid status")); + } + } + if let Some(size) = options.page_size { + if !(1..=100).contains(&size) { + return Err(params_error("pageSize must be between 1 and 100")); + } + } + Ok(options) + } + + pub(crate) fn project(self, tasks: Vec) -> Result { + let mut filtered: Vec<_> = tasks + .into_iter() + .filter_map(|task| { + if self + .context_id + .as_ref() + .is_some_and(|context| task["contextId"].as_str() != Some(context)) + || self + .status + .as_ref() + .is_some_and(|status| task["status"]["state"].as_str() != Some(status)) + { + return None; + } + let timestamp = task["status"]["timestamp"] + .as_str() + .and_then(|value| DateTime::parse_from_rfc3339(value).ok()); + if self + .status_timestamp_after + .is_some_and(|after| timestamp.is_none_or(|time| time < after)) + { + return None; + } + Some((timestamp, task)) + }) + .collect(); + filtered.sort_unstable_by(|(left_time, left), (right_time, right)| { + right_time + .cmp(left_time) + .then_with(|| left["id"].as_str().cmp(&right["id"].as_str())) + }); + + let total_size = filtered.len(); + let page_size = self.page_size.unwrap_or(50); + let start = match self.page_token.as_deref().filter(|token| !token.is_empty()) { + Some(token) => filtered + .iter() + .position(|(_, task)| task["id"].as_str() == Some(token)) + .map(|cursor| cursor + 1) + .ok_or_else(|| params_error("Invalid pageToken"))?, + None => 0, + }; + let end = (start + page_size).min(total_size); + // The cursor is the final task ID on the returned page, which is + // already visible to the caller. Resolve it only within the new, + // authorized and filtered result set on each request. + let next_page_token = if end < total_size { + filtered[end - 1].1["id"].as_str().unwrap_or("") + } else { + "" + }; + let next_page_token = next_page_token.to_owned(); + let tasks: Vec<_> = filtered + .into_iter() + .skip(start) + .take(page_size) + .map(|(_, mut task)| { + project_history(&mut task, self.history_length); + if let Some(fields) = task.as_object_mut() { + if self.include_artifacts { + fields.entry("artifacts").or_insert_with(|| json!([])); + } else { + fields.remove("artifacts"); + } + } + task + }) + .collect(); + Ok(json!({ + "tasks": tasks, + "totalSize": total_size, + "pageSize": page_size, + "nextPageToken": next_page_token, + })) + } +} diff --git a/a2a/rust/tests/integration.rs b/a2a/rust/tests/integration.rs index 4054432a..49bbfd69 100644 --- a/a2a/rust/tests/integration.rs +++ b/a2a/rust/tests/integration.rs @@ -1106,6 +1106,359 @@ async fn build_with_auth() -> axum::Router { router } +async fn versioned_rpc( + app: &axum::Router, + bearer: &str, + version: Option<&str>, + id: &str, + method: &str, + params: Value, +) -> Value { + let mut request = Request::post("/") + .header("content-type", "application/json") + .header("authorization", bearer); + if let Some(version) = version { + request = request.header("a2a-version", version); + } + let response = app + .clone() + .oneshot( + request + .body(Body::from( + json!({ + "jsonrpc":"2.0","id":id,"method":method,"params":params + }) + .to_string(), + )) + .unwrap(), + ) + .await + .unwrap(); + let value = body_json(response).await; + assert_eq!(value["id"], id); + value +} + +fn versioned_send(skill: &str, context: &str, immediate: bool) -> Value { + json!({ + "message":{"messageId":uuid::Uuid::new_v4().to_string(),"role":"ROLE_USER","parts":[{"data":{"echo":true}}],"contextId":context}, + "configuration":{"returnImmediately":immediate}, + "metadata":{"skillId":skill} + }) +} + +#[tokio::test] +async fn a2a_v1_wire_negotiates_before_execution_and_preserves_legacy_methods() { + let app = build_with_auth().await; + for method in ["message/send", "SendMessage"] { + let reply = versioned_rpc( + &app, + "Bearer good", + Some("99.0"), + "unsupported", + method, + versioned_send("test.echo", "rejected", false), + ) + .await; + assert_eq!(reply["error"]["code"], -32009); + } + let reply = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "empty", + "ListTasks", + json!({}), + ) + .await; + assert_eq!( + reply["result"], + json!({"tasks":[],"totalSize":0,"pageSize":50,"nextPageToken":""}) + ); + let (legacy, compat) = (None, Some("")); + for version in [legacy, compat, Some("0.3")] { + let reply = versioned_rpc( + &app, + "Bearer good", + version, + "legacy", + "message/send", + versioned_send("test.echo", "legacy", false), + ) + .await; + assert_eq!(reply["result"]["status"]["state"], "TASK_STATE_COMPLETED"); + assert!(reply["result"]["id"].is_string()); + } + let card = body_json( + app.clone() + .oneshot( + Request::get("/.well-known/agent-card.json") + .header("a2a-version", "1.0") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(), + ) + .await; + assert_eq!(card["supportedInterfaces"][0]["protocolVersion"], "1.0"); + assert_eq!(card["capabilities"]["streaming"], false); + assert_eq!(card["capabilities"]["pushNotifications"], false); + for (method, code) in [ + ("SendStreamingMessage", -32004), + ("SubscribeToTask", -32004), + ("CreateTaskPushNotificationConfig", -32003), + ] { + let reply = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "optional", + method, + json!({}), + ) + .await; + assert_eq!(reply["error"]["code"], code); + } + let legacy_card = body_json( + app.oneshot( + Request::get("/.well-known/agent-card.json") + .header("a2a-version", "0.3") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(), + ) + .await; + assert_eq!(legacy_card["protocolVersion"], "0.3"); + assert_eq!(legacy_card["preferredTransport"], "JSONRPC"); +} + +#[tokio::test] +async fn a2a_v1_wire_runs_and_paginates_owned_tasks() { + let app = build_with_auth().await; + for context in ["keep", "keep", "other"] { + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + let reply = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "send", + "SendMessage", + versioned_send("test.echo", context, false), + ) + .await; + assert_eq!( + reply["result"]["task"]["status"]["state"], + "TASK_STATE_COMPLETED" + ); + let task = &reply["result"]["task"]; + let get = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "get", + "GetTask", + json!({"id": task["id"]}), + ) + .await; + assert_eq!(&get["result"], task); + } + let sent = versioned_rpc( + &app, + "Bearer other", + Some("1.0"), + "pending", + "SendMessage", + versioned_send("test.slow", "keep", true), + ) + .await; + let task = &sent["result"]["task"]; + assert_eq!(task["status"]["state"], "TASK_STATE_SUBMITTED"); + let get = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "foreign", + "GetTask", + json!({"id":task["id"]}), + ) + .await; + assert_eq!(get["error"]["code"], -32001); + let cancel = versioned_rpc( + &app, + "Bearer other", + Some("1.0"), + "cancel", + "CancelTask", + json!({"id":task["id"]}), + ) + .await; + assert_eq!(cancel["result"]["status"]["state"], "TASK_STATE_CANCELED"); + + let unfiltered = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "all", + "ListTasks", + json!({"pageSize":2}), + ) + .await; + assert_eq!(unfiltered["result"]["totalSize"], 3); + assert_eq!(unfiltered["result"]["tasks"].as_array().unwrap().len(), 2); + let first = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "first", + "ListTasks", + json!({ + "pageSize":1,"contextId":"keep","status":"TASK_STATE_COMPLETED","includeArtifacts":true + }), + ) + .await; + assert_eq!(first["result"]["totalSize"], 2); + assert_eq!(first["result"]["pageSize"], 1); + assert_eq!( + first["result"]["tasks"][0]["artifacts"] + .as_array() + .unwrap() + .len(), + 1 + ); + let token = first["result"]["nextPageToken"].as_str().unwrap(); + assert!(!token.is_empty()); + let second = versioned_rpc(&app, "Bearer good", Some("1.0"), "second", "ListTasks", json!({ + "pageSize":1,"pageToken":token,"contextId":"keep","status":"TASK_STATE_COMPLETED","includeArtifacts":true + })).await; + assert_eq!(second["result"]["nextPageToken"], ""); + assert_ne!( + first["result"]["tasks"][0]["id"], + second["result"]["tasks"][0]["id"] + ); + assert!(unfiltered["result"]["tasks"][0].get("artifacts").is_none()); + assert_eq!(&unfiltered["result"]["tasks"][0]["contextId"], "other",); + let timestamp = &unfiltered["result"]["tasks"][0]["status"]["timestamp"]; + let filtered = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "timestamp", + "ListTasks", + json!({"contextId":"other", "statusTimestampAfter": timestamp, "historyLength": 0}), + ) + .await; + assert_eq!(filtered["result"]["totalSize"], 1); + assert!(filtered["result"]["tasks"][0].get("history").is_none()); + + for params in [ + json!({"pageSize":101}), + json!({"historyLength":-1}), + json!({"statusTimestampAfter":"invalid"}), + json!({"pageToken": task["id"]}), + ] { + let reply = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "bad-filter", + "ListTasks", + params, + ) + .await; + assert_eq!(reply["error"]["code"], -32602); + } +} + +#[tokio::test] +async fn a2a_v1_wire_background_send_completes_and_approval_is_enforced() { + let (app, _) = apcore_a2a::build_app_with_auth( + BackendSource::Registry(gated_registry()), + APCoreA2AConfig::default(), + Some(Arc::new(TestAuth)), + ) + .await + .unwrap(); + let submitted = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "immediate", + "SendMessage", + versioned_send("test.echo", "background", true), + ) + .await; + assert_eq!( + submitted["result"]["task"]["status"]["state"], + "TASK_STATE_SUBMITTED" + ); + let id = &submitted["result"]["task"]["id"]; + let completed = tokio::time::timeout(std::time::Duration::from_secs(3), async { + loop { + let reply = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "poll", + "GetTask", + json!({"id": id}), + ) + .await; + if reply["result"]["status"]["state"] == "TASK_STATE_COMPLETED" { + break reply; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("background task finished"); + assert_eq!( + completed["result"]["artifacts"][0]["parts"][0]["data"], + json!({"echo":true}) + ); + + for (bearer, code) in [("Bearer good", -32004), ("Bearer other", -32001)] { + let mut continuation = versioned_send("test.echo", "background", false); + continuation["message"]["taskId"] = id.clone(); + let response = versioned_rpc( + &app, + bearer, + Some("1.0"), + "continuation", + "SendMessage", + continuation, + ) + .await; + assert_eq!(response["error"]["code"], code); + } + let response = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "approval", + "SendMessage", + versioned_send("admin.users.delete", "gated", false), + ) + .await; + assert_eq!( + response["result"]["task"]["status"]["state"], + "TASK_STATE_REJECTED" + ); + assert_eq!(response["result"]["task"]["artifacts"], json!([])); + let owned = versioned_rpc( + &app, + "Bearer good", + Some("1.0"), + "owned", + "ListTasks", + json!({}), + ) + .await; + assert_eq!(owned["result"]["totalSize"], 2); +} + #[tokio::test] async fn auth_rejects_unauthenticated_jsonrpc() { let req = Request::builder() diff --git a/a2a/rust/tests/openapi_backend_conformance.rs b/a2a/rust/tests/openapi_backend_conformance.rs index 7f42ffa9..c5ac4657 100644 --- a/a2a/rust/tests/openapi_backend_conformance.rs +++ b/a2a/rust/tests/openapi_backend_conformance.rs @@ -1205,7 +1205,7 @@ async fn test_backend_refuses_startup_when_a_host_validator_rejects_a_scanned_mo ) -> ValidationResult { let mut result = ValidationResult::default(); result.valid = - !descriptor.is_some_and(|descriptor| descriptor.module_id == "update_item"); + descriptor.is_none_or(|descriptor| descriptor.module_id != "update_item"); if !result.valid { result.errors = vec![ValidationErrorDetail::message_only("rejected by host rule")]; } diff --git a/a2a/typescript/src/server/factory.ts b/a2a/typescript/src/server/factory.ts index 67ead081..823e6eea 100644 --- a/a2a/typescript/src/server/factory.ts +++ b/a2a/typescript/src/server/factory.ts @@ -1,5 +1,5 @@ import express from "express"; -import type { Express, Request, Response } from "express"; +import type { Express, NextFunction, Request, Response } from "express"; import type { AgentCard, AgentCapabilities } from "@a2a-js/sdk"; import { InMemoryTaskStore, @@ -54,6 +54,25 @@ try { const ACTIVE_STATES = new Set(["submitted", "working", "input-required"]); +/** Preserve standard JSON-RPC fields omitted by the SDK's response serializer. */ +function preserveJsonRpcFields(req: Request, res: Response, next: NextFunction): void { + const requestId = req.body?.id; + const method = req.body?.method; + const send = res.json.bind(res); + res.json = (body) => { + // The SDK uses "id || null" when rejecting an unsupported version. + if (body?.error?.code === -32009 && (typeof requestId === "string" || Number.isFinite(requestId))) { + return send({ ...body, id: requestId }); + } + if (method === "ListTasks" && body?.result !== undefined) { + // ProtoJSON elides defaults, but these fields are required on the wire. + return send({ ...body, result: { tasks: [], nextPageToken: "", totalSize: 0, ...body.result } }); + } + return send(body); + }; + next(); +} + /** * In-process counters for the A2A `/metrics` endpoint. These count A2A * task-state transitions (submitted/working/completed/...) on the wire @@ -424,6 +443,7 @@ export class A2AServerFactory { // UnauthenticatedUser bucket and ListTasks returned every caller's tasks. app.post( "/", + preserveJsonRpcFields, jsonRpcHandler({ requestHandler, userBuilder: identityUserBuilder, diff --git a/a2a/typescript/src/server/task-persistence.ts b/a2a/typescript/src/server/task-persistence.ts index d4141757..ca06022d 100644 --- a/a2a/typescript/src/server/task-persistence.ts +++ b/a2a/typescript/src/server/task-persistence.ts @@ -145,13 +145,16 @@ class TaskPersistence implements TaskStore { } } - async list(...args: Parameters): ReturnType { - const [params, context] = args; + async list(...[request, context]: Parameters): ReturnType { + const { status, ...withoutStatus } = request; + // The decoder defaults omitted status to UNSPECIFIED, but the store's + // optional filter expects an absent key despite the generated type. + const params = status === TaskState.TASK_STATE_UNSPECIFIED ? (withoutStatus as typeof request) : request; const identity = identityOf(context); const authority = identity?.authorityKey?.(); if (authority != null) return this.listScoped(params, context, authority); - const page = await this.store.list(...args); + const page = await this.store.list(params, context); const tasks = page.tasks.filter(task => this.canRead(task, context)); if (tasks.length === page.tasks.length) return page; // The underlying cursor may contain the last task's id. Only expose a diff --git a/a2a/typescript/tests/security/task-scoping.test.ts b/a2a/typescript/tests/security/task-scoping.test.ts index 971699d6..3f0dbdfb 100644 --- a/a2a/typescript/tests/security/task-scoping.test.ts +++ b/a2a/typescript/tests/security/task-scoping.test.ts @@ -143,11 +143,7 @@ async function submit(app: Express, who: string, messageId: string, skillId = "e } async function listTaskIds(app: Express, who: string): Promise { - // An explicit status is required: a2a-js decodes an absent `status` as the - // proto default TASK_STATE_UNSPECIFIED (0) and then filters on it, so an - // unfiltered ListTasks returns nothing. That is upstream behaviour and - // orthogonal to scoping. - const body = await rpc(app, who, "ListTasks", { status: "TASK_STATE_COMPLETED" }); + const body = await rpc(app, who, "ListTasks", {}); expect(body.error, JSON.stringify(body)).toBeUndefined(); const tasks = (body.result as { tasks?: { id: string }[] }).tasks ?? []; return tasks.map((t) => t.id).sort(); @@ -381,3 +377,39 @@ describe("task scoping", () => { }); }); }); + + + +it("paginates unfiltered and filtered results using live JSON-RPC with caller isolation", async () => { + const app = makeApp(bearerIsPrincipal); + const card = await request(await serverFor(app)).get("/.well-known/agent-card.json"); + expect(card.body.capabilities).toMatchObject({ streaming: true, pushNotifications: true, extendedAgentCard: true }); + const extended = await rpc(app, ALICE, "GetExtendedAgentCard", {}); + expect(extended.result?.name).toBe(card.body.name); + const firstAlice = await submit(app, ALICE, "page-alice-first"); + const secondAlice = await submit(app, ALICE, "page-alice-second"); + const bobTask = await submit(app, BOB, "page-bob"); + + type Page = { tasks: { id: string; contextId: string }[]; totalSize: number; pageSize: number; nextPageToken: string }; + for (const filter of [{}, { status: "TASK_STATE_COMPLETED" }]) { + const params = { pageSize: 1, ...filter }; + const first = await rpc(app, ALICE, "ListTasks", params); + expect(first.error).toBeUndefined(); + const page = first.result as Page; + expect(page.totalSize).toBe(2); + expect(page.pageSize).toBe(1); + expect(page.tasks).toHaveLength(1); + expect(page.nextPageToken).toBeTruthy(); + + const next = await rpc(app, ALICE, "ListTasks", { ...params, pageToken: page.nextPageToken }); + const final = next.result as Page; + expect(final.totalSize).toBe(2); + expect(final.nextPageToken).toBe(""); + expect([...page.tasks, ...final.tasks].map(t => t.id).sort()).toEqual([firstAlice, secondAlice].sort()); + expect(page.tasks[0].id).not.toBe(bobTask); + + const byContext = await rpc(app, ALICE, "ListTasks", { contextId: page.tasks[0].contextId, ...filter }); + expect(byContext.result).toMatchObject({ pageSize: 50, totalSize: 1, nextPageToken: "" }); + expect((byContext.result as Page).tasks.map(t => t.id)).toEqual([page.tasks[0].id]); + } +}); diff --git a/a2a/typescript/tests/server/legacy-compat.test.ts b/a2a/typescript/tests/server/legacy-compat.test.ts index 45b953c2..8feec1b0 100644 --- a/a2a/typescript/tests/server/legacy-compat.test.ts +++ b/a2a/typescript/tests/server/legacy-compat.test.ts @@ -26,10 +26,10 @@ function makeRegistry(): Registry { }; } -function makeApp(): Express { +function makeApp(callAsync = vi.fn().mockResolvedValue({ result: "ok" })): Express { const { app } = new A2AServerFactory().create( makeRegistry(), - { callAsync: vi.fn().mockResolvedValue({ result: "ok" }) }, + { callAsync }, { name: "Legacy Agent", description: "d", version: "1", url: "http://localhost" }, ); return app; @@ -114,3 +114,34 @@ describe("A2A 0.3 compatibility", () => { expect(res.body.url).toBeUndefined(); }); }); + + + +describe("A2A version negotiation", () => { + it.each([ + ["SendMessage", 0], ["message/send", 0], ["SendMessage", ""], ["message/send", ""], + ])("rejects an unsupported version of %s with request ID %j without side effects", async (method, id) => { + const callAsync = vi.fn().mockResolvedValue({ result: "ok" }); + const app = makeApp(callAsync); + const body = explorerSendBody(); + const response = await request(app).post("/").set("A2A-Version", "99.0").send({ ...body, method, id }); + + expect(response.body).toMatchObject({ jsonrpc: "2.0", id, error: { code: -32009 } }); + expect(callAsync).not.toHaveBeenCalled(); + const list = await request(app).post("/").set("A2A-Version", "1.0").send({ + jsonrpc: "2.0", id: "list", method: "ListTasks", params: {}, + }); + expect(list.body.result).toEqual({ tasks: [], pageSize: 50, totalSize: 0, nextPageToken: "" }); + }); + + it("accepts an empty A2A-Version header on the legacy send and get routes", async () => { + const app = makeApp(); + const sent = await request(app).post("/").set("A2A-Version", "").send(explorerSendBody()); + expect(sent.body.error).toBeUndefined(); + const taskId = sent.body.result.id; + const got = await request(app).post("/").set("A2A-Version", "").send({ + jsonrpc: "2.0", id: "get-legacy", method: "tasks/get", params: { id: taskId }, + }); + expect(got.body.result.id).toBe(taskId); + }); +});