Sources: Anthropic tool use, handle tool calls and OpenAI function calling. Volatile: re-check field names.
What this means for architects
Under the hood: The agent loop as a state machine
Intuition
The ReAct paper by Yao et al. (arXiv 2210.03629; v3 is the ICLR camera-ready version) interleaves reasoning traces with actions. Strip the framing and an agent is a while loop: call the model, run the requested tool, append the result, repeat. Anthropic's loop continues while the stop reason is tool_use, so only the model decides when to stop.
Mechanism
Figure 6. States of one agent run
stateDiagram-v2
accTitle: Agent loop as a state machine
accDescr: A run starts in reasoning, where the model is called. A choice follows. A final text ends the run as answered. A tool request with budget left goes to validation, then to the policy check, then either straight to the tool or to an approval wait first. Invalid arguments, denials, rejections and tool results return to reasoning. A tool request with no budget left ends the run at the budget stop. A model failure ends it as failed. A kill switch or user cancel ends it as cancelled, and any non-terminal state may take that exit.
state Decide <>
[*] --> Reasoning
Reasoning --> Decide: model reply received
Reasoning --> Failed: model call fails after retry
Reasoning --> Cancelled: kill switch or user cancel
Decide --> Answered: final text
Decide --> Validating: tool request and budget left
Decide --> BudgetStop: tool request and no budget left
Validating --> PolicyCheck: arguments valid
Validating --> Reasoning: invalid, error returned to model
PolicyCheck --> ExecutingTool: allowed
PolicyCheck --> AwaitingApproval: approval required
PolicyCheck --> Reasoning: denied, error returned to model
AwaitingApproval --> ExecutingTool: approved
AwaitingApproval --> Reasoning: rejected or expired, error returned
AwaitingApproval --> Cancelled: kill switch or user cancel
ExecutingTool --> Reasoning: result or error returned
Answered --> [*]
BudgetStop --> [*]
Failed --> [*]
Cancelled --> [*]
note right of Cancelled: Every non-terminal state may take this exit, only two arrows are drawn
How to read this: boxes are states, arrows are conditions, the diamond is an instant choice and the note is an exit every state shares.
The ReAct paper shows why exits matter.
One model family, not a benchmark for current models: a loop has costs, and a fallback is part of the design.
Retries are the other hazard, since the model, the Orchestrator and the Tool server can each retry. Set layers to 3 and attempts to 3.
Check yourself: the model, the Orchestrator and the Tool server each try a failing write 3 times. How many attempts reach the ERP for one intended write?
27 (3 x 3 x 3). Each layer retries every failed call from the layer above, so the attempts multiply. Give one layer the retry and key the write.
What this means for architects
Under the hood: Context growth and compaction
Intuition
The API is stateless, so every iteration resends the prompt, schemas, task and all messages and results so far. Each step adds a roughly constant amount, so the total grows with the square of the steps. Anthropic's Effective context engineering for AI agents (published 2025-09-29) calls context a finite resource with an "attention budget".
Mechanism
Let S be the system prompt and tool schema tokens, U the task, a the tokens emitted per step and r the tokens per tool result. With nothing removed:
I(k) = S + U + (k - 1) * (a + r)
Total(N) = sum of I(k) for k = 1..N = N * (S + U) + (a + r) * N * (N - 1) / 2
Assumptions (illustrative, not measured): S + U = 3,500, a = 150, r = 1,200, so a + r = 1,350.
Doubling the steps from 20 to 40 multiplies total input by 1,193,000 / 326,500 = 3.65, not 2. Caching lowers the price per resent token, not the count.
Check yourself: with S + U = 3,500 and a + r = 1,350, how many input tokens does the 6th request carry?
10,250 (3,500 + 5 x 1,350). The 5th carries 8,900 in the table, and each step adds 1,350.
Three controls change the formula, shown at N = 40:
Figure 7. Compaction when the context nears its trigger
sequenceDiagram
accTitle: Compaction sequence
accDescr: Before each model call the Orchestrator counts input tokens. When the count passes the trigger it archives the full transcript to the Trace store, asks the model through the Model gateway to summarise the older turns, replaces those turns with the summary while keeping the latest turns and each tool call with its result, and continues. If the summarising call fails, it falls back to clearing old tool results, and if that is not enough it stops with a checkpoint.
autonumber
participant O as Orchestrator
participant TR as Trace store
participant M as Model gateway
participant L as LLM provider
Note over O: Count input tokens before the next call - 21,050 is over the 20,000 trigger
O->>TR: archive the full transcript unchanged
O->>M: summarise the older turns, keep decisions, ids and open questions
M->>L: model request
alt Summary returned
L-->>M: summary of about 1,500 tokens
M-->>O: summary
Note over O: Replace older turns with the summary, keep recent turns and call-result pairs
O->>M: next step request of about 5,000 tokens
else Summarising call fails
Note over O: Fall back to clearing old tool results, else stop with a checkpoint
end
How to read this: the top note is the trigger decision and the alt block shows success and the fallback.
What this means for architects
Under the hood: Memory tiers
Intuition
"Memory" names three things that fail differently. LangGraph's documentation draws the line: short-term memory remembers previous interactions "within a single thread or conversation", and long-term memory "stores user-specific or application-level data across sessions".
Mechanism
Spring AI separates chat memory, "the information that a large-language model retains and uses to maintain contextual awareness", from chat history, the entire conversation, for which memory "is not the best fit". Keep history whole as the audit record in the Trace store.
Anthropic's memory tool is one design: file operations on a /memories directory. "Claude requests file operations, and your application runs them." The safeguards are yours: reject paths that escape /memories, cap sizes, expire unused files, validate what is written.
Figure 8. Memory across a session
sequenceDiagram
accTitle: Memory tiers across a session
accDescr: At the start of a session the Orchestrator reads a bounded set of notes for this user from the Memory store. Each turn is appended to the Session store, and the working prompt is assembled from the notes, the recent turns and the new message. At the end the Orchestrator asks the model for candidate notes, the Policy engine decides whether each may be stored, and allowed notes are written with a source and an expiry.
autonumber
participant C as Client app
participant O as Orchestrator
participant S as Session store
participant MS as Memory store
participant P as Policy engine
participant M as Model gateway
C->>O: new session for user U
O->>MS: read notes for user U, at most 10 notes
MS-->>O: notes with source and age
loop Each turn
O->>S: append the turn
Note over O: Working memory - system prompt, notes, recent turns, new message
O->>M: model call
M-->>O: reply
end
O->>M: propose notes worth keeping
M-->>O: candidate notes
O->>P: may these notes be stored for user U?
P-->>O: allow, with sensitive items removed
O->>MS: write notes with source, expiry and owner
How to read this: the loop repeats once per turn, and the final write passes a policy decision first.
Check yourself: Figure 8 injects at most 10 notes at the start. If each is 80 tokens (illustrative), how many extra input tokens do they add over a 20-step run, before caching?
16,000 (10 x 80 x 20). The notes ride in every request, so memory is a fixed cost on every step, not a one-off.
What this means for architects
Under the hood: The MCP lifecycle
Intuition
MCP gives tool servers one wire format: JSON-RPC 2.0 with conventions on top. Revisions up to 2025-11-25 open with an initialize handshake. 2026-07-28 removes the handshake and sessions, so every request is self-contained. The versioning page names 2026-07-28 as current as of 2026-10-21.
Mechanism
JSON-RPC 2.0 in four rules (specification): a request has jsonrpc exactly "2.0", a method and an id, and the server replies with the same id (MCP forbids a null or still-pending id). A notification has no id and gets no reply. A response has result or error, never both. An error has an integer code (-32700 to -32603 are predefined, -32000 to -32099 reserved for servers) and a message.
In 2025-11-25 the client sends only pings until initialize is answered. Its first message, trimmed (the specification's example adds optional fields):
{
"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": { "roots": { "listChanged": true }, "sampling": {}, "elicitation": { "form": {}, "url": {} } },
"clientInfo": { "name": "ExampleClient", "title": "Example Client Display Name", "version": "1.0.0" }
}
}
Figure 9. MCP lifecycle, revision 2025-11-25
sequenceDiagram
accTitle: MCP lifecycle in revision 2025-11-25
accDescr: The Orchestrator, acting as MCP client, sends an initialize request with its version, capabilities and identity. The Tool server replies with the agreed version and its capabilities. The client sends the initialized notification. During operation the client lists tools and calls a tool. If the server does not support the requested version it answers with another version it supports, or an error, and the client disconnects if it cannot use that version. Shutdown has no message and uses the transport.
autonumber
participant O as Orchestrator (MCP client)
participant T as Tool server (MCP server)
O->>T: initialize request with protocolVersion, capabilities, clientInfo
alt Version supported
T-->>O: initialize result with protocolVersion, capabilities, serverInfo
O-)T: notifications/initialized (no id, no reply)
O->>T: tools/list
T-->>O: tools with name, description, inputSchema
O->>T: tools/call with name and arguments
T-->>O: content, isError
Note over O,T: Shutdown has no message - close stdin on stdio or close the HTTP connection
else Version not supported
T-->>O: initialize result with another supported protocolVersion, or an error such as -32602 with data.supported
Note over O: Client disconnects if it cannot use that version
end
How to read this: the first four arrows are initialisation, the rest operation, and the alt block is a version mismatch.
In 2026-07-28, protocolVersion and clientCapabilities in _meta are required on every request, and results carry a resultType. clientInfo and serverInfo are self-reported and not for security decisions. This tools/call pair adds the _meta block that the specification's examples omit for brevity. The tool issues_search is an example for this page.
{
"jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": {
"name": "issues_search",
"arguments": { "query": "timeout" },
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": { "name": "ExampleClient", "version": "1.0.0" },
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}
{
"jsonrpc": "2.0", "id": 3,
"result": {
"resultType": "complete",
"content": [ { "type": "text", "text": "3 issues match: #412, #397, #388" } ],
"isError": false
}
}
Figure 10. MCP lifecycle, revision 2026-07-28
sequenceDiagram
accTitle: MCP lifecycle in revision 2026-07-28
accDescr: The Orchestrator, acting as MCP client, optionally calls server/discover and receives supported versions and capabilities. It then sends tools/list and tools/call, each carrying the protocol version and client capabilities in its metadata. If the version is not supported the server returns an unsupported-protocol-version error listing supported versions and the client retries with one of them. A tool failure comes back as a result with isError true, while an unknown tool is a protocol error.
autonumber
participant O as Orchestrator (MCP client)
participant T as Tool server (MCP server)
opt Client wants versions and capabilities up front
O->>T: server/discover with _meta
T-->>O: supportedVersions, capabilities, serverInfo, ttlMs
end
O->>T: tools/list with _meta
alt Version supported
T-->>O: tools with inputSchema, ttlMs, cacheScope
O->>T: tools/call with name, arguments and _meta
alt Tool ran
T-->>O: result with content and isError false or true
else Unknown tool or malformed request
T-->>O: JSON-RPC error -32602
end
else Version not supported
T-->>O: error -32022 with supported versions
Note over O: Retry with a mutually supported version
end
How to read this: the opt block is optional discovery, and the alt blocks show the version check and two kinds of tool failure.
MCP has two standard transports. With stdio the client launches the server as a subprocess and exchanges newline-delimited JSON-RPC. With Streamable HTTP every client message is its own POST to one endpoint, answered with a JSON object or a request-scoped SSE stream.
In 2026-07-28 each POST must also carry Mcp-Method (and Mcp-Name for tools/call, resources/read and prompts/get) beside MCP-Protocol-Version, which 2025-11-25 already required after initialization. Gateways can then route without parsing the body.
POST /mcp HTTP/1.1
Content-Type: application/json
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: issues_search
Both revisions require Origin validation on Streamable HTTP (403 if invalid).
Per the specification's compatibility matrix, a modern client fails against a legacy server and the reverse; only dual-era clients work against both. Step through their stdio probe.
Check yourself: a legacy server receives server/discover on stdio. What does the client conclude, and what does it send next?
An error that is not a recognised modern one (a modern version error such as -32022 means a modern server, so it retries with a listed version), or no reply in time, means a legacy server, so it falls back to initialize.
What this means for architects
Decision framework
Figure 11. Which controls does a new capability need?
flowchart TD
accTitle: Which controls a new agent capability needs
accDescr: A decision tree. If the steps are known before the request arrives, write a workflow. Otherwise ask in turn whether a tool can do something irreversible, whether a result can be large, whether tools come from servers you do not run, and whether facts are needed across conversations, adding the matching control for each yes. Every agent loop finishes with three caps on model calls, tokens and wall-clock time.
A{"Steps known before the request arrives?"} -->|"yes"| A1["Workflow in code, model only for language steps"]
A -->|"no"| B{"Can a tool change something that cannot be undone?"}
B -->|"yes"| B1["Idempotency key, policy decision, approval above a limit"]
B -->|"no"| C
B1 --> C{"Can a tool result be large?"}
C -->|"yes"| C1["Paginate, filter, truncate or return a handle"]
C -->|"no"| D
C1 --> D{"Tools from servers you do not run?"}
D -->|"yes"| D1["Allow-list, pin versions, prefix names, treat as untrusted"]
D -->|"no"| E
D1 --> E{"Facts needed across conversations?"}
E -->|"yes"| E1["Scoped long-term memory with policy-checked expiring writes"]
E -->|"no"| F
E1 --> F["Cap model calls, tokens and wall-clock time"]
How to read this: only the first question skips the loop, and each later yes adds one control.
Comparison of the main options
Failure scenarios to design for
Which control stops each of these?
Worked example
A fixed workflow against an agent loop for one invoice, using the formulas above. Assumptions (illustrative, not measurements):
- S + U = 3,500 tokens, a = 150, r = 1,200.
- The workflow makes 3 model calls (extract, check, compose), each with a fresh 3,500 + 1,200 = 4,700 input tokens.
- The agent needs N = 8 iterations and is capped at 12.
- A model call takes 3.0 s and a tool call 0.5 s: 3 tool calls in the workflow, one per iteration in the agent.
- Each step succeeds with probability 0.97 independently, a simplification.
The loop costs 4.7 to 9.3 times the input tokens, 2.7 to 4.0 times the latency and succeeds less often. For a known shape that is not worth it: use the workflow for the common path and a bounded loop (12 steps, approval on posting) for the exception queue.
Standard library only, 33 lines: strict validation, a role check in code, an approval bound to the exact call and an idempotency key.
import hashlib, json
SCHEMA = {"invoice_id": str, "amount_cents": int, "idempotency_key": str}
APPROVAL_ABOVE_CENTS = 500_000
posted = {}
def error(msg, **extra):
return {"is_error": True, "content": msg, **extra}
def validate(args):
if not isinstance(args, dict) or set(args) != set(SCHEMA):
return f"arguments must be exactly {sorted(SCHEMA)}"
for name, typ in SCHEMA.items():
if not isinstance(args[name], typ) or isinstance(args[name], bool):
return f"{name} must be of type {typ.__name__}"
return None if args["amount_cents"] > 0 else "amount_cents must be positive"
def call_id(name, args):
return hashlib.sha256(json.dumps([name, args], sort_keys=True).encode()).hexdigest()[:16]
def dispatch(name, args, user_roles, approved_ids):
if name != "erp_post_invoice":
return error(f"unknown tool {name}")
if (problem := validate(args)):
return error(problem)
if "ap_clerk" not in user_roles:
return error("denied: caller may not post invoices")
cid = call_id(name, args)
if args["amount_cents"] > APPROVAL_ABOVE_CENTS and cid not in approved_ids:
return error("approval required", approval_id=cid)
key = args["idempotency_key"]
posted.setdefault(key, {"status": "posted", "invoice_id": args["invoice_id"]})
return {"is_error": False, "content": posted[key]}
Run results: a first call with 120,000 cents posts and a repeat returns the same result. A string amount, boolean amount, extra key, negative amount and unknown tool each return a tool error, and a caller without ap_clerk is denied. A call for 900,000 cents needs an approval id, and a changed amount of 950,000 with the same id is refused.
Limits: posted is process-local and not concurrency-safe (use a unique constraint on the key), and a repeated key with a different payload should be rejected.
Common mistakes
- Starting with a loop because the demo works. Draw Figure 2 and write the exits first.
- Putting permission rules in the system prompt. Enforce identity, limits and approvals in code.
- Returning whole records from tools. Return what the task needs, or an id and a summary.
- Retrying writes without an idempotency key. Three layers may each retry a timed-out write.
- Trimming history across a call and its result. The window turns a context problem into a 400 error.
- Assuming "MCP" means one lifecycle. A handshake client fails against a stateless server and the reverse.
Try it
Time: 30 to 40 minutes. You need Python 3.8 or later.
- Run the dispatcher with the cases above and add one case that should be refused.
- Wrap it in a loop with a scripted fake model and a step cap that reports
answered or budget_stop. Test it with a script that never finishes.
- Compute
Total(N) for your agent at N = 5, 10 and 20 (S, U and r from the token counter).
Done when the dispatcher cases give the outcomes described, your loop stops at its budget with the reason reported, and you can state the token total for your agent at N = 20 and the formula behind it.
Key takeaways
- An agent is a loop around a model call; choose it only when the steps cannot be written down in advance.
- A tool call is a request your code runs: validate, decide policy and approve irreversible actions outside the model.
- Make the loop a state machine: three budgets, explicit exits, one audit event per terminal state.
- Input tokens grow with the square of the steps: shrink tool results first, then clear, trim or compact.
- MCP is JSON-RPC 2.0. Clients must handle both the 2025-11-25 handshake and the stateless 2026-07-28 revision, and third-party tool text stays untrusted.
Self-check
1. A task has four known steps and needs a model only to extract fields from a document. Should it be an agent loop?
No. The steps are known, so the control flow belongs in code with the model as one step. A loop adds latency, cost and a lower compound success rate for no needed flexibility.
2. The model replies with a tool call. Has anything run yet, and what must your code do before running it?
Nothing has run. Your code validates the arguments, makes the policy decision, requires approval if the action is irreversible, and only then calls the tool.
3. With S + U = 3,500, a = 150 and r = 1,200, what is the 10th request's input, and why does 40 steps cost more than twice 20?
I(10) = 3,500 + 9 x 1,350 = 15,650 tokens. The history is resent, so the total has an N squared term: 1,193,000 against 326,500, a ratio of 3.65.
4. What are the two kinds of tool failure in MCP, and which should the model see?
A protocol error is a JSON-RPC error object. A tool execution error is a normal result with isError true, and clients should give it to the model so it can correct itself.
5. A 2025-11-25 client connects to a server that implements only 2026-07-28. What happens, and how does a dual-era client avoid it?
It fails: the server has no initialize method and expects per-request metadata. A dual-era client probes first (server/discover on stdio) and falls back to initialize only if the server does not answer in the modern way.
Further reading
Last verified: 2026-10-22
Next
Continue with page 7, multi-agent and event-driven AI architecture, where agents run asynchronously, share work through an event bus and need idempotency, outbox and saga patterns.