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
39 changes: 39 additions & 0 deletions fasta2a/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@
parse_extensions_header,
select_activated_extensions,
)
from .jsonrpc_v1 import from_v1_request, to_v1_json, to_v1_sse
from .schema import (
A2ARequest,
A2AResponse,
AgentCapabilities,
AgentCard,
AgentExtension,
AgentInterface,
AgentProvider,
InvalidRequestError,
SecurityRequirement,
SecurityScheme,
SendMessageResponse,
Skill,
a2a_request_ta,
Expand All @@ -57,6 +61,8 @@ def __init__(
provider: AgentProvider | None = None,
skills: list[Skill] | None = None,
extensions: list[AgentExtension] | None = None,
security_schemes: dict[str, SecurityScheme] | None = None,
security_requirements: list[SecurityRequirement] | None = None,
docs_url: str | None = '/docs',
# Starlette
debug: bool = False,
Expand All @@ -83,6 +89,10 @@ def __init__(
self.provider = provider
self.skills = skills or []
self.extensions = extensions or []
# What the card says a caller authenticates with. Said, not enforced:
# the server checks it in a middleware of its own (`middleware`).
self.security_schemes = security_schemes
self.security_requirements = security_requirements
self.docs_url = docs_url
# NOTE: For now, I don't think there's any reason to support any other input/output modes.
self.default_input_modes = ['application/json']
Expand Down Expand Up @@ -121,6 +131,10 @@ async def _agent_card_endpoint(self, request: Request) -> Response:
)
if self.provider is not None:
agent_card['provider'] = self.provider
if self.security_schemes:
agent_card['security_schemes'] = self.security_schemes
if self.security_requirements:
agent_card['security_requirements'] = self.security_requirements
self._agent_card_json_schema = agent_card_ta.dump_json(agent_card, by_alias=True)
return Response(content=self._agent_card_json_schema, media_type='application/json')

Expand Down Expand Up @@ -158,7 +172,32 @@ async def _agent_run_endpoint(self, request: Request) -> Response:
3. The server will send a "working" on the first chunk on `tasks/pushNotification/get`.
"""
data = await request.body()
# A request with an A2A 1.0 method name is read as the method it names,
# and answered with 1.0's enums (see `jsonrpc_v1`).
try:
v1_request = from_v1_request(json.loads(data))
except ValueError:
v1_request = None
if v1_request is not None:
data = json.dumps(v1_request).encode()
a2a_request = a2a_request_ta.validate_json(data)
response = await self._answer(request, a2a_request)
if v1_request is None:
return response
if isinstance(response, StreamingResponse):
return StreamingResponse(
to_v1_sse(response.body_iterator), # type: ignore[arg-type]
media_type='text/event-stream',
headers={k: v for k, v in response.headers.items() if k.lower() != 'content-type'},
)
return Response(
content=to_v1_json(bytes(response.body)),
media_type='application/json',
headers={k: v for k, v in response.headers.items() if k.lower() not in ('content-length', 'content-type')},
)

async def _answer(self, request: Request, a2a_request: A2ARequest) -> Response:
"""Answer one A2A request, as this library names its methods."""

# Extensions are negotiated per request: the client names the ones it
# wants in the `A2A-Extensions` header, the agent activates those it
Expand Down
135 changes: 135 additions & 0 deletions fasta2a/jsonrpc_v1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""A2A 1.0 JSON-RPC method names and enum values.

The agent card says the server speaks A2A 1.0 (`protocolVersion: "1.0"`), and its
objects have the 1.0 shape. The JSON-RPC binding of 1.0 also renamed the methods
(`message/stream` is `SendStreamingMessage`) and writes enums as their proto names
(`working` is `TASK_STATE_WORKING`, `agent` is `ROLE_AGENT`). A 1.0 client, such as
`@a2a-js/sdk` 1.x or `a2a-sdk` 1.x, sends the new names and reads the new values.

The server answers both. A request made with a 1.0 method name is read as the
method it names, its enums read as this library's, and its answer, JSON or event
stream, is written with 1.0's enums. A request made with the names this library
has always used is answered exactly as before.
"""

from __future__ import annotations as _annotations

import json
from collections.abc import AsyncIterator
from typing import Any, cast

__all__ = (
'V1_METHODS',
'from_v1_request',
'to_v1',
'to_v1_json',
'to_v1_sse',
)

V1_METHODS: dict[str, str] = {
'SendMessage': 'message/send',
'SendStreamingMessage': 'message/stream',
'GetTask': 'tasks/get',
'CancelTask': 'tasks/cancel',
'SubscribeToTask': 'tasks/resubscribe',
'ListTasks': 'tasks/list',
}
"""The A2A 1.0 JSON-RPC methods this server answers, by the name it gives them."""

_ROLE_FROM_V1 = {'ROLE_USER': 'user', 'ROLE_AGENT': 'agent'}
_ROLE_TO_V1 = {value: key for key, value in _ROLE_FROM_V1.items()}
_STATES = (
'submitted',
'working',
'input-required',
'completed',
'canceled',
'failed',
'rejected',
'auth-required',
)
_STATE_TO_V1 = {state: 'TASK_STATE_' + state.upper().replace('-', '_') for state in _STATES}
_STATE_FROM_V1 = {value: key for key, value in _STATE_TO_V1.items()}


def _object(value: Any) -> dict[str, Any]:
return cast(dict[str, Any], value)


def _array(value: Any) -> list[Any]:
return cast(list[Any], value)


def _enums_from_v1(value: Any) -> Any:
if isinstance(value, dict):
out: dict[str, Any] = {}
for key, item in _object(value).items():
if key == 'role' and isinstance(item, str):
out[key] = _ROLE_FROM_V1.get(item, item)
elif key == 'state' and isinstance(item, str):
out[key] = _STATE_FROM_V1.get(item, item)
else:
out[key] = _enums_from_v1(item)
return out
if isinstance(value, list):
return [_enums_from_v1(item) for item in _array(value)]
return value


def to_v1(value: Any) -> Any:
"""A result of this server with its enums as A2A 1.0 writes them: `ROLE_*` and `TASK_STATE_*`."""
if isinstance(value, dict):
out: dict[str, Any] = {}
for key, item in _object(value).items():
if key == 'role' and isinstance(item, str):
out[key] = _ROLE_TO_V1.get(item, item)
elif key == 'state' and isinstance(item, str):
out[key] = _STATE_TO_V1.get(item, item)
else:
out[key] = to_v1(item)
Comment on lines +71 to +89
return out
if isinstance(value, list):
return [to_v1(item) for item in _array(value)]
return value


def from_v1_request(request: Any) -> dict[str, Any] | None:
"""A 1.0 JSON-RPC request as this server reads it, or `None` when it is not one.

The method is renamed and the enums of its params read as this library's. A
1.0 request may name a tenant, which an agent served here does not have, and
its configuration may say `returnImmediately`, which this server does not read
and which needs `acceptedOutputModes` beside it.
"""
if not isinstance(request, dict):
return None
envelope = _object(request)
method = envelope.get('method')
if not isinstance(method, str) or method not in V1_METHODS:
return None
params = _object(_enums_from_v1(dict(_object(envelope.get('params') or {}))))
params.pop('tenant', None)
configuration = params.get('configuration')
if isinstance(configuration, dict):
settings = _object(configuration)
settings.setdefault('acceptedOutputModes', [])
settings.pop('returnImmediately', None)
return {**envelope, 'method': V1_METHODS[method], 'params': params}


def to_v1_json(content: bytes) -> bytes:
"""A JSON-RPC answer, its `result` written as 1.0 writes it."""
answer: Any = json.loads(content)
if isinstance(answer, dict) and 'result' in answer:
envelope = _object(answer)
answer = {**envelope, 'result': to_v1(envelope['result'])}
return json.dumps(answer, separators=(',', ':')).encode()


async def to_v1_sse(events: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
"""An event stream of JSON-RPC answers, each one's `result` written as 1.0 writes it."""
async for event in events:
if event.startswith(b'data: '):
yield b'data: ' + to_v1_json(event[len(b'data: ') :].strip()) + b'\n\n'
else: # pragma: no cover - the task manager writes only data events
yield event
101 changes: 101 additions & 0 deletions tests/test_jsonrpc_v1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""A2A 1.0 JSON-RPC: the method names and enum values a 1.0 client speaks."""

from __future__ import annotations as _annotations

import json
from typing import Any

import pytest

from fasta2a.applications import FastA2A
from fasta2a.broker import InMemoryBroker
from fasta2a.jsonrpc_v1 import from_v1_request, to_v1
from fasta2a.storage import InMemoryStorage

from .test_applications import create_test_client
from .test_streaming import create_streaming_app

pytestmark = pytest.mark.anyio


def _v1_message(method: str) -> dict[str, Any]:
"""What `@a2a-js/sdk` 1.x sends."""
return {
'jsonrpc': '2.0',
'id': 1,
'method': method,
'params': {
'tenant': '',
'message': {'messageId': 'm-1', 'role': 'ROLE_USER', 'parts': [{'text': 'Hello'}]},
'configuration': {'returnImmediately': False},
},
}


def _events(body: str) -> list[dict[str, Any]]:
return [json.loads(line[len('data: ') :]) for line in body.splitlines() if line.startswith('data: ')]


async def test_a_1_0_stream_is_answered_with_1_0_enums():
async with create_streaming_app() as client:
response = await client.post('/', json=_v1_message('SendStreamingMessage'))
assert response.status_code == 200
assert response.headers['content-type'].startswith('text/event-stream')
results = [event['result'] for event in _events(response.text)]
assert results[0]['task']['status']['state'] == 'TASK_STATE_SUBMITTED'
assert results[0]['task']['history'][0]['role'] == 'ROLE_USER'
states = [result['statusUpdate']['status']['state'] for result in results if 'statusUpdate' in result]
assert states == ['TASK_STATE_WORKING', 'TASK_STATE_COMPLETED']


async def test_a_1_0_send_and_get_are_answered_with_1_0_enums():
async with create_streaming_app() as client:
sent = (await client.post('/', json=_v1_message('SendMessage'))).json()
assert sent['result']['task']['status']['state'] == 'TASK_STATE_SUBMITTED'
task_id = sent['result']['task']['id']
got = (
await client.post('/', json={'jsonrpc': '2.0', 'id': 2, 'method': 'GetTask', 'params': {'id': task_id}})
).json()
assert got['result']['id'] == task_id
assert got['result']['status']['state'].startswith('TASK_STATE_')


async def test_the_names_this_library_used_are_answered_as_before():
request = _v1_message('message/send')
request['params'] = {'message': {'messageId': 'm-1', 'role': 'user', 'parts': [{'text': 'Hello'}]}}
async with create_streaming_app() as client:
sent = (await client.post('/', json=request)).json()
assert sent['result']['task']['status']['state'] == 'submitted'


def test_a_1_0_request_is_read_as_the_method_it_names():
request = from_v1_request(_v1_message('SendStreamingMessage'))
assert request is not None
assert request['method'] == 'message/stream'
assert request['params']['message']['role'] == 'user'
assert 'tenant' not in request['params']
assert request['params']['configuration'] == {'acceptedOutputModes': []}
assert from_v1_request({'method': 'message/stream', 'params': {}}) is None
assert from_v1_request(['not', 'a', 'request']) is None


def test_an_answer_is_written_with_1_0_enums():
assert to_v1({'status': {'state': 'input-required'}, 'history': [{'role': 'agent'}]}) == {
'status': {'state': 'TASK_STATE_INPUT_REQUIRED'},
'history': [{'role': 'ROLE_AGENT'}],
}


async def test_the_card_says_how_a_caller_authenticates():
app = FastA2A(
storage=InMemoryStorage(),
broker=InMemoryBroker(),
security_schemes={'bearer': {'http_auth_security_scheme': {'scheme': 'Bearer', 'bearer_format': 'JWT'}}},
security_requirements=[{'schemes': {'bearer': []}}],
)
async with create_test_client(app) as client:
card = (await client.get('/.well-known/agent-card.json')).json()
assert card['securitySchemes'] == {
'bearer': {'httpAuthSecurityScheme': {'scheme': 'Bearer', 'bearerFormat': 'JWT'}}
}
assert card['securityRequirements'] == [{'schemes': {'bearer': []}}]
Loading