Skip to content

Build and run agents you can see, understand and trust.

feat(a2a): add `A2AAgent` class in the agent module (#2142)

YingchaoXeb251cdf3612
diff --git a/examples/a2a/README.md b/examples/a2a/README.md
new file mode 100644
index 000000000..1c4871904
--- /dev/null
+++ b/examples/a2a/README.md
@@ -0,0 +1,156 @@
+# A2A Agent
+
+This example puts AgentScope on both ends of the
+[A2A 1.0](https://a2a-protocol.org/) protocol:
+
+- `server.py` wraps an AgentScope `Agent` in an A2A `AgentExecutor` and serves
+ it over JSON-RPC/SSE.
+- `client.py` connects to it with `A2AAgent` and hands that agent to
+ `launch_console`, so the remote agent is chatted with exactly like a local
+ one.
+
+`A2AAgent` deliberately exposes Agent-like methods without inheriting from
+`Agent`. A local `Agent` owns a model, toolkit, state and reasoning loop;
+`A2AAgent` delegates all of that to the remote server and owns only the remote
+conversation (`context_id`) and the Task the next message continues
+(`task_id`).
+
+## Prerequisites
+
+- Python 3.11 or newer
+- AgentScope with the A2A extra:
+
+ ```bash
+ pip install "agentscope[a2a]"
+ ```
+
+ From an AgentScope source checkout, use `uv sync --extra a2a` instead.
+
+- A DashScope API key for the server's model.
+
+## Run it
+
+In one terminal:
+
+```bash
+export DASHSCOPE_API_KEY=sk-...
+python server.py # http://127.0.0.1:9999
+python server.py --port 8080 --model qwen3.7-max
+```
+
+In another:
+
+```bash
+python client.py
+python client.py --url http://127.0.0.1:8080 --verbosity debug
+```
+
+Type a message and the reply streams back through A2A artifact chunks. `exit`,
+`quit` or Ctrl+D leaves the console.
+
+## How the two sides map onto each other
+
+**Server** (`AgentScopeExecutor`). One AgentScope `Agent` per A2A
+`context_id`, so concurrent conversations stay independent. Each reply
+enqueues the `Task`, moves it to `WORKING`, publishes every
+`TextBlockDeltaEvent` as an artifact chunk (the last one marked
+`last_chunk=True`), and completes the Task.
+
+**Client** (`A2AAgent`). Every A2A Part of a response becomes one content
+block — text Parts become `TextBlock`, raw byte and URL Parts become
+`DataBlock` — streamed as ordinary AgentScope block events. Each block end
+event carries the A2A ids it came from under `metadata["a2a"]`, and the final
+message carries the `context_id`.
+
+## Using `A2AAgent` directly
+
+Resolve the card once and use the agent as an async context manager:
+
+```python
+import httpx
+from a2a.client import A2ACardResolver
+
+from agentscope.agent import A2AAgent
+from agentscope.message import UserMsg
+
+
+async with httpx.AsyncClient() as httpx_client:
+ card = await A2ACardResolver(
+ httpx_client=httpx_client,
+ base_url="http://127.0.0.1:9999",
+ ).get_agent_card()
+
+async with A2AAgent(card) as agent:
+ reply = await agent.reply(
+ UserMsg(name="user", content="Plan a weekend in Hangzhou."),
+ )
+ print(reply.get_text_content())
+
+ # The second call reuses the remote context automatically.
+ reply = await agent.reply(
+ UserMsg(name="user", content="Make it suitable for children."),
+ )
+```
+
+Use `reply_stream()` when the application needs the events instead. Messages
+passed to `observe()` are sent ahead of the next reply's own input:
+
+```python
+await agent.observe(previous_messages)
+reply = await agent.reply(current_message)
+```
+
+The adapter owns its A2A client and closes it on exit, so one instance serves
+one conversation and cannot be reopened.
+
+## Task lifecycle
+
+A remote Task suspends server-side, but nothing suspends locally, so every
+response stream ends the reply. The state it ended on decides how:
+
+- `COMPLETED`, `INPUT_REQUIRED`, `AUTH_REQUIRED` → `COMPLETED`. The Task status
+ message is emitted as ordinary content, so the remote agent's question is
+ part of the reply — answer it with the next `reply()`.
+- `CANCELED` → `INTERRUPTED`.
+- `FAILED`, `REJECTED` → `ERROR`.
+
+`state.task_id` is kept only while the server is waiting for input
+(`INPUT_REQUIRED` / `AUTH_REQUIRED`); the next message then continues that
+Task. Any other outcome clears it and the next message starts a new Task
+inside the same `context_id`. A Task the server has since forgotten degrades
+into a new one; a Task still running is reported as an error, because sending
+to it would run it a second time.
+
+A2A carries credentials out of band, so an `AUTH_REQUIRED` Task cannot be
+approved through this adapter — follow the instructions in the status message.
+
+## Resuming a conversation
+
+`A2AAgentState` holds everything worth persisting and is accepted by the
+constructor:
+
+```python
+from agentscope.state import A2AAgentState
+
+agent = A2AAgent(card, state=A2AAgentState(context_id=stored_context_id))
+```
+
+## Content support
+
+Text, raw bytes and URL Parts map to AgentScope text/data blocks in both
+directions. Structured-data Parts, thinking/tool/hint blocks and push
+notifications are not supported.
+
+`compress_context()` is intentionally a no-op: the remote server, not the
+local adapter, owns and compresses its conversation context.
+
+## Local E2E test
+
+```bash
+uv run --extra dev pytest tests/a2a_agent_e2e_test.py -v
+```
+
+The test starts an ephemeral A2A 1.0 server on localhost with the official SDK
+server primitives, connects `A2AAgent` to it over real JSON-RPC/SSE, and checks
+streamed artifact handling and context continuity across two turns. It needs no
+model, API key or network access.
diff --git a/examples/a2a/client.py b/examples/a2a/client.py
new file mode 100644
index 000000000..e774796f4
--- /dev/null
+++ b/examples/a2a/client.py
@@ -0,0 +1,45 @@
+# -*- coding: utf-8 -*-
+"""Chat with a remote A2A 1.0 agent in the terminal.
+
+``A2AAgent`` streams AgentScope events, so it goes straight into
+``launch_console`` like a local agent would. Start ``server.py`` first, then
+run::
+
+ python client.py [--url http://127.0.0.1:9999] [--verbosity default]
+"""
+import argparse
+import asyncio
+
+import httpx
+from a2a.client import A2ACardResolver
+
+from agentscope.agent import A2AAgent
+from agentscope.console import launch_console
+
+
+async def main() -> None:
+ """Resolve the remote Agent Card and hand the agent to the console."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--url", default="http://127.0.0.1:9999")
+ parser.add_argument(
+ "--verbosity",
+ choices=["quiet", "default", "debug"],
+ default="default",
+ )
+ args = parser.parse_args()
+
+ # The card is fetched once, over a client this example owns; A2AAgent
+ # builds its own transport from it.
+ async with httpx.AsyncClient() as httpx_client:
+ card = await A2ACardResolver(
+ httpx_client=httpx_client,
+ base_url=args.url,
+ ).get_agent_card()
+
+ print(f"Connected to {card.name!r} at {args.url}.")
+ async with A2AAgent(card) as agent:
+ await launch_console(agent, verbosity=args.verbosity)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/a2a/server.py b/examples/a2a/server.py
new file mode 100644
index 000000000..cf24d385e
--- /dev/null
+++ b/examples/a2a/server.py
@@ -0,0 +1,193 @@
+# -*- coding: utf-8 -*-
+"""Expose an AgentScope agent as an A2A 1.0 server.
+
+An ``AgentExecutor`` bridges the two event models: the agent's streamed
+``TextBlockDeltaEvent`` chunks are published as artifact chunks, so an A2A
+client sees the reply arrive incrementally. Each A2A ``context_id`` gets its
+own agent, which is what keeps the conversations independent. Run with::
+
+ export DASHSCOPE_API_KEY=sk-...
+ python server.py [--model qwen3.7-max] [--port 9999]
+"""
+import argparse
+import asyncio
+import os
+
+import uvicorn
+from a2a.server.agent_execution import AgentExecutor, RequestContext
+from a2a.server.events import EventQueue
+from a2a.server.request_handlers import DefaultRequestHandler
+from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
+from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
+from a2a.types import (
+ AgentCapabilities,
+ AgentCard,
+ AgentInterface,
+ AgentSkill,
+ Part,
+ Task,
+ TaskState,
+ TaskStatus,
+)
+from starlette.applications import Starlette
+
+from agentscope.agent import Agent
+from agentscope.credential import DashScopeCredential
+from agentscope.event import TextBlockDeltaEvent
+from agentscope.message import UserMsg
+from agentscope.model import DashScopeChatModel
+
+
+class AgentScopeExecutor(AgentExecutor):
+ """Run one AgentScope agent per A2A context."""
+
+ def __init__(self, model: str, api_key: str) -> None:
+ """Remember how to build an agent for a new conversation."""
+ self._model = model
+ self._api_key = api_key
+ self._agents: dict[str, Agent] = {}
+
+ async def execute(
+ self,
+ context: RequestContext,
+ event_queue: EventQueue,
+ ) -> None:
+ """Stream the agent's reply back as A2A artifact chunks."""
+ if context.task_id is None or context.context_id is None:
+ raise RuntimeError("A2A server did not assign Task/context IDs.")
+
+ if context.context_id not in self._agents:
+ self._agents[context.context_id] = Agent(
+ name="Friday",
+ system_prompt="You are a helpful assistant named Friday.",
+ model=DashScopeChatModel(
+ credential=DashScopeCredential(api_key=self._api_key),
+ model=self._model,
+ stream=True,
+ ),
+ )
+ agent = self._agents[context.context_id]
+
+ # The Task itself must reach the client before any update to it.
+ await event_queue.enqueue_event(
+ Task(
+ id=context.task_id,
+ context_id=context.context_id,
+ status=TaskStatus(state=TaskState.TASK_STATE_SUBMITTED),
+ ),
+ )
+ updater = TaskUpdater(
+ event_queue,
+ task_id=context.task_id,
+ context_id=context.context_id,
+ )
+ await updater.start_work()
+
+ # One artifact per reply, streamed chunk by chunk. Each chunk is
+ # held back one step so the last one can be marked as such.
+ artifact_id = f"{context.task_id}-reply"
+ pending, started = None, False
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content=context.get_user_input()),
+ ):
+ if not isinstance(event, TextBlockDeltaEvent):
+ continue
+ if pending is not None:
+ await updater.add_artifact(
+ [Part(text=pending)],
+ artifact_id=artifact_id,
+ append=started,
+ last_chunk=False,
+ )
+ started = True
+ pending = event.delta
+
+ if pending is not None:
+ await updater.add_artifact(
+ [Part(text=pending)],
+ artifact_id=artifact_id,
+ append=started,
+ last_chunk=True,
+ )
+ await updater.complete()
+
+ async def cancel(
+ self,
+ context: RequestContext,
+ event_queue: EventQueue,
+ ) -> None:
+ """Mark the Task canceled at the client's request."""
+ if context.task_id is None or context.context_id is None:
+ raise RuntimeError("Cannot cancel a Task without IDs.")
+ await TaskUpdater(
+ event_queue,
+ task_id=context.task_id,
+ context_id=context.context_id,
+ ).cancel()
+
+
+def create_app(base_url: str, model: str, api_key: str) -> Starlette:
+ """Build the A2A 1.0 application serving the agent."""
+ card = AgentCard(
+ name="Friday",
+ description="An AgentScope assistant exposed over A2A 1.0.",
+ version="1.0.0",
+ supported_interfaces=[
+ AgentInterface(
+ url=base_url,
+ protocol_binding="JSONRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ capabilities=AgentCapabilities(streaming=True),
+ default_input_modes=["text/plain"],
+ default_output_modes=["text/plain"],
+ skills=[
+ AgentSkill(
+ id="chat",
+ name="Chat",
+ description="Answer questions in a multi-turn conversation.",
+ tags=["chat"],
+ ),
+ ],
+ )
+ handler = DefaultRequestHandler(
+ agent_executor=AgentScopeExecutor(model=model, api_key=api_key),
+ task_store=InMemoryTaskStore(),
+ agent_card=card,
+ )
+ return Starlette(
+ routes=[
+ *create_agent_card_routes(card),
+ *create_jsonrpc_routes(handler, rpc_url="/"),
+ ],
+ )
+
+
+async def main() -> None:
+ """The main entry point of the server."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model", default="qwen3.7-max")
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=9999)
+ args = parser.parse_args()
+
+ api_key = os.environ.get("DASHSCOPE_API_KEY")
+ if not api_key:
+ raise RuntimeError(
+ "Set the DASHSCOPE_API_KEY environment variable before "
+ "running this demo.",
+ )
+
+ app = create_app(
+ base_url=f"http://{args.host}:{args.port}",
+ model=args.model,
+ api_key=api_key,
+ )
+ await uvicorn.Server(
+ uvicorn.Config(app, host=args.host, port=args.port),
+ ).serve()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/pyproject.toml b/pyproject.toml
index e9ab4da2d..909bf3b85 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -102,6 +102,10 @@ workspace = [
tools = [
"ripgrep",
]
+# ------------ A2A ------------
+a2a = [
+ "a2a-sdk>=1.1.1",
+]
# ------------ Vector stores ------------
vdb-qdrant = ["qdrant-client"]
vdb-milvus = [
@@ -160,6 +164,7 @@ full = [
"agentscope[channel]",
"agentscope[workspace]",
"agentscope[tools]",
+ "agentscope[a2a]",
"agentscope[rag]",
"agentscope[vdb-qdrant]",
"agentscope[vdb-milvus]",
diff --git a/src/agentscope/agent/__init__.py b/src/agentscope/agent/__init__.py
index e3c134d6d..54b852973 100644
--- a/src/agentscope/agent/__init__.py
+++ b/src/agentscope/agent/__init__.py
@@ -1,10 +1,12 @@
# -*- coding: utf-8 -*-
"""Initialize the agent module."""
from ._agent import Agent
+from ._a2a_agent import A2AAgent
from ._config import ContextConfig, InjectionConfig, ModelConfig, ReActConfig
__all__ = [
"Agent",
+ "A2AAgent",
"ContextConfig",
"InjectionConfig",
"ModelConfig",
diff --git a/src/agentscope/agent/_a2a_agent.py b/src/agentscope/agent/_a2a_agent.py
new file mode 100644
index 000000000..487124571
--- /dev/null
+++ b/src/agentscope/agent/_a2a_agent.py
@@ -0,0 +1,657 @@
+# -*- coding: utf-8 -*-
+"""A stateful client-side adapter for remote A2A agents."""
+from __future__ import annotations
+
+import base64
+from collections.abc import AsyncGenerator, Iterable
+from dataclasses import dataclass, field
+from typing import Any, TYPE_CHECKING
+
+from ..state import A2AAgentState
+from .._logging import logger
+from .._utils._common import _generate_id
+from ..event import (
+ ReplyEndEvent,
+ ReplyFinishedReason,
+ ReplyStartEvent,
+ AgentEvent,
+ DataBlockDeltaEvent,
+ DataBlockEndEvent,
+ DataBlockStartEvent,
+ TextBlockDeltaEvent,
+ TextBlockEndEvent,
+ TextBlockStartEvent,
+)
+from ..message import (
+ AssistantMsg,
+ Msg,
+ TextBlock,
+ Base64Source,
+ DataBlock,
+ URLSource,
+)
+
+if TYPE_CHECKING:
+ from a2a.client import Client
+ from a2a.types import AgentCard
+ from a2a.types import Part
+
+
+@dataclass
+class _TextRun:
+ """The text block that consecutive text Parts stream into.
+
+ A2A marks continuation per artifact update rather than per Part, so a
+ run is identified by the metadata its Parts share and ends as soon as
+ anything else is emitted.
+ """
+
+ block_id: str | None = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+def _parts_to_events(
+ parts: Iterable[Part],
+ reply_id: str,
+ metadata: dict[str, Any],
+ run: _TextRun,
+ append: bool = False,
+ last_chunk: bool = True,
+) -> list[AgentEvent]:
+ """Build the events for one group of A2A Parts sharing one source.
+
+ ``append`` and ``last_chunk`` are the artifact update flags of the same
+ name: together they say whether this group continues the block ``run``
+ holds open and whether anything more can join it. Text Parts stream into
+ that one block, because reopening a block per chunk fragments one reply
+ into many; every other Part is a block of its own. The A2A ids the Parts
+ came from are carried on each block end event.
+ """
+ events: list[AgentEvent] = []
+
+ def close_run() -> None:
+ """End the open text block, if any."""
+ if run.block_id:
+ events.append(
+ TextBlockEndEvent(
+ reply_id=reply_id,
+ block_id=run.block_id,
+ metadata=run.metadata,
+ ),
+ )
+ run.block_id = None
+
+ if not (append and run.metadata == metadata):
+ close_run()
+
+ for part in parts:
+ kind = part.WhichOneof("content")
+ if kind == "text":
+ if run.block_id is None:
+ run.block_id, run.metadata = _generate_id(), metadata
+ events.append(
+ TextBlockStartEvent(
+ reply_id=reply_id,
+ block_id=run.block_id,
+ ),
+ )
+ if part.text:
+ events.append(
+ TextBlockDeltaEvent(
+ reply_id=reply_id,
+ block_id=run.block_id,
+ delta=part.text,
+ ),
+ )
+ continue
+
+ close_run()
+ if kind not in ("raw", "url"):
+ raise ValueError(
+ "A2AAgent supports text, raw, and URL parts; got "
+ f"unsupported {kind or 'empty'} content.",
+ )
+
+ block_id = _generate_id()
+ media_type = part.media_type or "application/octet-stream"
+ events.append(
+ DataBlockStartEvent(
+ reply_id=reply_id,
+ block_id=block_id,
+ media_type=media_type,
+ name=part.filename or None,
+ ),
+ )
+ if kind == "url":
+ events.append(
+ DataBlockDeltaEvent(
+ reply_id=reply_id,
+ block_id=block_id,
+ url=part.url,
+ media_type=media_type,
+ ),
+ )
+ elif part.raw:
+ events.append(
+ DataBlockDeltaEvent(
+ reply_id=reply_id,
+ block_id=block_id,
+ data=base64.b64encode(part.raw).decode("ascii"),
+ media_type=media_type,
+ ),
+ )
+ events.append(
+ DataBlockEndEvent(
+ reply_id=reply_id,
+ block_id=block_id,
+ metadata=metadata,
+ ),
+ )
+
+ if last_chunk:
+ close_run()
+ return events
+
+
+def _get_finished_reason(state: int) -> ReplyFinishedReason:
+ """Map the A2A Task state a response stream ended on to a reply outcome.
+
+ A Task waiting for input ends the reply normally: it is suspended
+ server-side, but nothing is suspended locally, so its status message is
+ an ordinary turn that the caller answers with the next reply.
+ """
+ from a2a.types import TaskState
+
+ if state in (
+ TaskState.TASK_STATE_COMPLETED,
+ TaskState.TASK_STATE_INPUT_REQUIRED,
+ TaskState.TASK_STATE_AUTH_REQUIRED,
+ ):
+ return ReplyFinishedReason.COMPLETED
+ if state == TaskState.TASK_STATE_CANCELED:
+ return ReplyFinishedReason.INTERRUPTED
+ # FAILED and REJECTED, plus a stream that died on SUBMITTED or WORKING
+ # without ever resolving.
+ return ReplyFinishedReason.ERROR
+
+
+def _awaiting_input(state: int) -> bool:
+ """Whether a Task in this state is suspended waiting for the caller, so
+ the next message continues it instead of starting a new Task."""
+ from a2a.types import TaskState
+
+ return state in (
+ TaskState.TASK_STATE_INPUT_REQUIRED,
+ TaskState.TASK_STATE_AUTH_REQUIRED,
+ )
+
+
+class A2AAgent:
+ """A stateful client-side adapter for an A2A 1.0 agent.
+
+ This class intentionally provides Agent-like interaction methods without
+ inheriting :class:`agentscope.agent.Agent`. A local ``Agent`` owns a model,
+ toolkit, state, and reasoning loop; this adapter delegates those concerns
+ to the remote A2A server and owns only the remote conversation
+ (``context_id``) and the Task the next message continues (``task_id``),
+ both held in :class:`agentscope.state.A2AAgentState`.
+
+ Each A2A Part of a response becomes one content block: text Parts become
+ :class:`~agentscope.message.TextBlock`, raw byte and URL Parts become
+ :class:`~agentscope.message.DataBlock`.
+
+ The adapter owns its A2A client and closes it in :meth:`aclose`, so it is
+ single-use: once closed it cannot be reopened.
+ """
+
+ def __init__(
+ self,
+ agent_card: AgentCard,
+ *,
+ client: Client | None = None,
+ state: A2AAgentState | None = None,
+ ) -> None:
+ """Initialize the A2A agent adapter.
+
+ Args:
+ agent_card (`a2a.types.AgentCard`):
+ The remote Agent Card, used both to identify the peer (its
+ ``name`` becomes this adapter's ``name``) and to select a
+ transport. The SDK picks the newest protocol version the card
+ advertises for the chosen binding, falling back to its A2A 0.3
+ compatibility transport when that is all the peer offers.
+ client (`a2a.client.Client | None`, optional):
+ An official SDK client, e.g. one configured for gRPC or with
+ custom auth. If omitted, a streaming client is built from
+ the card, which then requires a ``JSONRPC`` or ``HTTP+JSON``
+ interface. The adapter owns the client either way and closes
+ it in :meth:`aclose`.
+ state (`agentscope.state.A2AAgentState | None`, optional):
+ An existing state to resume, e.g. one saved from an earlier
+ adapter, so its ``context_id`` continues the same remote
+ conversation. A fresh state is created when omitted.
+ """
+ try:
+ import a2a # noqa: F401 pylint: disable=unused-import
+ except ImportError as error:
+ raise ImportError(
+ "A2AAgent requires the A2A extra. Install it with "
+ "`pip install 'agentscope[a2a]'`.",
+ ) from error
+
+ self._agent_card = agent_card
+ self.name = self._agent_card.name
+ if client is None:
+ from a2a.client import ClientConfig, ClientFactory
+ from a2a.utils.constants import TransportProtocol
+
+ client = ClientFactory(
+ ClientConfig(
+ streaming=True,
+ polling=False,
+ supported_protocol_bindings=[
+ TransportProtocol.JSONRPC,
+ TransportProtocol.HTTP_JSON,
+ ],
+ ),
+ ).create(self._agent_card)
+
+ self._client = client
+ self.state = state or A2AAgentState()
+ self._closed = False
+
+ async def __aenter__(self) -> A2AAgent:
+ """Enter the asynchronous context manager.
+
+ Leaving the block closes the owned client, and nothing reopens it,
+ so an adapter can only be entered before it is closed.
+ """
+ if self._closed:
+ raise RuntimeError("A2AAgent is closed.")
+ return self
+
+ async def __aexit__(self, *_: Any) -> None:
+ """Close the owned client when leaving the context manager."""
+ await self.aclose()
+
+ async def aclose(self) -> None:
+ """Close the owned A2A client. Repeated calls are safe."""
+ if not self._closed:
+ await self._client.close()
+ self._closed = True
+
+ async def reply_stream(
+ self,
+ inputs: Msg | list[Msg] | None = None,
+ yield_final_msg: bool = False,
+ ) -> AsyncGenerator[AgentEvent | Msg, None]:
+ """Send input and stream the remote reply as AgentScope events.
+
+ Args:
+ inputs (`Msg | list[Msg] | None`, optional):
+ The messages to send, preceded by the observed ones.
+ yield_final_msg (`bool`, defaults to `False`):
+ Whether to yield the final reply message after the events.
+
+ Yields:
+ `AgentEvent | Msg`:
+ Streamed events produced during the reply.
+ """
+ async for event_or_msg in self._reply(inputs):
+ if isinstance(event_or_msg, Msg) and not yield_final_msg:
+ continue
+ yield event_or_msg
+
+ async def reply(self, inputs: Msg | list[Msg] | None = None) -> Msg:
+ """Send input and return the final assistant message.
+
+ Args:
+ inputs (`Msg | list[Msg] | None`, optional):
+ The messages to send, preceded by the observed ones.
+
+ Returns:
+ `Msg`:
+ The reply message, assembled from the streamed events.
+ """
+ final_msg: Msg | None = None
+ async for event_or_msg in self._reply(inputs):
+ if isinstance(event_or_msg, Msg):
+ final_msg = event_or_msg
+ if final_msg is None:
+ raise RuntimeError("A2AAgent did not produce a final message.")
+ return final_msg
+
+ async def _reply(
+ self,
+ inputs: Msg | list[Msg] | None = None,
+ ) -> AsyncGenerator[AgentEvent | Msg, None]:
+ """Send one A2A Message and stream its response back.
+
+ The observed messages lead the input, and the whole turn is flattened
+ into a single A2A Message. It continues the remote Task the previous
+ reply left waiting for input, if any, and otherwise starts a new one
+ within the same ``context_id``.
+
+ Args:
+ inputs (`Msg | list[Msg] | None`):
+ The input message(s) to send, preceded by the observed ones.
+
+ Yields:
+ `AgentEvent | Msg`:
+ The streamed events, then the final reply message.
+
+ Raises:
+ `RuntimeError`:
+ If the remote Task from an earlier reply is still running,
+ since a second message would execute it again.
+ """
+ from a2a.types import GetTaskRequest, TaskState
+ from a2a.utils.errors import TaskNotFoundError
+
+ # Ensure the client is open
+ self._ensure_open()
+
+ # Normalize the inputs into a2a-acceptable objects
+ if isinstance(inputs, Msg):
+ input_msgs = [inputs]
+ elif isinstance(inputs, list) and all(
+ isinstance(_, Msg) for _ in inputs
+ ):
+ input_msgs = inputs
+ else:
+ input_msgs = []
+
+ # Observed messages are earlier context, so they lead this input.
+ input_msgs = [*self.state.observed_context, *input_msgs]
+ self.state.observed_context.clear()
+
+ if not input_msgs:
+ raise ValueError(
+ "A2AAgent reply requires at least one message.",
+ )
+
+ # A Task left over from an earlier reply decides what this input
+ # does, and only the server knows how it ended.
+ if self.state.task_id:
+ try:
+ task = await self._client.get_task(
+ GetTaskRequest(id=self.state.task_id),
+ )
+ except TaskNotFoundError:
+ # The server has forgotten the Task; start a new one.
+ self.state.task_id = None
+ else:
+ if task.status.state in (
+ TaskState.TASK_STATE_SUBMITTED,
+ TaskState.TASK_STATE_WORKING,
+ ):
+ # The server taps the running Task's own queue, so
+ # sending now would execute it a second time.
+ raise RuntimeError(
+ f"A2A task {self.state.task_id} is still running "
+ "on the remote server; retry once it has finished.",
+ )
+ if not _awaiting_input(task.status.state):
+ self.state.task_id = None
+
+ reply_id = _generate_id()
+ # The reply message is assembled from the very events streamed to
+ # the caller, so the two can never disagree.
+ msg = AssistantMsg(
+ id=reply_id,
+ name=self._agent_card.name,
+ content=[],
+ )
+
+ yield ReplyStartEvent(
+ session_id=self.state.session_id,
+ reply_id=reply_id,
+ name=self._agent_card.name,
+ )
+
+ finished_reason = ReplyFinishedReason.COMPLETED
+ run = _TextRun()
+
+ async for response in self._client.send_message(
+ self._build_request(input_msgs),
+ ):
+ events: list[AgentEvent] = []
+ match response.WhichOneof("payload"):
+ case "message":
+ # A direct Message response carries no Task status, and
+ # answering it never continues a Task.
+ message = response.message
+ if message.context_id:
+ self.state.context_id = message.context_id
+ self.state.task_id = None
+
+ events += _parts_to_events(
+ message.parts,
+ reply_id,
+ {"a2a": {"message_id": message.message_id}},
+ run,
+ )
+
+ case "artifact_update":
+ # An artifact carries no Task status, so it never
+ # decides whether the Task is still to be continued.
+ update = response.artifact_update
+ if update.context_id:
+ self.state.context_id = update.context_id
+
+ # `append` is the only continuation A2A gives, and it
+ # is per update, so the chunks of one artifact are what
+ # keeps a text block open.
+ events += _parts_to_events(
+ update.artifact.parts,
+ reply_id,
+ {
+ "a2a": {
+ "task_id": update.task_id,
+ "artifact_id": update.artifact.artifact_id,
+ },
+ },
+ run,
+ append=update.append,
+ last_chunk=update.last_chunk,
+ )
+
+ case "status_update":
+ update = response.status_update
+ if update.context_id:
+ self.state.context_id = update.context_id
+ self.state.task_id = (
+ update.task_id
+ if _awaiting_input(update.status.state)
+ else None
+ )
+
+ # Last write wins: the outcome is decided by the
+ # state the stream ends on.
+ finished_reason = _get_finished_reason(
+ update.status.state,
+ )
+
+ events += _parts_to_events(
+ update.status.message.parts,
+ reply_id,
+ {"a2a": {"task_id": update.task_id}},
+ run,
+ )
+
+ case "task":
+ # A full Task snapshot, the only payload the
+ # non-streaming path and GetTask return.
+ task = response.task
+ if task.context_id:
+ self.state.context_id = task.context_id
+ self.state.task_id = (
+ task.id if _awaiting_input(task.status.state) else None
+ )
+
+ finished_reason = _get_finished_reason(
+ task.status.state,
+ )
+
+ for artifact in task.artifacts:
+ events += _parts_to_events(
+ artifact.parts,
+ reply_id,
+ {
+ "a2a": {
+ "task_id": task.id,
+ "artifact_id": artifact.artifact_id,
+ },
+ },
+ run,
+ )
+
+ events += _parts_to_events(
+ task.status.message.parts,
+ reply_id,
+ {"a2a": {"task_id": task.id}},
+ run,
+ )
+
+ case _:
+ raise RuntimeError(
+ "A2A response contained no payload.",
+ )
+
+ for event in events:
+ msg.append_event(event)
+ yield event
+
+ metadata = {"a2a": {"context_id": self.state.context_id}}
+
+ # A stream that ended mid-artifact still owes the block its end.
+ for event in _parts_to_events([], reply_id, {}, run):
+ msg.append_event(event)
+ yield event
+
+ # `append_event` stamps finished_reason and finished_at from the
+ # end event, so the message must see it before it is yielded.
+ end_event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=reply_id,
+ finished_reason=finished_reason,
+ metadata=metadata,
+ )
+ msg.append_event(end_event)
+ yield end_event
+
+ msg.metadata = metadata
+ yield msg
+
+ def _build_request(self, messages: list[Msg]) -> Any:
+ """Flatten AgentScope messages into one A2A user Message.
+
+ Args:
+ messages (`list[Msg]`):
+ The messages of this turn, whose blocks become the Parts of
+ a single user Message.
+
+ Returns:
+ `a2a.types.SendMessageRequest`:
+ The request, carrying the remote ``context_id`` and, when the
+ Task is waiting for input, its ``task_id``.
+ """
+ from a2a.types import Part, Message, Role, SendMessageRequest
+
+ # Convert Msg objects into A2A message parts.
+ parts = []
+ for msg in messages:
+ for block in msg.content:
+ if isinstance(block, TextBlock):
+ parts.append(Part(text=block.text))
+
+ elif isinstance(block, DataBlock):
+ if isinstance(block.source, Base64Source):
+ try:
+ raw = base64.b64decode(
+ block.source.data,
+ validate=True,
+ )
+ except ValueError as error:
+ raise ValueError(
+ "A2AAgent received invalid base64 input data.",
+ ) from error
+ parts.append(
+ Part(
+ raw=raw,
+ media_type=block.source.media_type,
+ filename=block.name or "",
+ ),
+ )
+
+ elif isinstance(block.source, URLSource):
+ parts.append(
+ Part(
+ url=str(block.source.url),
+ media_type=block.source.media_type,
+ filename=block.name or "",
+ ),
+ )
+
+ else:
+ raise TypeError(
+ f"A2AAgent cannot send block of type {type(block)}.",
+ )
+
+ message = Message(
+ message_id=_generate_id(),
+ role=Role.ROLE_USER,
+ parts=parts,
+ )
+
+ # Use the current session id as the a2a context id if already set
+ if self.state.context_id:
+ message.context_id = self.state.context_id
+
+ if self.state.task_id:
+ message.task_id = self.state.task_id
+
+ return SendMessageRequest(message=message)
+
+ def _ensure_open(self) -> None:
+ """Reject operations after client closure."""
+ if self._closed:
+ raise RuntimeError("A2AAgent is closed.")
+
+ # =================================================================
+ # The functions that not implemented by the A2A protocol, leaving for
+ # alignment with the Agent interface.
+ # =================================================================
+
+ async def compress_context( # pylint: disable=unused-argument
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing because the remote A2A server owns its context.
+
+ The arguments are accepted for interface compatibility with
+ :class:`agentscope.agent.Agent`.
+ """
+ logger.warning(
+ "Ignoring compress_context() on A2AAgent %s: the remote A2A "
+ "server owns its own conversation context.",
+ self.name,
+ )
+
+ async def observe(self, msgs: Msg | list[Msg] | None = None) -> None:
+ """Cache messages to send ahead of the next reply's own input.
+
+ Args:
+ msgs (`Msg | list[Msg] | None`, optional):
+ The messages to remember. ``None`` is ignored.
+ """
+ if msgs is None:
+ return
+ messages = [msgs] if isinstance(msgs, Msg) else msgs
+ if not isinstance(messages, list) or not all(
+ isinstance(msg, Msg) for msg in messages
+ ):
+ raise TypeError("msgs must be a Msg, a list of Msg, or None.")
+ self._ensure_open()
+ self.state.observed_context.extend(messages)
diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.py
index 1203f5b40..59d5f8d4d 100644
--- a/src/agentscope/event/_event.py
+++ b/src/agentscope/event/_event.py
@@ -203,6 +203,8 @@ class DataBlockStartEvent(EventBase):
"""Unique identifier of the data block."""
media_type: str
"""MIME type of the data content (e.g. "image/png")."""
+ name: str | None = None
+ """Name of the data, e.g. a file name."""
class DataBlockDeltaEvent(EventBase):
@@ -214,10 +216,21 @@ class DataBlockDeltaEvent(EventBase):
"""ID of the reply message this block belongs to."""
block_id: str
"""Unique identifier of the data block."""
- data: str
- """Incremental base64-encoded data."""
media_type: str
"""MIME type of the data content."""
+ data: str | None = None
+ """Incremental base64-encoded data, mutually exclusive with `url`."""
+ url: str | None = None
+ """URL pointing to the data, mutually exclusive with `data`."""
+
+ @model_validator(mode="after")
+ def validate_data_source(self) -> Self:
+ """Ensure exactly one data source is provided."""
+ if (self.data is None) == (self.url is None):
+ raise ValueError(
+ "Exactly one of `data` or `url` must be provided.",
+ )
+ return self
class DataBlockEndEvent(EventBase):
diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.py
index 0d51f35aa..b5bbf9e16 100644
--- a/src/agentscope/message/_base.py
+++ b/src/agentscope/message/_base.py
@@ -241,7 +241,7 @@ class Msg(BaseModel):
return block
return None
- def append_event( # pylint: disable=too-many-branches
+ def append_event( # pylint: disable=too-many-branches,too-many-statements
self,
event: AgentEvent,
) -> Self:
@@ -323,6 +323,7 @@ class Msg(BaseModel):
data="",
media_type=event.media_type,
),
+ name=event.name,
),
)
@@ -333,6 +334,13 @@ class Msg(BaseModel):
"DataBlock %s not found, skipping.",
event.block_id,
)
+ elif event.type == EventType.DATA_BLOCK_DELTA and event.url:
+ # A URL is the whole content, so it replaces the empty
+ # base64 source the start event created.
+ block.source = URLSource(
+ url=event.url,
+ media_type=event.media_type,
+ )
elif event.type == EventType.DATA_BLOCK_DELTA and event.data:
# Each delta is an independently base64-encoded chunk
# (with its own padding); naive string concat would
diff --git a/src/agentscope/state/__init__.py b/src/agentscope/state/__init__.py
index 13f47eca7..f7de6a3c4 100644
--- a/src/agentscope/state/__init__.py
+++ b/src/agentscope/state/__init__.py
@@ -3,6 +3,8 @@
from ._state import AgentState, TaskContext, ReplyContext, ToolContext
from ._task import Task
+from ._a2a_state import A2AAgentState
+
__all__ = [
"Task",
@@ -10,4 +12,5 @@ __all__ = [
"ReplyContext",
"ToolContext",
"AgentState",
+ "A2AAgentState",
]
diff --git a/src/agentscope/state/_a2a_state.py b/src/agentscope/state/_a2a_state.py
new file mode 100644
index 000000000..bec1c0d9f
--- /dev/null
+++ b/src/agentscope/state/_a2a_state.py
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+"""The a2a agent state."""
+
+from pydantic import BaseModel, Field
+
+from ..message import Msg
+from .._utils._common import _generate_id
+
+
+class A2AAgentState(BaseModel):
+ """The A2A agent state."""
+
+ session_id: str = Field(default_factory=_generate_id)
+ """The session id of the agent, used to group its streamed events."""
+
+ context_id: str | None = None
+ """The context_id of the A2A protocol."""
+
+ task_id: str | None = None
+ """The current task id of the agent."""
+
+ observed_context: list[Msg] = Field(default_factory=list)
+ """The observed context of the agent."""
diff --git a/tests/a2a_agent_e2e_test.py b/tests/a2a_agent_e2e_test.py
new file mode 100644
index 000000000..36b98749e
--- /dev/null
+++ b/tests/a2a_agent_e2e_test.py
@@ -0,0 +1,216 @@
+# -*- coding: utf-8 -*-
+# flake8: noqa: E402
+# pylint: disable=wrong-import-position
+"""Local HTTP/SSE end-to-end test for A2AAgent."""
+from __future__ import annotations
+
+import asyncio
+import socket
+from unittest import IsolatedAsyncioTestCase
+
+import pytest
+
+pytest.importorskip("a2a", reason="A2A E2E test requires the a2a extra")
+
+import httpx
+import uvicorn
+from a2a.client import A2ACardResolver, ClientConfig, ClientFactory
+from a2a.server.agent_execution import AgentExecutor, RequestContext
+from a2a.server.events import EventQueue
+from a2a.server.request_handlers import DefaultRequestHandler
+from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
+from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
+from a2a.types import (
+ AgentCapabilities,
+ AgentCard,
+ AgentInterface,
+ AgentSkill,
+ Part,
+ Task,
+ TaskState,
+ TaskStatus,
+)
+from a2a.utils.constants import TransportProtocol
+from starlette.applications import Starlette
+
+from agentscope.agent import A2AAgent
+from agentscope.event import TextBlockDeltaEvent
+from agentscope.message import UserMsg
+
+
+class _StatefulExecutor(AgentExecutor):
+ """Deterministic remote agent that records user turns by context ID."""
+
+ def __init__(self) -> None:
+ self._history: dict[str, list[str]] = {}
+
+ async def execute(
+ self,
+ context: RequestContext,
+ event_queue: EventQueue,
+ ) -> None:
+ """Stream a two-chunk answer through the official server SDK."""
+ if context.task_id is None or context.context_id is None:
+ raise RuntimeError("A2A server did not assign Task/context IDs.")
+
+ updater = TaskUpdater(
+ event_queue,
+ task_id=context.task_id,
+ context_id=context.context_id,
+ )
+ await event_queue.enqueue_event(
+ Task(
+ id=context.task_id,
+ context_id=context.context_id,
+ status=TaskStatus(state=TaskState.TASK_STATE_SUBMITTED),
+ ),
+ )
+ await updater.start_work()
+
+ turns = self._history.setdefault(context.context_id, [])
+ turns.append(context.get_user_input())
+ answer = f"turn={len(turns)}; users={' | '.join(turns)}"
+ split_at = max(1, len(answer) // 2)
+ artifact_id = f"{context.task_id}-answer"
+ await updater.add_artifact(
+ [Part(text=answer[:split_at])],
+ artifact_id=artifact_id,
+ append=False,
+ last_chunk=False,
+ )
+ await updater.add_artifact(
+ [Part(text=answer[split_at:])],
+ artifact_id=artifact_id,
+ append=True,
+ last_chunk=True,
+ )
+ await updater.complete()
+
+ async def cancel(
+ self,
+ context: RequestContext,
+ event_queue: EventQueue,
+ ) -> None:
+ """Mark the test Task as canceled."""
+ if context.task_id is None or context.context_id is None:
+ raise RuntimeError("Cannot cancel a Task without IDs.")
+ await TaskUpdater(
+ event_queue,
+ task_id=context.task_id,
+ context_id=context.context_id,
+ ).cancel()
+
+
+def _create_app(base_url: str) -> Starlette:
+ """Create the deterministic local A2A 1.0 harness."""
+ card = AgentCard(
+ name="Local E2E Harness",
+ description="Deterministic A2AAgent end-to-end test server.",
+ version="1.0.0",
+ supported_interfaces=[
+ AgentInterface(
+ url=base_url,
+ protocol_binding="JSONRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ capabilities=AgentCapabilities(streaming=True),
+ default_input_modes=["text/plain"],
+ default_output_modes=["text/plain"],
+ skills=[
+ AgentSkill(
+ id="chat",
+ name="Chat",
+ description="Return deterministic multi-turn responses.",
+ tags=["test"],
+ ),
+ ],
+ )
+ handler = DefaultRequestHandler(
+ agent_executor=_StatefulExecutor(),
+ task_store=InMemoryTaskStore(),
+ agent_card=card,
+ )
+ return Starlette(
+ routes=[
+ *create_agent_card_routes(card),
+ *create_jsonrpc_routes(handler, rpc_url="/"),
+ ],
+ )
+
+
+class A2AAgentE2ETest(IsolatedAsyncioTestCase):
+ """Exercise Agent Card resolution, JSON-RPC/SSE, and context reuse."""
+
+ async def test_streaming_and_multi_turn_context(self) -> None:
+ """Use a real localhost transport with no model or external API."""
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen()
+ port = listener.getsockname()[1]
+ base_url = f"http://127.0.0.1:{port}"
+ server = uvicorn.Server(
+ uvicorn.Config(_create_app(base_url), log_level="warning"),
+ )
+ server_task = asyncio.create_task(server.serve(sockets=[listener]))
+
+ try:
+ for _ in range(100):
+ if server.started:
+ break
+ await asyncio.sleep(0.01)
+ self.assertTrue(server.started, "local A2A harness did not start")
+
+ async with httpx.AsyncClient(trust_env=False) as resolver_client:
+ card = await A2ACardResolver(
+ httpx_client=resolver_client,
+ base_url=base_url,
+ ).get_agent_card()
+
+ transport_client = httpx.AsyncClient(trust_env=False)
+ client = ClientFactory(
+ ClientConfig(
+ streaming=True,
+ polling=False,
+ httpx_client=transport_client,
+ supported_protocol_bindings=[TransportProtocol.JSONRPC],
+ ),
+ ).create(card)
+ async with A2AAgent(card, client=client) as agent:
+ deltas: list[str] = []
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content="FIRST"),
+ ):
+ if isinstance(event, TextBlockDeltaEvent):
+ deltas.append(event.delta)
+
+ first_context_id = agent.state.context_id
+ self.assertTrue(first_context_id)
+ # Two artifact chunks, but one text block: the appended
+ # chunk continues the block the first one opened.
+ self.assertListEqual(
+ deltas,
+ ["turn=1; u", "sers=FIRST"],
+ )
+
+ reply = await agent.reply(
+ UserMsg(name="user", content="SECOND"),
+ )
+ # The same context spans both turns, and each completed Task
+ # is over, so nothing is carried into the next one.
+ self.assertEqual(agent.state.context_id, first_context_id)
+ self.assertIsNone(agent.state.task_id)
+ self.assertEqual(
+ reply.get_text_content(),
+ "turn=2; users=FIRST | SECOND",
+ )
+ finally:
+ server.should_exit = True
+ await server_task
+
+
+if __name__ == "__main__":
+ import unittest
+
+ unittest.main()
diff --git a/tests/a2a_agent_test.py b/tests/a2a_agent_test.py
new file mode 100644
index 000000000..e87c80a9f
--- /dev/null
+++ b/tests/a2a_agent_test.py
@@ -0,0 +1,812 @@
+# -*- coding: utf-8 -*-
+# flake8: noqa: E402
+# pylint: disable=wrong-import-position
+"""Tests for the A2A agent adapter."""
+from collections.abc import AsyncGenerator
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+from unittest.mock import patch
+
+import pytest
+
+pytest.importorskip("a2a", reason="A2A tests require the a2a extra")
+
+from a2a import types
+from a2a.utils.errors import TaskNotFoundError
+from utils import AnyString
+
+from agentscope.agent import A2AAgent
+from agentscope.message import UserMsg
+from agentscope.state import A2AAgentState
+
+
+class _FakeClient:
+ """Deterministic fake for the official SDK Client interface."""
+
+ def __init__(
+ self,
+ responses: list[list[types.StreamResponse]] | None = None,
+ *,
+ get_tasks: list[types.Task | BaseException] | None = None,
+ ) -> None:
+ self.responses = responses or []
+ self.get_tasks = get_tasks or []
+ self.requests: list[types.SendMessageRequest] = []
+ self.get_requests: list[types.GetTaskRequest] = []
+ self.close_count = 0
+
+ async def send_message(
+ self,
+ request: types.SendMessageRequest,
+ *,
+ context: Any = None,
+ ) -> AsyncGenerator[types.StreamResponse, None]:
+ """Record the request and yield one configured response stream."""
+ del context
+ self.requests.append(request)
+ for response in self.responses.pop(0):
+ yield response
+
+ async def get_task(
+ self,
+ request: types.GetTaskRequest,
+ *,
+ context: Any = None,
+ ) -> types.Task:
+ """Return one configured Task snapshot."""
+ del context
+ self.get_requests.append(request)
+ task = self.get_tasks.pop(0)
+ if isinstance(task, BaseException):
+ raise task
+ return task
+
+ async def close(self) -> None:
+ """Record client closure."""
+ self.close_count += 1
+
+
+class A2AAgentConstructionTest(IsolatedAsyncioTestCase):
+ """Test A2AAgent construction and transport selection."""
+
+ async def test_default_client_configuration(self) -> None:
+ """The default client streams over the two supported bindings."""
+ client = _FakeClient()
+ card = types.AgentCard(
+ name="remote-agent",
+ description="test agent",
+ supported_interfaces=[
+ types.AgentInterface(
+ url="http://example.test/0.3",
+ protocol_binding="JSONRPC",
+ protocol_version="0.3",
+ ),
+ types.AgentInterface(
+ url="http://example.test/1.0",
+ protocol_binding="JSONRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ )
+ with patch("a2a.client.ClientFactory") as factory_class:
+ factory_class.return_value.create.return_value = client
+ agent = A2AAgent(card)
+
+ config = factory_class.call_args.args[0]
+ self.assertTrue(config.streaming)
+ self.assertFalse(config.polling)
+ self.assertListEqual(
+ [binding.value for binding in config.supported_protocol_bindings],
+ ["JSONRPC", "HTTP+JSON"],
+ )
+ # The card reaches the SDK untouched, so the factory can fall back to
+ # its A2A 0.3 compatibility transport when a peer offers nothing newer.
+ self.assertIs(
+ factory_class.return_value.create.call_args.args[0],
+ card,
+ )
+ self.assertEqual(agent.name, "remote-agent")
+ await agent.aclose()
+
+ async def test_injected_client_may_use_another_binding(self) -> None:
+ """Transport restrictions belong only to the default client path."""
+ client = _FakeClient()
+ agent = A2AAgent(
+ types.AgentCard(
+ name="remote-agent",
+ description="test agent",
+ supported_interfaces=[
+ types.AgentInterface(
+ url="http://example.test/1.0",
+ protocol_binding="GRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ ),
+ client=client,
+ )
+ await agent.aclose()
+ await agent.aclose()
+ self.assertEqual(client.close_count, 1)
+
+
+class A2AAgentReplyTest(IsolatedAsyncioTestCase):
+ """Test how A2A responses become AgentScope events and messages."""
+
+ def setUp(self) -> None:
+ """Build a card shared by the reply tests."""
+ self.card = types.AgentCard(
+ name="remote-agent",
+ description="test agent",
+ supported_interfaces=[
+ types.AgentInterface(
+ url="http://example.test/1.0",
+ protocol_binding="JSONRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ )
+
+ async def test_direct_message_response(self) -> None:
+ """A bare Message becomes text blocks and leaves no Task behind."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ message=types.Message(
+ message_id="msg-1",
+ context_id="context-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[types.Part(text="hello")],
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ events = [
+ _.model_dump(mode="json")
+ async for _ in agent.reply_stream(
+ UserMsg(name="user", content="hi"),
+ )
+ ]
+
+ self.assertListEqual(
+ events,
+ [
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "REPLY_START",
+ "session_id": AnyString(),
+ "reply_id": AnyString(),
+ "name": "remote-agent",
+ "role": "assistant",
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "TEXT_BLOCK_START",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "TEXT_BLOCK_DELTA",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ "delta": "hello",
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {"a2a": {"message_id": "msg-1"}},
+ "type": "TEXT_BLOCK_END",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {"a2a": {"context_id": "context-1"}},
+ "type": "REPLY_END",
+ "session_id": AnyString(),
+ "reply_id": AnyString(),
+ "finished_reason": "completed",
+ "error": None,
+ },
+ ],
+ )
+ self.assertEqual(agent.state.context_id, "context-1")
+ self.assertIsNone(agent.state.task_id)
+ await agent.aclose()
+
+ async def test_streamed_artifact_chunks_are_one_text_block(self) -> None:
+ """Appended chunks continue one block; a binary Part ends it."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ artifact_update=types.TaskArtifactUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ artifact=types.Artifact(
+ artifact_id="artifact-1",
+ parts=[types.Part(text="first ")],
+ ),
+ ),
+ ),
+ types.StreamResponse(
+ artifact_update=types.TaskArtifactUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ artifact=types.Artifact(
+ artifact_id="artifact-1",
+ parts=[types.Part(text="second")],
+ ),
+ append=True,
+ ),
+ ),
+ types.StreamResponse(
+ artifact_update=types.TaskArtifactUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ artifact=types.Artifact(
+ artifact_id="artifact-1",
+ parts=[
+ types.Part(
+ raw=b"bytes",
+ media_type="image/png",
+ filename="chart.png",
+ ),
+ ],
+ ),
+ append=True,
+ last_chunk=True,
+ ),
+ ),
+ types.StreamResponse(
+ status_update=types.TaskStatusUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(
+ state=types.TaskState.TASK_STATE_COMPLETED,
+ ),
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ msg = await agent.reply(UserMsg(name="user", content="draw"))
+
+ self.assertDictEqual(
+ msg.model_dump(mode="json"),
+ {
+ "id": AnyString(),
+ "name": "remote-agent",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "first second",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": AnyString(),
+ },
+ {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": "Ynl0ZXM=",
+ "media_type": "image/png",
+ },
+ "name": "chart.png",
+ "created_at": AnyString(),
+ "finished_at": AnyString(),
+ },
+ ],
+ "metadata": {"a2a": {"context_id": "context-1"}},
+ "created_at": AnyString(),
+ "finished_at": AnyString(),
+ "finished_reason": "completed",
+ "error": None,
+ "usage": None,
+ "structured_output": None,
+ },
+ )
+ # A completed Task is over, so the next reply starts a new one.
+ self.assertIsNone(agent.state.task_id)
+ await agent.aclose()
+
+ async def test_task_snapshot_yields_artifacts_then_status(self) -> None:
+ """A full Task snapshot is reduced in the order it presents data."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ task=types.Task(
+ id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(
+ state=types.TaskState.TASK_STATE_COMPLETED,
+ message=types.Message(
+ message_id="msg-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[types.Part(text="done")],
+ ),
+ ),
+ artifacts=[
+ types.Artifact(
+ artifact_id="artifact-1",
+ parts=[types.Part(text="report")],
+ ),
+ ],
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ events = [
+ _.model_dump(mode="json")
+ async for _ in agent.reply_stream(
+ UserMsg(name="user", content="go"),
+ )
+ ]
+
+ self.assertListEqual(
+ events,
+ [
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "REPLY_START",
+ "session_id": AnyString(),
+ "reply_id": AnyString(),
+ "name": "remote-agent",
+ "role": "assistant",
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "TEXT_BLOCK_START",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "TEXT_BLOCK_DELTA",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ "delta": "report",
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {
+ "a2a": {
+ "task_id": "task-1",
+ "artifact_id": "artifact-1",
+ },
+ },
+ "type": "TEXT_BLOCK_END",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "TEXT_BLOCK_START",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "TEXT_BLOCK_DELTA",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ "delta": "done",
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {"a2a": {"task_id": "task-1"}},
+ "type": "TEXT_BLOCK_END",
+ "reply_id": AnyString(),
+ "block_id": AnyString(),
+ },
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {"a2a": {"context_id": "context-1"}},
+ "type": "REPLY_END",
+ "session_id": AnyString(),
+ "reply_id": AnyString(),
+ "finished_reason": "completed",
+ "error": None,
+ },
+ ],
+ )
+ await agent.aclose()
+
+ async def test_raw_and_url_parts_become_data_blocks(self) -> None:
+ """Both binary forms of a Part survive the round trip."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ message=types.Message(
+ message_id="msg-1",
+ context_id="context-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[
+ types.Part(
+ raw=b"bytes",
+ media_type="image/png",
+ filename="chart.png",
+ ),
+ types.Part(
+ url="https://example.test/report.pdf",
+ media_type="application/pdf",
+ ),
+ ],
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ msg = await agent.reply(UserMsg(name="user", content="files"))
+
+ self.assertListEqual(
+ [_.model_dump(mode="json") for _ in msg.content],
+ [
+ {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": "Ynl0ZXM=",
+ "media_type": "image/png",
+ },
+ "name": "chart.png",
+ "created_at": AnyString(),
+ "finished_at": AnyString(),
+ },
+ {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "url",
+ "url": "https://example.test/report.pdf",
+ "media_type": "application/pdf",
+ },
+ "name": None,
+ "created_at": AnyString(),
+ "finished_at": AnyString(),
+ },
+ ],
+ )
+ await agent.aclose()
+
+ async def test_unsupported_part_is_rejected(self) -> None:
+ """An empty Part carries no content the adapter can map."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ message=types.Message(
+ message_id="msg-1",
+ context_id="context-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[types.Part()],
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ with self.assertRaises(ValueError) as error:
+ await agent.reply(UserMsg(name="user", content="hi"))
+
+ self.assertEqual(
+ str(error.exception),
+ "A2AAgent supports text, raw, and URL parts; got unsupported "
+ "empty content.",
+ )
+ await agent.aclose()
+
+ async def test_input_blocks_become_parts_of_one_message(self) -> None:
+ """Observed messages lead the input inside a single user Message."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ message=types.Message(
+ message_id="msg-1",
+ context_id="context-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[types.Part(text="ok")],
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ await agent.observe(UserMsg(name="user", content="earlier"))
+ await agent.reply(UserMsg(name="user", content="later"))
+
+ self.assertListEqual(
+ [_.text for _ in client.requests[0].message.parts],
+ ["earlier", "later"],
+ )
+ self.assertEqual(client.requests[0].message.role, types.Role.ROLE_USER)
+ # Observations are consumed by the reply that sends them.
+ self.assertListEqual(agent.state.observed_context, [])
+ await agent.aclose()
+
+ async def test_reply_without_any_input_is_rejected(self) -> None:
+ """There is nothing to send without input or observed messages."""
+ agent = A2AAgent(self.card, client=_FakeClient())
+
+ with self.assertRaises(ValueError) as error:
+ await agent.reply()
+
+ self.assertEqual(
+ str(error.exception),
+ "A2AAgent reply requires at least one message.",
+ )
+ await agent.aclose()
+
+
+class A2AAgentTaskContinuationTest(IsolatedAsyncioTestCase):
+ """Test which remote Task the next message continues."""
+
+ def setUp(self) -> None:
+ """Build a card shared by the continuation tests."""
+ self.card = types.AgentCard(
+ name="remote-agent",
+ description="test agent",
+ supported_interfaces=[
+ types.AgentInterface(
+ url="http://example.test/1.0",
+ protocol_binding="JSONRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ )
+
+ async def test_final_state_decides_the_reply_outcome(self) -> None:
+ """The state a stream ends on sets both outcome and continuation."""
+ outcomes = []
+ for state in [
+ types.TaskState.TASK_STATE_COMPLETED,
+ types.TaskState.TASK_STATE_INPUT_REQUIRED,
+ types.TaskState.TASK_STATE_AUTH_REQUIRED,
+ types.TaskState.TASK_STATE_CANCELED,
+ types.TaskState.TASK_STATE_FAILED,
+ types.TaskState.TASK_STATE_REJECTED,
+ ]:
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ status_update=types.TaskStatusUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(state=state),
+ ),
+ ),
+ ],
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+ msg = await agent.reply(UserMsg(name="user", content="hi"))
+ outcomes.append(
+ (
+ types.TaskState.Name(state),
+ msg.finished_reason.value,
+ agent.state.task_id,
+ ),
+ )
+ await agent.aclose()
+
+ self.assertListEqual(
+ outcomes,
+ [
+ ("TASK_STATE_COMPLETED", "completed", None),
+ ("TASK_STATE_INPUT_REQUIRED", "completed", "task-1"),
+ ("TASK_STATE_AUTH_REQUIRED", "completed", "task-1"),
+ ("TASK_STATE_CANCELED", "interrupted", None),
+ ("TASK_STATE_FAILED", "error", None),
+ ("TASK_STATE_REJECTED", "error", None),
+ ],
+ )
+
+ async def test_task_waiting_for_input_is_continued(self) -> None:
+ """The next message joins the Task the server is waiting on."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ status_update=types.TaskStatusUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(
+ state=(
+ types.TaskState.TASK_STATE_INPUT_REQUIRED
+ ),
+ message=types.Message(
+ message_id="msg-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[types.Part(text="which one?")],
+ ),
+ ),
+ ),
+ ),
+ ],
+ [
+ types.StreamResponse(
+ status_update=types.TaskStatusUpdateEvent(
+ task_id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(
+ state=types.TaskState.TASK_STATE_COMPLETED,
+ ),
+ ),
+ ),
+ ],
+ ],
+ get_tasks=[
+ types.Task(
+ id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(
+ state=types.TaskState.TASK_STATE_INPUT_REQUIRED,
+ ),
+ ),
+ ],
+ )
+ agent = A2AAgent(self.card, client=client)
+
+ first = await agent.reply(UserMsg(name="user", content="hi"))
+ await agent.reply(UserMsg(name="user", content="the second"))
+
+ self.assertEqual(first.get_text_content(), "which one?")
+ self.assertListEqual(
+ [
+ (_.message.context_id, _.message.task_id)
+ for _ in client.requests
+ ],
+ [("", ""), ("context-1", "task-1")],
+ )
+ self.assertIsNone(agent.state.task_id)
+ await agent.aclose()
+
+ async def test_running_task_is_rejected(self) -> None:
+ """A second message would execute the running Task all over again."""
+ client = _FakeClient(
+ get_tasks=[
+ types.Task(
+ id="task-1",
+ context_id="context-1",
+ status=types.TaskStatus(
+ state=types.TaskState.TASK_STATE_WORKING,
+ ),
+ ),
+ ],
+ )
+ agent = A2AAgent(
+ self.card,
+ client=client,
+ state=A2AAgentState(context_id="context-1", task_id="task-1"),
+ )
+
+ with self.assertRaises(RuntimeError) as error:
+ await agent.reply(UserMsg(name="user", content="hi"))
+
+ self.assertEqual(
+ str(error.exception),
+ "A2A task task-1 is still running on the remote server; "
+ "retry once it has finished.",
+ )
+ self.assertListEqual(client.requests, [])
+ await agent.aclose()
+
+ async def test_forgotten_task_starts_a_new_one(self) -> None:
+ """A Task the server dropped degrades into a new one."""
+ client = _FakeClient(
+ [
+ [
+ types.StreamResponse(
+ message=types.Message(
+ message_id="msg-1",
+ context_id="context-1",
+ role=types.Role.ROLE_AGENT,
+ parts=[types.Part(text="ok")],
+ ),
+ ),
+ ],
+ ],
+ get_tasks=[TaskNotFoundError()],
+ )
+ agent = A2AAgent(
+ self.card,
+ client=client,
+ state=A2AAgentState(context_id="context-1", task_id="stale-task"),
+ )
+
+ await agent.reply(UserMsg(name="user", content="hi"))
+
+ self.assertEqual(client.requests[0].message.task_id, "")
+ self.assertEqual(client.requests[0].message.context_id, "context-1")
+ self.assertIsNone(agent.state.task_id)
+ await agent.aclose()
+
+
+class A2AAgentLifecycleTest(IsolatedAsyncioTestCase):
+ """Test the adapter lifecycle and the interface no-ops."""
+
+ def setUp(self) -> None:
+ """Build a card shared by the lifecycle tests."""
+ self.card = types.AgentCard(
+ name="remote-agent",
+ description="test agent",
+ supported_interfaces=[
+ types.AgentInterface(
+ url="http://example.test/1.0",
+ protocol_binding="JSONRPC",
+ protocol_version="1.0",
+ ),
+ ],
+ )
+
+ async def test_closed_agent_rejects_further_use(self) -> None:
+ """The adapter owns its client, so closing it is final."""
+ client = _FakeClient()
+ async with A2AAgent(self.card, client=client) as agent:
+ pass
+
+ self.assertEqual(client.close_count, 1)
+ with self.assertRaises(RuntimeError) as error:
+ await agent.reply(UserMsg(name="user", content="hi"))
+ self.assertEqual(str(error.exception), "A2AAgent is closed.")
+
+ with self.assertRaises(RuntimeError):
+ async with agent:
+ pass
+
+ async def test_compress_context_is_a_no_op(self) -> None:
+ """The remote server owns its context, so there is nothing to do."""
+ agent = A2AAgent(self.card, client=_FakeClient())
+
+ with self.assertLogs("as", level="WARNING") as logs:
+ await agent.compress_context("anything", keyword="ignored")
+
+ self.assertIn("compress_context", logs.output[0])
+ await agent.aclose()
+
+
+if __name__ == "__main__":
+ import unittest
+
+ unittest.main()
diff --git a/tests/tts_middleware_test.py b/tests/tts_middleware_test.py
index 0b94be346..a4dd54daa 100644
--- a/tests/tts_middleware_test.py
+++ b/tests/tts_middleware_test.py
@@ -104,13 +104,15 @@ class TestTTSMiddlewareNonRealtime(IsolatedAsyncioTestCase):
"reply_id": "reply-1",
"block_id": block_id,
"media_type": "audio/wav",
+ "name": None,
},
{
"type": "DATA_BLOCK_DELTA",
"reply_id": "reply-1",
"block_id": block_id,
- "data": audio_b64,
"media_type": "audio/wav",
+ "data": audio_b64,
+ "url": None,
},
{
"type": "DATA_BLOCK_END",
@@ -243,20 +245,23 @@ class TestTTSMiddlewareNonRealtime(IsolatedAsyncioTestCase):
"reply_id": "reply-1",
"block_id": block_id,
"media_type": "audio/wav",
+ "name": None,
},
{
"type": "DATA_BLOCK_DELTA",
"reply_id": "reply-1",
"block_id": block_id,
- "data": "AAAA",
"media_type": "audio/wav",
+ "data": "AAAA",
+ "url": None,
},
{
"type": "DATA_BLOCK_DELTA",
"reply_id": "reply-1",
"block_id": block_id,
- "data": "BBBB",
"media_type": "audio/wav",
+ "data": "BBBB",
+ "url": None,
},
{
"type": "DATA_BLOCK_END",
@@ -327,20 +332,23 @@ class TestTTSMiddlewareRealtime(IsolatedAsyncioTestCase):
"reply_id": "reply-1",
"block_id": block_id,
"media_type": "audio/wav",
+ "name": None,
},
{
"type": "DATA_BLOCK_DELTA",
"reply_id": "reply-1",
"block_id": block_id,
- "data": "PUSH1",
"media_type": "audio/wav",
+ "data": "PUSH1",
+ "url": None,
},
{
"type": "DATA_BLOCK_DELTA",
"reply_id": "reply-1",
"block_id": block_id,
- "data": "DRAIN",
"media_type": "audio/wav",
+ "data": "DRAIN",
+ "url": None,
},
{
"type": "DATA_BLOCK_END",
@@ -409,13 +417,15 @@ class TestTTSMiddlewareRealtime(IsolatedAsyncioTestCase):
"reply_id": "reply-1",
"block_id": block_id,
"media_type": "audio/wav",
+ "name": None,
},
{
"type": "DATA_BLOCK_DELTA",
"reply_id": "reply-1",
"block_id": block_id,
- "data": "FINAL",
"media_type": "audio/wav",
+ "data": "FINAL",
+ "url": None,
},
{
"type": "DATA_BLOCK_END",