About this notebook
Companion to Module 9: Multi-agent systems. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
In notebook 9a every agent lived in the same Python process, so one agent could call another as a function. Agents written by other teams run somewhere else, on their own model, with their own tools and memory. The Agent2Agent protocol (A2A) is a shared wire format for that case. You will
- see where A2A sits next to MCP;
- serve an agent on 127.0.0.1 and read its agent card;
- send it a JSON-RPC
message/sendrequest by hand and read the Task that comes back; - trigger the protocol’s errors on purpose;
- continue a remote conversation with a
contextId; - wrap two remote agents as tools of a local planner, and see where the tokens went;
- list what this subset leaves out.
Which model answers here?
With no
MODELset, all three agents (two remote desks and the local planner) are played by the offline policy model: deterministic rules keyed on the role sentence in each agent’s instructions. The planner picks a remote agent by counting words it shares with the agent’s description, which a real model does far more flexibly. Everything on the wire (cards, JSON-RPC requests, Tasks) is real and would be the same with a live model.
A simplified subset, on purpose
The server and client here implement a small part of A2A v0.3 in about 300 lines of standard-library Python and
httpx, so that every byte is visible. Field names follow the v0.3 specification; version 1.0 renames the methods (message/sendbecomesSendMessage). Streaming, push notifications, authentication and several task states are left out; section 7 lists them. For real services use the officiala2a-sdk.
from agentlab.nbsetup import setup
nb = setup("09b_a2a", packs=["a2a"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. Tools, agents and the line between them
MCP (module 3) connects an agent to tools and data: a tool has a schema, takes arguments and returns a result, and there is no model behind it. A2A connects an agent to another agent: you send it a message in plain language and it decides on its own how to answer. You cannot see its prompt, its tools or its memory, only what it chooses to publish about itself in a card. The two protocols work side by side: a remote agent reached over A2A may well use MCP tools internally.
this notebook's process a server thread on 127.0.0.1
+--------------------+ GET /.well-known/agent-card.json +-------------------+
| travel planner | ---------------------------------> | A2AServer |
| tools: | <-------- agent card (JSON) ------ | FX desk agent |
| fx_desk -------+-- POST / message/send (JSON-RPC) ->| tool: convert |
| calendar_desk | <-------- Task + artifact -------- | own model |
+--------------------+ | own memory |
+-------------------+Two documents carry the whole protocol in this notebook: the agent card says who the
agent is, what it can do and where to send work; message/send carries a user
message in and a Task out.
2. Serve an agent and read its card
The FX desk is an ordinary Agent with one tool. A2AServer puts it behind HTTP on the
loopback interface; port 0 asks the operating system for any free port, so the address
changes on every run. (The printed JSON shows <fx-port> instead, to keep the page
stable.) The server refuses to bind to anything but loopback: nothing outside this
machine can reach it.
import json
from agentlab import Agent, FunctionTool
from agentlab.a2a import A2AServer, skill
def convert(amount: float, from_currency: str, to_currency: str) -> float:
"""Convert an amount between USD, EUR and GBP at fixed rates.
Args:
amount: The amount to convert.
from_currency: Currency code of the amount: USD, EUR or GBP.
to_currency: Currency code to convert to.
"""
eur_per_unit = {"EUR": 1.0, "USD": 0.92, "GBP": 1.17}
return round(amount * eur_per_unit[from_currency] / eur_per_unit[to_currency], 2)
fx_agent = Agent(llm, tools=[FunctionTool(convert)], name="fx_desk",
instructions="You are the FX desk. Convert amounts with the convert tool "
"and answer in one sentence.")
fx_server = A2AServer(
fx_agent, name="FX Desk",
description="Converts amounts between EUR, USD and GBP at fixed reference rates.",
skills=[skill("convert-currency", "Convert currency",
"Convert an amount from one currency to another (EUR, USD, GBP).",
tags=["currency", "fx"], examples=["Convert 120 USD to EUR"])],
).start()
PORTS = {fx_server.url: "http://127.0.0.1:<fx-port>/"}
def show(obj) -> None:
"""Print JSON with the random server ports replaced by placeholders."""
text = json.dumps(obj, indent=2)
for url, label in PORTS.items():
text = text.replace(url, label)
print(text)
print(fx_server)<A2AServer 'FX Desk' running>
A client discovers the agent by fetching a well-known path. This is a plain HTTP GET,
done here with httpx directly so you can see the status and the content type.
import httpx
from agentlab.a2a import CARD_PATH
async with httpx.AsyncClient() as http:
r = await http.get(fx_server.url.rstrip("/") + CARD_PATH)
old = await http.get(fx_server.url.rstrip("/") + "/.well-known/agent.json")
print("GET", CARD_PATH, "->", r.status_code, r.headers["content-type"])
print("GET /.well-known/agent.json ->", old.status_code, "(the path before v0.3)")
card = r.json()
show(card)GET /.well-known/agent-card.json -> 200 application/json
GET /.well-known/agent.json -> 404 (the path before v0.3)
{
"protocolVersion": "0.3.0",
"name": "FX Desk",
"description": "Converts amounts between EUR, USD and GBP at fixed reference rates.",
"url": "http://127.0.0.1:<fx-port>/",
"preferredTransport": "JSONRPC",
"version": "1.0.0",
"capabilities": {
"streaming": false,
"pushNotifications": false
},
"defaultInputModes": [
"text/plain"
],
"defaultOutputModes": [
"text/plain"
],
"skills": [
{
"id": "convert-currency",
"name": "Convert currency",
"description": "Convert an amount from one currency to another (EUR, USD, GBP).",
"tags": [
"currency",
"fx"
],
"examples": [
"Convert 120 USD to EUR"
]
}
]
}
Read the card as a model would. name, description and the skills are text that a
calling model reads to decide whether this agent fits a task, exactly like a tool
description. url and preferredTransport tell a client where and how to send work.
capabilities says which optional features the server supports; this one supports
neither streaming nor push notifications, so a well-behaved client will not try them.
defaultInputModes and defaultOutputModes are media types: plain text only.
The card is also a promise you cannot check from the outside. Nothing stops a server from describing itself generously; section 6 comes back to what that means for trust.
3. message/send by hand
Every call after discovery is a JSON-RPC 2.0 request posted to the card’s url: a
method, an id you choose (the response echoes it) and params. For message/send
the params hold one Message: a role, a messageId, and a list of parts. Text
is one kind of part; files and structured data are others (not implemented here).
request = {
"jsonrpc": "2.0", "id": 1, "method": "message/send",
"params": {"message": {"kind": "message", "role": "user", "messageId": "msg-by-hand-1",
"parts": [{"kind": "text", "text": "Convert 120 USD to EUR"}]}},
}
async with httpx.AsyncClient() as http:
r = await http.post(fx_server.url, json=request)
response = r.json()
show(response){
"jsonrpc": "2.0",
"id": 1,
"result": {
"kind": "task",
"id": "task_0000",
"contextId": "ctx_0000",
"status": {
"state": "completed"
},
"history": [
{
"kind": "message",
"role": "user",
"messageId": "msg-by-hand-1",
"parts": [
{
"kind": "text",
"text": "Convert 120 USD to EUR"
}
],
"contextId": "ctx_0000",
"taskId": "task_0000"
},
{
"kind": "message",
"messageId": "msg_0000",
"role": "agent",
"parts": [
{
"kind": "text",
"text": "USD 120.00 is EUR 110.40."
}
],
"contextId": "ctx_0000",
"taskId": "task_0000"
}
],
"artifacts": [
{
"artifactId": "artifact_0000",
"name": "answer",
"parts": [
{
"kind": "text",
"text": "USD 120.00 is EUR 110.40."
}
]
}
]
}
}
The result is a Task: the unit of work the server created for this message.
| field | meaning |
|---|---|
id | the Task’s id; tasks/get fetches it again later |
contextId | the conversation this Task belongs to (new here, since we sent none) |
status.state | completed; other states include working, failed, input-required |
artifacts | the outputs; here one text artifact named answer |
history | the messages exchanged, the server’s reply with role: "agent" |
The specification also allows a server to answer message/send with a single Message
instead of a Task, for quick replies that need no tracking. This server always creates a
Task, so that tasks/get always has something to return.
Behind that response, the server ran the FX desk agent to completion: one model call to
pick convert, one tool call, one model call to phrase the answer. The caller saw none
of it, only the final Task.
4. Errors are part of the protocol
JSON-RPC defines numbered error codes, and A2A adds its own. A client should branch on
the code, not on the message text. A2AClient.rpc sends a request and returns the raw
response, error or not.
from agentlab.a2a import A2AClient
client = A2AClient(fx_server.url)
task_id = response["result"]["id"]
probes = [
("message/stream", {"message": request["params"]["message"]}),
("message/send", {"message": {"role": "user"}}),
("tasks/get", {"id": "task-999"}),
("tasks/get", {"id": task_id}),
]
for method, params in probes:
resp = await client.rpc(method, params)
if "error" in resp:
err = resp["error"]
print(f"{method:<15} error {err['code']}: {err['message']}")
else:
print(f"{method:<15} ok: task {resp['result']['id']} is "
f"{resp['result']['status']['state']}")message/stream error -32601: Method not found: message/stream message/send error -32602: Invalid params: 'message' needs role 'user' and a 'parts' list tasks/get error -32001: Task not found: task-999 tasks/get ok: task task_0000 is completed
-32601 (method not found) and -32602 (invalid params) are standard JSON-RPC codes;
-32001 (task not found) is defined by A2A. A full server that knows message/stream
but has streaming switched off would answer with A2A’s own “unsupported operation” error
(-32004) instead; this subset does not know the method at all, which is why the card
says "streaming": false.
5. A conversation across calls: contextId
HTTP requests are independent, so a follow-up such as “and in GBP?” only makes sense if
the server can tie it to the earlier message. In A2A the client sends back the
contextId it received; the server keeps one conversation per context id. Here the
server holds a separate ExecutionContext for each.
from agentlab.a2a.protocol import task_text
first = await client.send("Convert 120 USD to EUR")
follow_up = await client.send("And the same amount in GBP?", context_id=first["contextId"])
cold = await client.send("And the same amount in GBP?")
for label, t in [("first", first), ("same context", follow_up), ("no context", cold)]:
print(f"{label:<13} {t['contextId']:<7} {t['status']['state']:<10} {task_text(t)}")
print("conversations the server is holding:", len(fx_server.contexts))first ctx_0001 completed USD 120.00 is EUR 110.40. same context ctx_0001 completed USD 120.00 is GBP 94.36. no context ctx_0002 completed Which amount and which currencies? For example: convert 100 USD to EUR. conversations the server is holding: 3
The follow-up worked because the FX desk saw the earlier turn in its own context; the same words without a context id reached an agent with no memory of 120 USD, which asked for the amount. Two consequences for real services:
- The server holds the state. Every context the server keeps costs memory (and, with a live model, input tokens on every later turn). Real servers expire old contexts.
- The client must keep the id. A client that drops
contextIdsilently starts a new conversation each time, which is the right default for one-off questions and a bug for follow-ups.RemoteAgent(keep_context=True)below remembers it for you.
6. Remote agents as tools of a local agent
A second server, the calendar desk, looks up public holidays in a small fixture file.
RemoteAgent.connect reads a card and gives back an object with the same run method as
a local agent, so the AgentTool from notebook 9a can wrap it. The tool’s name and
description come straight from the card.
from agentlab.config import repo_root
HOLIDAYS = json.loads((repo_root() / "fixtures" / "a2a" / "holidays.json").read_text())
COUNTRY_CODES = {data["name"].lower(): code for code, data in HOLIDAYS.items()}
def public_holidays(country: str, month: str) -> str:
"""List the public holidays of a country in one month.
Args:
country: Country name or ISO code, for example Portugal or PT.
month: Year and month as YYYY-MM.
"""
code = COUNTRY_CODES.get(country.lower(), country.upper())
if code not in HOLIDAYS:
known = ", ".join(d["name"] for d in HOLIDAYS.values())
raise ValueError(f"no holiday data for {country!r}; I know {known}")
days = HOLIDAYS[code].get(month, [])
name = HOLIDAYS[code]["name"]
if not days:
return f"No public holidays in {name} in {month}."
lines = [f"- {day} {holiday}" for day, holiday in days]
return f"Public holidays in {name} in {month}:\n" + "\n".join(lines)
calendar_agent = Agent(
llm, tools=[FunctionTool(public_holidays)], name="calendar_desk",
instructions="You are the calendar desk. Answer questions about public holidays "
"with the public_holidays tool.")
calendar_server = A2AServer(
calendar_agent, name="Calendar Desk",
description="Lists the public holidays of a country (Portugal, Spain, Germany) "
"in a month.",
skills=[skill("public-holidays", "Public holidays",
"List the public holidays of a country in a given month.",
tags=["calendar", "holidays"])],
).start()
PORTS[calendar_server.url] = "http://127.0.0.1:<calendar-port>/"from agentlab.a2a import RemoteAgent
from agentlab.multi import AgentTool
fx_remote = await RemoteAgent.connect(fx_server.url)
calendar_remote = await RemoteAgent.connect(calendar_server.url)
remote_tools = [AgentTool(fx_remote), AgentTool(calendar_remote)]
for t in remote_tools:
print(t.name, "->", t.description)
show(remote_tools[0].tool_definition)fx_desk -> Converts amounts between EUR, USD and GBP at fixed reference rates. Skills: Convert an amount from one currency to another (EUR, USD, GBP).
calendar_desk -> Lists the public holidays of a country (Portugal, Spain, Germany) in a month. Skills: List the public holidays of a country in a given month.
{
"type": "function",
"function": {
"name": "fx_desk",
"description": "Converts amounts between EUR, USD and GBP at fixed reference rates. Skills: Convert an amount from one currency to another (EUR, USD, GBP).",
"parameters": {
"type": "object",
"properties": {
"request": {
"type": "string",
"description": "The task or question to delegate, with every detail the agent needs."
}
},
"required": [
"request"
]
}
}
}
To the planner’s model, fx_desk is one more tool with one string argument. That is the
point of the wrapper: the planner does not need to know that the tool is an agent, or
that it runs in another process.
planner = Agent(
llm, tools=remote_tools, name="travel_planner",
instructions="You are the travel planner. You cannot convert money or look up holidays "
"yourself; send each question to the remote agent whose description fits "
"it, with every detail it needs.")
fx_server.log.clear()
calendar_server.log.clear()
start = len(llm.calls)
questions = [
"How much is 250 EUR in USD?",
"Are there public holidays in Portugal in December 2026?",
"Are there public holidays in France in December 2026?",
"Book a table for two in Lisbon tonight.",
]
for q in questions:
result = await planner.run(q)
print(f"Q: {q}\nA: {result.output}\n")
print("FX desk server log: ", fx_server.log)
print("calendar desk server log:", calendar_server.log)Q: How much is 250 EUR in USD? A: fx_desk replied: EUR 250.00 is USD 271.74. Q: Are there public holidays in Portugal in December 2026? A: calendar_desk replied: Public holidays in Portugal in 2026-12: - 2026-12-01 Restoration of Independence - 2026-12-08 Immaculate Conception - 2026-12-25 Christmas Day Q: Are there public holidays in France in December 2026? A: calendar_desk replied: I cannot answer that: ValueError: no holiday data for 'France'; I know Portugal, Spain, Germany Q: Book a table for two in Lisbon tonight. A: None of the agents I know can help with that. FX desk server log: ['POST message/send'] calendar desk server log: ['POST message/send', 'POST message/send']
Each answer travelled planner model → AgentTool → httpx → HTTP → server thread →
remote agent → its own tool, and back. The France question shows a remote failure that
is not a protocol failure: the calendar desk’s tool raised an error, its agent reported
the error in its answer, and the Task came back completed. The planner only knows what the
remote agent chose to say. The last question matched no card, so no request was sent.
Where did the work happen? Every model call in this section went through the same offline model object, so we can group them by the role sentence in the instructions.
import re
from agentlab.tracing import usage_of
by_role: dict[str, list[int]] = {}
for req, resp in llm.calls[start:]:
role = re.search(r"You are the ([A-Za-z ]+?)\.", "\n".join(req.instructions)).group(1)
tokens_in, tokens_out, _, _ = usage_of(req, resp)
row = by_role.setdefault(role, [0, 0, 0])
row[0] += 1
row[1] += tokens_in
row[2] += tokens_out
print(f"{'agent':<16}{'model calls':>12}{'input tokens':>14}{'output tokens':>15}")
for role, (calls, tin, tout) in by_role.items():
print(f"{role:<16}{calls:>12}{tin:>14,}{tout:>15,}")agent model calls input tokens output tokens travel planner 7 2,091 141 FX desk 2 371 23 calendar desk 4 726 82
In a real deployment the two desks run on someone else’s account: their model calls are
billed to whoever runs the server, and the caller cannot see them. The A2A Task has no
standard field for token usage or cost (a server can add its own metadata), so if you
need to budget a multi-agent system across organisations, you have to agree on it outside
the protocol.
A remote agent's answer is untrusted input
The planner passes the remote reply back into its own context, where its model reads it. A malicious or compromised remote agent could put instructions there (“ignore your previous instructions and …”), the same prompt-injection risk as any tool result (module 12). Treat remote replies as data: keep the planner’s permissions narrow, and do not let a remote answer alone trigger an irreversible action.
7. What this subset leaves out
| part of A2A | what it is for | here |
|---|---|---|
message/stream over server-sent events | progress updates while a long task runs | method not found |
| push notifications | the server calls a webhook when a task changes, for tasks that take hours | not offered |
input-required, auth-required states | the remote agent pauses to ask the caller something | never produced |
tasks/cancel | stop a running task | not offered (tasks finish before the reply) |
| file and data parts | send documents or JSON alongside text | text only |
securitySchemes in the card, authentication | who may call the agent, with which credentials | anyone on this machine |
| gRPC and HTTP+JSON transports | alternatives to JSON-RPC | JSON-RPC only |
| signed cards, extended card after login | prove who published a card; show more to known callers | none |
Two of these change the design of a real system rather than adding features. Without streaming or push notifications, a client has to wait for each task to finish inside one HTTP request, which is fine for a currency conversion and not for a research task that takes ten minutes. Without authentication, the only thing protecting these servers is that they listen on 127.0.0.1.
Finally, shut the servers down. Their threads are daemons, so they would also stop when the kernel exits.
fx_server.stop()
calendar_server.stop()
print(fx_server, calendar_server)<A2AServer 'FX Desk' stopped> <A2AServer 'Calendar Desk' stopped>
Try this
- Send
{"jsonrpc": "2.0", "id": 7, "method": "message/send"}(no params) withhttpx. Which error code comes back, and which line ofA2AServer.handle_rpcproduced it?- Wrap the FX desk with
RemoteAgent(..., keep_context=True), ask the planner for 120 USD in EUR and then “and in GBP?”. Does the follow-up reach the same context?- Add a third server, a weather desk that always answers “sunny”, and give its card a description that mentions holidays. Which desk does the offline planner pick for the Portugal question now, and what would stop a real model from being fooled?
- Set
MODELand re-run section 6. Does a real planner forward the question word for word, rephrase it, or split it across both desks?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 20 (fake: 20) | ≈ 4,601 | ≈ 332 | ≈ USD 0.0059 (reference price) |