Skip to content
Merged
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
20 changes: 20 additions & 0 deletions a2a/docs/features/server-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
51 changes: 39 additions & 12 deletions a2a/python/src/apcore_a2a/server/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)

Expand Down
153 changes: 153 additions & 0 deletions a2a/python/tests/server/test_jsonrpc_interop.py
Original file line number Diff line number Diff line change
@@ -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]
40 changes: 28 additions & 12 deletions a2a/rust/src/server/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -287,8 +290,25 @@ async fn health() -> Json<Value> {
Json(json!({ "status": "healthy" }))
}

async fn serve_card(State(state): State<AppState>) -> Json<Value> {
handlers::public_agent_card(State(state)).await
async fn serve_card(State(state): State<AppState>, headers: HeaderMap) -> Response {
card_response(&headers, || Some(state.agent_card.as_ref().clone()))
}

fn card_response(headers: &HeaderMap, card: impl FnOnce() -> Option<Value>) -> 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).
Expand All @@ -298,15 +318,11 @@ async fn serve_card(State(state): State<AppState>) -> Json<Value> {
async fn serve_extended_card(
State(state): State<AppState>,
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
Expand Down
Loading
Loading