a2a-protocol · diff
v1.0.0 to v1.1.0
109 added, 150 removed. Audit A to B.
What this update changes in the checks
This update newly trips 1 check:
- No link to a raw IP address
matched: http://127.0.0.1:9000
A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.
---
name: a2a-protocol
description: >-
- Builds Agent-to-Agent (A2A) servers and clients following Google's open
- protocol for agent interoperability. Use when the user wants to create
+ Builds Agent2Agent (A2A) servers and clients, the open protocol (originally from
+ Google, now under the Linux Foundation) that lets AI agents from different
+ frameworks call each other. Use when the user wants to create
an A2A-compliant agent, build an Agent Card, implement task management,
connect agents across frameworks, set up agent discovery, handle streaming
responses, implement push notifications, or orchestrate multi-agent
workflows. Trigger words: a2a, agent to agent, agent2agent, a2a protocol,
a2a server, a2a client, agent card, agent interoperability, agent
collaboration, multi-agent, agent discovery, a2a sdk, a2a task.
license: Apache-2.0
- compatibility: "Python 3.10+ (a2a-sdk) or Node.js 18+ (@a2a-js/sdk). Go and Java SDKs also available."
+ compatibility: "Python 3.10+ (a2a-sdk 1.x) or Node.js 20+ (@a2a-js/sdk 1.x). Go, Java and .NET SDKs also exist."
metadata:
author: terminal-skills
- version: "1.0.0"
+ version: "1.1.0"
category: development
tags: ["a2a", "agents", "interoperability", "protocol"]
+ repository: https://github.com/a2aproject/A2A
---
# A2A Protocol
## Overview
- Implements the Agent2Agent (A2A) open protocol for communication between AI agents built on different frameworks. A2A enables agents to discover each other via Agent Cards, negotiate interaction modalities, manage collaborative tasks, and exchange data — all without exposing internal state, memory, or tools. Supports JSON-RPC 2.0 over HTTP(S), streaming via SSE, gRPC, and async push notifications.
+ The Agent2Agent (A2A) protocol lets agents built on different frameworks discover each other through an Agent Card, exchange messages, and run long-lived tasks without exposing their internals. The current spec is **1.0** (a2a-protocol.org/v1.0.0/specification) with three bindings: JSON-RPC 2.0 over HTTP, HTTP+JSON/REST and gRPC; streaming uses SSE and async work can use webhook push notifications. This skill was checked against `a2a-sdk` 1.2.1 (Python) and `@a2a-js/sdk` 1.3.0.
+ Most tutorials online still show the 0.2/0.3 API (`A2AStarletteApplication`, `TextPart`, `/.well-known/agent.json`, `A2AClient`). Those no longer exist in 1.x. If a project pins `a2a-sdk<1`, follow the SDK's v0.3 to v1.0 migration guide (docs/migrations/v1_0 in the a2a-python repo) rather than mixing styles.
+
## Instructions
- ### 1. Core Concepts
+ ### 1. Core concepts (v1.0)
- - **A2A Client**: Initiates requests to an A2A Server (on behalf of a user or another agent)
- - **A2A Server (Remote Agent)**: Exposes an A2A-compliant endpoint, processes tasks
- - **Agent Card**: JSON metadata at `/.well-known/agent.json` describing identity, capabilities, skills, endpoint, auth
- - **Task**: Unit of work with lifecycle (submitted → working → input-required → completed/failed/canceled/rejected)
- - **Message**: Communication turn (role: "user" or "agent") containing Parts (text, file, or JSON)
- - **Artifact**: Output generated by the agent (documents, images, structured data)
+ - **Agent Card**: JSON served at `/.well-known/agent-card.json`. Lists name, version, `supportedInterfaces` (one entry per transport: `protocolBinding` `JSONRPC`, `HTTP+JSON` or `GRPC`, plus `url`), capabilities, skills and security schemes. There is no top-level `url` any more.
+ - **Task**: stateful unit of work. States: `TASK_STATE_SUBMITTED`, `WORKING`, `INPUT_REQUIRED`, `AUTH_REQUIRED`, `COMPLETED`, `FAILED`, `CANCELED`, `REJECTED`.
+ - **Message**: one turn with `role` (`ROLE_USER` / `ROLE_AGENT`) and `parts`. A `Part` is a single unified type with `text`, `raw` (bytes), `url` or `data`; the old `TextPart`/`FilePart`/`DataPart` wrappers are gone.
+ - **Artifact**: output of a task (documents, files, structured data).
+ - Enum names in the SDKs are SCREAMING_SNAKE_CASE (`TaskState.TASK_STATE_WORKING`, `Role.ROLE_USER`).
- ### 2. Python SDK Setup
+ ### 2. Install
```bash
- pip install a2a-sdk # Core
- pip install "a2a-sdk[http-server]" # With FastAPI/Starlette
- pip install "a2a-sdk[grpc]" # With gRPC
+ pip install "a2a-sdk[http-server]" # core + Starlette/SSE server pieces
+ pip install "a2a-sdk[grpc]" # gRPC; also: [fastapi] [postgresql] [mysql] [sqlite] [telemetry] [all]
+ npm install @a2a-js/sdk express # Node; express is a peer dependency of the server helpers
```
- ### 3. Building an A2A Server (Python)
+ ### 3. Server in Python
+ A server must follow one of two streaming patterns, or the SDK raises `InvalidAgentResponseError`: enqueue exactly one `Message`, or enqueue a `Task` first and then status/artifact updates until a terminal state. Never mix them.
+
```python
- from a2a.types import AgentCard, AgentSkill, AgentCapabilities
+ import uvicorn
+ from starlette.applications import Starlette
+ from a2a.helpers import (new_task_from_user_message, new_text_artifact_update_event,
+ new_text_status_update_event)
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
- from a2a.server.apps.starlette import A2AStarletteApplication
- from a2a.server.request_handler import DefaultRequestHandler
- from a2a.types import Message, TextPart, TaskState, TaskStatus
- import uvicorn
-
- agent_card = AgentCard(
- name="Research Assistant",
- description="Searches the web and answers questions with citations.",
- url="https://research-agent.example.com",
- version="1.0.0",
- capabilities=AgentCapabilities(streaming=True, pushNotifications=True),
- skills=[AgentSkill(
- id="web-search", name="Web Search",
- description="Search the web for current information",
- tags=["search", "research"], examples=["Find the latest news about AI regulation"],
- )],
- defaultInputModes=["text/plain"],
- defaultOutputModes=["text/plain", "application/json"],
- )
+ 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
+ from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill, TaskState
- class ResearchAgentExecutor(AgentExecutor):
+ class BillingAgent(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue):
- query = context.get_user_message().parts[0].text
- await event_queue.enqueue_event(
- TaskStatus(state=TaskState.working, message=Message(
- role="agent", parts=[TextPart(text="Searching...")]
- ))
- )
- result = await self._research(query)
- await event_queue.enqueue_event(
- TaskStatus(state=TaskState.completed, message=Message(
- role="agent", parts=[TextPart(text=result)]
- ))
- )
+ task = context.current_task or new_task_from_user_message(context.message)
+ await event_queue.enqueue_event(task) # Task first
+ await event_queue.enqueue_event(new_text_status_update_event(
+ task_id=task.id, context_id=task.context_id,
+ state=TaskState.TASK_STATE_WORKING, text="Looking up the invoice..."))
+ answer = f"Invoice INV-2041 is paid. You asked: {context.get_user_input()}"
+ await event_queue.enqueue_event(new_text_artifact_update_event(
+ task_id=task.id, context_id=task.context_id, name="answer", text=answer))
+ await event_queue.enqueue_event(new_text_status_update_event(
+ task_id=task.id, context_id=task.context_id,
+ state=TaskState.TASK_STATE_COMPLETED, text="Done"))
async def cancel(self, context: RequestContext, event_queue: EventQueue):
- await event_queue.enqueue_event(TaskStatus(state=TaskState.canceled))
-
- async def _research(self, query: str) -> str:
- return f"Research results for: {query}"
-
- # Start server — Agent Card auto-served at /.well-known/agent.json
- agent_executor = ResearchAgentExecutor()
- request_handler = DefaultRequestHandler(agent_executor=agent_executor, task_store=InMemoryTaskStore())
- app = A2AStarletteApplication(agent_card=agent_card, http_handler=request_handler)
- uvicorn.run(app.build(), host="0.0.0.0", port=8000)
- ```
-
- ### 4. Building an A2A Client (Python)
-
- ```python
- from a2a.client import A2AClient
- from a2a.types import MessageSendParams, SendMessageRequest, Message, TextPart
+ await event_queue.enqueue_event(new_text_status_update_event(
+ task_id=context.task_id, context_id=context.context_id,
+ state=TaskState.TASK_STATE_CANCELED, text="Canceled"))
- client = await A2AClient.get_client_from_agent_card_url(
- "https://research-agent.example.com/.well-known/agent.json"
+ card = AgentCard(
+ name="Billing Agent", description="Answers questions about invoices.", version="1.0.0",
+ supported_interfaces=[AgentInterface(protocol_binding="JSONRPC", url="http://127.0.0.1:9000/")],
+ capabilities=AgentCapabilities(streaming=True),
+ default_input_modes=["text/plain"], default_output_modes=["text/plain"],
+ skills=[AgentSkill(id="invoice-status", name="Invoice status",
+ description="Look up whether an invoice is paid", tags=["billing"],
+ examples=["Is invoice INV-2041 paid?"])],
)
+ handler = DefaultRequestHandler(agent_executor=BillingAgent(), task_store=InMemoryTaskStore(),
+ agent_card=card) # agent_card is required in 1.x
+ app = Starlette(routes=[*create_agent_card_routes(card),
+ *create_jsonrpc_routes(handler, rpc_url="/")])
+ uvicorn.run(app, host="127.0.0.1", port=9000)
+ ```
- # Synchronous request
- request = SendMessageRequest(params=MessageSendParams(
- message=Message(role="user", parts=[TextPart(text="Latest quantum computing developments?")])
- ))
- response = await client.send_message(request)
+ `create_rest_routes(handler)` adds the HTTP+JSON binding (declare it in `supported_interfaces` too). To serve old 0.3 clients as well, add a 0.3 `AgentInterface` with `protocol_version="0.3"` and pass `enable_v0_3_compat=True` to the route factories.
- if hasattr(response, 'status'):
- print(f"Task {response.id}: {response.status.state}")
- if response.status.message:
- print(response.status.message.parts[0].text)
+ ### 4. Client in Python
- # Streaming response
- async for event in client.send_message_streaming(request):
- if hasattr(event, 'status') and event.status.message:
- for part in event.status.message.parts:
- if hasattr(part, 'text'):
- print(part.text, end="", flush=True)
- ```
+ ```python
+ import asyncio
+ from a2a.client import create_client
+ from a2a.helpers import new_text_message, get_artifact_text
+ from a2a.types import Role, SendMessageRequest
- ### 5. Node.js SDK
+ async def ask(url: str, text: str) -> str:
+ client = await create_client(url) # fetches the Agent Card, picks a transport
+ try:
+ answer = ""
+ request = SendMessageRequest(message=new_text_message(text, role=Role.ROLE_USER))
+ async for chunk in client.send_message(request): # yields StreamResponse objects
+ if chunk.HasField("artifact_update"):
+ answer += get_artifact_text(chunk.artifact_update.artifact)
+ elif chunk.HasField("message"):
+ answer = chunk.message.parts[0].text
+ return answer
+ finally:
+ await client.close()
- ```bash
- npm install @a2a-js/sdk
+ print(asyncio.run(ask("http://127.0.0.1:9000", "Is invoice INV-2041 paid?")))
```
- ```javascript
- import { A2AServer, A2AClient, TaskState } from '@a2a-js/sdk';
+ Each `StreamResponse` holds exactly one of `task`, `message`, `status_update` or `artifact_update`; test with `HasField`. Types are protobuf objects, so convert with `MessageToDict` and do not assign arbitrary attributes.
- // Server
- const server = new A2AServer({
- agentCard: {
- name: 'Code Reviewer', description: 'Reviews code for bugs and best practices',
- url: 'https://code-reviewer.example.com', version: '1.0.0',
- capabilities: { streaming: true },
- skills: [{ id: 'review', name: 'Code Review', description: 'Analyze code for issues', tags: ['code', 'review'] }],
- defaultInputModes: ['text/plain'], defaultOutputModes: ['text/plain'],
- },
- async onMessage(context, eventQueue) {
- const userText = context.getUserMessage().parts[0].text;
- await eventQueue.enqueue({ status: { state: TaskState.WORKING, message: { role: 'agent', parts: [{ text: 'Reviewing...' }] } } });
- const review = await reviewCode(userText);
- await eventQueue.enqueue({ status: { state: TaskState.COMPLETED, message: { role: 'agent', parts: [{ text: review }] } } });
- },
- });
- server.listen(8000);
+ ### 5. Node.js
- // Client
- const client = await A2AClient.fromAgentCardUrl('https://code-reviewer.example.com/.well-known/agent.json');
- const response = await client.sendMessage({
- message: { role: 'user', parts: [{ text: 'Review: function add(a,b) { return a + b; }' }] },
- });
- ```
+ `@a2a-js/sdk` 1.x exports `ClientFactory` (`createFromUrl(baseUrl)`, `createFromAgentCard(card)`), clients with `sendMessage` / `sendMessageStream` / `getTask` / `cancelTask`, and server pieces `DefaultRequestHandler(agentCard, taskStore, agentExecutor)`, `InMemoryTaskStore`, plus `agentCardHandler` and `jsonRpcHandler` from `@a2a-js/sdk/server/express`, `AGENT_CARD_PATH` for the well-known path. An executor implements `execute(requestContext, eventBus)` and `cancelTask(taskId, eventBus)` and publishes with `eventBus.publish(AgentEvent.task(...))`, `AgentEvent.statusUpdate(...)`. The 1.x types are generated from protobuf (`Part.content` is `{ $case: 'text', value: '...' }`, enums are `TaskState.TASK_STATE_WORKING`). Start from the sample-agent and cli.ts files in the a2a-js repo (src/samples) and adapt them.
- ### 6. Multi-Agent Orchestration
+ ### 6. Multi-agent orchestration
```python
- # Sequential: research → write → review
- research_agent = await A2AClient.get_client_from_agent_card_url("https://research-agent.example.com/.well-known/agent.json")
- writer_agent = await A2AClient.get_client_from_agent_card_url("https://writer-agent.example.com/.well-known/agent.json")
-
- research_result = await research_agent.send_message(SendMessageRequest(
- params=MessageSendParams(message=Message(role="user", parts=[TextPart(text="Research quantum computing breakthroughs 2025")]))
- ))
- article = await writer_agent.send_message(SendMessageRequest(
- params=MessageSendParams(message=Message(role="user", parts=[TextPart(text=f"Write blog post: {research_result.status.message.parts[0].text}")]))
- ))
+ # Sequential: research -> write
+ facts = await ask("http://research-agent.internal:9001", "Summarize 2026 quantum error-correction results")
+ post = await ask("http://writer-agent.internal:9002", f"Write a 300-word blog post from these notes:\n{facts}")
# Parallel fan-out
- import asyncio
- results = await asyncio.gather(
- query_agent(agent_a, "Analyze market trends"),
- query_agent(agent_b, "Analyze competitor products"),
- query_agent(agent_c, "Analyze customer feedback"),
+ market, rivals, feedback = await asyncio.gather(
+ ask("http://market-agent.internal:9003", "Analyze market trends"),
+ ask("http://competitor-agent.internal:9004", "Analyze competitor products"),
+ ask("http://support-agent.internal:9005", "Analyze customer feedback"),
)
```
### 7. A2A vs MCP
| | A2A | MCP |
|---|---|---|
- | **Purpose** | Agent-to-agent communication | Agent-to-tool communication |
- | **Actors** | Agent ↔ Agent | Agent ↔ Tool/Data source |
- | **Tasks** | Stateful, long-running, async | Stateless function calls |
- | **Use when** | Delegating to another autonomous agent | Calling a specific tool/API |
+ | Purpose | Agent-to-agent delegation | Agent-to-tool/data access |
+ | Interaction | Stateful, long-running tasks, streaming, push | Stateless tool calls |
+ | Use when | Handing work to another autonomous agent | Calling a specific API or data source |
## Examples
- ### Example 1: Customer Support Router
+ ### Example 1: Customer support router
- **Input:** "Build an A2A server that acts as a customer support router. It receives customer queries and delegates to specialized agents: billing-agent, technical-agent, and sales-agent based on the query content."
+ **User request:** "Build an A2A server that routes customer queries to billing-agent, technical-agent and sales-agent."
- **Output:** A2A server with Agent Card listing routing as its primary skill, message handler that classifies queries, A2A client connections to 3 downstream agents, task forwarding with context preservation, aggregated response, and fallback to human handoff.
+ Create one `AgentExecutor` whose `execute` classifies the text from `context.get_user_input()`, calls the matching agent with `ask(...)`, and publishes the reply as an artifact in a task stream (Task, WORKING update, artifact, COMPLETED). Serve a card with a single `route-support-query` skill. Run it with `python router.py`, then check `curl -s http://127.0.0.1:9000/.well-known/agent-card.json`: it returns the card JSON with `supportedInterfaces`. If no agent matches, end with `TASK_STATE_INPUT_REQUIRED` and a question, or hand off to a human.
- ### Example 2: Code Pipeline Agents
+ ### Example 2: Code pipeline
- **Input:** "Create a multi-agent code pipeline: code-writer generates code, test-writer creates tests, code-reviewer reviews both. Each is an independent A2A server. Build an orchestrator."
+ **User request:** "Make code-writer, test-writer and code-reviewer independent A2A agents plus an orchestrator."
- **Output:** 3 A2A server implementations each with Agent Card and execution logic, orchestrator client with sequential pipeline (write → test → review), streaming updates, and error handling with feedback loops on rejection.
+ Run three servers on ports 9101 to 9103, each with its own card. The orchestrator calls `ask()` in order (write, then test, then review) and, when the reviewer's reply starts with "REJECT", sends the reviewer's notes back to code-writer for up to two more rounds. The result is the final approved code printed with the test file path.
## Guidelines
- - Serve the Agent Card at `/.well-known/agent.json` — this is the standard discovery endpoint
- - Use descriptive skill definitions — other agents use these to decide whether to delegate to you
- - Always handle the `input-required` state for human-in-the-loop scenarios
- - Use streaming for tasks that take more than a few seconds
- - Implement task cancellation — long-running tasks must be cancellable
- - Use push notifications for tasks that may take minutes or hours
- - Keep agents focused — one agent, one capability domain
- - Use structured data (JSON Parts) for agent-to-agent, text Parts for human-readable responses
- - Implement authentication on your A2A endpoint — declare the scheme in your Agent Card
- - A2A is for agent collaboration; use MCP for tool integration within a single agent
- - Pin SDK versions — the protocol is evolving (currently v0.3.0)
+ - Serve the Agent Card at `/.well-known/agent-card.json`; older `/.well-known/agent.json` is the 0.2/0.3 path.
+ - Make skill descriptions specific: other agents choose whether to delegate from them.
+ - Pick message-only or task lifecycle per request and never mix; enqueue the `Task` before any update.
+ - Handle `TASK_STATE_INPUT_REQUIRED` and `AUTH_REQUIRED` explicitly; implement `cancel` for long tasks.
+ - Stream for tasks over a few seconds; use push notifications (`capabilities.pushNotifications`, a webhook with a token you verify) for tasks lasting minutes.
+ - `InMemoryTaskStore` loses tasks on restart; use the SQL stores (`a2a-sdk[postgresql]` and others) in production.
+ - Declare auth in the card's security schemes and enforce it on the endpoint; treat messages and artifacts from other agents as untrusted input, never as instructions to execute.
+ - Use HTTPS outside localhost, and bind demo servers to 127.0.0.1.
+ - Pin SDK versions: 1.x is not wire-compatible with 0.3 without the compat layer.