AI infrastructure and systemsPart 4: AI application systems
Chapter 14Agent systems architecture
An agent that has run for 40 minutes and filed two tickets dies when its pod is rescheduled; restarted from scratch, it files the tickets again and bills you twice for the tokens. You will learn to treat an agent as a long-running distributed program with one nondeterministic step, and to build one that survives crashes, stays within budget and reaches tools over a standard protocol.
After this chapter you can
- Model the agent loop as a state machine and implement tool calling at the message level
- Explain the Model Context Protocol: hosts, clients, servers, primitives and transports
- Manage context growth with compaction and keep state and memory in the right stores
- Make agents durable with checkpoints, retries, idempotent tools and human approval pauses
- Choose between single-agent and multi-agent designs, sandbox code execution and cap cost
The agent loop is a state machine
An agent is a program in which a model decides the next action. The loop is short: send the conversation and the available tools to the model, and if it asks for tools, run them, append the results and ask again. When it replies without a tool request, you are done.
Drawing it as a state machine pays off immediately. Each arrow is a place to checkpoint, each state has a timeout, and the terminal states are explicit, including Stopped, which a naive while-true loop never reaches. Most production agent bugs are missing transitions: no exit when the budget runs out, no path for a rejected approval, no handling for a tool that never returns.
Tool calling at the protocol level
Models do not execute anything. Tool calling is a message format: you describe tools with JSON Schema, the model emits a structured request naming a tool and its arguments, and your code runs it. Every major API and every OpenAI-compatible server, including vLLM and Ollama, uses the same shape.
{
"model": "qwen3:4b",
"messages": [{"role": "user", "content": "What does 5 bags of rice cost?"}],
"tools": [{
"type": "function",
"function": {
"name": "lookup_price",
"description": "Return the unit price in USD for an item.",
"parameters": {
"type": "object",
"properties": {"item": {"type": "string"}},
"required": ["item"]
}
}
}]
}{
"role": "assistant",
"content": "",
"tool_calls": [{
"id": "call_9f2c",
"type": "function",
"function": {"name": "lookup_price", "arguments": "{\"item\": \"rice\"}"}
}]
}You then append a message with "role": "tool", the same tool_call_id and the result as text, and call the model again. Three engineering details matter more than any prompt:
- Arguments are untrusted strings. Parse and validate them against the schema; models produce invalid JSON and invented fields, especially small ones.
- Errors go back as results. A tool failure becomes a tool message such as "error: item not found", so the model can recover. Raising an exception kills the run.
- Calls can arrive in parallel. One response may contain several tool calls. Run independent ones concurrently, and return every result before the next model call.
The Model Context Protocol
Every agent framework once had its own tool plug-in format, so every integration was written many times over. The Model Context Protocol (MCP) standardizes how an AI application discovers and calls external capabilities. It is JSON-RPC 2.0 underneath, and it separates three roles.
| Role | What it is |
|---|---|
| Host | The application the user interacts with; it owns the model, the conversation and the permission decisions |
| Client | A connector inside the host, one per server connection |
| Server | A program that exposes capabilities, local or remote |
Servers expose three core primitives. Tools are functions the model may call (tools/list, tools/call). Resources are readable data identified by URIs, such as a file or a database row, that the application can place into context. Prompts are reusable templates the user can invoke.
There are two standard transports. stdio runs the server as a local subprocess and exchanges JSON-RPC over its standard input and output. Streamable HTTP serves a single HTTP endpoint that accepts JSON-RPC in POST requests and may stream responses back as server-sent events; remote servers use OAuth for authorization.
The current specification revision, 2026-07-28, made the core protocol stateless. It removed the initialize handshake and the Mcp-Session-Id header; each request now carries its protocol version and client capabilities in _meta, and servers advertise themselves through a server/discover method. List results carry cache hints (ttlMs, cacheScope). Long-running operations moved into an official tasks extension, and the Roots, Sampling and Logging features are deprecated.
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "lookup_price",
"arguments": {"item": "rice"},
"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28"}
}
}Statelessness matters for infrastructure: any replica behind a load balancer can serve any request, so remote MCP servers scale like ordinary HTTP services. Servers that need state across calls now mint explicit handles and pass them as tool arguments.
Context, state and memory
Context is a budget, not a log
Every model call resends the system prompt, all tool schemas and the full history. A long agent run grows that history with every tool result until it hits the context limit, and cost and latency grow with it long before that. Context engineering is managing what goes into each call.
| Technique | How it works | Trade-off |
|---|---|---|
| Truncate tool output | Cap each result, for example at 2,000 tokens, with a note that it was cut | Model may miss data at the end |
| Store results out of band | Save large outputs to a file or table; give the model a handle and a read tool | Extra tool calls |
| Clear stale tool results | Replace old results with a one-line placeholder | Model cannot reread them |
| Compaction | When context passes a threshold, summarize history into a short brief and continue from it | Lossy; breaks the prompt cache prefix |
| Sub-agents | Delegate a subtask to a fresh context and receive only its summary | More total tokens, less sharing |
Compaction and cache-friendly prompts pull in opposite directions. Provider prompt caches reuse an exact prefix, so rewriting history invalidates the cache from the first changed token. Compact rarely and in large steps rather than trimming a little every turn, as the chapter "LLM gateways, routing and caching" explains in detail.
Put each kind of state in the right store
| Kind | Example | Lifetime | Store |
|---|---|---|---|
| Run state | Messages, step count, pending tool calls | One run | Durable checkpoint store or workflow history |
| Session memory | Earlier turns in this conversation | One session | Database row keyed by session |
| Long-term memory | User preferences, learned facts | Months | Key-value or document store, often retrieved with vector search |
| Artifacts | Generated files, reports, datasets | As needed | Object storage, referenced by URI |
Long-term memory is retrieval over things the agent wrote down earlier, so everything in the previous chapter applies, including freshness and deletion. Keep run state out of process memory: an in-memory message list disappears on the first crash.
Durable execution for long-running agents
Long agents fail in boring ways: pods are evicted, deploys restart workers, model APIs return 529s, tools time out. Durable execution means a run resumes from its last completed step after any such failure, without redoing completed work. It rests on four mechanisms.
Checkpoint after every transition
Persist the run state after each model response and each tool result, before doing anything else. A checkpoint records results, not intentions, so a resumed run never asks the model to redo a step it already took.
Retry with limits
Retry transient failures with exponential backoff and jitter, cap attempts, and separate retryable errors (timeouts, 429, 5xx) from permanent ones (invalid arguments, 4xx).
Make side effects idempotent
A crash between running a tool and saving its result means the tool runs again on resume. Pass an idempotency key, derived from the run ID and the tool call ID, so the second execution is recognized and ignored.
Pause durably for humans
Approval for sensitive actions can take hours. Persist the pending call, release the worker, and resume when the approval signal arrives, rather than holding a thread open.
You can build this on a database table, as the lab does. For production, a workflow engine gives you all four mechanisms as primitives. In Temporal, workflow code is deterministic and every model call and tool call runs as an activity, whose result is recorded in an event history. When a worker dies, another one replays the history, skipping completed activities by using their recorded results.
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
with workflow.unsafe.imports_passed_through():
from activities import call_model, run_tool
RETRY = RetryPolicy(maximum_attempts=5, backoff_coefficient=2.0)
@workflow.defn
class AgentWorkflow:
def __init__(self) -> None:
self.approval: bool | None = None
@workflow.signal
def approve(self, ok: bool) -> None:
self.approval = ok
@workflow.run
async def run(self, task: str, max_steps: int = 20) -> str:
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = await workflow.execute_activity(
call_model, messages, retry_policy=RETRY,
start_to_close_timeout=timedelta(minutes=2))
messages.append(reply)
if not reply.get("tool_calls"):
return reply["content"]
for call in reply["tool_calls"]:
if call["function"]["name"] == "issue_refund":
self.approval = None
await workflow.wait_condition(lambda: self.approval is not None)
if not self.approval:
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": "rejected by a human reviewer"})
continue
result = await workflow.execute_activity(
run_tool, args=[call, f"{workflow.info().workflow_id}:{call['id']}"],
retry_policy=RETRY, start_to_close_timeout=timedelta(minutes=5))
messages.append({"role": "tool", "tool_call_id": call["id"], "content": result})
return "stopped: step budget exhausted"Checkpoints in your own database
- One table, no new infrastructure
- You write resume logic, retries and timers yourself
- Fine for short runs and a single worker type
A workflow engine
- Temporal, Restate, DBOS, Inngest, or framework checkpointers such as LangGraph's
- Retries, timers, signals and replay built in
- Workflow code must be deterministic; every model and tool call goes through activities
Multi-agent patterns and when not to use them
A multi-agent system splits work across several model-driven loops with their own prompts and contexts. It is fashionable, and it is often the wrong first choice.
| Pattern | Shape | Good for |
|---|---|---|
| Single agent with tools | One loop | The default; most tasks |
| Workflow or chain | Fixed sequence of model calls in code | Predictable multi-stage tasks |
| Router | Classifier picks a specialized prompt or agent | Distinct request types |
| Orchestrator and workers | Lead agent plans, spawns workers in parallel, merges results | Broad research, independent subtasks |
| Evaluator loop | One model produces, another critiques until it passes | Output with clear acceptance criteria |
Multi-agent designs cost more than they look. Workers each re-read context, so token use commonly rises by several times or more. Information is lost at every handoff, because a worker sees only the brief it was given. Failures become harder to trace across many loops.
Reach for orchestration only when subtasks are truly independent, parallelism shortens wall-clock time in a way users value, and one context window cannot hold the work.
Sandboxes, failure modes and cost control
Code execution needs real isolation
Agents that write and run code need a sandbox: an environment where arbitrary code cannot reach your hosts, credentials or network.
| Isolation | Boundary | Start time | Notes |
|---|---|---|---|
| Plain container | Shared kernel, namespaces and cgroups | Sub-second | Not enough on its own for untrusted code |
| gVisor | User-space kernel intercepts system calls | Sub-second | Strong hardening for containers |
| Firecracker microVM | Hardware virtualization, minimal VMM | About a second or less | Used by hosted sandboxes such as E2B |
| Hosted sandbox service | Provider-managed microVMs or containers | Varies | Fastest path; data leaves your network |
Whatever you choose, deny network egress by default, mount no credentials, set CPU, memory and wall-clock limits, and destroy the sandbox after the run.
Failure modes and budgets
| Failure mode | Symptom | Control |
|---|---|---|
| Infinite loop | Same tool and arguments repeated | Step budget plus repeat detection |
| Runaway cost | Tokens grow every step | Per-run token or dollar cap enforced at the gateway |
| Bad arguments | Schema errors, invented fields | Validate; return the error as a tool result |
| Context overflow | Late steps forget early facts or fail outright | Truncation, compaction, out-of-band storage |
| Duplicate side effects | Two refunds after a restart | Idempotency keys |
| Silent wrong answer | Run succeeds, result is wrong | Trajectory evals, covered in "Evaluation infrastructure" |
A step budget is the simplest and most important control: a hard cap on model calls per run, ending in an explicit Stopped state that a human or a supervisor can inspect. Add a token budget and a wall-clock timeout on top.
Key terms
- Agent loop
- The cycle of calling a model, executing requested tools and feeding results back until a final answer or a stop.
- Tool call
- A structured request from the model naming a function and JSON arguments, which your code executes.
- MCP
- An open JSON-RPC protocol through which hosts discover and call tools, resources and prompts on servers.
- Streamable HTTP
- The MCP transport for remote servers: JSON-RPC over HTTP POST with optional streamed responses.
- Compaction
- Replacing a long conversation history with a shorter summary so the run can continue within the context window.
- Durable execution
- Running a program so that after any crash it resumes from its last completed step without repeating work.
- Idempotency key
- A unique identifier that lets a tool recognize and ignore a repeated execution of the same request.
- Activity
- In Temporal, a side-effecting step whose result is recorded so that replay can skip it.
- Step budget
- A hard cap on model calls per run that forces an explicit stop.
Build a crash-proof agent with MCP tools and a step budget
Goal: build an agent whose two tools live in an MCP server, kill it mid-task, resume it from a checkpoint without duplicating side effects, and stop it with a step budget.
You need: Python 3.11 or newer and Ollama. The qwen3:4b model supports tool calling and runs on a laptop CPU, slowly; a GPU or Apple silicon makes it pleasant.
- Set up the project.
mkdir agent-lab && cd agent-lab
ollama pull qwen3:4b
python3 -m venv .venv && source .venv/bin/activate
pip install "mcp[cli]" openai- Write the MCP server.
lookup_priceis read-only.record_linehas a side effect, sleeps to give you a window to kill the agent, and uses an idempotency key so a repeat is harmless.
import json
import sqlite3
import sys
import time
from mcp.server import MCPServer
mcp = MCPServer("shop")
PRICES = {"apples": 0.50, "bread": 2.25, "rice": 3.10}
ALIASES = {"apple": "apples", "loaf": "bread", "loaves": "bread", "bag of rice": "rice"}
db = sqlite3.connect("ledger.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS ledger (idempotency_key TEXT PRIMARY KEY, "
"item TEXT, qty INTEGER, line_total REAL)")
@mcp.tool()
def lookup_price(item: str) -> str:
"""Return the unit price in USD for one item: apples, bread or rice."""
name = ALIASES.get(item.strip().lower(), item.strip().lower())
if name not in PRICES:
return f"error: unknown item {item!r}"
return json.dumps({"item": name, "unit_price": PRICES[name]})
@mcp.tool()
def record_line(item: str, qty: int, line_total: float, idempotency_key: str = "") -> str:
"""Record one order line. The runtime fills idempotency_key."""
time.sleep(1.5) # a slow side effect: your window to kill the agent
cur = db.execute("INSERT OR IGNORE INTO ledger VALUES (?, ?, ?, ?)",
(idempotency_key, item, qty, line_total))
db.commit()
print(f"record_line {idempotency_key} rowcount={cur.rowcount}", file=sys.stderr)
return "recorded" if cur.rowcount else "duplicate ignored: already recorded"
if __name__ == "__main__":
mcp.run() # stdio transport- Write the agent. It checkpoints after every transition, resumes pending tool calls on restart, injects idempotency keys and enforces a step budget.
import argparse, asyncio, json, os, sqlite3, sys
from openai import AsyncOpenAI
from mcp import Client, StdioServerParameters
from mcp.types import TextContent
MODEL = os.getenv("AGENT_MODEL", "qwen3:4b")
MAX_STEPS = int(os.getenv("MAX_STEPS", "12"))
TASK = ("Price this order: 3 apples, 2 bread, 5 rice. For each item call lookup_price, "
"then call record_line with qty and line_total. Finally reply with the grand total.")
llm = AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
db = sqlite3.connect("checkpoints.db")
db.execute("CREATE TABLE IF NOT EXISTS runs (run_id TEXT PRIMARY KEY, step INT, "
"status TEXT, messages TEXT)")
checkpoints = 0
def save(run_id, step, status, messages, crash_after=0):
global checkpoints
db.execute("INSERT OR REPLACE INTO runs VALUES (?, ?, ?, ?)",
(run_id, step, status, json.dumps(messages)))
db.commit()
checkpoints += 1
if crash_after and checkpoints == crash_after:
print(f"simulated crash after checkpoint {checkpoints}")
os._exit(1)
def pending_calls(messages):
for i in range(len(messages) - 1, -1, -1):
if messages[i]["role"] == "assistant":
answered = {m["tool_call_id"] for m in messages[i + 1:] if m["role"] == "tool"}
return [c for c in messages[i].get("tool_calls", []) if c["id"] not in answered]
return []
def to_openai_tool(t):
schema = json.loads(json.dumps(t.input_schema))
schema.get("properties", {}).pop("idempotency_key", None) # hidden from the model
return {"type": "function", "function": {
"name": t.name, "description": t.description or "", "parameters": schema}}
async def run(run_id, crash_after):
row = db.execute("SELECT step, status, messages FROM runs WHERE run_id = ?",
(run_id,)).fetchone()
if row:
step, status, messages = row[0], row[1], json.loads(row[2])
if status != "running":
print(f"run {run_id} already {status}"); return
print(f"resuming {run_id} at step {step}")
else:
step, messages = 0, [
{"role": "system", "content": "You are a careful order clerk. Never guess prices."},
{"role": "user", "content": TASK}]
save(run_id, step, "running", messages)
server = StdioServerParameters(command=sys.executable, args=["mcp_server.py"])
async with Client(server) as mcp:
tools = [to_openai_tool(t) for t in (await mcp.list_tools()).tools]
while True:
for call in pending_calls(messages):
name = call["function"]["name"]
try:
args = json.loads(call["function"]["arguments"] or "{}")
if name == "record_line":
args["idempotency_key"] = f"{run_id}:{call['id']}"
print(f"calling {name} {args}")
result = await mcp.call_tool(name, args)
text = "".join(b.text for b in result.content if isinstance(b, TextContent))
except Exception as exc: # errors go back to the model as results
text = f"error: {exc}"
messages.append({"role": "tool", "tool_call_id": call["id"], "content": text})
save(run_id, step, "running", messages, crash_after)
last = messages[-1]
if last["role"] == "assistant" and not last.get("tool_calls"):
save(run_id, step, "done", messages)
print("FINAL:", last["content"]); return
if step >= MAX_STEPS:
save(run_id, step, "budget_exceeded", messages)
print(f"stopped: step budget of {MAX_STEPS} exhausted"); return
resp = await llm.chat.completions.create(model=MODEL, messages=messages, tools=tools)
msg, step = resp.choices[0].message, step + 1
entry = {"role": "assistant", "content": msg.content or ""}
if msg.tool_calls: # our own ids: unique per run, stable across restarts
entry["tool_calls"] = [{
"id": f"s{step}c{i}", "type": "function",
"function": {"name": c.function.name, "arguments": c.function.arguments}}
for i, c in enumerate(msg.tool_calls)]
messages.append(entry)
save(run_id, step, "running", messages, crash_after)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--run-id", required=True)
p.add_argument("--crash-after", type=int, default=0)
a = p.parse_args()
asyncio.run(run(a.run_id, a.crash_after))- Run it once without interruptions. The correct total is 3 times 0.50 plus 2 times 2.25 plus 5 times 3.10, which is 21.50.
python agent.py --run-id r1You should see several calling lookup_price and calling record_line lines, then FINAL: with a total. If a small model gets the arithmetic wrong, note it: that is a quality problem for evals, not a durability problem.
- Simulate a crash after the fourth checkpoint, inspect the saved state, then resume.
python agent.py --run-id r2 --crash-after 4 # prints: simulated crash after checkpoint 4
python -c "import sqlite3; print(sqlite3.connect('checkpoints.db').execute(\"SELECT step, status FROM runs WHERE run_id='r2'\").fetchall())"
python agent.py --run-id r2 # prints: resuming r2 at step ...- Now a real crash inside a side effect. Start a run, and in a second terminal kill it with
kill -9the moment you seecalling record_line, while the server is sleeping. Resume it and watch forduplicate ignoredif the call had already landed.
python agent.py --run-id r3
# second terminal:
pkill -9 -f "agent.py --run-id r3"
# first terminal again:
python agent.py --run-id r3- Check the ledger. Every run must have exactly one row per item, whatever happened.
python -c "
import sqlite3
q = 'SELECT substr(idempotency_key, 1, 2), item, COUNT(*) FROM ledger GROUP BY 1, 2'
for row in sqlite3.connect('ledger.db').execute(q): print(row)"- Trip the step budget.
MAX_STEPS=2 python agent.py --run-id r4 # prints: stopped: step budget of 2 exhaustedCheck your work: runs r2 and r3 finish after resuming, the ledger shows a count of 1 for every run and item pair, and r4 ends with status budget_exceeded in checkpoints.db instead of looping.
Stretch: add a human approval pause. Mark record_line calls with a line_total above 10 as needing approval: save the run with status awaiting_approval, exit, and add an --approve flag that records the decision and resumes. Then port the loop to Temporal using the workflow sketch in this chapter.
Check yourself
An agent crashes after a refund tool succeeds but before the result is checkpointed. On resume it runs the refund again. What is the root-cause fix?
Why does a durable agent checkpoint the model's response instead of re-calling the model on resume?
Under the 2026-07-28 MCP specification, what lets a remote MCP server scale horizontally like an ordinary web service?
A team proposes five cooperating agents for a support bot that answers questions from a knowledge base. What is the strongest objection?
An agent's per-run cost has doubled since adding automatic summarization every turn, even though total tokens are similar. What is the likely cause?
Recap
- An agent is a state machine with one nondeterministic step; engineer everything around it as distributed-systems code.
- Tool calling is a message format: validate arguments, return errors as results and handle parallel calls.
- MCP standardizes tools, resources and prompts over stdio or Streamable HTTP, and its 2026-07-28 revision is stateless.
- Treat context as a budget, compact rarely and keep run state, memory and artifacts in durable stores.
- Durability rests on checkpoints, bounded retries, idempotent side effects and durable human approval pauses.
- Prefer one agent inside a deterministic workflow, isolate code execution properly and always enforce a step budget.
Go deeper
- Model Context Protocol specification, 2026-07-28: the authoritative protocol reference, including the changelog of the stateless revision.
- MCP Python SDK documentation: the v2 SDK used in the lab, with server, client and transport guides.
- Building effective agents (Anthropic): a practical catalogue of workflow and agent patterns and when each fits.
- Effective context engineering for AI agents (Anthropic): compaction, note-taking and sub-agent strategies for long runs.
- Temporal documentation: workflows, activities, signals and the replay model behind durable execution.