Handoffs, Routing, Shared State and Communication
Most multi-agent failures happen between the agents. Make every transfer explicit, checked and owned.
A handoff transfers responsibility for a task; delegation asks for a result while the sender stays responsible. Both need a structured packet with the goal, facts and sources, done condition, user identity, history and limited permissions. Share state through a versioned record with owners and expiring claims, describe what each agent can do in a registry and let code route, allocate and enforce limits.
What you will learn: handoff versus delegation, packet contracts, routing and team formation, blackboard designs, communication protocols, identities and capability contracts, and task allocation.
Prerequisites: Topologies, Specialist Teams and Debate and Tool Permissions, Approvals and Abuse Risks.
Handoff or delegation?
| Question | Delegation | Handoff |
|---|---|---|
| Who is responsible afterward? | The sender | The receiver |
| What comes back? | A result to check and use | Nothing required; perhaps a return transfer |
| Who talks to the user? | Usually the sender | Usually the receiver |
| Example | Lead asks a researcher for figures | Intake transfers a conversation to billing |
Libraries use these words in their own ways. In your design, state who owns the task after the transfer, and make that a field in a record.
What goes in the packet
| Field | Why it matters |
|---|---|
| Task identifier and goal | Everyone refers to the same work |
| Done condition | The receiver knows when to stop |
| Facts with sources | Claims can be checked |
| Actions already taken | Nothing is repeated |
| Open questions | Uncertainty stays visible |
| Originating user and tenant | Permissions remain correct |
| Allowed scopes | Rights are narrow and explicit |
| Path, depth and budget | Loops and runaway work are stopped |
| Deadline | Waiting has an end |
Do not forward the whole conversation by default. It costs context, spreads sensitive data and carries any hostile instructions along. Send what the receiver needs and a reference to the rest.
Check before accepting
"""Check a handoff before another agent accepts it."""
AGENTS = {"intake": {"read:order"},
"billing": {"read:order", "write:refund"},
"writer": {"read:order"}}
REQUIRED = ("task", "goal", "facts", "done_when", "user", "path", "scopes")
def check(packet, sender, receiver, max_depth=3):
missing = [f for f in REQUIRED if not packet.get(f)]
if missing:
return [f"missing: {', '.join(missing)}"]
problems = []
if receiver not in AGENTS:
return ["unknown receiver"]
if receiver in packet["path"]:
problems.append(f"loop: {receiver} already handled this task")
if len(packet["path"]) >= max_depth:
problems.append("too many handoffs, send to a person")
extra = set(packet["scopes"]) - (AGENTS[sender] & AGENTS[receiver])
if extra:
problems.append(f"scope not allowed: {', '.join(sorted(extra))}")
problems += [f"fact without source: {text}"
for text, source in packet["facts"] if not source]
return problems
good = {"task": "t7", "goal": "Explain a double charge",
"facts": [("two charges of 20", "payments record 881")],
"done_when": "cause stated with evidence", "user": "kim",
"path": ["intake"], "scopes": ["read:order"]}
cases = {
"good": (good, "intake", "billing"),
"incomplete": ({**good, "done_when": ""}, "intake", "billing"),
"grabs power": ({**good, "scopes": ["write:refund"]},
"intake", "billing"),
"bounces back": ({**good, "path": ["intake", "billing"]},
"billing", "intake"),
"hearsay": ({**good, "facts": [("customer is a fraud", "")]},
"intake", "writer"),
}
for name, args in cases.items():
print(f"{name:<13}{'; '.join(check(*args)) or 'accepted'}")
Output:
good accepted
incomplete missing: done_when
grabs power scope not allowed: write:refund
bounces back loop: intake already handled this task
hearsay fact without source: customer is a fraud
One packet passes. The others are refused for a missing done condition, an attempt to give a receiver a right the sender lacks, a return to an agent already on the path and an unsupported claim about a customer. The checker proves only that a source is named, not that the source says what is claimed, and it assumes the runtime sets the sender and path itself instead of trusting the sender's text.
Writing a brief that works
A delegation fails most often because the sender knows something it did not say. Anthropic reported that vague instructions to subagents led to duplicated work and gaps in its research system. A good brief answers, in a few lines each:
- Objective: the question to answer or the state to reach.
- Boundaries: what is out of scope and what others are covering.
- Inputs: identifiers and sources to start from.
- Output shape: fields, units and how to cite evidence.
- Effort: time, step and spend limits.
- Stop and ask: conditions under which to return without finishing.
| Weak brief | Better brief |
|---|---|
| Look into the late order | Find why order 1042 missed its date; check carrier and warehouse records only; return the cause with record identifiers; stop after eight tool calls |
| Review this change | Check the change against the logging policy; list each violation with file and line; do not edit files |
The orders and files in this table are invented. Test briefs the way you test code: give the packet to a person who has not seen the conversation and ask what they would need to ask. Their questions are your missing fields.
Routing and dynamic team formation
Routing picks which agent receives a task. Team formation picks several. Start with rules and a small registry; use a model to choose among permitted candidates when language varies.
- Filter candidates by permission, data rules and health.
- Match declared capabilities to the task.
- Rank by measured success, cost and current load.
- Let a model choose among the survivors if needed.
- Confirm acceptance; on refusal, try the next or escalate.
- Record why the choice was made.
Keep a fallback for "nobody fits". Dynamic teams are harder to test, so cap team size and keep the registry reviewed. See Single-Agent, Router and Retrieval Patterns for router measurement.
Shared state and the blackboard
A blackboard is a shared space where agents post tasks, findings and decisions, and pick up what suits them. It decouples agents and gives one place to look. Without rules it becomes a scratchpad where anyone overwrites anything.
"""A shared board with owners, expiring claims and safe updates."""
class Board:
def __init__(self):
self.tasks, self.notes = {}, {}
def add(self, task, skill):
self.tasks[task] = {"skill": skill, "owner": None, "until": 0,
"done": False}
def claim(self, agent, skills, now, lease=10):
for name, t in self.tasks.items():
free = t["owner"] is None or t["until"] <= now
if not t["done"] and free and t["skill"] in skills:
t.update(owner=agent, until=now + lease)
return name
return None
def finish(self, agent, task, now):
t = self.tasks[task]
if t["owner"] != agent or t["until"] <= now:
return f"rejected: {agent} no longer holds {task}"
t["done"] = True
return f"{task} finished by {agent}"
def write(self, key, value, author, source, expected):
version = self.notes.get(key, {}).get("version", 0)
if version != expected:
return f"conflict: {key} is at version {version}"
self.notes[key] = {"value": value, "author": author,
"source": source, "version": version + 1}
return f"{key} v{version + 1} by {author}"
board = Board()
board.add("find-invoices", "search")
board.add("check-totals", "math")
print("A claims", board.claim("A", {"search"}, now=0))
print("B claims", board.claim("B", {"search", "math"}, now=1))
print("C claims", board.claim("C", {"search"}, now=5))
print("C claims", board.claim("C", {"search"}, now=12))
print(board.finish("A", "find-invoices", now=13))
print(board.finish("C", "find-invoices", now=14))
print(board.write("total", 240, "B", "invoice list", expected=0))
print(board.write("total", 260, "C", "old export", expected=0))
Output:
A claims find-invoices
B claims check-totals
C claims None
C claims find-invoices
rejected: A no longer holds find-invoices
find-invoices finished by C
total v1 by B
conflict: total is at version 1
Agent C cannot take a task while A's claim is alive, takes it after the claim expires, and A's late attempt to finish is rejected. The second write to the total is refused because C expected an empty entry. Each accepted note records its author, source and version. This version runs in one process; with several, the claim and the version check must each be a single atomic operation in the store, and long work needs a way to renew the claim.
| State design | Strength | Risk |
|---|---|---|
| Private state, messages only | Clear ownership | Repeated context, lost facts |
| Shared blackboard | One view, loose coupling | Conflicts and contamination |
| Central task record plus private notes | Control with isolation | Coordinator load |
| Event log with derived views | History and replay | More machinery |
Separate observations, conclusions and approved facts. A web page's claim that an agent copied to the board should not become an instruction or truth for the next reader. See Context Isolation, Provenance and Governance.
Communication protocols
Inside one program, a function call with typed data is the simplest protocol. Across processes or organizations you need agreed message formats, identity and task lifecycle.
| Option | Use |
|---|---|
| Function calls and shared types | Agents in one codebase |
| Queues and events | Asynchronous work with retries |
| Ordinary APIs | Known services with fixed operations |
| Agent2Agent (A2A) | Independent agents discovering and delegating across systems |
| Model Context Protocol | Connecting an agent to tools and data |
A2A reached version 1.0 in 2026 as its first stable specification, with agents describing themselves in an Agent Card and clients stating the protocol version they speak. A protocol standardizes the exchange; it does not decide whether the other party is trustworthy or its answer correct. Check the current specification before implementing.
Whatever you use, give messages an identifier, sender, recipient, task, type, time and schema version. Make receivers ignore duplicates and reject unknown message types.
Identity, roles and capability contracts
A role name in a prompt is not an identity. Each agent needs its own authenticated identity so that permissions and logs attach to it. A capability contract says what the agent offers and expects.
| Contract item | Example |
|---|---|
| Owner and version | Payments team, 3.2 |
| Accepts | Billing questions with an order identifier |
| Returns | Cause, evidence references, proposed action |
| Refuses | Legal disputes, other tenants' data |
| Rights needed | Read orders; propose refunds |
| Limits | Concurrency, time, cost |
| Measured quality | Evaluation set version and results |
Treat self-descriptions as claims. Register only reviewed agents, verify identity on each call and test the contract before routing real work. Capabilities declared by an outside agent should never expand your user's rights.
Task allocation and load balancing
| Method | How it works | Mind |
|---|---|---|
| Pull from a queue | Free workers take the next task | Priority and fairness |
| Round robin | Take turns | Ignores task size |
| Least loaded | Choose the emptiest worker | Load figures can be stale |
| Capability match | Only suitable workers | Rare skills become bottlenecks |
| Bidding | Agents estimate, coordinator picks | Estimates are unreliable and cost calls |
Pull queues with expiring claims are a sound default. Add priorities, per-tenant limits and a place for tasks that repeatedly fail. Balance on model and tool rate limits as well as on agent processes, since those are often the real constraint.
The task record
Keep one authoritative record per task, written by the runtime and not by free text from agents. A small state set is enough: offered, accepted, working, waiting, done, failed and canceled. Each change stores who made it, when, and the expected previous state, so that two agents cannot both accept. Offers expire. A canceled task refuses later results, and the record says what was already done outside it.
This record answers the questions that matter in operation: who owns this now, what is it waiting for, how long has it waited, how many times has it moved and under whose authority. A list of stuck and bouncing tasks falls out of it directly. The ideas are the same as the explicit states in Graphs, State Machines, Parallelism and Sagas.
When a transfer goes wrong
| Symptom | Cause | Control |
|---|---|---|
| Task bounces between agents | No owner or overlapping scope | Path check and handoff limit |
| Receiver asks the user again | Facts missing from packet | Required fields and tests |
| Work vanishes | Fire-and-forget transfer | Acceptance and deadline |
| Done twice | Duplicate delivery | Task keys and claims |
| Wrong rights | Receiver uses its own powers for the user | Intersect permissions |
| False certainty | Summary lost the doubt | Carry sources and open questions |
What the user should experience
A handoff is visible to people even when they cannot see the agents. Tell the user when responsibility changes, what will happen next and how long it may take. Do not ask again for information you already hold, but do confirm anything consequential that was inferred. If a transfer goes to a person, give that person the same packet in readable form, with the sources one click away, and tell the user whether they need to stay. Never let an agent promise an action that the receiving side has not accepted. Offer a way to reach a human that does not depend on the agents agreeing that one is needed.
Review a sample of transferred conversations from the user's side. Internal metrics can show every handoff as accepted while the person experienced three greetings, two repeated questions and no answer.
Test transfers directly
Build cases for each route: complete packet, missing fields, unavailable receiver, refusal, duplicate, expired claim and hostile text in a fact. Use scripted agents so results are repeatable, then evaluate real agents on whether their packets let the receiver succeed without extra questions. Count transfers per task in production.
Customers complain that they must give their order number three times. Traces show that intake forwards a paragraph summary. The team replaces it with a packet containing the identifier, what was checked and the source of each fact, and rejects packets without them. Repeated questions fall and wrong summaries become easy to spot.
Returning results
A delegated result needs a contract as much as the request does: status, findings with evidence references, actions taken, confidence limits stated in words, unresolved items and cost used. Allow "could not complete" as an ordinary answer with a reason. The sender validates the shape in code, checks important claims and decides whether to retry, ask another agent or tell the user. Never let a result silently change the sender's instructions or permissions.
Changing packets over time
Agents are released separately, so formats drift. Version the packet, add fields as optional first, and have receivers reject versions they cannot read with a clear error. Keep contract tests for each pair that communicates, run them whenever either side changes and list dependents in the registry before removing anything. Long-waiting tasks may carry an old format for days, so plan their upgrade as in Stateful and Long-Running Agent Architecture.
Common mistakes
- Free-text handoffs with no required fields.
- Forwarding the entire history.
- No explicit owner after a transfer.
- Shared state anyone can overwrite.
- Trusting an agent's description of itself.
- Letting delegation add permissions.
- Routing without a fallback.
Checklist
- Every transfer has a validated packet.
- One owner is recorded at all times.
- Receivers accept or refuse explicitly.
- Paths, depth and budgets are enforced.
- Shared writes check versions and record sources.
- Claims expire and can be renewed.
- Agents have identities and reviewed contracts.
- Transfer failures are tested.
Frequently asked questions
Should agents share one memory?
Share a task record with rules. Keep working notes and long-term memory separate unless a stated need and permissions justify sharing.
Is natural language fine between agents?
Use it inside fields such as the goal or findings. Keep routing, identity, permissions and status structured.
Do I need A2A?
Usually only when agents are built or run independently and must discover and delegate across boundaries. Direct calls are simpler within one system.
Who resolves a refused handoff?
The sender keeps ownership until another accepts, or a defined person or queue takes it.
References and further reading
- Agent2Agent (A2A) protocol specification
- Model Context Protocol
- Anthropic: how we built our multi-agent research system
- RFC 8693: OAuth 2.0 Token Exchange
Next steps
Parallelism, Deadlocks and Conflict Resolution
Handle simultaneous work.
A2A Security and Interoperability
Secure agent-to-agent calls.
Securing, Evaluating and Running Multi-Agent Systems
Run the system.