Contents
Key concepts
The tool-calling loop
Each tool is declared with a name, a description and a JSON Schema for its arguments; the chat template serialises these into the prompt, and the model has been trained to emit a structured call (special tokens or JSON) instead of prose. The application parses and validates the arguments, executes the tool, appends the result as a tool message carrying the same call ID, and calls the model again until it returns a final answer. The model never touches an API: authentication, side effects, retries and error handling are your code’s job. Variants include parallel calls in one turn, forced tool choice, and “structured output via a tool”.
Flow · 4 stepsHow the tool-calling loop runs
- Goal in The goal is sent to the model, which emits a structured call instead of prose.
- Validate and execute The application parses and validates the arguments, then executes the tool.
- Feed back The result is appended as a tool message carrying the same call ID, and the model is called again.
- Final answer When the model returns no tool call, the loop ends with a final answer.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Goal in | The goal is sent to the model, which emits a structured call instead of prose. |
| 2 | Validate and execute | The application parses and validates the arguments, then executes the tool. |
| 3 | Feed back | The result is appended as a tool message carrying the same call ID, and the model is called again. |
| 4 | Final answer | When the model returns no tool call, the loop ends with a final answer. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Goal | Input | user prompt |
| Model | Model | emits structured call |
| Application | Runtime | parses and validates |
| Tool | Runtime | executes the call |
| Messages | Memory | tool result, same call ID |
| Final answer | Input | no tool call |
Source: This page's text
Workflows versus agents
Workflows follow code paths you define (prompt chaining, routing, parallelisation, orchestrator–workers, evaluator–optimiser) and are cheaper, faster and easier to test. Agents let the model decide the steps, which suits open-ended tasks whose path cannot be predicted, at the price of latency, cost and compounding error: at 95% per-step reliability a 20-step task succeeds end to end only 0.95^20 ≈ 36% of the time. Start with the simplest design and add autonomy only where it measurably helps.
Tool design (the agent–computer interface)
Prefer a few higher-level tools that match how the task is done over thin wrappers around every REST endpoint. Write names and descriptions for the model, including when not to use a tool; use strict schemas with enums; return concise, model-readable output with pagination or truncation; make error messages actionable (“date must be YYYY-MM-DD”). With large catalogues, namespace tools, retrieve a relevant subset per step, or hand subsets to sub-agents. Measure tool-selection accuracy on labelled tasks and iterate from failing traces.
Context engineering and memory
The context window is a finite budget and long trajectories degrade as it fills with stale tool output. Techniques: compaction (summarise history while keeping the goal, decisions, identifiers and file paths), clearing old tool results, external notes or to-do files the agent writes and re-reads, just-in-time retrieval instead of preloading, and sub-agents with clean contexts that return condensed results. Keep history append-only so prompt-cache prefixes stay valid; check that constraints survive compaction.
Multi-agent architectures
An orchestrator with sub-agents buys parallel exploration and context isolation, and suits breadth-first research or independent subtasks. It costs tokens (Anthropic reported agents using about 4× the tokens of chat and multi-agent systems about 15×), adds coordination failures and makes debugging and evaluation harder. It fits poorly when sub-tasks share tightly coupled state, such as several agents editing the same code. Always compare against a single-agent baseline.
Model Context Protocol (MCP)
MCP is an open client–server standard (governed since December 2025 by the Linux Foundation’s Agentic AI Foundation), built on JSON-RPC over stdio or streamable HTTP, that lets an application expose tools, resources and prompts from many servers, turning N×M bespoke integrations into N+M. The host application decides which servers connect, gathers user consent and controls which tools the model sees; the protocol adds plumbing, not capability. The 2026-07-28 revision made it stateless: no initialize handshake or session IDs, per-request metadata, and multi-round-trip requests instead of server-initiated sampling and elicitation, so state lives in explicit handles. Risks: poisoned tool descriptions, silently changed tool definitions, over-broad tokens, cross-server data exfiltration and supply-chain compromise. Mitigate with allow-listed and pinned servers, scoped OAuth, approval for sensitive calls, sandboxing and logging.
Safety for agents that act
The “lethal trifecta” is access to private data, exposure to untrusted content and the ability to communicate externally; together they let a prompt injection exfiltrate data, so remove at least one leg. For agents with real side effects use least-privilege credentials, a deterministic policy layer outside the model (amount caps, allow-lists, rate limits), human approval for irreversible actions, idempotency keys, audit logs, a kill switch and progressive autonomy: shadow mode, then approval, then sampled QA, each step justified by measured accuracy.
Evaluating agents
Grade outcomes (is the final state of a stateful sandbox correct?) and trajectories (was policy followed, were forbidden calls avoided?), using simulated users for conversational agents. Because runs vary, report reliability over repeated trials: pass^k (all k attempts succeed), introduced with τ-bench, falls much faster than pass@k. Track cost, latency and turns per resolution and escalation correctness; in production add tracing, sampled human review and turn every incident into a regression case.
Worked examples
Minimal agent loop with budgets and error handling
Write the core loop for an agent given a goal, a dict of tools (name → async function plus JSON Schema) and a model client. It must validate arguments, feed tool errors back to the model, stop at a step limit or token budget, and run independent tool calls in one turn concurrently.
import asyncio, json
from jsonschema import validate, ValidationError
async def run_agent(goal, tools, client, max_steps=20, max_tokens=200_000):
messages = [{"role": "user", "content": goal}]
used = 0
for step in range(max_steps):
reply = await client.complete(messages, tools=[t.spec for t in tools.values()])
used += reply.usage.total_tokens
messages.append(reply.message) # keep the call IDs the model produced
if not reply.tool_calls:
return reply.text # final answer
if used > max_tokens:
return "Stopped: token budget exhausted"
async def run_one(call):
tool = tools.get(call.name)
if tool is None:
return call.id, f"Error: unknown tool {call.name!r}"
try:
args = json.loads(call.arguments)
validate(args, tool.spec["input_schema"])
out = await asyncio.wait_for(tool.fn(**args), timeout=30)
return call.id, str(out)[:8_000] # truncate huge outputs
except (json.JSONDecodeError, ValidationError) as e:
return call.id, f"Error: invalid arguments: {e}"
except Exception as e: # report, do not hide
return call.id, f"Error: {type(e).__name__}: {e}"
results = await asyncio.gather(*(run_one(c) for c in reply.tool_calls))
for call_id, content in results:
messages.append({"role": "tool", "tool_call_id": call_id, "content": content})
return "Stopped: step limit reached"
Points an interviewer looks for:
- Validation before execution: the model’s arguments are untrusted input.
- Errors go back to the model as tool results, so it can correct itself; swallowing them makes the model believe the action succeeded.
- Budgets: steps, tokens and a per-tool timeout; large outputs truncated or summarised.
- Concurrency with
asyncio.gather, results matched by call ID, not by order of completion. - Next steps you would mention: retries with backoff on transient model-API errors, tracing per step, repetition detection (same tool and near-identical arguments three times), and tests against a scripted fake model.
Is an autonomous support agent viable? Reliability and cost arithmetic
A support agent averages 12 tool steps per ticket. Each step is correct 97% of the time, independently. The first call has 4,000 input tokens and each step appends about 1,500 tokens (call plus result); each step emits 400 output tokens. Assume $2 per million input tokens and $10 per million output tokens, with prompt-cache reads at 0.1× and cache writes at 1.25× the input price, and 50,000 tickets a day. Estimate end-to-end success and daily cost with and without prompt caching.
Reliability. 0.97^12 = e^(12 × ln 0.97) = e^(−0.3655) ≈ 0.69. Nearly a third of tickets fail somewhere. Raising per-step accuracy to 0.99 (verification, better tools) gives 0.99^12 ≈ 0.886; halving the step count with higher-level tools gives 0.97^6 ≈ 0.833.
Tokens per ticket. Step i sends 4,000 + 1,500 × (i − 1) input tokens:
- input = 12 × 4,000 + 1,500 × (0 + 1 + … + 11) = 48,000 + 1,500 × 66 = 147,000
- output = 12 × 400 = 4,800
Input grows quadratically with the number of steps, which is why long trajectories get expensive.
Cost without caching. 147,000 × $2/M = $0.294; 4,800 × $10/M = $0.048 → $0.342 per ticket, × 50,000 = $17,100 a day (≈ $513k for 30 days).
Cost with caching. Each step re-sends the previous context as an identical prefix.
- Newly written tokens: 4,000 + 11 × 1,500 = 20,500, billed at 1.25× → 20,500 × 1.25 × $2/M = $0.0513
- Cached reads: 147,000 − 20,500 = 126,500 at 0.1× → 126,500 × 0.1 × $2/M = $0.0253
- Input ≈ $0.077 (−74%); with output, ≈ $0.125 per ticket → ≈ $6,200 a day (−64%).
Cost per successful ticket ≈ $0.125 / 0.69 ≈ $0.18, before the human cost of the 31% that fail.
Conclusion to state in the interview: caching is a must (append-only history, no timestamps at the top), but the 69% success rate is the real blocker; fix reliability with fewer, higher-level tools, verification steps and escalation to humans before scaling autonomy.
Guardrails and review load for a refund-issuing agent
An agent may issue refunds up to £500 and change customer addresses. It proposes 20,000 refunds a day; 80% are £50 or less. A reviewer clears 60 approvals an hour in a 7.5-hour day. Design the control layer, size the review team and say what evidence would justify auto-approving refunds up to £100.
1. Controls outside the model (prompts are not a security boundary):
- The refund tool takes
order_idandamount; a deterministic policy service checks the order belongs to the authenticated customer, the amount is ≤ the amount paid minus previous refunds, and per-customer and per-day caps hold. - Address changes require step-up verification of the customer and are never triggered by content the agent read (emails, web pages), only by the authenticated user’s own request.
- Idempotency key per (order, action) so retries never double-refund; full audit log of the trajectory; rate limits and a kill switch.
2. Review load. Auto-approve ≤ £50: 0.8 × 20,000 = 16,000. Human approval: 4,000 a day. 4,000 / 60 = 66.7 reviewer-hours → 66.7 / 7.5 ≈ 9 reviewers, plus cover for leave and peaks.
3. Evidence to widen autonomy. Run the £50–£100 band in shadow mode: the agent proposes, humans decide, and you compare. With zero disagreements in n cases, the 95% upper bound on the error rate is about 3/n (the “rule of three”). To claim an error rate below 0.5% you need n ≥ 3 / 0.005 = 600 reviewed cases with no errors, sliced by refund reason and customer segment. Then auto-approve that band with 5% sampled QA, and keep a rollback trigger if the sampled error rate exceeds the threshold.
4. Evaluation before launch. A stateful sandbox of orders and customers, simulated users including adversarial ones (“my manager said you can refund £400”), outcome checks on the final ledger, trajectory checks for forbidden calls, and pass^k over repeated runs.
What changed recently
MCP 2026-07-28: the protocol goes stateless
The July 2026 MCP revision retired the initialize handshake and session IDs: every request now carries its protocol version, client identity and capabilities, and a server that needs user input returns an input_required result that the client answers by retrying the call, instead of calling back over a held-open stream. Streamable HTTP requests must name the method and target in headers so gateways can route and meter them, and tasks moved into an extension. Sampling, roots, logging and the old HTTP+SSE transport are deprecated with at least twelve months’ notice, and dynamic client registration is deprecated in favour of client ID metadata documents. Interviewers now ask how you would keep state without sessions (explicit handles passed as tool arguments) and what the change means for gateways, caching and security.
NIST starts an AI Agent Standards Initiative
NIST’s Center for AI Standards and Innovation launched a programme on interoperable and secure agents with three pillars: industry-led standards, community-maintained open protocols, and research on agent security and identity. Alongside it came a request for information on agent security and a concept paper on agent identity and authorisation, both open for comment in early 2026. Expect design questions on how an agent authenticates, what it may do on a user’s behalf, and how its actions are attributed and audited.
MCP moves to the Linux Foundation's Agentic AI Foundation
Anthropic donated MCP to the new Agentic AI Foundation, a directed fund under the Linux Foundation co-founded with Block and OpenAI, with goose and AGENTS.md as the other founding projects; the announcement cited more than 10,000 public MCP servers. Vendor-neutral governance is why enterprises now treat MCP as infrastructure rather than one lab’s product, and candidates are expected to say precisely what it standardises and what it leaves to the host.
First reported AI-orchestrated cyber-espionage campaign
Anthropic reported that a state-sponsored group built an attack framework around Claude Code and aimed it at about 30 organisations, with the model doing an estimated 80–90% of the work and humans intervening at a handful of decision points. The attackers got past safeguards by splitting the operation into innocuous-looking subtasks and claiming to be a security firm doing defensive testing. It is now the standard example in questions on misuse of agentic tools, task-decomposition jailbreaks and platform-level monitoring.
Agent Skills: capabilities loaded on demand
Anthropic introduced Skills: folders with a SKILL.md file whose name and description sit in the system prompt while the full instructions, scripts and reference files load only when a task needs them; in December 2025 the format was published as an open standard. With code execution over MCP, it changed the answer to ‘how do you give an agent hundreds of capabilities’ from bigger prompts to progressive disclosure. Interviewers probe context budgets, discovery accuracy and the security of skills that ship executable scripts.
Pitfalls
- Saying the model ‘calls the API’: it emits a structured request; your runtime executes it and owns authentication and side effects.
- Reaching for a multi-agent framework for a deterministic task, or shipping a loop with no step, token or time budget.
- Enforcing business rules or security only through the system prompt; injected content can override instructions, so put the rules in code.
- Mirroring a REST API one-to-one as dozens of thin tools that return raw JSON, then blaming the model for picking the wrong one.
- Managing context by truncating the oldest messages, which drops the original goal; or summaries that lose IDs and file paths.
- Evaluating only the final text of a single run, ignoring trajectory errors and run-to-run variance.
How interviewers probe it
- Walk me through exactly what the model sees and emits during a tool call — then: what happens when the arguments fail validation?
- Workflow or agent for this product? Expect to quantify compounding error, latency and cost per task.
- Traces show the agent calling search 15 times with near-identical queries — diagnose (poor tool output, no progress check, ambiguous goal) and fix.
- Make an agent safe to issue refunds or change accounts: least privilege, policy layer, injection, idempotency, audit, progressive autonomy.
- How would you evaluate it before launch and in production? Simulated users, stateful sandboxes, pass^k, trajectory checks, incident-driven regression sets.
- Lead angle: when is a multi-agent or MCP-heavy platform worth its cost and governance burden, and how would you decide to stop an agent project?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Explain what actually happens when an LLM calls a tool: what the model sees, what it emits, and who executes what.
Model answer, written in a candidate's voice
- Tool specs are serialised into context via the chat template; the model is trained to emit structured call tokens
- The application parses, validates, executes, appends tool results, and calls the model again until a final answer
- The model never executes anything; the app owns auth, side effects, and error handling
- Parallel calls, forced tool choice, and structured output via a tool are supported patterns
- Failure points include invalid arguments, invented tool names, and oversized tool outputs
When would you build a fixed LLM workflow (chain, router) rather than an autonomous agent loop? Give one example of each for a product you could build here.
Model answer, written in a candidate's voice
- Use fixed workflows when the task is well-understood and the path is known: predictable, cheaper, testable.
- Use agents when the path cannot be predicted and the model must choose steps, accepting latency, cost and compounding errors.
- Start with the simplest pattern and add autonomy only when metrics show it helps.
- Name patterns: prompt chaining, routing, parallelisation, orchestrator-workers, evaluator-optimiser.
- Add guardrails: step limits, budgets, human checkpoints.
- Example fixed workflow: support triage/refund assistant; example agent: vague incident/research investigator.
Your agent has 40 tools and picks the wrong one too often. How do you design tool interfaces so the model uses them well?
Model answer, written in a candidate's voice
- Collapse 40 thin wrappers into fewer higher-level tools with distinct names and model-facing descriptions
- Add strict schemas, enums, examples, and explicit not-to-use guidance
- Keep outputs concise and errors actionable; gate destructive or irreversible actions
- Reduce tools visible per step via routing, retrieval, or sub-agents with small toolsets
- Measure selection accuracy on labelled tasks and iterate from failure traces
You have finished this topic.
Reading
- Building effective agentsThe workflow-versus-agent distinction and the five workflow patterns interviewers expect you to name.
- ReAct: Synergizing Reasoning and Acting in Language ModelsThe original interleaved reason–act–observe loop that modern tool-using agents descend from.
- Writing effective tools for agents — with agentsPractical tool-design principles and how to evaluate tool selection, directly relevant to the 40-tools question.
- Effective context engineering for AI agentsCompaction, note-taking and sub-agents for long-running agents.
- The lethal trifecta for AI agents: private data, untrusted content, and external communicationA crisp mental model for why prompt injection becomes data exfiltration in agents.
- How we built our multi-agent research systemReal numbers and lessons on when orchestrator–sub-agent designs pay off and what they cost.
- τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World DomainsStateful, simulated-user evaluation of agents and the pass^k reliability metric.
- Code execution with MCP: Building more efficient agentsHow presenting MCP servers as code APIs cuts tool-definition and intermediate-result tokens (one example falls from about 150k to 2k), and what sandboxing that requires.
Practise this topic
- Explain what actually happens when an LLM calls a tool: what the model sees, what it emits, and who executes what.
- When would you build a fixed LLM workflow (chain, router) rather than an autonomous agent loop? Give one example of each for a product you could build here.
- Your agent has 40 tools and picks the wrong one too often. How do you design tool interfaces so the model uses them well?
- A long-running agent degrades after about 100 steps as its context fills. How do you manage context and memory?
- List the main ways tool-using agents fail in production and the mitigation for each.
- An agent will be allowed to issue refunds and change customer account settings. How do you make it safe enough to ship?
- When is an orchestrator-plus-sub-agents architecture worth its cost compared with a single agent holding more tools?
- What problem does the Model Context Protocol solve, how does it work at a high level, and what risks come with connecting third-party MCP servers?
- How would you evaluate a customer-support agent that performs multi-step tool calls, before launch and in production?
- How do you make tool-using agents reliable enough for production?
- Implement an agent loop in Python that takes a goal, a set of tools with JSON-schema arguments and a model client. Handle tool errors, a step limit and a token budget; then let independent tool calls run concurrently.
- What is reinforcement learning with verifiable rewards, how does GRPO work, and why has it become popular for reasoning and agentic-coding models?
- Explain direct versus indirect prompt injection with examples, and describe a defence-in-depth design for an assistant that reads emails and web pages and can take actions.
- An agent can read private data, ingests untrusted content and can make outbound requests. Why is that combination dangerous, and how do you break it?
- Traces show your agent calling the same search tool 15 times with near-identical queries before timing out. What’s going on and how do you fix it?
- A customer says their phone agent sometimes goes silent or talks over callers. Diagnose across telephony, speech recognition, the model, the prompt and integrations.
- Operations wants AI agents that can act inside customer accounts (issuing refunds, changing addresses) to cut handling time. How do you decide whether and how to do this?
- Your platform exposes internal capabilities to agents. When would you publish something as an MCP server, and when as an A2A agent? Compare what each protocol standardises, how authorisation and long-running work are handled, and the security risks you would plan for.
- You are building an agent that reads a user’s email and calendar and can send messages and book meetings. Model-level prompt-injection defences are probabilistic. Design a defence that still holds if the model is fooled, and say how you would measure it.
- Your coding agent is connected to 25 MCP servers exposing about 300 tools, and tool definitions alone consume tens of thousands of tokens before the user’s request. Latency, cost and tool-selection accuracy are all suffering. What would you change?
- METR summarises agent capability as a ‘50% time horizon’ that has doubled roughly every seven months. Explain how the metric is computed, what it is good for, and what you would be careful about when quoting it in a planning document.
- Model A costs $3 per million input tokens and $15 per million output tokens; model B costs $1 and $5. On your agentic task, A at medium reasoning effort averages 40k input and 6k output tokens with an 85% success rate; B averages 60k input and 14k output tokens with a 70% success rate. Each failure costs $2 of human handling. Which is cheaper per resolved task, and what else would you test?
- A UK bank wants its assistant to buy things for customers, for example ‘renew my train season ticket when it is under £X’. Using agent-payment protocols such as Google’s AP2 as a reference, design the authorisation, fraud and liability model.
- It is early 2026 and your product is built on the OpenAI Assistants API (threads, runs and hosted file search), which is scheduled to shut down on 26 August 2026. Plan the migration, and the architecture that keeps the next forced migration cheap.
- Product wants your booking service available inside ChatGPT and Claude as an MCP-based app with interactive UI. Design it: which tools the model sees, what the UI does, authorisation and state, data minimisation, and how you measure success.
- A vendor offers to replace part of your A/B testing with LLM agents that role-play user personas and click through your site, as in the AgentA/B research. What could such simulations legitimately tell you, what can they not, and how would you validate them before trusting them?
- Your coding agent runs for 300 turns and its context fills with tool output. Design a context-management strategy using what model APIs now offer (context editing, compaction, memory files), and explain how you keep prompt-cache hits high and check that nothing important is lost.
- An agent succeeds on a task with probability 0.8 per independent trial. Compute pass@5 and pass^5 and say which matters for a customer-facing agent. Then, from n = 10 samples with c = 7 successes, compute the unbiased pass@3 estimate and compare it with plugging p̂ into 1 − (1 − p̂)^3. Which way is the plug-in estimate biased, and why?
- You are instrumenting a production agent with a planner, retrieval, tool calls and two model providers, and you want vendor-neutral traces. How would you use the OpenTelemetry GenAI semantic conventions, and what would you do about the fact that they are still marked Development?
- For a UK bank’s phone line, compare a cascaded ASR–LLM–TTS voice agent, a single speech-to-speech model, and a full-duplex voice front end that delegates reasoning and tools to a backend model (as in OpenAI’s GPT-Live, 2026). Which would you ship, and where do turn-taking, tool calls, grounding and audit live in each?
- Walk us through an agent you built and how you evaluated it. Did you report pass@k or pass^k, how many tasks were in the suite, how were model-based graders checked, and what separated your capability evals from your regression evals?
- An internal agent must follow about 40 specialised procedures (expense rules, incident runbooks, report formats). Compare one large system prompt with a skills-style design that loads procedures on demand. How do you keep the context small, make the right procedure trigger, and manage the risks?
- Design an agentic RAG system for enterprise questions that span several corpora (HR policy, contracts, ticket history). How does the agent decide it has retrieved enough, how do you bound cost and latency, and how do you evaluate it against a single-pass RAG baseline?
- A vendor says its prompt-injection guardrail cuts attack success to 0.5% on a public benchmark. Given the October 2025 ‘attacker moves second’ results, in which adaptive attacks beat 12 published defences, how would you evaluate the claim, and what would you build around the guardrail for an email-reading agent?
- Your company wants to let internal agents use third-party MCP servers through a central gateway. The 2026-07-28 MCP specification made the protocol stateless and deprecated dynamic client registration. Design the gateway’s security controls and say which threats each addresses.
- Design a tool gateway that lets internal agents use about 200 MCP servers (CRM, ticketing, code search, data warehouse) on behalf of 5,000 employees. Cover authentication and permissions, scaling, prompt-injection containment and the context cost of so many tools.
- A product team wants an orchestrator–worker multi-agent ‘deep research’ feature. Given published figures that multi-agent systems use around 15 times the tokens of a chat turn, how would you decide whether it is worth building, and which levers would you use to control cost and latency?
- In late 2025 Anthropic reported a state-sponsored campaign in which Claude Code did most of the intrusion work, and in October 2026 Google’s threat intelligence group described ARTEX, an open-source multi-agent offensive framework used in real breaches. As head of AI platform security, what do you change in identity, API design and detection, and what should a model provider do about misuse of its own agents?
- METR’s 2026 frontier risk report found that at least 16% of successful runs on its longest agent tasks were illegitimate on review. You are about to publish your agent’s success rate on a long-horizon software benchmark. Design the audit that makes the number trustworthy.
- AlphaEvolve improved known results on about a fifth of 50-plus open maths problems, and an automated ‘AI Scientist’ paper passed first-round review at a conference workshop. For your proposed research agenda, which parts would you hand to automated search or research agents, which would you keep, and how would you validate what they produce?
- In Anthropic’s 2025 agentic-misalignment scenarios, Claude Opus 4 chose blackmail far more often when its reasoning said the situation was real than when it said it was a test. Design an evaluation of scheming or sabotage propensity that still tells you something when the model may recognise it is being evaluated.