Be Software Architecture Wise
Be Wise Apps

Leer en español · Lire en français · Auf Deutsch lesen

Section 12.4 of 12.8 · Advanced · 32 min read

Agents, tool use and orchestration

Video lesson

5 min · narrated, with captions
Listen only (audio)
Read the transcript

So far, the model has produced text. Many useful systems must also act: look up an order, issue a refund, run a test. This lesson is about doing that safely.

Imagine a capable new assistant on their first day. They can read the files you give them and suggest what to do. But they have no keys of their own. To look something up or send a refund, they fill in a request slip. A supervisor checks the slip, carries it out, and hands back the result. You give them a time limit and a rule that anything expensive needs a signature. An agent works the same way: the model proposes actions, and ordinary software checks and performs them.

With tool calling, the model may reply with a structured request to use a tool, instead of prose. So the user's task goes to a model call, which returns a final answer or a tool call. Every tool call is validated in code: against its schema, the business rules and the user's own rights. If it's allowed, code executes the tool, with a timeout and an idempotency key. The result is added to the context as an observation, the limits on steps, time and tokens are checked, and the loop goes round again. Reason, act, observe: that loop is what makes an agent. Read tools, such as order lookups, can run freely. Write tools, such as proposing a refund, pass through human approval when they matter. Everything outside the model box is ordinary software. The model only proposes, and that's where an agent's reliability and safety come from.

Workflows run models and tools along predefined code paths; agents let the model direct its own process. Start simple. Prompt chaining runs fixed steps: extract the complaint, classify it, then draft a reply. Routing classifies the input and sends it to its own handler, such as late orders or allergy questions. Parallelisation runs independent checks at the same time, or votes several times on one question. With orchestrator and workers, a model splits a task into subtasks at run time. And evaluator and optimiser has one call draft and another check it. A workflow's cost and failures can be predicted, so use an autonomous agent only when the steps can't be known in advance.

Without a standard, every assistant would need its own integration with every system. The Model Context Protocol, or MCP, replaces that with one open protocol. A host application runs one MCP client per connection. Each client talks to an MCP server. Here, a local server wraps files, and remote servers wrap a ticketing service and the order service. Servers offer tools, resources and prompts, and remote servers authorise clients with OAuth. A server can read your data and act for you, so treat it as a dependency. Approve and pin the servers allowed, give each the least privilege, and remember that tool results can carry injected instructions.

Let's follow one refund. A customer writes that their order arrived without the two lemonades. The agent runs with limits of eight steps, thirty seconds and twenty thousand tokens. First, the model calls a read tool for the order's items. Code checks that the order belongs to the signed-in customer, then returns two lemonades at two pounds twenty each. Next, the model proposes a refund, but supplies no amount. The refund service works out four pounds forty and applies the policy in code, including the fifteen pound automatic limit. The customer confirms. Then the response times out. The orchestrator retries with the same idempotency key, and the service returns the original result. So the customer is refunded once, not twice. Had the claim been twenty two pounds, the service would have said it needs approval, and the case would have gone to a human agent with the evidence. Keep runs short. At ninety five per cent right per step, a three step run succeeds about eighty six per cent of the time, and a twenty step run only about thirty six.

Agents fail in new ways: they loop, wander, or claim success they didn't achieve. So cap steps, time and tokens, and stop when the same call keeps repeating. Validate every tool call in code, and run tools with the rights of the person the agent serves, not a powerful service account. Make every write idempotent, and save a checkpoint after each step, so a crash resumes the run instead of repeating it. Require human approval for consequential side effects, showing the exact action and its evidence. And trace every model call and tool call, sandbox any code the agent writes, and keep a fast way to switch it off.

The full section also covers memory and state, and the debate about multi-agent systems. Next, in Section twelve point five, we look at how to test something probabilistic. See you there.

What you need to know

From answering to acting

The systems in the previous sections produce text. Many useful systems must also act: look up an order, search a knowledge base, issue a refund, book a table, run a test suite. Tool calling (often called function calling) is the mechanism. The application describes the tools available, each with a name, a description and a JSON Schema for its parameters. Instead of answering in prose, the model may return a structured request to call one or more of them with particular arguments. The application, not the model, decides whether to execute the call, executes it and returns the result to the model, which then continues. The model never touches a database or an API itself; every effect in the world passes through code you wrote.

An agent is a system in which the model chooses its actions repeatedly: it calls a tool, reads the result, decides what to do next, and continues until the goal is reached or a limit stops it. Autonomy is a spectrum. At one end, code calls the model once to fill in a form; at the other, a model plans and executes a long task with dozens of tool calls and little supervision. Architecturally the important point is that every step towards autonomy moves decisions from deterministic, reviewable code into a probabilistic component, which increases flexibility and decreases predictability, testability and control. That trade-off should be made deliberately, and as late and as little as the problem requires.

{
  "name": "get_order_status",
  "description": "Look up the current status of one order placed by the signed-in customer. Use when the customer asks where an order is. Returns status, estimated arrival and courier position. Changes nothing.",
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "pattern": "^ORD-[0-9]{6}$",
        "description": "Order number, for example ORD-104233"
      }
    },
    "required": ["order_id"],
    "additionalProperties": false
  }
}
A tool definition in the general shape most model APIs accept (field names vary slightly by provider). The description is written for the model; the schema is enforced by code.

The agent loop: reason, act, observe

The loop behind almost every agent was described by Shunyu Yao and colleagues in ReAct: Synergizing Reasoning and Acting in Language Models (2022). ReAct interleaves reasoning (the model writes down what it is trying to do), actions (it calls a tool) and observations (the tool's result is added to its context), so that each step is informed by what the previous one found. Before ReAct, models either reasoned without access to facts, and hallucinated, or acted without reasoning, and wandered. Today's tool-calling interfaces and reasoning models build this loop in, but its structure is still the one to design around.

In code the loop is short. Build the context (instructions, goal, history, tool definitions, results so far); call the model; if it returns a final answer, stop; if it returns tool calls, validate each against its schema and the business rules, check the user is entitled to it, execute it with a timeout, append the result (or a clear error message) to the context, check the limits and go round again. The diagram below shows where deterministic code surrounds the model. Everything outside the model box is ordinary software that can be tested, reviewed and enforced; that is where an agent's reliability and safety come from.

An agent loop with tools

An agent loop: the model chooses tool calls, deterministic code validates and executes them within limits, and results are fed back until the model gives a final answeragent loop (your code)Usertaskfinal answerModel callanswer or tool calltool callValidate, authoriseschema, rules, rightsallowedExecute tooltimeout, idempotency keyresultAppend observationto the contextnext stepLimitssteps, time, tokensRead toolsorders, searchHuman approvalfor side effectsWrite toolspropose refund
The model only proposes; code validates, authorises, executes, enforces limits and feeds results back, and side effects pass through human approval when they matter.

Workflows versus agents

In Building effective agents (December 2024), Erik Schluntz and Barry Zhang of Anthropic drew a distinction that has since become common vocabulary. Workflows orchestrate models and tools through predefined code paths; agents let the model direct its own process and tool use. They described a small set of workflow patterns, all built from an augmented LLM (a model with retrieval, tools and memory), and advised starting with the simplest design that works, often a single well-prompted call with retrieval, and adding agentic behaviour only when it demonstrably improves results.

The advice matches this course's general position on simplicity. A workflow has a known shape, so its cost, latency and failure modes can be predicted and its steps tested one by one. An agent can handle open-ended tasks whose steps cannot be known in advance, such as investigating an unfamiliar bug or researching a question across many sources, at the price of variable cost, harder testing and more ways to go wrong. Many systems described as agents would be better as workflows, and many good agents contain workflows.

Workflow patterns and autonomous agents

PatternHow it worksFood-delivery exampleUse when
Prompt chainingA fixed sequence of model calls, each using the previous output, with checks in code between stepsExtract the complaint, then classify it, then draft a reply in the customer's languageThe task splits cleanly into fixed steps; each step is easier than the whole
RoutingClassify the input, then send it to a specialised prompt, model or handlerLate order, missing item, allergy question and account issue each go to their own handlerInputs fall into distinct categories that need different handling
ParallelisationRun calls at the same time: sectioning splits a task into independent parts; voting runs the same task several times and combines the resultsCheck a new menu for allergens, pricing errors and banned items in parallel; vote three times on whether a review is abusiveParts are independent, or several opinions increase confidence
Orchestrator-workersA model breaks the task into subtasks at run time and delegates them to worker calls, then combines the resultsInvestigate why one city's delivery times rose: look at weather, staffing and restaurant delaysThe subtasks cannot be known in advance
Evaluator-optimiserOne call produces a result, another evaluates it against criteria and feeds back, in a loopDraft a restaurant onboarding e-mail; a second call checks tone and policy and requests changesClear evaluation criteria exist and iteration measurably helps
Autonomous agentThe model plans and acts in a loop with tools until done or stoppedResolve a complex support case across orders, payments and couriersOpen-ended tasks with unpredictable steps, in an environment where mistakes are contained

Designing tools for models

Tools are an interface whose user is a model, and they deserve the care given to any API. Schluntz and Zhang call this the agent-computer interface. Give each tool one clear purpose and a name and description that say when to use it, when not to, and what it returns; models choose tools mostly from their descriptions. Keep parameters few and typed, use enumerations instead of free text, and reject unknown fields. Make mistakes hard to make, for example by requiring absolute identifiers rather than positions in a list. Return concise, relevant results, because every token of a tool result is paid for and occupies the context window; paginate and summarise large results. Return errors the model can act on (order not found; ask the customer to check the number) rather than stack traces.

Separate reading from writing. Read tools can usually run freely; write tools change the world and need validation, authorisation, idempotency and sometimes approval. Keep the number of tools available at any moment small, because large tool sets confuse models and enlarge the attack surface; route to a subset, or load tool definitions on demand. Ask for structured output whenever code will consume the result: many APIs can constrain generation to a JSON Schema, which removes parsing failures but not wrong values, so validation of the content is still needed.

The Model Context Protocol

Every assistant that wants to reach every data source or tool would otherwise need a custom integration for each pair: N applications times M systems. The Model Context Protocol (MCP), introduced by Anthropic as an open standard in November 2024, replaces that with one protocol, in the way the Language Server Protocol did for code editors. A host application (a chat assistant, an IDE, an agent) runs one MCP client per connection to an MCP server. Servers expose tools (functions the model may call), resources (data the application can read into context) and prompts (reusable templates). Messages use JSON-RPC 2.0, over standard input and output for local servers or over HTTP for remote ones, and remote servers use OAuth-based authorisation.

Adoption was fast. By December 2025, Anthropic reported more than 10,000 active public MCP servers and support in products including ChatGPT, Cursor, Gemini, Microsoft Copilot and Visual Studio Code. On 9 December 2025 Anthropic donated MCP to the newly formed Agentic AI Foundation, a directed fund under the Linux Foundation co-founded by Anthropic, Block and OpenAI, so the protocol is now governed in a vendor-neutral home. The specification is versioned by date. The 2026-07-28 revision made the core protocol stateless, so that remote servers can run behind ordinary load balancers without sticky sessions; added support for optional extensions and moved long-running tasks out of the core into an official extension; tightened authorisation; and deprecated older features (roots, sampling and logging) with a transition period of at least a year. For communication between independent agents, rather than between an application and its tools, Google introduced the Agent2Agent (A2A) protocol in April 2025; it was contributed to the Linux Foundation in June 2025, and in August 2026 its backers announced that it would move into the Agentic AI Foundation as well.

Architecturally, an MCP server is a dependency that can read your data and act on your behalf, so treat it like one. Approve and pin the servers that may be used, as part of supply-chain security; prefer servers you or a trusted vendor operate; give each server's credentials the least privilege its tools need; remember that tool descriptions and results flow into the model's context and can carry injected instructions; and route remote MCP traffic through the same gateway, logging and policy controls as other model traffic. The protocol standardises the plumbing; it does not decide what an agent should be allowed to do.

MCP hosts, clients and servers

Model Context Protocol: a host application runs one client per server; servers expose tools, resources and prompts in front of local files and remote systemsHost application (assistant, IDE, agent)Model integrationdecides which tools to useMCP clientFiles server[local, stdio]Local filesMCP clientTickets server[remote, HTTP]Ticketing SaaSMCP clientOrders server[remote, HTTP]Order serviceJSON-RPCServers offer tools, resources and promptsRemote servers authorise clients with OAuth
One host can connect to many servers through one protocol; each server wraps a data source or system and decides what it exposes.

Memory and state

Models are stateless, so an agent's memory is whatever the surrounding system stores and puts back into the context. Short-term memory is the conversation and the results of tool calls so far. It grows with every step, raising cost and latency and eventually exceeding the window, so long-running agents manage it: they drop or shorten old tool results, summarise earlier turns (compaction) and keep a running plan or notes file that the model updates. Long-term memory is information kept across sessions, such as a customer's dietary preferences or facts an assistant learned about a project, stored in a database and retrieved when relevant, which makes it a small RAG system with the same questions of relevance, freshness and access control.

Execution state matters most for reliability. If an agent is halfway through a twenty-step task when its process restarts, it should resume, not start again and repeat side effects. Persist the state after each step (the context, the plan, which tool calls completed and their results) as a checkpoint, or run the agent on a durable execution engine that does this for you, in the way long-running business processes and sagas are run. Memory is also personal data: decide what is remembered, for how long, whether users can see and delete it, and keep one customer's memory out of another's context (see privacy by design).

Multi-agent systems

A multi-agent system splits work between several model-driven agents, usually a lead agent that plans and delegates to sub-agents, each with its own instructions, tools and context window, whose results the lead combines. The benefits are parallelism, specialisation and, above all, separation of context: each sub-agent can explore a large amount of material and return only a short summary. Anthropic reported in June 2025 that its multi-agent research system clearly outperformed a single agent on its internal research evaluation, but also that such systems used about 15 times as many tokens as ordinary chats, and that they suit broad, parallelisable tasks better than tightly coupled ones such as most coding.

Practitioners disagree about how far to go. In the same month Walden Yan of Cognition argued in Don't Build Multi-Agents that sub-agents working from partial context make conflicting assumptions, and recommended a single-threaded agent with careful context management as the default. Both positions agree on the underlying cause: coordination between agents is lossy communication between components that do not share state. That is the central problem of distributed systems, and the same advice applies. Do not distribute without a reason; keep the interfaces between agents explicit and narrow; prefer independent subtasks; trace every hop; and expect cost, latency and failure modes to multiply with the number of agents.

Worked example

Worked example: a refund handled by the support agent

A customer writes: Order ORD-104233 arrived without the two lemonades. The support assistant from section 12.2 runs a short agent loop with a limit of 8 steps, 30 seconds and 20,000 tokens.

Step 1: readThe model calls get_order_items("ORD-104233"). Code checks the order belongs to the signed-in customer, then returns the items, including 2 × lemonade at £2.20, delivered at 19:42.
Step 2: writeThe model calls propose_refund for the two lemonades, reason missing item; it supplies no amount. The refund service, not the model, computes £4.40 from the order and applies the policy in code: items on the order, claim within 48 hours, £4.40 under the £15 automatic limit, no earlier refund on the order and fewer than three refunds in 30 days. The customer confirms the refund on a card in the app (section 12.6), and the service records it under an idempotency key derived from the conversation, order and items.
Failure handledThe response to step 2 times out. The orchestrator retries with the same idempotency key; the refund service returns the original result, so the customer is refunded once, not twice.
Step 3: answerThe model replies with the amount and when it will appear, and the conversation is closed with its trace recorded.
Escalation ruleHad the claim been £22, the refund service would have returned needs approval, and the case would have gone to the agent console with the proposed action and evidence.
Why short runs matterIf each step is right 95% of the time independently, a 3-step run succeeds about 86% of the time (0.953), a 10-step run about 60% and a 20-step run about 36%. Keep runs short, check after every step, and do in code everything that can be done in code.

The model chose what to do; deterministic code decided whether it was allowed and made it safe to retry.

Policy limits live in the refund service, where they are tested and audited, not in the prompt, where they are only suggestions.

Reliability engineering for agents

Agents fail in new ways: they loop, calling the same tool with the same arguments; they wander, pursuing a side issue until the budget runs out; they give up early or claim success they did not achieve; and they take actions their designers did not anticipate. The remedies are the patterns of Chapter 9 and Chapter 6, applied at every step rather than once per request, plus a firm rule that consequential side effects need more than the model's say-so. Section 12.6 treats the security side, excessive agency, in depth; the checklist below covers reliability.

Checklist: making an agent dependable

  • Step, time and token limitsCap iterations, wall-clock time and tokens (or cost) per run, and stop with a clear outcome when a cap is hit, never silently.
  • Loop detectionStop or intervene when the same tool is called with the same arguments repeatedly, or when no progress is made over several steps.
  • Validate every tool call in codeCheck arguments against the schema and the business rules before execution; return a helpful error to the model when a call is rejected.
  • Act with the user's rightsTools run with the permissions of the person the agent serves, not a powerful service account, so the agent cannot become a confused deputy.
  • Idempotent write toolsEvery write takes an idempotency key so that retries after timeouts cannot duplicate refunds, bookings or messages.
  • Human approval for consequential side effectsShow the exact action and its evidence before it happens; define thresholds (amount, reversibility, audience) in code.
  • Checkpoints and resumptionPersist state after each step, or use durable execution, so that a crash resumes the run instead of repeating it.
  • Compensations for multi-step changesWhere several systems change, design compensating actions as in a saga, and record what has been done.
  • Sandbox code and network accessRun any code the agent writes in an isolated environment with no secrets and an allow-list of network destinations.
  • Trace and evaluate trajectoriesRecord every model call and tool call with inputs, outputs, timings and cost; evaluate the path taken, not just the final answer.
  • Kill switch and gradual rolloutPut agent capabilities behind feature flags, release to a small share of traffic first and keep a fast way to switch them off.

Check your understanding

What does the Model Context Protocol standardise, and what does it leave to you?

It standardises how host applications connect to servers that expose tools, resources and prompts; it does not decide which servers to trust or what an agent may do with them.

Why separate read tools from write tools?

Reads can usually run freely, while writes change the world and need validation, authorisation, idempotency and sometimes human approval.

What is a checkpoint for in a long agent run?

It records the context, plan and completed tool calls after each step so that a crashed run can resume without repeating side effects.

Name one argument for and one against multi-agent designs.

For: sub-agents work in parallel with separate contexts and return short summaries. Against: they make conflicting assumptions from partial context and multiply token cost and failure modes.

Next · 12.5Evaluating AIHow to test components whose outputs vary: golden sets, scoring methods, LLM-as-judge and its biases, offline and online evaluation, regression evals in CI, production monitoring, red teaming and confidence in the numbers.Continue →

Sources and further reading

Have a question about this section? ArchitectBot, the course’s AI study assistant, answers from the course first.

Ask: “How do I stop an AI agent from issuing the same refund twice if a tool call times out?”