How to Build a Multi-Agent Orchestrator From Scratch ?

Want to build a multi-agent orchestrator from scratch? Learn the four layers that turn Claude Code, Codex and Gemini CLI into one team.

Ashley Innocent

Ashley Innocent

2 December 2026

How to Build a Multi-Agent Orchestrator From Scratch ?

Quick answer: To build a multi-agent orchestrator from scratch, keep each coding agent in its native harness and add four layers above it: capability injection (how an agent learns it can delegate), communication (an RPC tree or a persistent mailbox), state and fault tolerance (a transactional outbox plus dispatch IDs), and context handoff (reuse each harness’s session and send only the missing turns).

You run Claude Code in one terminal, Codex in another, and Gemini CLI when you want a second opinion. Each one is good alone. None of them knows the others exist. You are the router: you copy a diff from one window, paste a question into another, and remember which agent touched which file.

A multi-agent orchestrator is the program that takes that job off you. This guide builds one from first principles: the goal and trade-off of each layer, with short code sketches. If you’d rather use one than build one, Sharkly runs this design on a task board, and the last section shows how. For the concept itself, start with what AI agent orchestration is.

Harness vs orchestrator: where the line sits

A harness wraps one model with its tools and its agent loop. Claude Code and Codex are harnesses. The model is post-trained against that loop, so its tool calls, file edits and recovery habits are tuned to it. Swap the harness and you lose that tuning.

So keep the native harness. The orchestrator sits one layer up and treats each harness as a black box that takes a prompt, works in a directory and returns a result.

Running several models inside one harness is easy; most harnesses already switch models. The hard part is collaboration across harnesses that were never designed to talk. That raises four problems, in this order:

  1. How does an agent learn it can summon others?
  2. How do messages move between agents?
  3. What happens when a process crashes or a worker times out?
  4. How do you switch models without throwing away context?

Layer 1: capability injection

An agent can’t delegate work it doesn’t know it can delegate. You have two ways to tell it.

Option A: an MCP server. Expose tools such as delegate_task and send_message through the Model Context Protocol. Every call is checked against a JSON schema, so the agent can’t misspell an argument. The cost: every tool schema sits in the context window on every turn, and each call is one round trip.

Option B: a CLI plus a skill file. Ship a small command-line tool and a runbook the agent reads when it needs it. Any agent with a terminal can use it on day one, and it composes in shell pipelines:

# fan out one review sub-task per changed file
git diff --name-only main \
  | xargs -I{} orch delegate --to reviewer --title "Review {}" --wait=false

The cost: the agent can misremember a flag or quote a path badly, and nothing catches it before the command runs.

MCP tools CLI + skill file
Reliability High: schema-checked arguments Medium: flags can drift
Composition One call at a time Pipes, loops, xargs
Integration cost An MCP client in every harness Any agent with a shell
Context overhead Every schema, every turn Only when the skill is read

Pick MCP when calls are few and correctness matters. Pick the CLI when agents fan out work or when you support many harnesses.

Layer 2: communication

Agents never talk to each other directly. The orchestrator is always the middleman. The question is what shape the conversation takes.

The RPC execution tree

A coordinator delegates a sub-task, gets a handle back and awaits the result. It’s simple to build and easy to reason about.

It breaks when a worker has a question. The worker can’t ask; it has to return a partial result and stop. The coordinator becomes a relay for every clarification, and two workers can never ask each other anything.

The persistent mailbox: agents as actors

The alternative follows the actor model. Every agent has an addressable inbox. A blocked worker sends a message to a peer and suspends where it is. The orchestrator queues the message until the recipient’s current turn ends, delivers it, and later wakes the sender with the reply.

Sequence diagram of a mailbox orchestrator: a worker agent sends a question addressed to a reviewer agent and suspends; the orchestrator stores it in the reviewer's inbox because the reviewer is mid-turn; when the reviewer's turn ends the orchestrator delivers the message, the reviewer replies, and the orchestrator wakes the worker where it left off with the answer

That’s real peer-to-peer. The price is that the orchestrator now owns routing, queuing, suspend and wake. Storage choices, from simplest to most durable:

  • JSON inbox files per agent on local disk: easy to inspect, fragile under concurrent writes.
  • In-memory queues: fast, gone on restart.
  • SQLite or another database: durable and transactional, and it sets up Layer 3.
CREATE TABLE messages (
  id          INTEGER PRIMARY KEY,
  to_agent    TEXT NOT NULL,
  from_agent  TEXT NOT NULL,
  body        TEXT NOT NULL,
  delivered   INTEGER NOT NULL DEFAULT 0,
  created_at  TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

For more on what gets lost when agents pass work along, see why agent handoffs lose reasoning.

Layer 3: state and fault tolerance

Agent processes crash, hang and time out. Your state has to survive all three. Two patterns cover the two dangerous moments.

Before dispatch: the transactional outbox. The bug looks like this: you mark a task running, then the orchestrator crashes before the agent process starts. Now the task says running and nothing is running. The transactional outbox fixes it. Write the status change and a pending dispatch command in the same database transaction. A background loop picks up pending commands and starts the agent. Either both rows land or neither does.

with db:  # one transaction
    db.execute("UPDATE tasks SET status='queued' WHERE id=?", (task_id,))
    db.execute("INSERT INTO outbox(task_id, command) VALUES (?, 'dispatch')", (task_id,))

# dispatcher loop, separate process
for row in db.execute("SELECT id, task_id FROM outbox WHERE done=0"):
    dispatch_id = new_dispatch(row.task_id)     # mints a fresh ID
    start_agent(row.task_id, dispatch_id)
    db.execute("UPDATE outbox SET done=1 WHERE id=?", (row.id,))

After dispatch: fence with dispatch IDs. Split the logical task from each attempt to run it. Every assignment or retry mints a new dispatch ID and records it as the task’s current one. When a worker reports, it sends its dispatch ID. If the ID is stale, the report is dropped. A worker that timed out, was replaced, and then woke up can’t overwrite its replacement’s output. Martin Kleppmann calls this a fencing token.

def accept_result(task_id, dispatch_id, output):
    current = db.execute("SELECT current_dispatch_id FROM tasks WHERE id=?", (task_id,)).fetchone()[0]
    if dispatch_id != current:
        return "dropped: stale dispatch"
    save_output(task_id, output)

The two work together. The outbox loop retries, and a retry can start a duplicate dispatch. Dispatch IDs make that duplicate harmless.

Schema of the orchestrator's state: one database transaction updates the tasks table and inserts a row into the outbox; a dispatcher loop reads pending outbox rows, mints a dispatch with a new dispatch ID and starts the agent; the agent's result carries its dispatch ID and is accepted only if it matches the task's current dispatch, while a stale ID is dropped; a separate context layer keeps an app thread and a provider thread table with each harness's session ID and sync cursor

Layer 4: context handoff between models

Say Codex handles turns 1 to 3, Claude takes turns 4 and 5, and Codex comes back for turn 6. Replaying the whole conversation into a fresh Codex session throws away the prompt cache and every file Codex already read, so you pay for the same tokens twice.

Keep two layers instead:

  • App thread: the full, user-facing ledger of every turn, whoever wrote it.
  • Provider thread table: per harness, its native session ID and a cursor marking the last app turn synced into it.

When you switch back to Codex, resume its native session and append only the turns after its cursor as a delta.

def run_turn(app_thread, harness):
    # the new user prompt is already the last turn in app_thread
    pt = provider_threads.get(app_thread.id, harness.name)
    delta = app_thread.turns[pt.cursor:] if pt else app_thread.turns
    session = harness.resume(pt.session_id) if pt else harness.new_session()
    reply = session.send(delta)
    app_thread.turns.append(reply)
    provider_threads.save(app_thread.id, harness.name, session.id, cursor=len(app_thread.turns))
    return reply

Watch the cache clock. Prompt caches expire after minutes to an hour depending on the provider; see Anthropic’s prompt caching and OpenAI’s prompt caching docs. Switch back after a long gap and the delta saves context, not cache.

Putting the multi-agent orchestrator together

  1. Harness: keep each agent’s native loop; orchestrate above it.
  2. Capability injection: MCP for few, exact calls; CLI plus a skill file for fan-out and many harnesses.
  3. Communication: RPC tree if workers never ask questions; mailbox if they do.
  4. State: outbox before dispatch, dispatch IDs after.
  5. Context: app thread plus provider threads, deltas on switch.

For a worked example of these layers in one pipeline, see multi-agent system design from a production PR reviewer.

Sharkly runs this design so you don’t have to build it

If your goal is a team of agents rather than an orchestrator codebase, Sharkly maps the same layers onto a task board. Here’s what it does today, per the help docs:

  • Assignment is the dispatch. Assign a task to an Agent and Sharkly queues a run and dispatches it to a connected Computer, where a local service prepares an isolated task directory and starts the Runtime: Claude Code, Codex or another detected agent tool, in its own harness.
  • The task is the mailbox. An @mention of an Agent in a comment starts a new chat with that Agent on the task, using the comment as its first message. Several runs of one Agent on one task queue behind each other instead of running in parallel.
  • Loops are cut. When an Agent mentions another Agent that already has a pending run on the task, the mention is skipped.
  • Runs stay bound to the task. Results, comments and run history live on the task, and Needs your reply or Needs your review hands work back to a person.
  • Agents get the CLI. An active run gets a scoped credential for the Sharkly CLI, the CLI-plus-skill route from Layer 1.
A Sharkly task in the Cancel Anything demo organization with the Assignee control boxed: the task is assigned to a person and to the Echo Agent, which is what dispatches a run

The Call Agent button opens a new conversation with a second Agent on the same task, which is the peer request from Layer 2 without writing a router.

The same Sharkly task with the Call Agent button boxed at the top of the side panel, where you start a new conversation with another Agent on the task

Compare it with other options in our guide to what a multi-agent collaboration platform needs, or see why teams orchestrate the agents they already pay for.

Build it or run it

Build the orchestrator when the routing logic is your product or you need control over every layer. Use a board when you want agents shipping work this week. Either way, the four layers stay the same. Sharkly is free to start: connect a Computer and assign your first task.

FAQ

What is a multi-agent orchestrator?

It’s a program that sits above several coding agents, gives them a way to delegate and message each other, tracks the state of every task, and moves context between models. Each agent keeps running in its own harness.

Should I use MCP or a CLI to give agents orchestration tools?

Use MCP when you have a few tools and need schema-checked calls. Use a CLI with a skill file when agents fan out work in pipelines or you support many harnesses, since it costs no context until read.

What is a transactional outbox in agent orchestration?

It’s writing the task’s status change and its pending dispatch command in one database transaction, then starting agents from a background loop. A crash can’t leave a task marked running with no process behind it.

How do I stop a timed-out agent from overwriting newer work?

Give every dispatch attempt its own ID and store the current one on the task. Reject any result whose dispatch ID doesn’t match.

How do I switch models mid-task without losing context?

Keep a full app thread plus a table of each harness’s native session ID and sync cursor. On switching back, resume the native session and send only the turns it missed.

Explore more

How ClickUp Brain 2 Works: Super Agents, Credits and Limits

How ClickUp Brain 2 Works: Super Agents, Credits and Limits

How does ClickUp Brain 2 work? Learn how Super Agents are triggered, what each run costs in AI Credits, and where the design stops for code.

2 December 2026

Monday AI Agents: How They Work and What They Cost

Monday AI Agents: How They Work and What They Cost

How do monday AI agents work? Learn what triggers them, what they can access, and how to estimate the credits your team will spend.

2 December 2026

Linear Agents Explained: Delegation, Coding Sessions and Credits

Linear Agents Explained: Delegation, Coding Sessions and Credits

How do Linear agents work? Learn what happens when you delegate an issue, where the code runs, and when Linear charges for the work.

2 December 2026

How to Build a Multi-Agent Orchestrator From Scratch ?