Protocols between agents
Hand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.
What it covers7
Why it matters
The subagents you have built so far were yours: same harness, same process, your own prompt. The next step is an agent that hands work to an agent somebody else built, on another company's servers, with a model and tools you will never see. That only works if both sides agree on how to say "here is a task", "I need to ask you something" and "it's done". A protocol between agents is that agreement. This lesson builds a small one, so that the real ones read as variations on something you already understand.
What you'll be able to do
- Explain what a protocol between agents is for, and how it differs from a protocol for tools
- Read an agent card, and choose an agent by the skills it lists
- Follow a task through its states, and tell a legal history from a broken one
- Trace a task on the wire: send a message, poll, answer a question, collect the result
- Make requests safe to retry with message ids, and treat a remote agent's claims and output as untrusted
Show the answer
Nothing: only what it can do and how to talk to it
The other agent is a closed box, and it should be. Its model, prompt and tools belong to its owner and can change any day. What your agent needs is a description of what it offers, an address, and an agreed way to hand over a task and hear back. That is what a protocol between agents provides.
The idea: an agent you did not build is a closed box with a card
Recall: JSON-RPC 2.0 in depth taught the envelope that MCP uses, and Subagents handed work to agents you wrote. This lesson hands work to one you did not.
An agent you didn't build
You have met one protocol already. MCP connects an agent to tools: functions with a schema, which are called and return. A tool doesn't think, and a call is over in one exchange.
An agent on the other end is a different kind of thing. It takes a task in plain language. It may work for minutes or days. It may come back with a question, or decline. It has its own judgment, and it is opaque: you see what it says, never how it got there.
A protocol between agents is built for that. The best known is Agent2Agent, or A2A: announced by Google in April 2025 and now an open project under the Linux Foundation. This lesson follows its ideas with a small protocol of our own. Its exact method and field names have changed between versions, so read the current specification before building against it.
The first idea is the agent card: a small document an agent publishes at a known address on its site. It says who the agent is, where to reach it, how to sign in, and what skills it offers.
Setup (runs before every cell) · 13 lines
The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.
MOVES = {
"submitted": ["working", "rejected", "canceled"],
"working": ["input-required", "completed", "failed", "canceled"],
"input-required": ["working", "canceled"],
# final: nothing follows
"completed": [], "failed": [], "canceled": [], "rejected": [],
}
def move(task, state):
if state not in MOVES[task["state"]]:
raise ValueError(task["state"] + " -> " + state + " is not allowed")
task["state"] = state
task["history"].append(state)cards = [
{
"name": "Room Booker", "url": "https://rooms.example.org/agent",
"description": "Finds and books meeting rooms.",
"skills": [{"id": "book-room", "tags": ["rooms", "booking", "calendar"]}],
"capabilities": {"streaming": False}, "auth": "oauth2"},
{
"name": "Travel Desk", "url": "https://travel.example.org/agent",
"description": "Plans trips and books trains and hotels.",
"skills": [
{"id": "plan-trip", "tags": ["travel", "booking"]},
{"id": "expense-estimate", "tags": ["travel", "costs"]}],
"capabilities": {"streaming": True}, "auth": "oauth2"},
{
"name": "Figures Checker", "url": "https://audit.example.org/agent",
"description": "Checks the numbers in a report against its tables.",
"skills": [{"id": "check-figures", "tags": ["reports", "numbers"]}],
"capabilities": {"streaming": True}, "auth": "api key"},
]
def agents_for(cards, tag):
"""The agents that list a skill with this tag, and which skill it is."""
return [
(
card["name"], skill["id"]
) for card in cards for skill in card["skills"] if tag in skill["tags"]]
for tag in ("rooms", "booking", "numbers", "payroll"):
print(tag.ljust(8), "->", agents_for(cards, tag))
print()
print("glue to write so that every one of our agents can use every outside agent:")
for ours, theirs in ((2, 3), (5, 10), (20, 50)):
print(
str(ours).rjust(3), "of ours x", str(theirs).rjust(2),
"of theirs | one adapter per pair:", str(ours * theirs).rjust(4),
"| one protocol, each side once:", ours + theirs)Finding an agent is a search over cards. One agent books rooms. Two list something about booking, so your agent would read both descriptions before choosing. Nobody does payroll, and the honest result is an empty list.
The second half of the output is the case for a shared protocol at all. If every pair of agents needs its own adapter, 20 of ours and 50 of theirs means 1,000 adapters. With one protocol, each agent implements it once: 70 pieces of work. It is the same sum that made MCP worth having for tools.
Show the answer
How an AI app connects to tools and data sources
MCP is a standard way to plug tools and data into any AI app: a server offers tools, resources and prompts, and any host can use them. The two protocols fit together. An agent uses MCP to reach its own tools, and a protocol between agents to reach other agents, each of which has tools of its own behind it.
Choose an agent by its card
Write pick_agent(cards, tags, need_streaming). Each card has a "name", a list of "skills" (each with a list of "tags"), and "capabilities" with a "streaming" flag. Score a card by how many of the wanted tags appear among the tags of any of its skills, counting each wanted tag once. Skip cards that score 0, and, when need_streaming is true, cards that don't offer streaming. Return the name of the highest-scoring card. On a tie, the earlier card in the list wins. Return None if no card qualifies.
Uses the setup above, 13 lines.
def pick_agent(cards, tags, need_streaming): return None cards = [ { "name": "Room Booker", "skills": [{"id": "book-room", "tags": ["rooms", "booking"]}], "capabilities": {"streaming": False}}, { "name": "Travel Desk", "skills": [{"id": "plan-trip", "tags": ["travel", "booking"]}], "capabilities": {"streaming": True}}, ] print(pick_agent(cards, ["booking", "rooms"], False))
Only some moves are legal. Writing them down lets a program check a history.
Write a sentence or two, then compare it with a good answer in the lesson.
In code: tasks, the wire and lost messages
A task has a life
A tool call has two moments: called, returned. A task given to an agent has a life, and both sides need to agree on where it is. So the protocol gives every task an id and a state.
- submitted: received, not started.
- working: the agent is on it.
- input-required: the agent has a question, and waits for you.
- completed, failed, canceled, rejected: over. These are final.
Only some moves between states make sense, and writing them down turns a vague conversation into something a program can check.
Uses the setup above, 13 lines.
task = {"id": "task-1", "state": "submitted", "history": ["submitted"]}
for state in ("working", "input-required", "working", "completed"):
move(task, state)
print(" -> ".join(task["history"]))
for start, state in (
("completed", "working"), ("submitted", "completed"),
("input-required", "completed")):
try:
move({"id": "t", "state": start, "history": [start]}, state)
except ValueError as err:
print("refused:", err)
final = [s for s in MOVES if not MOVES[s]]
print("final states:", final)
The first line is a healthy task: it started, asked something, got its answer, finished. The three refusals each say something about the design. A completed task can't start again: you would send a new one. A task can't complete without having been worked on. And a task that is waiting for an answer can't finish until it has gone back to work.
Two more words. What the two sides say to each other are messages. What the agent produces, the booking or the report or the file, is an artifact, kept apart from the chat so that a program can pick it up without reading the conversation.
input-required is the state that most separates an agent from a tool. A tool with a missing argument returns an error. An agent asks.
MOVES = {
"submitted": ["working", "rejected", "canceled"],
"working": ["input-required", "completed", "failed", "canceled"],
"input-required": ["working", "canceled"],
"completed": [], "failed": [], "canceled": [], "rejected": [],
}
steps = [
("submitted", "rejected"), ("working", "rejected"), ("input-required", "canceled"),
("failed", "working")]
print([after in MOVES[before] for before, after in steps])Show the answer
[True, False, True, False]
An agent can reject a task on arrival, before doing anything. Once it has started, declining is no longer the right word: the task fails or is canceled. A waiting task can be canceled. And a failed task is final, so nothing follows it.
Is this history possible?
Write valid_history(states). MOVES is given. Return True only if the list is non-empty, starts with "submitted", and every step from one state to the next is allowed by MOVES. A state name that isn't in MOVES makes the history invalid.
Uses the setup above, 13 lines.
MOVES = {
"submitted": ["working", "rejected", "canceled"],
"working": ["input-required", "completed", "failed", "canceled"],
"input-required": ["working", "canceled"],
"completed": [], "failed": [], "canceled": [], "rejected": [],
}
def valid_history(states):
return True
print(valid_history(["submitted", "working", "completed"]))
print(valid_history(["submitted", "completed"]))
On the wire
Underneath, the two agents exchange JSON over HTTPS. The usual envelope is JSON-RPC, the same one MCP uses: a request names a method and carries params, and the response carries a result or an error, with the request's id so the two can be matched.
Our protocol needs only two methods to get through a whole task. message/send hands over a message: a new task, or an answer to a question on an existing one. tasks/get asks how a task is doing.
The cell is a complete remote agent and a client driving it. Read the output first, then the class.
Uses the setup above, 13 lines.
class RoomBooker: """A remote agent. All anyone outside can see is what it answers on the wire.""" def __init__(self): self.tasks, self.by_message = {}, {} def handle(self, request): method, params = request["method"], request.get("params", {}) if method == "message/send": message = params["message"] # a repeat of something already received if message["messageId"] in self.by_message: return self.reply( request, self.tasks[self.by_message[message["messageId"]]]) # an answer to a question the agent asked if "taskId" in message: task = self.tasks[message["taskId"]] task["messages"].append(message["text"]) task["question"] = None move(task, "working") else: task = { "id": "task-" + str(len(self.tasks) + 1), "state": "submitted", "history": ["submitted"], "messages": [ message["text"] ], "question": None, "artifacts": []} self.tasks[task["id"]] = task self.by_message[message["messageId"]] = task["id"] return self.reply(request, task) if method == "tasks/get": task = self.tasks.get(params["id"]) if task is None: return { "jsonrpc": "2.0", "id": request["id"], "error": {"code": -32001, "message": "task not found"}} self.work(task) return self.reply(request, task) return { "jsonrpc": "2.0", "id": request["id"], "error": {"code": -32601, "message": "method not found"}} def work(self, task): """One step of the agent's own work. What happens in here is its business.""" if task["state"] == "submitted": move(task, "working") elif task["state"] == "working" and len(task["messages"]) == 1: task["question"] = "Which day?" move(task, "input-required") elif task["state"] == "working": task["artifacts"].append( { "name": "booking", "text": "Room 4.2, " + task["messages"][1] + ", 10:00, 6 seats"}) move(task, "completed") def reply(self, request, task): shown = { "id": task["id"], "state": task["state"], "question": task["question"], "artifacts": task["artifacts"]} return {"jsonrpc": "2.0", "id": request["id"], "result": dict(shown)} agent, sent = RoomBooker(), 0 def call(method, params): global sent sent += 1 request = {"jsonrpc": "2.0", "id": sent, "method": method, "params": params} response = agent.handle(request) seen = response.get("result") or response["error"] print( str(sent).rjust(2), method.ljust(12), "->", {k: v for k, v in seen.items() if v not in (None, [])}) return response.get("result") task = call( "message/send", { "message": { "messageId": "m-1", "text": "Book a room for 6 people, 10:00, one hour"}}) while task["state"] not in ("completed", "failed", "canceled", "rejected"): if task["state"] == "input-required": task = call( "message/send", {"message": {"messageId": "m-2", "taskId": task["id"], "text": "Thursday"}}) else: task = call("tasks/get", {"id": task["id"]}) print("result:", task["artifacts"][0]["text"])
Five requests carried the whole job. The first created task-1. The client then asked how it was going, twice, and the second answer was a question: which day? The client answered with another message/send, this time naming the task. One more look, and the task was completed, with the booking as an artifact.
Look at what the client never learned: how the agent chose room 4.2, what tools it used, whether a model was involved at all. The work method could be replaced by anything.
Asking again and again is called polling. It is simple and wasteful. Real protocols add two other ways to hear back. With streaming, the connection stays open and the agent sends updates as they happen. With push, the client leaves an address and the agent calls it when something changes, which suits a task that takes hours. The states are the same in all three.
Show the answer
Leave an address for the agent to call when the state changes
Push suits long tasks: the client registers an address, disconnects, and is called when the task changes state. A streaming connection held for hours will break and must be resumed. Polling every second is twenty thousand requests for one answer. Sending the task again would start new tasks.
When messages get lost, and whom to trust
Networks lose messages. When a request goes unanswered, the client can't tell which half was lost. If the request was lost, nothing happened and sending again is right. If the reply was lost, the task was created, and sending again creates a second one. For a room booking, that is two rooms.
The cure is for the client to give every message an id of its own, and for the agent to remember the ids it has seen. A repeat then returns the task that already exists. A request that is safe to send twice is called idempotent.
Uses the setup above, 13 lines.
import random def run(n, with_ids, seed, lost=0.15): """n bookings over a network that loses messages. A lost request never arrives. A lost reply arrives, and the answer vanishes.""" rng = random.Random(seed) created, seen, sends = 0, set(), 0 for i in range(n): # the client retries until it hears back for attempt in range(8): sends += 1 if rng.random() < lost: # the request was lost: nothing happened continue if with_ids and i in seen: # the agent knows this message: same task again pass else: created += 1 seen.add(i) if rng.random() < lost: # the reply was lost: the client can't tell the difference continue break return created, sends for with_ids in (False, True): created, sends = run(1000, with_ids, 0) print( "message ids" if with_ids else "no ids ", "| wanted 1000 bookings | requests sent:", sends, "| bookings made:", created, "| extra:", created - 1000)
The network was the same in both runs: 1,399 requests to get 1,000 bookings acknowledged. Without ids, the agent made 1,184 bookings, 184 more than anyone wanted. With ids it made exactly 1,000. This is why the remote agent in the last cell checked by_message before anything else.
The other thing a protocol can't do for you is trust.
- A card is a claim. Anyone can publish a card that says "official payments agent". Use agents your organization has chosen, check who signed a card where signatures are offered, and sign in with credentials that are scoped to the task.
- What comes back is untrusted input. A remote agent's messages and artifacts enter your agent's context like any web page. They can be wrong, and they can carry instructions. The gate from the last lesson applies to them unchanged.
- Send only what the task needs. Whatever goes into a message has left your systems.
seen = {}
def send(message_id, text):
if message_id not in seen:
seen[message_id] = "task-" + str(len(seen) + 1)
return seen[message_id]
print(
send("m-1", "book a room"), send("m-2", "book a room"), send("m-1", "book a room"))Show the answer
task-1 task-2 task-1
The agent goes by the message id, not the text. "m-2" is a new message that happens to say the same thing, so it is a second booking, and that is right: people do book two rooms. The third call repeats "m-1", so it returns the first task and creates nothing.
Lost replies, with and without message ids
Each request books a room. When the reply is lost, the client sends it again. Without ids the agent books again on every repeat.
Uses the setup above, 13 lines.
import random import matplotlib.pyplot as plt def bookings(use_ids, lost_reply_rate, n=100, seed=3): rng = random.Random(seed) seen, made = set(), 0 for i in range(n): message_id = "m" + str(i) while True: if not use_ids or message_id not in seen: made += 1 seen.add(message_id) if rng.random() >= lost_reply_rate: break return made rates = [0, 0.1, 0.2, 0.3, 0.4] without = [bookings(False, r) for r in rates] with_ids = [bookings(True, r) for r in rates] print("no ids: ", without) print("with ids:", with_ids) plt.plot(rates, without, marker="o", label="no message ids") plt.plot(rates, with_ids, marker="s", label="with message ids") plt.xlabel("share of replies lost") plt.ylabel("rooms booked for 100 requests") plt.legend() plt.show()
Write a sentence or two, then compare it with a good answer in the lesson.
In a production harness: cards, requests and what to trust
Show the answer
Treat it as text from outside, with no authority
The protocol delivers messages. It doesn't vouch for what they say. The remote agent may have read a hostile document itself and passed the text along in good faith. A signed card tells you who runs the agent, not that every line it relays is safe. Sending the contract anywhere is a commit, and goes through the gate.
Worked example: read five tasks
An orchestrating agent has handed out five tasks to five remote agents, and has each task's history of states. For each one it has to decide what to do next. read checks that the history is possible, and then looks at the last state.
Uses the setup above, 13 lines.
MOVES = {
"submitted": ["working", "rejected", "canceled"],
"working": ["input-required", "completed", "failed", "canceled"],
"input-required": [
"working", "canceled"
], "completed": [], "failed": [], "canceled": [], "rejected": []}
traces = {
"Room Booker": [
"submitted", "working", "input-required", "working", "completed"],
"Travel Desk": ["submitted", "working", "failed"],
"Figures Checker": ["submitted", "rejected"],
"Translator": ["submitted", "working", "completed", "working"],
"Summarizer": ["submitted", "working", "input-required"],
}
def read(states):
for before, after in zip(states, states[1:]):
if after not in MOVES[before]:
return "broken: " + before + " -> " + after
last = states[-1]
if last == "completed":
return "done: use the artifacts"
if last == "input-required":
return "waiting for us: answer, or cancel"
if last in ("failed", "rejected"):
return "ended with no result: try another agent, or say so"
return "still running: look again later"
for name, states in traces.items():
print(name.ljust(16), "|", read(states).ljust(50), "|", " -> ".join(states))The Room Booker's task is done, and its artifacts can be used. The Travel Desk failed and the Figures Checker rejected: both are final without a result, so the orchestrator tries another agent with the skill, or tells the person. It must not simply wait. The Translator's history is impossible, completed and then working again, which means a bug or a misbehaving agent on the other end, and its result shouldn't be trusted. The Summarizer is the one that is easy to miss: nothing is wrong, and nothing will happen until the orchestrator answers its question. An orchestrator that only looks for "completed" would wait on that task forever.
Write a sentence or two, then compare it with a good answer in the lesson.
Practice what you just read
- 6 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 12 review cards for spaced repetition
Try a quiz question
What is the main difference between calling a tool and giving a task to another agent?
Before this lesson
Where this lesson leads.
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Phase 10 · about 20 hours of study
Agent harnesses
Build the software around a model that turns it into a capable, safe agent
24 lessons 1 free
- What an agent harness is FreeThe software around a model that turns it into an agent.35 min
- The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
- A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
- File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
- Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
- Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
- Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
- Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
- Multi-agent systemsCoordinating many agents on one large job.35 min
- Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
- Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
- SubagentsHand a focused task to a fresh context with fewer tools.40 min
- Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
- Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
- Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
- Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
- Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
- Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
- The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
- Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
- Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
- Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
- Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
- Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write