Handoffs, Routing, Shared State and Communication

Most multi-agent failures happen between the agents. Make every transfer explicit, checked and owned.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

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.

Beginner Passing work

Handoff or delegation?

QuestionDelegationHandoff
Who is responsible afterward?The senderThe receiver
What comes back?A result to check and useNothing required; perhaps a return transfer
Who talks to the user?Usually the senderUsually the receiver
ExampleLead asks a researcher for figuresIntake 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.

Senderbuilds a packet
Gatevalidate, authorize, limit
Receiveraccepts or refuses
Task recordnew owner and history
↺ Refusal returns the task to the sender or a person, with a reason
The transfer is complete only when someone has accepted it.

What goes in the packet

FieldWhy it matters
Task identifier and goalEveryone refers to the same work
Done conditionThe receiver knows when to stop
Facts with sourcesClaims can be checked
Actions already takenNothing is repeated
Open questionsUncertainty stays visible
Originating user and tenantPermissions remain correct
Allowed scopesRights are narrow and explicit
Path, depth and budgetLoops and runaway work are stopped
DeadlineWaiting 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 briefBetter brief
Look into the late orderFind 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 changeCheck 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.

Intermediate Routing and shared state

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.

  1. Filter candidates by permission, data rules and health.
  2. Match declared capabilities to the task.
  3. Rank by measured success, cost and current load.
  4. Let a model choose among the survivors if needed.
  5. Confirm acceptance; on refusal, try the next or escalate.
  6. 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 designStrengthRisk
Private state, messages onlyClear ownershipRepeated context, lost facts
Shared blackboardOne view, loose couplingConflicts and contamination
Central task record plus private notesControl with isolationCoordinator load
Event log with derived viewsHistory and replayMore 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.

OptionUse
Function calls and shared typesAgents in one codebase
Queues and eventsAsynchronous work with retries
Ordinary APIsKnown services with fixed operations
Agent2Agent (A2A)Independent agents discovering and delegating across systems
Model Context ProtocolConnecting 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.

Expert Contracts and allocation

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 itemExample
Owner and versionPayments team, 3.2
AcceptsBilling questions with an order identifier
ReturnsCause, evidence references, proposed action
RefusesLegal disputes, other tenants' data
Rights neededRead orders; propose refunds
LimitsConcurrency, time, cost
Measured qualityEvaluation 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

MethodHow it worksMind
Pull from a queueFree workers take the next taskPriority and fairness
Round robinTake turnsIgnores task size
Least loadedChoose the emptiest workerLoad figures can be stale
Capability matchOnly suitable workersRare skills become bottlenecks
BiddingAgents estimate, coordinator picksEstimates 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

SymptomCauseControl
Task bounces between agentsNo owner or overlapping scopePath check and handoff limit
Receiver asks the user againFacts missing from packetRequired fields and tests
Work vanishesFire-and-forget transferAcceptance and deadline
Done twiceDuplicate deliveryTask keys and claims
Wrong rightsReceiver uses its own powers for the userIntersect permissions
False certaintySummary lost the doubtCarry 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.

Illustrative example: the repeating question

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

Next steps