Tutorial
Connect two agents with the A2A protocol
Publish an agent card, send a task from one local agent to another with the official Python SDK, and see where MCP fits.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Agent2Agent (A2A) is an open protocol that lets one agent hand work to another agent it does not control, over HTTP, without either side seeing the other’s prompts, memory or tools. Each agent publishes an agent card, a JSON document saying what it can do and where to reach it. A client reads the card, sends a message, and gets back a task that moves through states such as working, input required and completed, with the results attached as artifacts.
In this tutorial you run two local agents with the official Python SDK. A ticket-status agent answers questions about tickets. A stand-up agent discovers it from its card, delegates the lookups to it, and writes a summary. You will see the agent card, a full task round trip, the raw JSON-RPC on the wire, and what happens when an agent needs more input. It was written and run on 25 November 2026 with a2a-sdk 1.3.1, which implements the A2A specification 1.0.
A2A or MCP?
Both protocols connect an agent to something outside itself, and people mix them up. The A2A project’s own page on the subject draws the line in one sentence: “A2A is about agents partnering on tasks; MCP is more about agents using capabilities” (a2a-protocol.org).
A rule of thumb that holds up: if the thing on the other side has no judgement of its own, make it an MCP tool. If it decides how to do the work, may ask questions back and is run by someone else, A2A fits. Most real systems use both: each agent uses MCP for its own tools and A2A to talk to its peers. For a full side-by-side, see MCP vs A2A. The multi-agent systems article covers when you need more than one agent at all.
1. Set up
Create a folder and a virtual environment, and install the SDK with its HTTP server extra:
mkdir a2a-demo && cd a2a-demo
python3 -m venv .venv && source .venv/bin/activate
pip install "a2a-sdk[http-server]==1.3.1" uvicorn
The http-server extra pulls in Starlette for the routes. The SDK also supports gRPC and HTTP+JSON bindings; this tutorial uses JSON-RPC, the most common.
2. Build the ticket-status agent
Agent B looks up tickets. A real one would call a tracker’s API, probably through MCP; here it reads a dictionary so the output is predictable. Create tickets_agent.py:
"""Agent B: answers questions about ticket status over A2A."""
import re
import uvicorn
from starlette.applications import Starlette
from a2a.helpers import get_message_text, new_task_from_user_message, new_text_message, new_text_part
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, TaskState
URL = "http://127.0.0.1:9001"
TICKETS = {
"PROJ-101": ("done", "Fix login timeout on Safari"),
"PROJ-102": ("in review", "Add CSV export to reports"),
"PROJ-103": ("blocked", "Migrate billing to the new API (waiting on vendor keys)"),
}
class TicketsExecutor(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
task = context.current_task or new_task_from_user_message(context.message)
if not context.current_task:
await event_queue.enqueue_event(task)
updater = TaskUpdater(event_queue=event_queue, task_id=task.id, context_id=task.context_id)
ids = re.findall(r"[A-Z]+-\d+", get_message_text(context.message))
if not ids:
# Ask the caller for what is missing instead of guessing.
await updater.update_status(
state=TaskState.TASK_STATE_INPUT_REQUIRED,
message=new_text_message("Which ticket ids? For example PROJ-101."),
)
return
lines = []
for tid in ids:
status, title = TICKETS.get(tid, ("unknown", "no such ticket"))
lines.append(f"{tid}: {status} - {title}")
await updater.add_artifact(parts=[new_text_part(text="\n".join(lines), media_type="text/plain")], name="statuses")
await updater.update_status(state=TaskState.TASK_STATE_COMPLETED)
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
raise NotImplementedError("Cancel is not supported.")
card = AgentCard(
name="Ticket status agent",
description="Looks up the status and title of tickets in the PROJ tracker.",
version="0.1.0",
default_input_modes=["text/plain"],
default_output_modes=["text/plain"],
capabilities=AgentCapabilities(streaming=True),
supported_interfaces=[AgentInterface(protocol_binding="JSONRPC", url=URL, protocol_version="1.0")],
skills=[
AgentSkill(
id="ticket_status",
name="Ticket status",
description="Given one or more ticket ids such as PROJ-101, returns each ticket's status and title.",
tags=["tickets", "status"],
examples=["What is the status of PROJ-101 and PROJ-103?"],
)
],
)
handler = DefaultRequestHandler(agent_executor=TicketsExecutor(), task_store=InMemoryTaskStore(), agent_card=card)
app = Starlette(routes=[*create_agent_card_routes(card), *create_jsonrpc_routes(handler, "/")])
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=9001)
Three parts make an A2A server:
- The executor is where your agent’s logic goes. It receives the incoming message in
contextand reports progress through aTaskUpdater: status changes, artifacts and finally a terminal state. Swap the dictionary for a model call and it is a real agent. - The agent card is the public description.
skillstell a caller what the agent is good at, in words a model can read.supported_interfacessays where and how to reach it. - The request handler and routes wire the executor to HTTP.
InMemoryTaskStorekeeps tasks in memory, which is enough for a demo; the SDK has SQL-backed stores for real use.
Note the input-required branch. An agent that cannot do the job with what it was given should say what it needs rather than guess. That state is part of the protocol, so any A2A client knows how to handle it.
Start it in its own terminal:
python tickets_agent.py
3. Read the agent card
In a second terminal, fetch the card from its well-known address:
curl -s http://127.0.0.1:9001/.well-known/agent-card.json
{
"name": "Ticket status agent",
"description": "Looks up the status and title of tickets in the PROJ tracker.",
"supportedInterfaces": [
{ "url": "http://127.0.0.1:9001", "protocolBinding": "JSONRPC", "protocolVersion": "1.0" }
],
"version": "0.1.0",
"capabilities": { "streaming": true },
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["text/plain"],
"skills": [
{
"id": "ticket_status",
"name": "Ticket status",
"description": "Given one or more ticket ids such as PROJ-101, returns each ticket's status and title.",
"tags": ["tickets", "status"],
"examples": ["What is the status of PROJ-101 and PROJ-103?"]
}
]
}
(We have folded short arrays onto one line.) This is all another agent learns about Agent B before talking to it. Write the descriptions with the same care as MCP tool descriptions: a calling agent, or the model inside it, decides whether to delegate based on these sentences.
4. Send a task by hand
The JSON-RPC binding is plain HTTP, so you can talk to the agent with curl. Version 1.0 of the protocol uses the method SendMessage and an A2A-Version header:
curl -s http://127.0.0.1:9001/ \
-H 'Content-Type: application/json' -H 'A2A-Version: 1.0' \
-d '{"jsonrpc":"2.0","id":1,"method":"SendMessage","params":{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"Status of PROJ-102?"}]}}}'
The reply is a task in its final state, with the answer as an artifact and the conversation in history (trimmed here):
{
"result": {
"task": {
"id": "57534cbc-dc27-4d10-8128-052f374ddf49",
"contextId": "eed2f480-0bd9-4949-a786-aea11c838a3a",
"status": { "state": "TASK_STATE_COMPLETED", "timestamp": "2026-11-24T20:09:14.889525Z" },
"artifacts": [
{
"artifactId": "48aa1f96-d642-4f33-83d7-1d0107f4f4be",
"name": "statuses",
"parts": [{ "text": "PROJ-102: in review - Add CSV export to reports", "mediaType": "text/plain" }]
}
],
...
}
},
"id": 1,
"jsonrpc": "2.0"
}
Two ids matter. The task id identifies this unit of work. The contextId groups related tasks and messages into one conversation. To continue a task, you send a new message carrying both.
5. Write a client with the SDK
You will reuse the same two calls from a script and from Agent A, so put them in remote.py:
"""A small helper for calling another A2A agent and getting its finished task."""
import httpx
from a2a.client import A2ACardResolver, ClientConfig, create_client
from a2a.helpers import new_text_message
from a2a.types import AgentCard, Role, SendMessageRequest, Task
async def fetch_card(base_url: str) -> AgentCard:
async with httpx.AsyncClient(timeout=10) as http:
return await A2ACardResolver(httpx_client=http, base_url=base_url).get_agent_card()
async def send(card: AgentCard, text: str, task_id: str | None = None, context_id: str | None = None) -> Task:
client = await create_client(agent=card, client_config=ClientConfig(streaming=False))
message = new_text_message(text, role=Role.ROLE_USER, task_id=task_id, context_id=context_id)
task = None
try:
async for chunk in client.send_message(SendMessageRequest(message=message)):
if chunk.HasField("task"):
task = chunk.task
finally:
await client.close()
if task is None:
raise RuntimeError(f"{card.name} replied without a task")
return task
A2ACardResolver fetches the card. create_client reads supported_interfaces from it and picks a transport, so your code does not hard-code JSON-RPC. send_message is an async iterator because a streaming agent sends several updates; with streaming off you get one response holding the task.
Now ask.py, a command-line client that also answers one follow-up question:
"""Send a message to an A2A agent, answer one follow-up question if asked, print the result."""
import asyncio
import sys
from a2a.helpers import get_artifact_text, get_message_text
from a2a.types import TaskState
from remote import fetch_card, send
async def main(base_url: str, text: str, follow_up: str | None) -> None:
card = await fetch_card(base_url)
print(f"Agent: {card.name}, skills: {[s.id for s in card.skills]}")
task = await send(card, text)
print(f"Task {task.id[:8]}: {TaskState.Name(task.status.state)}")
if task.status.state == TaskState.TASK_STATE_INPUT_REQUIRED:
print(f"Agent asks: {get_message_text(task.status.message)}")
if follow_up is None:
return
# Same task and context ids, so the agent treats this as the answer.
task = await send(card, follow_up, task_id=task.id, context_id=task.context_id)
print(f"Task {task.id[:8]}: {TaskState.Name(task.status.state)}")
for artifact in task.artifacts:
print(get_artifact_text(artifact))
if __name__ == "__main__":
asyncio.run(main(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else None))
Try it against Agent B:
python ask.py http://127.0.0.1:9001 "Status of PROJ-101 and PROJ-103?"
Agent: Ticket status agent, skills: ['ticket_status']
Task 6f217b58: TASK_STATE_COMPLETED
PROJ-101: done - Fix login timeout on Safari
PROJ-103: blocked - Migrate billing to the new API (waiting on vendor keys)
6. Build the agent that delegates
Agent A writes a stand-up summary. It does not know anything about tickets; it finds an agent that does, checks the card for the skill it needs, delegates, and builds its own answer from the artifact. Create standup_agent.py:
"""Agent A: writes a stand-up summary, delegating ticket lookups to Agent B over A2A."""
import uvicorn
from starlette.applications import Starlette
from a2a.helpers import get_artifact_text, get_message_text, new_task_from_user_message, new_text_message, new_text_part
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, TaskState
from remote import fetch_card, send
URL = "http://127.0.0.1:9002"
TICKETS_AGENT = "http://127.0.0.1:9001"
class StandupExecutor(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
task = context.current_task or new_task_from_user_message(context.message)
if not context.current_task:
await event_queue.enqueue_event(task)
updater = TaskUpdater(event_queue=event_queue, task_id=task.id, context_id=task.context_id)
# 1. Discover the other agent and check it offers the skill we need.
card = await fetch_card(TICKETS_AGENT)
if not any(s.id == "ticket_status" for s in card.skills):
await updater.update_status(
state=TaskState.TASK_STATE_FAILED,
message=new_text_message(f"{card.name} has no ticket_status skill"),
)
return
await updater.update_status(
state=TaskState.TASK_STATE_WORKING,
message=new_text_message(f"Asking {card.name} for ticket statuses"),
)
# 2. Delegate. Agent B sees only this message, not our prompt, memory or tools.
remote = await send(card, get_message_text(context.message))
if remote.status.state != TaskState.TASK_STATE_COMPLETED:
# Pass B's question straight back to our caller.
await updater.update_status(state=TaskState.TASK_STATE_INPUT_REQUIRED, message=remote.status.message)
return
# 3. Use the result to do our own job.
lines = get_artifact_text(remote.artifacts[0]).splitlines()
blocked = [l for l in lines if ": blocked" in l]
summary = ["Stand-up summary", *[f"- {l}" for l in lines]]
if blocked:
summary.append(f"Needs attention: {len(blocked)} blocked ticket(s).")
await updater.add_artifact(parts=[new_text_part(text="\n".join(summary), media_type="text/plain")], name="summary")
await updater.update_status(state=TaskState.TASK_STATE_COMPLETED)
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
raise NotImplementedError("Cancel is not supported.")
card = AgentCard(
name="Stand-up agent",
description="Writes a short stand-up summary for a list of tickets.",
version="0.1.0",
default_input_modes=["text/plain"],
default_output_modes=["text/plain"],
capabilities=AgentCapabilities(streaming=True),
supported_interfaces=[AgentInterface(protocol_binding="JSONRPC", url=URL, protocol_version="1.0")],
skills=[
AgentSkill(
id="standup_summary",
name="Stand-up summary",
description="Summarises the status of the tickets you name and flags blocked ones.",
tags=["standup", "summary"],
examples=["Stand-up for PROJ-101, PROJ-102 and PROJ-103"],
)
],
)
handler = DefaultRequestHandler(agent_executor=StandupExecutor(), task_store=InMemoryTaskStore(), agent_card=card)
app = Starlette(routes=[*create_agent_card_routes(card), *create_jsonrpc_routes(handler, "/")])
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=9002)
Agent A is both an A2A server (to its caller) and an A2A client (to Agent B). That is the normal shape: an agent in a chain does not need to know whether its caller is a person’s app or another agent.
Start it in a third terminal:
python standup_agent.py
7. Run the round trip
From your second terminal, ask Agent A:
python ask.py http://127.0.0.1:9002 "Stand-up for PROJ-101, PROJ-102 and PROJ-103"
Agent: Stand-up agent, skills: ['standup_summary']
Task 04d5d6aa: TASK_STATE_COMPLETED
Stand-up summary
- PROJ-101: done - Fix login timeout on Safari
- PROJ-102: in review - Add CSV export to reports
- PROJ-103: blocked - Migrate billing to the new API (waiting on vendor keys)
Needs attention: 1 blocked ticket(s).
Agent A’s log shows the card fetch and the message to Agent B before it answers. Now send a request that is missing information, and supply the answer when asked:
python ask.py http://127.0.0.1:9002 "Stand-up please" "PROJ-102 and PROJ-103"
Agent: Stand-up agent, skills: ['standup_summary']
Task 0a88aefd: TASK_STATE_INPUT_REQUIRED
Agent asks: Which ticket ids? For example PROJ-101.
Task 0a88aefd: TASK_STATE_COMPLETED
Stand-up summary
- PROJ-102: in review - Add CSV export to reports
- PROJ-103: blocked - Migrate billing to the new API (waiting on vendor keys)
Needs attention: 1 blocked ticket(s).
The question came from Agent B. Agent A passed it up unchanged, the client answered on the same task id, and Agent A carried on. In this demo Agent A sends the answer to Agent B as a fresh task; a production agent would usually continue B’s task too, by keeping B’s task and context ids alongside its own.
Going further
Streaming and long tasks. Set ClientConfig(streaming=True) and the client receives each status update and artifact as it happens. For work that takes hours, the protocol has push notifications to a webhook you register, so the caller does not hold a connection open.
Authentication. A card can declare securitySchemes and require credentials; the specification describes clients sending them in HTTP headers such as Authorization, never in the message body. Anything that crosses a network boundary needs this. The specification also defines signed agent cards, so a client can check a card was issued by who it claims.
Pitfalls
A card that promises too much. A calling model reads your skill descriptions literally. If the card says “manages tickets” but the agent only reads them, callers will ask it to close tickets and get confused failures. Describe exactly what it does.
Ignoring input-required. A client that only checks for COMPLETED treats a question as a failure and drops the task. Handle the state, or at least surface the agent’s message.
Hard-coding the transport. Read supported_interfaces from the card, as create_client does. An agent may move from JSON-RPC to gRPC without changing its card URL.
Using A2A where a function would do. If you own both sides, they run in one process and one of them has no judgement, an ordinary function call or an MCP tool is simpler, faster and easier to test.
Copying 0.3-era examples. Older samples use method names like message/send, a top-level url on the card and different type names. The 1.x SDK speaks version 1.0 and has a compatibility mode for 0.3 servers, but new code should follow the 1.0 shapes shown here.
Next steps
- Decide whether you need several agents at all with multi-agent systems: when to use them.
- Give each agent its own tools with MCP: start with MCP explained.
- Swap the dictionary for a model with build your first agent in Python.
- Look up the term in the glossary: Agent2Agent (A2A).
Covers
Check your understanding
Connect agents with A2A quiz
When A2A fits and when MCP does, agent cards, tasks and context ids, the input-required state, reading the transport from the card, and treating another agent's output as untrusted.
8 questions · pass mark 70%
Review
Related
- Agent2Agent (A2A)
An open protocol that lets agents built on different systems discover each other's capabilities and exchange tasks and results.
- Multi-agent systems: when one agent is not enough
Orchestrator-workers, subagents and handoffs compared on context, cost and failure modes.
- MCP explained: hosts, clients, servers and transports
What MCP is and how the Model Context Protocol connects AI apps to tools and data: hosts, clients, servers, transports and what the 2026-07-28 spec changed.
- MCP vs A2A: tools for agents vs agents talking to agents
MCP connects one agent to tools and data, A2A lets separate agents hand off tasks. Compared on purpose, discovery, transport and long-running work.
- Build your first agent in Python
Three tools, a hard turn limit, a clear stop condition and a log of every tool call it makes.