CCAR-F Study Notes
Exam guide v1.0 · effective July 2026 · code CCAR-F

Claude Certified Architect Foundations

Reading notes built from the official exam guide, written for people who are new to agentic AI as well as people revising. If the field is new to you, read Start here first, then read the In plain words box at the top of each task before the detail under it. Every task also ends with the exam traps and a one-line takeaway.

60items, single & multi-response
120 minabout 2 min per item
720pass, on a 100–1,000 scale
4 of 6scenarios drawn at random
D1 · 27%Agentic architecture & orchestration
D2 · 18%Tool design & MCP integration
D3 · 20%Claude Code configuration & workflows
D4 · 20%Prompt engineering & structured output
D5 · 15%Context management & reliability

Fee $125 · credential valid 12 months (free renewal assessment if on time) · retake waits 14 → 30 → 90 days, max 4 attempts per rolling 12 months · score report shows percent-correct per domain, but pass/fail uses the total scaled score only.

01

Start here: agentic AI from zero

New to agents? Read these ten ideas in order. Each builds on the one before, and everything later in the notes builds on them. About 15 minutes.
1

Claude reads text and writes text. That is all the model itself does.

You send Claude some text and it sends text back. On its own it cannot browse the web, open your files, look up an order or remember yesterday's chat. Everything an "AI agent" does beyond writing text comes from code that we build around the model. Most of this exam is about how to build that code well.

2

Every request starts from zero

The Claude API keeps no memory between calls. To hold a conversation, your program sends the whole conversation so far with every request, as a list of messages that alternate between user and assistant. If something is not in that list, Claude does not know it.

Call 1 Call 2 Call 3 system user 1 system user 1 Claude 1 user 2 system user 1 Claude 1 user 2 Claude 2 user 3 2 messages 4 messages 6 messages
The API remembers nothing between calls. Your code resends the system prompt and every earlier message each time, adding only the newest one (outlined). That is why long conversations cost more and eventually fill the context window.

Each request can also carry a system prompt: standing instructions that set the role and the rules.

Example system prompt: "You are the support agent for Acme Kitchenware. Be concise. Refunds over $500 need a human."

3

The context window is Claude's working memory

Everything you send (system prompt, messages, tool results) must fit in the context window. Its size is measured in tokens; a token is roughly three quarters of an English word. The window is large but not unlimited.

More text also means more to pay attention to. Details buried in the middle of a very long input are easier to miss, and when a long chat gets summarized to save space, exact numbers get blurred. A lot of Domain 5 is about keeping the important facts visible.

4

Tools let Claude take actions

Claude cannot query your database. But you can describe a tool to it: a name, a description and the inputs it accepts. When Claude decides a tool would help, it does not run anything itself. It replies with a request, called a tool_use: "please run lookup_order with order number 12345". Your code runs the real function and sends the answer back as a tool_result. Claude reads it and carries on.

Your code Claude API messages + tool list tool_use lookup_order("12345") your function queries the DB tool_result "shipped 2 Oct" final text stop_reason: end_turn
Claude never runs your tools; it asks, and your code does the work. Read top to bottom: the request goes in, Claude answers with a tool_use request, your function runs, the result goes back as a tool_result, and Claude writes the answer. Each arrow to the right is a new API call that carries the whole conversation.

Analogy: Claude is a manager on the phone who cannot touch a computer. It tells an assistant (your code) exactly what to look up, and the assistant reads the answer back.

5

An agent is that exchange in a loop

One tool call does not make an agent. An agent repeats the cycle: Claude looks at the situation, chooses an action, your code carries it out, the result is added to the conversation, and Claude chooses again, until it decides the task is finished. Claude decides the steps; your code runs the loop.

How does your code know whether Claude wants a tool or is finished? Every response carries a field called stop_reason. tool_use means "run the tools and come back"; end_turn means "I'm done". Task 1.1 builds this loop.

6

Workflow or agent? Pick the simplest thing that works

If you already know the steps (extract the fields, validate them, save them), write those steps as ordinary code that calls Claude at each one. That is a workflow: predictable, cheap and easy to test. Use an agent when the next step depends on what is discovered along the way, as in debugging or open-ended research.

The exam often rewards the simpler, more targeted option. "Over-engineered" is a common reason an answer is wrong.

7

Several agents can work as a team

For big jobs, a coordinator agent splits the work and hands pieces to subagents. Each subagent is a separate Claude conversation with its own focused instructions and its own small set of tools: a searcher, an analyst, a writer. Results flow back to the coordinator, which combines them and checks for gaps.

The key fact: a subagent starts with a blank memory. It only knows what the coordinator writes in its instructions, so the coordinator must pass along everything it needs.

8

Prompts guide; code guarantees

Instructions in a prompt work most of the time. Code works every time. When a rule must never be broken, such as verifying identity before a refund, enforce it in code: a hook that inspects every tool call before it runs, or a check inside the tool itself. Use prompts for guidance, tone and judgment.

Rule in the prompt Rule in code (hook) ≈98 of 100 follow it 100 of 100 probabilistic deterministic
A prompt makes the right behaviour likely; code makes it certain. Each dot is one conversation. For tone and judgment, "usually" is fine. For a refund limit or an identity check, the two red dots are incidents, so the rule belongs in a hook or in the tool itself.

This single idea, deterministic code versus probabilistic prompts, answers a surprising number of exam questions.

9

Programs need data, not prose

A downstream system cannot read a friendly paragraph. The reliable way to get structured data (JSON with fixed fields) is to define a tool whose input schema is exactly the shape you want and have Claude "call" it. The arguments it fills in are your data, and they always match the shape.

A correct shape does not mean correct content, though. Numbers can still be misread, so you check the values in code and retry with specific feedback.

10

The building blocks you will meet

Claude Codecoding agent: CLI + IDE built on Claude Agent SDKruns the loop for you built on Messages APIstateless calls Batchesbulk, 24 h Claude model MCP servers tools + data
Each layer does more of the work for you. With the Messages API you write the loop yourself. The Agent SDK runs the loop, tools, subagents, hooks and sessions. Claude Code is a finished agent on the same engine. MCP servers plug extra tools and data into either of the top two.
NameWhat it isThink of it as
Claude API (Messages API)The raw interface: send messages and tool descriptions, get a reply. You write the loop yourself.The engine
Claude Agent SDKA Python / TypeScript library that runs the agent loop for you, with built-in tools, subagents, hooks and saved sessions. It is the engine that powers Claude Code, packaged as a library.A ready-made car around the engine
Claude CodeAnthropic's coding agent for the terminal and IDE. You configure it with CLAUDE.md files, rules, skills and settings.A finished product built on that car
MCP (Model Context Protocol)A standard way to plug tools and data into any agent. Write an MCP server for Jira once, and Claude Code or your SDK agent can use it.USB ports for tools
Message Batches APISend thousands of requests at once. Half the price; results within 24 hours, no faster guarantee.Overnight bulk processing

Glossary

TermMeaning in one line
AgentClaude running in a loop, choosing its own next action with tools until the task is done.
Agentic loopThe code cycle: call Claude → run requested tools → send results back → repeat.
Anti-patternA common approach that looks reasonable but causes problems; usually a wrong answer on the exam.
CalibrationChecking confidence scores against known correct answers so the numbers can be trusted.
CLAUDE.mdA text file of instructions that Claude Code reads automatically at the start of every session.
Context windowThe maximum amount of text Claude can consider in one request.
CoordinatorThe agent that splits work, delegates to subagents and combines their results.
Deterministic / probabilisticSame result every time (code) versus usually the right result (prompts).
EscalationHanding a case to a human.
Few-shot examplesA handful of worked examples placed in the prompt to show the desired behaviour.
HallucinationThe model stating something false or made up as if it were true.
HookYour code that runs automatically before or after a tool call, and can block or modify it.
JSON schemaA precise description of the shape of some JSON data: field names, types, which are required.
MCP server / resourceA program that offers tools (actions) and resources (read-only content) to agents over MCP.
Plan modeA Claude Code mode where it explores and proposes a plan before changing anything.
ProvenanceWhere a piece of information came from: source, date, location.
Session (resume / fork)A saved conversation. Resume continues it; fork copies it to try something else.
Skill / slash commandA saved, reusable instruction you trigger by name, such as /review.
stop_reasonThe field on each response that says why Claude stopped: wants a tool, finished, ran out of space…
SubagentA separate agent with its own instructions and tools, started by a coordinator for one piece of work.
System promptStanding instructions sent with every request that set Claude's role and rules.
TokenThe unit text is measured in; about ¾ of an English word.
Tool / tool definitionA function Claude can ask your code to run, described by a name, a description and an input schema.
tool_use / tool_resultClaude's request to run a tool / your reply carrying the tool's output.
tool_choiceA request setting: Claude may use tools, must use one, must use a specific one, or may not use any.
WorkflowFixed steps written in code, calling Claude at each step; the path is decided in advance.

How to study with these notes

  1. Read this section once, slowly. Come back to the glossary whenever a word is unfamiliar.
  2. Go domain by domain. In each task, read In plain words first, then the detail, then the trap box and the Remember line.
  3. Tick Reviewed when you could explain the Remember line to a colleague without looking.
  4. Try the practice question for that domain before moving on.
  5. Do at least the first two hands-on labs. Building the loop once makes Domains 1, 2 and 5 much easier to reason about.
  6. In the last week, use How to pick answers and Signal → answer for quick revision.
★

How to pick the right answer

Ten rules that resolve most questions. The sample questions in the guide follow them consistently.
  1. Guarantees come from code, not prompts.If a rule must hold every time (identity check before refund, refund cap), choose hooks or programmatic gates. Prompt instructions and few-shot examples have a non-zero failure rate.
  2. Take the proportionate first step that fixes the root cause.Better tool descriptions, explicit criteria, or few-shot examples come before routing layers, classifiers, or new ML infrastructure. "Over-engineered" is a common reason a distractor is wrong.
  3. Fix the component the evidence points at.If logs show the coordinator decomposed a topic narrowly, the bug is in the coordinator, not in the subagents that did what they were told.
  4. Least privilege for tools.Give each agent the 4–5 tools its role needs. Add a narrow cross-role tool for the frequent case; route the rare complex case through the coordinator.
  5. Structured beats generic.Errors carry category, retryability, what was attempted and partial results. Handoffs carry IDs, root cause, amounts and a recommendation. Findings carry source, date and location.
  6. Never hide a failure, never let one failure kill everything.Returning empty-as-success and terminating the whole workflow are both wrong. Recover locally, then propagate what you could not fix.
  7. More context is not more attention.A bigger context window does not fix diluted attention. Split into focused passes, trim tool output, put key facts at the start.
  8. Self-reported confidence and sentiment are weak proxies.Do not route escalation on "confidence 1–10" or frustration level. Field-level confidence is acceptable only after calibration against a labeled validation set.
  9. A fresh instance reviews better than the author.The generating session keeps its own reasoning and rarely challenges it. Use an independent reviewer instance without that context.
  10. Distrust options that name features you have never seen.The guide's distractors include CLAUDE_HEADLESS=true, a --batch flag and .claude/config.json with a commands array. None exist.
D1

Agentic Architecture & Orchestration

27% of scored items, the largest domain · primary in scenarios 1, 3 and 4

The domain tests whether you can build the loop correctly, split work across agents without losing information, and decide when the model may choose freely versus when code must force the order.

TASK 1.1

Agentic loops for autonomous task execution

In plain words

Think of Claude as a capable colleague who cannot touch the keyboard. You give it a task, and each reply is one of two things: "please run this tool for me" or "here is my final answer".

Your program goes round in a loop: run the tools Claude asked for, show it the results, ask again, until Claude says it is finished. How does the program tell the two kinds of reply apart? Not by reading the words. Every response carries a label, stop_reason. tool_use means "run the tools and come back"; end_turn means "done". The loop checks that label.

New terms: agentic loop, tool_use, tool_result, stop_reason

Concepts in depth

What problem does the loop solve?

A single call to the Messages API gives you one reply from Claude. That is enough to answer a question from what Claude already knows, but not enough to do something in the world: look up an order, read a file, issue a refund. For that, Claude has to ask your program to run a tool, wait for the answer, think about it, and possibly ask for another tool. Nobody knows in advance how many rounds that will take. One order lookup may be enough; a messy refund case may need five tool calls.

The agentic loop is the small piece of control flow that makes this work. It keeps calling the API, runs whatever tools Claude asks for, feeds the results back, and stops only when Claude signals that it has finished. Everything else in Domain 1 (subagents, hooks, sessions) is built on top of this loop, so it is worth understanding line by line.

Step 1: describe the tools Claude may use

Claude cannot see your code. It only sees a tool definition: a name, a description written for the model, and an input_schema (a JSON Schema) that says which arguments the tool takes. You send this list with every request. Claude reads it the way a developer reads API documentation and decides which tool, if any, fits the situation.

TOOL DEFINITIONS · PYTHON (SENT WITH EVERY REQUEST)
TOOLS = [
    {
        "name": "get_customer",
        "description": (
            "Look up a customer by email or phone. Returns customer_id, name and "
            "account status. Call this before any order or refund action."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "email": {"type": "string", "description": "Customer email address"},
                "phone": {"type": "string", "description": "E.164, e.g. +14155550100"},
            },
        },
    },
    {
        "name": "lookup_order",
        "description": (
            "Get one order by order number (format #12345). Returns status, items, "
            "amounts and delivery date. Not for finding who a customer is."
        ),
        "input_schema": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "e.g. 12345"}},
            "required": ["order_id"],
        },
    },
]
  • name The identifier Claude uses when it asks for the tool. Your code uses the same name to decide which real function to run.
  • description The most important field. It is the only explanation Claude gets of what the tool does and when to use it. Vague descriptions cause wrong tool choices (Task 2.1).
  • input_schema A JSON Schema for the arguments. Claude fills in arguments that match it. required lists the arguments that must always be present.

Step 2: the loop itself, annotated

The loop below is a complete, minimal agent. Read the comments in order. Notice that the program never inspects Claude's wording to decide what to do next. It only reads stop_reason and the types of the content blocks.

COMPLETE AGENT LOOP · PYTHON, ANTHROPIC SDK
import json
import anthropic

client = anthropic.Anthropic()            # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-sonnet-5-5"
SYSTEM = "You are Acme's support agent. Verify the customer before order actions."

def run_tool(name, args):
    """Run the real function. Return (text_for_claude, failed)."""
    try:
        if name == "get_customer":
            return json.dumps(crm.find_customer(**args)), False
        if name == "lookup_order":
            return json.dumps(orders.get(args["order_id"])), False
        return f"Unknown tool: {name}", True
    except TimeoutError:
        return json.dumps({"errorCategory": "transient", "isRetryable": True}), True

def run_agent(task, safety_cap=25):
    messages = [{"role": "user", "content": task}]      # the conversation so far
    for _ in range(safety_cap):                         # safety net, not the stop rule
        resp = client.messages.create(
            model=MODEL, max_tokens=4096, system=SYSTEM,
            tools=TOOLS, messages=messages,
        )
        # 1. Always keep Claude's full turn, including any tool_use blocks.
        messages.append({"role": "assistant", "content": resp.content})

        # 2. Decide what to do from stop_reason, never from the text.
        if resp.stop_reason == "end_turn":
            return "".join(b.text for b in resp.content if b.type == "text")

        if resp.stop_reason == "tool_use":
            results = []
            for block in resp.content:                  # may hold several tool_use blocks
                if block.type == "tool_use":
                    text, failed = run_tool(block.name, block.input)
                    results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,        # must match the request
                        "content": text,
                        "is_error": failed,
                    })
            # 3. All results go back together, as one user turn.
            messages.append({"role": "user", "content": results})
            continue

        if resp.stop_reason == "max_tokens":
            raise RuntimeError("Reply was cut off. Raise max_tokens or ask it to continue.")
        raise RuntimeError(f"Unhandled stop_reason: {resp.stop_reason}")

    raise RuntimeError("Safety cap reached without finishing. Investigate the run.")

How the message list grows

The API is stateless: it remembers nothing between calls. The messages list is the agent's memory. Every iteration appends two entries: Claude's turn (which may contain text and tool requests) and a user turn carrying the tool results. Here is what the list looks like after a short support case:

THE MESSAGES LIST AFTER THREE API CALLS
[0] user       "Where is order #12345? My email is ana@example.com"
[1] assistant  text      "Let me find your account first."
               tool_use  id=toolu_01  get_customer {"email": "ana@example.com"}
[2] user       tool_result  toolu_01  {"customer_id": "C-88213", "status": "active"}
[3] assistant  tool_use  id=toolu_02  lookup_order {"order_id": "12345"}
[4] user       tool_result  toolu_02  {"status": "shipped", "shipped_at": "2026-10-02"}
[5] assistant  text      "Your order shipped on 2 October and should arrive..."
                                                         stop_reason = "end_turn"

Three things to notice. First, entry [1] contains both text and a tool request. That is normal, and it is why "the response contains text" is not a sign that Claude is done. Second, tool results travel in a user turn: from Claude's point of view, your program is the other side of the conversation. Third, the list only grows. Long tasks make it large, which is why Domain 5 talks about trimming tool output.

[0]user "Where is order #12345?" [1]assistant text: "Let me check." tool_use: lookup_order id: toolu_01 [2]user tool_result tool_use_id: toolu_01 [3]assistant text: "It shipped 2 Oct." stop_reason: end_turn same id
Results come back as a user turn and are matched by id. Entry [1] holds both text and a tool request, so "the reply contains text" never means "done". The tool_result in [2] must carry the same id as the tool_use it answers, and the list only ever grows.

The fields that control the loop

  • stop_reason Why Claude stopped generating. tool_use means "run the tools I asked for and call me again". end_turn means "I have finished". max_tokens means the reply was cut off, which is not the same as finished.
  • tool_use block A request to run a tool. It carries an id (unique per request), the tool name, and the input arguments that match the schema.
  • tool_result block Your answer. tool_use_id must equal the request's id so Claude knows which result belongs to which request. Every tool_use needs a matching result, or the next API call fails.
  • is_error Tells Claude the tool failed, so it can recover (retry, try another route, explain) instead of treating an error message as data.

Every stop_reason value, and what your loop should do

Most of the time you will see only tool_use and end_turn. A production loop still has to handle the other values, because each one means something different and treating them all as "done" silently loses work.

A COMPLETE STOP_REASON DISPATCH · PYTHON
def next_step(resp, messages):
    reason = resp.stop_reason
    if reason == "end_turn":
        return "done"                       # Claude finished its turn normally
    if reason == "tool_use":
        run_tools_and_append(resp, messages)
        return "continue"                   # call the API again with the results
    if reason == "max_tokens":
        # The reply was cut off mid-way. It is NOT finished.
        messages.append({"role": "assistant", "content": resp.content})
        messages.append({"role": "user", "content": "Continue exactly where you stopped."})
        return "continue"                   # or retry with a larger max_tokens
    if reason == "stop_sequence":
        return "done"                       # hit one of YOUR stop_sequences; you chose this
    if reason == "pause_turn":
        # A long-running server tool (e.g. web search run by Anthropic) paused the turn.
        messages.append({"role": "assistant", "content": resp.content})
        return "continue"                   # send it back unchanged so it can resume
    if reason == "refusal":
        return "refused"                    # surface to a human; do not loop retrying
    raise ValueError(f"unexpected stop_reason: {reason}")
  • end_turn The normal finish. The last text block is the answer.
  • tool_use Claude wants one or more tools. Run every tool_use block in the response, send all results back in one user message, and call again.
  • max_tokens The output hit the max_tokens limit you set. The answer is incomplete. Either raise the limit or ask Claude to continue. Treating this as success is a classic bug: the user gets half an answer.
  • stop_sequence Generation stopped because it produced a string you listed in stop_sequences. You only see this if you configured stop sequences, so your code already knows what it means for your design.
  • pause_turn Some tools run on Anthropic's side (server tools such as web search). If such a turn runs long, the API pauses it. Send the response back as the next assistant turn, unchanged, and the model picks up where it left off.
  • refusal The model declined for safety reasons. Retrying the same request in a loop will not help; report it or route it to a person.

Model-driven versus pre-configured

In this loop, Claude chooses which tool to call next, based on what it has learned so far. If the customer gives an order number but no email, Claude may decide to ask for the email. That flexibility is what makes it an agent. The alternative is a pre-configured sequence: your code always calls get_customer, then lookup_order, then sends one final prompt. That is a workflow. It is cheaper and more predictable, and it is the right choice when the path never changes. Choose the agent when the next step depends on what was discovered.

How this shows up on the exam

Questions describe a loop that ends too early or runs forever and ask for the cause. The answer is almost always that the loop decides from the wrong signal: it checks for text, looks for a phrase like "task complete", or relies on an iteration cap as the main stop condition. The correct design branches on stop_reason, runs every tool_use block in a response, appends the results to history, and keeps a cap only as a safety net.

Revision summary

An agentic loop is plain control flow around the Messages API. You send the conversation plus tool definitions. Claude either asks for tools or finishes. Your code decides what to do by reading stop_reason, never by reading Claude's prose.

1 · Call the API messages + tools 2 · Read stop_reason never parse the text tool_use 3 · Run each tool_use your code executes it 4 · Append to messages assistant + tool_result next iteration end_turn Return the answer
The loop is driven by one field: stop_reason. tool_use sends you down the left side: run the tools, append the results, call again. end_turn exits on the right. Any other value (max_tokens, pause_turn, refusal) needs its own handling, never a silent exit.
MINIMAL LOOP (PYTHON, CLAUDE API)
messages = [{"role": "user", "content": task}]
while True:
    resp = client.messages.create(model=MODEL, max_tokens=4096,
                                  system=SYSTEM, tools=TOOLS, messages=messages)
    messages.append({"role": "assistant", "content": resp.content})  # keep the full turn

    if resp.stop_reason == "end_turn":
        break                                                    # the model decided it is finished
    if resp.stop_reason == "tool_use":
        results = []
        for block in resp.content:
            if block.type == "tool_use":
                out = run_tool(block.name, block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": out.text, "is_error": out.failed})
        messages.append({"role": "user", "content": results})    # results go back as a user turn
        continue
    handle_other(resp)   # e.g. max_tokens = output truncated; decide to continue or fail
stop_reasonMeaningLoop should
end_turnModel finished its turnReturn the answer
tool_useModel wants one or more toolsRun every tool_use block, append the results, call again
max_tokensOutput hit your max_tokensTreat as truncated, not done: raise the limit or continue
stop_sequenceHit one of your custom stop sequencesHandle per your design
pause_turnA long server-tool turn was pausedSend the response back unchanged so it can continue
refusalModel declined for safety reasonsSurface it; do not retry blindly

Key ideas

  • Tool results are appended to history. That is how the model "sees" what happened and reasons about the next action. Each tool_result must reference the matching tool_use_id.
  • Model-driven vs pre-configured. In an agent, Claude decides which tool to call next from context. A hard-coded decision tree or fixed tool sequence is a workflow, not an agent. Use the agent when the path depends on what is discovered; use fixed code when the path is known.
  • A single response can contain text and several tool_use blocks. Execute all of them before the next call.
Anti-patterns the exam lists
  • Stopping when the text says "I'm done" or "Task complete" (parsing natural language for termination).
  • Using an iteration cap as the primary stop condition. A cap is fine as a safety net, not as the design.
  • Treating "the response contains text" as completion. Claude often writes text alongside a tool call.
Scenario

Your support agent sometimes ends the conversation mid-investigation. The loop exits whenever resp.content[0].type == "text". Claude had written "Let me check your order" and then requested lookup_order. Fix: branch on stop_reason only.

RememberBranch on stop_reason. tool_use → run tools, append results, loop. end_turn → done. Never parse prose to decide.

TASK 1.2

Multi-agent systems with coordinator–subagent patterns

In plain words

Some jobs are too big for one agent, such as researching a broad topic. So you set up a team: a coordinator (the project manager) and subagents (specialists such as a searcher, an analyst and a writer).

The coordinator breaks the job into pieces, gives each piece to the right specialist, collects the results and checks whether anything is missing. Specialists never talk to each other directly; everything goes through the coordinator, like spokes on a wheel meeting at the hub. That makes the system easy to watch and debug. If the final report is missing a whole area, look first at how the coordinator split the work.

New terms: coordinator, subagent, hub-and-spoke, decomposition

Concepts in depth

Why split work across several agents at all?

A single agent can, in principle, search the web, read documents, write a report and check its own facts. In practice it gets worse as the job grows. Its context window fills with raw search results, its system prompt has to cover every role at once, and it has twenty tools to choose from. A multi-agent system splits the job so that each agent has a narrow role, a short focused prompt, a small toolset and a clean context window.

There are three concrete benefits. Focus: a search agent that only searches makes better search decisions. Context hygiene: the thousands of tokens a search agent reads stay in its own context; only its summarized findings travel back. Parallelism: independent pieces of work can run at the same time. The cost is coordination, which is the coordinator's job.

What the coordinator is responsible for

In a coordinator–subagent (hub-and-spoke) design, one agent sits in the middle and owns five responsibilities. Learn them as a list, because exam questions often ask which component should own a behaviour.

  • Decomposition Turn the user's request into distinct subtasks that together cover the whole question, without overlapping.
  • Delegation Choose which subagent handles each subtask, and write it a complete brief. Subagents know nothing else (Task 1.3).
  • Routing Pass outputs from one subagent to the next. Search results go to synthesis through the coordinator, never directly.
  • Error handling Decide what to do when a subagent fails: retry with a different query, use another source, or continue and record the gap.
  • Aggregation and gap checking Combine the results, compare them with the original plan, and send follow-up work for anything missing.

Subagents never talk to each other. That rule feels restrictive, but it gives you one place to log every hand-off, one place to apply error policy, and one place to look when something goes wrong.

An example decomposition

Suppose the question is "What is the impact of AI on creative industries?". A good coordinator first writes a plan. Asking the coordinator to produce the plan as structured data makes it easy to log and to check coverage later.

COORDINATOR PLAN · JSON
{
  "question": "Impact of AI on creative industries",
  "complexity": "broad",
  "subtasks": [
    {"id": "visual",  "scope": "Visual art, illustration, graphic design"},
    {"id": "music",   "scope": "Composition, production, royalties"},
    {"id": "writing", "scope": "Publishing, journalism, screenwriting"},
    {"id": "film",    "scope": "Film, TV, VFX, animation"},
    {"id": "games",   "scope": "Game art, narrative, audio"},
    {"id": "labour",  "scope": "Jobs and pay across all sectors"}
  ],
  "source_types": "trade press, industry reports, surveys, labour statistics",
  "quality_bar": "Two independent sources per major claim; every source dated"
}

Notice two properties. The subtasks cover the question: a reader would not say "you forgot music". And they are partitioned: no two subagents research the same thing, so you do not pay twice for duplicate searches. A plan that listed only "digital art, graphic design, photography" would be narrow. Every subagent would succeed, and the report would still miss most of the topic. The fault would be in this plan, not in the subagents.

Narrow plan Impact of AI on creative industries digital art agent 1 graphic design agent 2 photography agent 3 music never assigned writing never assigned film & TV never assigned
Broad, partitioned plan Impact of AI on creative industries visual art & design agent 1 music agent 2 writing agent 3 film & TV agent 4 games agent 5 jobs & pay agent 6
Both plans run without a single error; only one answers the question. In the narrow plan every subagent succeeds, yet music, writing and film never appear in the report because nobody was asked to look. The bug lives in the coordinator's plan. In the broad plan each area has exactly one owner: full coverage, no duplicate searching.

The coordinator's control flow

The code below is not a specific SDK. It spells out the coordinator's job as plain Python so each responsibility is visible. In the Agent SDK the coordinator is itself a Claude agent that performs these steps by calling the Task tool (Task 1.3), but the logic is the same.

COORDINATOR LOGIC · ILLUSTRATIVE PYTHON
async def research(question):
    plan = await make_plan(question)                       # 1. decompose

    if plan["complexity"] == "simple":                     # 2. select only what is needed
        return await run_subagent("web-searcher", plan["subtasks"][0])

    findings = await asyncio.gather(*[                     # 3. delegate in parallel
        run_subagent("web-searcher", st) for st in plan["subtasks"]
    ])

    for _ in range(2):                                     # 4. check coverage, refine
        gaps = await find_gaps(question, plan, findings)
        if not gaps:
            break
        findings += await asyncio.gather(*[
            run_subagent("web-searcher", gap) for gap in gaps
        ])

    draft = await run_subagent("synthesizer",              # 5. route everything onward
                               {"question": question, "findings": findings})
    return await run_subagent("report-writer", {"draft": draft})

Step 2 is dynamic selection. "When was Pixar founded?" does not need six searchers, a synthesizer and a report writer; one search is enough. Running the full pipeline for every query wastes time and money. Step 4 is iterative refinement: the coordinator reads what came back, notices that the film searcher returned only one weak source, and sends a targeted follow-up before synthesis.

Aggregation: what comes back and how it is combined

Aggregation is easy when subagents return structured results: a list of findings, each with its claim, source and date, plus a note about anything that failed. The coordinator can then count sources per subtask, spot subtopics with nothing reliable, and pass the complete set to synthesis. If subagents return free-form prose, the coordinator has to guess what was found, and source information is easily lost.

How this shows up on the exam

Expect questions where the output is incomplete or inconsistent and you must find the component at fault. Read the evidence in the question. If every subagent did what it was asked but the report still misses whole areas, the coordinator's decomposition is the cause. If a simple query is slow and expensive, the coordinator lacks dynamic selection. Options that let subagents message each other directly, or that fix a planning problem by changing subagent prompts, are usually distractors.

Revision summary

Hub-and-spoke: one coordinator owns decomposition, delegation, routing between subagents, error handling, and aggregation. Subagents never talk to each other directly. Every message passes through the hub, which gives you one place for observability, consistent error handling and controlled information flow.

REFERENCE DESIGN · RESEARCH SYSTEM (SCENARIO 3)
Coordinatoranalyse query → pick subagents → partition scope → aggregate → check gaps → re-delegate
Task calls ↓  ·  structured results ↑  ·  no spoke-to-spoke links
Web searchtools: web_search, load_document
Document analysistools: extract_data_points, summarize
Synthesistools: verify_fact (scoped)
Reporttools: write_report

Key ideas

  • Isolated context. A subagent starts with only what its prompt gives it. It does not inherit the coordinator's history and keeps no memory between invocations.
  • Dynamic selection. A good coordinator reads the query and invokes only the subagents it needs. A simple factual question should not run the full five-stage pipeline.
  • Partition scope to avoid duplicate work: give each subagent distinct subtopics or source types.
  • Iterative refinement. The coordinator evaluates the synthesis for gaps, sends targeted follow-up queries to search and analysis, and re-runs synthesis until coverage is sufficient.
Trap: narrow decomposition

"Impact of AI on creative industries" split into digital art, graphic design and photography. Every subagent succeeds, yet music, writing and film are missing. The root cause is the coordinator's decomposition, not search queries or synthesis instructions. Blame the component whose output was wrong, which here is the task list itself.

Scenario

A user asks "When was the company founded?" and the coordinator runs search, analysis, synthesis and report. A good coordinator reads the query and calls only the search agent.

RememberOne hub, isolated spokes. If the output misses whole areas while every subagent succeeded, suspect the coordinator's decomposition first.

TASK 1.3

Subagent invocation, context passing and spawning

In plain words

A subagent is like a contractor you brief by email: it knows only what is in the brief. It has not seen your earlier conversation and does not remember previous jobs. So the coordinator must write a complete brief: the task, the findings so far, and where each fact came from.

In the Agent SDK the coordinator starts a subagent by calling a tool named Task, so Task must be on its list of allowed tools. If the coordinator asks for several Task calls in a single reply, the subagents run at the same time. One Task call per reply means they run one after another.

New terms: Task tool, allowedTools, AgentDefinition, parallel delegation

Concepts in depth

What a subagent actually is

A subagent is a second Claude agent that runs its own agentic loop with its own context window, its own system prompt and its own list of tools. The coordinator starts it, hands it one piece of work, and receives its final answer. While the subagent works, everything it reads (search results, files, failed attempts) stays inside the subagent's context. Only its final message comes back to the coordinator.

Two consequences follow directly. First, the subagent starts with no memory: it has not seen the user's question, the coordinator's reasoning or other subagents' results unless they are written into the brief it receives. Second, it keeps nothing between invocations: calling the same subagent twice creates two independent conversations.

Coordinator's context user question its reasoning plan, subtasks other results brief Task input final message nothing else Subagent's context (starts empty) system prompt the brief internal work, stays here web_search × 4 fetch_page × 6 dead ends, raw pages
A subagent sees only its system prompt and the brief. The user's question, the coordinator's reasoning and other agents' results reach it only if the coordinator writes them into the brief. In the other direction, its searches and raw pages stay behind; the coordinator receives just the final message, which keeps the coordinator's context small.

Declaring subagents with AgentDefinition

In the Claude Agent SDK you do not write a separate program for each subagent. You declare each subagent type once, as an AgentDefinition, and register it on the coordinator's options. The coordinator can then start as many instances of each type as it needs. Here is a complete research coordinator with two subagent types:

COORDINATOR WITH TWO SUBAGENT TYPES · PYTHON, CLAUDE AGENT SDK
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

COORDINATOR_PROMPT = """You coordinate a research team.
Goal: a cited report covering every major area the question touches.
Quality bar: two independent sources per major claim; every source dated.
Send each subtopic to web-searcher, several at once. Then give ALL findings,
with their sources, to synthesizer. Check the draft for gaps and follow up."""

options = ClaudeAgentOptions(
    system_prompt=COORDINATOR_PROMPT,
    allowed_tools=["Task"],                   # the coordinator may only delegate
    agents={
        "web-searcher": AgentDefinition(
            description=(
                "Finds and reads sources for ONE assigned subtopic. "
                "Use whenever the question needs fresh evidence."
            ),
            prompt=(
                "You research exactly one subtopic. Return JSON only: a list of "
                "findings with claim, excerpt, url, title, published_at. "
                "If a search fails, say what you tried and return partial results."
            ),
            tools=["WebSearch", "WebFetch"],
            model="haiku",
        ),
        "synthesizer": AgentDefinition(
            description="Turns structured findings into a cited draft. Use last.",
            prompt=(
                "You receive findings as JSON. Write a draft in which every claim "
                "cites its url. Keep conflicting figures side by side with dates."
            ),
            tools=["Read"],
            model="sonnet",
        ),
    },
)

async def main():
    async for message in query(prompt="Impact of AI on creative industries",
                               options=options):
        print(message)

asyncio.run(main())

Each field of an AgentDefinition, explained

  • "web-searcher" (the dictionary key) The subagent type's name. The coordinator uses it to say which kind of subagent to start.
  • description Written for the coordinator, not for the subagent. The coordinator reads every description to decide which subagent fits a piece of work, exactly as it reads tool descriptions. A vague description ("helps with research") leads to wrong or missing delegation.
  • prompt The subagent's system prompt: its role, its rules and, very importantly, the output format it must return. Asking for structured JSON here is what makes aggregation and attribution possible later.
  • tools The tools this subagent may use. Keep it to what the role needs. A synthesizer with web search will start searching instead of writing. If you leave it out, the subagent inherits all available tools, which is rarely what you want.
  • model Which model runs this subagent: "haiku", "sonnet", "opus", or "inherit" to use the coordinator's model. Cheap, fast models suit narrow repetitive work such as searching.

Two coordinator options matter just as much. agents registers the definitions; without it there is nothing to delegate to. allowed_tools lists the tools the coordinator may use, and it must include "Task", the tool that starts subagents. If "Task" is missing, the coordinator cannot delegate at all and tries to do everything itself or gives up. Giving the coordinator only Task is a deliberate choice: it forces the coordinator to delegate rather than search on its own. (Recent SDK releases name this tool Agent; the exam guide uses Task.)

What a Task call looks like

Delegation is just a tool call. When the coordinator decides to use a subagent, its response contains a tool_use block for the Task tool. The SDK sees it, starts the named subagent with the given prompt, runs that subagent's loop to completion, and returns its final answer as the tool_result.

ONE DELEGATION, AS IT APPEARS IN THE COORDINATOR'S RESPONSE · JSON (PROMPT WRAPPED FOR READING)
{
  "type": "tool_use",
  "id": "toolu_01A",
  "name": "Task",
  "input": {
    "subagent_type": "web-searcher",
    "description": "Research AI in music",
    "prompt": "Subtopic: AI in music composition, production and royalties, 2023-2026.
               Overall question: impact of AI on creative industries.
               Out of scope: visual art, film, games (other agents cover these).
               Return JSON findings with claim, excerpt, url, title, published_at."
  }
}

The prompt inside the Task input is the entire brief the subagent receives on top of its own system prompt. That is why it repeats the overall question and the scope boundaries: the subagent cannot see them anywhere else.

Passing context explicitly

The most common multi-agent bug is a subagent that "should have known" something. A synthesizer told "synthesize the research so far" produces vague, uncited text because it never received the research. The fix is to put the earlier results into its prompt, in a structured form that keeps content and metadata (source, date, page) together:

A SYNTHESIS BRIEF THAT CARRIES ITS OWN CONTEXT · TEXT + JSON
Write the synthesis for: "Impact of AI on creative industries".

Findings from the search agents. Each claim keeps its source; cite the url.
[
  {"subtopic": "music", "claim": "38% of surveyed indie artists use generative tools",
   "excerpt": "...38 percent of independent artists surveyed...",
   "url": "https://example.org/indie-survey", "title": "Indie Artist Survey",
   "published_at": "2025-06-10"},
  {"subtopic": "music", "claim": "21% of artists use AI tools",
   "url": "https://example.org/label-report", "title": "Label Assoc. Report",
   "published_at": "2024-02-01"},
  {"subtopic": "film", "claim": "...", "url": "...", "published_at": "2025-11-03"}
]

Coverage notes: the games search timed out twice; one partial result is included.
Conflicts: keep both music figures with their dates; do not pick one.

Because every claim travels with its URL and date, the synthesizer can cite correctly, and the dates show that 21% versus 38% may be a trend rather than a contradiction.

Parallel versus sequential delegation

The SDK runs Task calls that arrive in the same response at the same time. If the coordinator puts six Task blocks in one response, six searchers run in parallel. If it emits one Task block, waits for the result, then emits the next, they run one after another, and the total time is the sum of all six. When subagents are independent, the coordinator's prompt should tell it to delegate them together.

assistant content (one response) = [
  {"type": "tool_use", "name": "Task",
   "input": {"subagent_type": "web-searcher", "prompt": "Subtopic: music..."}},
  {"type": "tool_use", "name": "Task",
   "input": {"subagent_type": "web-searcher", "prompt": "Subtopic: film..."}},
  {"type": "tool_use", "name": "Task",
   "input": {"subagent_type": "web-searcher", "prompt": "Subtopic: games..."}}
]                                                 # three subagents start together

Finally, notice the style of COORDINATOR_PROMPT. It states the goal and the quality bar, not a numbered procedure. A goal-based prompt lets the coordinator adapt (add a subtopic it discovered, skip one that turned out to be irrelevant) while still knowing what "done" means.

3 Task calls in one response music film games total = slowest time →
1 Task call per turn music film games total time → = sum + turns
Parallelism comes from putting several Task calls in the same response. The SDK starts them together, so the wait is only as long as the slowest subagent. One call per turn forces a full coordinator round-trip between them, and the times add up.

Fork-based sessions: exploring alternatives from one baseline

Sometimes the coordinator has done expensive groundwork, such as mapping a codebase, and you want to try two different approaches on top of it. Repeating the groundwork twice wastes time and money; running both approaches in one conversation lets them contaminate each other. A fork copies the session up to that point into a new, independent session. Each fork continues separately, and the original stays untouched. You then compare the outcomes. Task 1.7 shows the code (resume plus fork_session=True).

The same idea in Claude Code: agent files

Claude Code supports the same concept without any Python. A subagent is a Markdown file in .claude/agents/ (shared with the team) or ~/.claude/agents/ (personal). The YAML frontmatter holds the same fields as an AgentDefinition, and the body is the subagent's system prompt.

.claude/agents/web-searcher.md · MARKDOWN
---
name: web-searcher
description: Finds and reads sources for ONE assigned subtopic. Use whenever a
  question needs fresh evidence from the web.
tools: WebSearch, WebFetch
model: haiku
---
You research exactly one subtopic. Return a list of findings, each with claim,
excerpt, url, title and published_at. If a search fails, report what you tried
and include any partial results. Never summarize without sources.

How this shows up on the exam

Look for three symptoms. "The coordinator never delegates" points to "Task" missing from allowedTools. "Subagents run one at a time although they are independent" points to Task calls spread across turns instead of emitted together. "A subagent's output is vague or ignores earlier work" points to missing context in its prompt. Distractors usually claim subagents share memory, or try to fix a context problem with a bigger model or a longer system prompt.

Revision summary
  • The Task tool spawns subagents in the Agent SDK. The coordinator's allowedTools must include "Task" or it cannot delegate at all. (Recent SDK and Claude Code releases show this tool as Agent; the exam guide says Task, so answer with Task.)
  • An AgentDefinition configures each subagent type: a description (used to decide when to delegate), a system prompt, and a restricted tools list.
  • Context must be explicit. Pass the complete findings of earlier agents inside the subagent's prompt, for example web results and document analysis handed to synthesis.
  • Keep metadata separate from content using structured formats (claim, excerpt, URL, document name, page) so attribution survives the hand-off.
  • Parallelism happens when the coordinator emits several Task calls in one response. Calls spread across separate turns run sequentially.
  • Prompt the coordinator with goals and quality criteria ("cover all major sectors, two independent sources per claim") rather than step-by-step procedures, so subagents can adapt.
  • Fork-based sessions let you branch from a shared analysis baseline to explore divergent approaches (see 1.7).
AGENT SDK SHAPE (PYTHON, ILLUSTRATIVE)
options = ClaudeAgentOptions(
    system_prompt=COORDINATOR_GOALS,              # goals + quality bar, not a procedure
    allowed_tools=["Task"],                        # required to spawn subagents
    agents={
        "web-searcher": AgentDefinition(
            description="Finds and fetches sources for one assigned subtopic.",
            prompt="Return findings as JSON: claim, excerpt, url, published_at.",
            tools=["web_search", "load_document"]),
        "synthesizer": AgentDefinition(
            description="Merges structured findings into a cited draft.",
            prompt="Preserve every claim→source mapping. Flag conflicts.",
            tools=["verify_fact"]),
    })
Scenario

The synthesis agent writes vague, uncited text. Its prompt says "synthesize the research so far." It never received the research, because subagents do not share memory. Fix: put the structured findings, with their source metadata, into the synthesis prompt.

Trap
  • Assuming a subagent "remembers" earlier work or can read the coordinator's history.
  • Expecting parallelism from Task calls spread across several turns.
  • Writing the coordinator prompt as a rigid step list instead of goals and quality criteria.

RememberSubagents know only what their prompt contains. Allow Task, pass findings explicitly with source metadata, and emit parallel Task calls in one response.

TASK 1.4

Multi-step workflows with enforcement and handoff

In plain words

Some business steps must happen in a fixed order: confirm who the customer is before touching their money. You can tell Claude the order in the prompt, and it will usually follow it. "Usually" is not good enough for money or security.

So you add a gate in code: the refund tool refuses to run until a verified customer ID exists. And when the agent cannot finish and hands the case to a human, it writes a complete handover note, because the human will not read the whole chat.

New terms: programmatic enforcement, prerequisite gate, handoff

Concepts in depth

Two ways to make steps happen in order

Many business processes have a required order. A support agent must confirm who the customer is before it reads their orders, and must check the refund limit before it moves money. There are two ways to get that order.

Prompt guidance means writing the rule into the system prompt ("always call get_customer first") and perhaps adding examples. The model follows it most of the time. Programmatic enforcement means writing the rule in code, so the out-of-order action is impossible: the tool itself refuses to run, or a hook blocks it (Task 1.5). Prompt guidance is probabilistic; enforcement is deterministic. If the agent skips verification in 2% of a million conversations, that is 20,000 refunds to unverified callers. When a mistake costs money, breaks compliance or exposes someone's data, use code.

A prerequisite gate inside the tool code

A prerequisite gate is a check at the top of a tool that refuses to act until an earlier step has happened. The earlier step records its result in session state, data your program keeps for the conversation, outside the model's control. The model cannot fake a verified ID by writing one into its arguments, because the gate checks the session, not the arguments.

GATED SUPPORT TOOLS · PYTHON
def ok(data):
    return {"is_error": False, "content": data}

def error(category, message, retryable):
    return {"is_error": True, "content": {
        "errorCategory": category, "isRetryable": retryable, "message": message}}

class SupportSession:
    def __init__(self):
        self.verified_customer_id = None        # only get_customer may set this

def get_customer(session, email=None, phone=None):
    matches = crm.find(email=email, phone=phone)
    if len(matches) != 1:
        return error("validation",
                     f"{len(matches)} customers match. Ask for another identifier.",
                     retryable=True)
    session.verified_customer_id = matches[0].id
    return ok({"customer_id": matches[0].id, "name": matches[0].name})

def process_refund(session, order_id, amount):
    if session.verified_customer_id is None:                         # gate 1
        return error("permission",
                     "Identity not verified. Call get_customer first.", retryable=True)
    order = orders.get(order_id)
    if order.customer_id != session.verified_customer_id:            # gate 2
        return error("permission",
                     "This order belongs to a different customer.", retryable=False)
    if amount > 500:                                                 # gate 3
        return error("business",
                     "Refunds over $500 need a human. Call escalate_to_human.",
                     retryable=False)
    return ok(payments.refund(order_id, amount))
  • session.verified_customer_id The single source of truth for "has identity been checked?". It lives in your program, so no wording in the conversation can change it.
  • gate 1 Blocks refunds before verification. The message tells the model what to do next, so it recovers on its own instead of failing.
  • gate 2 Stops a verified customer from refunding someone else's order. Gates check relationships, not just "a step happened".
  • gate 3 A business limit. It is not retryable, and the message redirects to escalation, so the customer still gets help.

Even if a customer volunteers "my order number is 12345, refund it now", the model can try process_refund, receive the permission error, and go back to verification. The order is enforced, but the conversation still flows naturally.

Session: unverified verified_customer_id = None process_refund Refused (gate 1) error: verify first get_customer 1 match found Session: verified customer_id = C-88213 process_refund ≤ $500 > $500 Refund runs if order is theirs Denied escalate_to_human
The gate reads session state, not the model's arguments. Only a successful get_customer (exactly one match) can move the session to verified. Until then process_refund returns an error telling the model to verify first. After verification, code still enforces ownership and the $500 limit.

Requests with several concerns

Real messages often bundle issues: "My blender arrived broken, I was charged twice, and I want to change my email." A well-instructed agent decomposes this into three items, investigates each (the order, the payments, the account) against the same verified customer, and replies once, covering all three. Independent lookups can be requested in a single response so they run together. The failure mode to avoid is fixing the first issue and ending the conversation.

A structured handoff to a human

When the agent escalates, a human picks up the case. That person usually sees a ticket, not the whole chat. If the ticket says only "needs human", they must re-ask the customer everything. The fix is to make the escalation tool demand a complete, structured summary. Because it is a tool with a schema, the model has to fill in each field.

ESCALATION TOOL DEFINITION · JSON SCHEMA
{
  "name": "escalate_to_human",
  "description": "Hand the case to a human: on request, exception or over limit.",
  "input_schema": {
    "type": "object",
    "required": ["customer_id", "issue_summary", "why_escalated", "recommended_action"],
    "properties": {
      "customer_id":          {"type": "string"},
      "issue_summary":        {"type": "string", "description": "One or two sentences"},
      "root_cause":           {"type": ["string", "null"], "description": "If known"},
      "evidence":             {"type": "array", "items": {"type": "string"},
                               "description": "IDs, transaction refs, dates"},
      "amount":               {"type": ["number", "null"]},
      "actions_taken":        {"type": "array", "items": {"type": "string"}},
      "why_escalated":        {"type": "string"},
      "recommended_action":   {"type": "string"},
      "customer_expectation": {"type": ["string", "null"], "description": "Promises"}
    }
  }
}
  • issue_summary, root_cause Let the human understand the case in ten seconds.
  • evidence, amount Exact identifiers and numbers, so nothing has to be looked up again.
  • actions_taken Prevents the human from repeating steps the agent already did.
  • why_escalated, recommended_action Explain the decision and suggest the fix. The human can approve in one click.
  • customer_expectation Anything the customer was told ("refund by Friday"), so the promise is kept.

How this shows up on the exam

The classic question: "The agent skips identity verification in X% of conversations. What fixes it?" Options include stronger wording, more few-shot examples, a routing classifier, and a programmatic prerequisite. Only the programmatic prerequisite guarantees order; the others improve the odds. A related pattern: a handoff that forces the human to re-ask questions is fixed with a structured, self-contained escalation payload, not by sending the raw transcript.

Revision summary

Two ways to make steps happen in order: prompt guidance (probabilistic, usually works) and programmatic enforcement (hooks, prerequisite gates; deterministic). When a mistake costs money, breaks compliance or touches identity, prompts alone are not enough.

PREREQUISITE GATE · SUPPORT AGENT
get_customerreturns verified customer_id
→unlocks
lookup_orderscoped to that customer
→unlocks
process_refund≤ $500 else escalate

A gate in code checks session state before executing the tool. If verified_customer_id is missing, it returns an error that tells the model to verify first. The model cannot skip the step, even when the customer volunteers an order number.

Multi-concern requests

"My order arrived damaged, I was double-charged, and I want to change my email." Decompose into distinct items, investigate each in parallel against shared context (same customer, same session), then synthesize one unified reply.

Structured handoff to a human

The human agent does not see the transcript. The escalation payload must stand alone:

{
  "customer_id": "C-88213",
  "issue_summary": "Charged twice for order #12345 on 2026-09-28",
  "root_cause": "Payment retry created a duplicate capture",
  "evidence": ["capture_id pi_91a", "capture_id pi_91b"],
  "refund_amount": 742.10,
  "why_escalated": "Exceeds $500 autonomous refund limit",
  "recommended_action": "Void duplicate capture pi_91b",
  "customer_expectation": "Refund before Friday"
}
Trap

Sample Q1: the agent skips get_customer in 12% of cases. Stronger system-prompt wording and more few-shot examples are both still probabilistic. A tool-routing classifier changes which tools exist, not their order. Only a programmatic prerequisite fixes ordering.

RememberOrdering that must hold → a gate in code. The handoff payload must stand alone, because the human never sees the transcript.

TASK 1.5

Agent SDK hooks for interception and normalization

In plain words

A hook is a small piece of your own code that runs automatically at a fixed moment, like a security guard at a door. A PreToolUse hook runs just before a tool: it can inspect the request and block it ("refunds over $500 need a manager"). A PostToolUse hook runs just after: it can tidy the result before Claude sees it, for example turning three different date formats into one.

Because hooks are code, they behave the same way every time, unlike instructions in a prompt.

New terms: hook, PreToolUse, PostToolUse, normalization

Concepts in depth

What a hook is, technically

A hook is a function you register with the agent runtime that is called automatically at a specific point in the agent's lifecycle. The model does not decide whether to call it, and cannot skip it. The two points that matter most for this exam sit around every tool call:

  • PreToolUse Runs after Claude has asked for a tool but before the tool executes. It sees the tool name and arguments and can allow the call, deny it with a reason, or (in Claude Code) ask the user.
  • PostToolUse Runs after the tool has executed, before Claude reads the result. It can inspect the result, log it, or add context so the model sees a cleaner, consistent version.

The order of events for one tool call is: Claude emits tool_use → PreToolUse hooks run → (if allowed) the tool runs → PostToolUse hooks run → the tool_result goes back to Claude. Because hooks are ordinary code on this path, they give deterministic guarantees.

Claude emits tool_use process_refund 742.10 PreToolUse hook inspects the call deny + reason allow Tool runs real refund API raw: 1727049600 PostToolUse hook normalize, trim 2024-09-23 tool_result Claude reads it one clean format
Hooks are checkpoints your code owns, on both sides of every tool call. PreToolUse sees the request before anything happens and can refuse it; the reason goes back to Claude so it can take another route, such as escalating. PostToolUse sees the raw result and can clean it before Claude ever reads it.

Wiring hooks in the Agent SDK

Hooks are registered in ClaudeAgentOptions under hooks. The keys are event names. Each value is a list of HookMatcher objects; a matcher says which tools the hooks apply to and which functions to call.

REFUND CAP + AUDIT LOG · PYTHON, CLAUDE AGENT SDK
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

REFUND_LIMIT = 500

async def cap_refunds(input_data, tool_use_id, context):
    """PreToolUse: runs before every process_refund call."""
    amount = input_data["tool_input"].get("amount", 0)
    if amount > REFUND_LIMIT:
        return {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": (
                    f"Refunds over ${REFUND_LIMIT} need a human. Call "
                    "escalate_to_human with customer_id, amount and reason."
                ),
            }
        }
    return {}                                  # empty dict = no objection, allow

async def audit(input_data, tool_use_id, context):
    """PostToolUse: runs after every tool call, records what happened."""
    audit_log.write(tool=input_data["tool_name"], args=input_data["tool_input"],
                    result=input_data["tool_response"], call_id=tool_use_id)
    return {}

options = ClaudeAgentOptions(
    system_prompt=SUPPORT_PROMPT,
    mcp_servers={"support": support_server},   # exposes mcp__support__* tools
    allowed_tools=["mcp__support__get_customer", "mcp__support__lookup_order",
                   "mcp__support__process_refund", "mcp__support__escalate_to_human"],
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="mcp__support__process_refund", hooks=[cap_refunds]),
        ],
        "PostToolUse": [
            HookMatcher(matcher=None, hooks=[audit]),       # None = every tool
        ],
    },
)
  • matcher Which tool names the hook applies to. Custom tools served through an SDK MCP server are named mcp__<server>__<tool>. A matcher of None applies to all tools.
  • input_data A dictionary describing the event: tool_name, tool_input (the arguments) and, for PostToolUse, tool_response.
  • tool_use_id The ID of the tool request, useful for correlating Pre and Post events in logs.
  • permissionDecision: "deny" Blocks the call. The permissionDecisionReason is shown to Claude, so a good reason redirects the model to the right action instead of leaving it stuck.
  • return {} No decision; the call proceeds normally.

Normalizing tool results before the model reads them

Agents often call several backends that format data differently: one returns dates as Unix timestamps, another as ISO 8601 strings, a third as "09/23/24". Status might be 3 in one system and "shipped" in another. Asking the model to "be careful with formats" is unreliable. The deterministic fix is to convert every result into one schema in code, on the way back to the model.

NORMALIZATION LOGIC · ILLUSTRATIVE (OUTPUT-REWRITE FIELDS VARY BY SDK VERSION)
from datetime import datetime, timezone

STATUS_NAMES = {1: "placed", 2: "packed", 3: "shipped", 4: "delivered"}

def to_iso8601(value):
    if isinstance(value, (int, float)):                       # 1727049600
        return datetime.fromtimestamp(value, tz=timezone.utc).isoformat()
    if isinstance(value, str) and "/" in value:              # "09/23/24"
        return datetime.strptime(value, "%m/%d/%y").date().isoformat()
    return value                                             # already ISO

def normalize_order(result):
    for key in ("created_at", "shipped_at", "delivered_at"):
        if key in result:
            result[key] = to_iso8601(result[key])
    result["status"] = STATUS_NAMES.get(result.get("status"), result.get("status"))
    keep = ("order_id", "status", "items", "total_cents", "created_at", "delivered_at")
    return {k: result[k] for k in keep if k in result}       # trim noise too

Run this from a PostToolUse hook where your SDK version lets a hook replace a tool's output, or in the single wrapper that all your custom tools return through. The principle is the same either way: the model only ever sees clean, consistent data, and the cleanup does not depend on the model remembering an instruction.

The same mechanism in Claude Code

Claude Code exposes the same events through .claude/settings.json. Instead of a Python function, each hook is usually a shell command. The command receives the event as JSON on standard input. Exit code 0 allows the call; exit code 2 blocks it, and whatever the command printed to standard error is passed back to Claude as the reason.

.claude/settings.json · JSON
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": ".claude/hooks/block-prod-deploy.sh" }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": ".claude/hooks/format-file.sh" }]
      }
    ]
  }
}
.claude/hooks/block-prod-deploy.sh · BASH
#!/usr/bin/env bash
input=$(cat)                                        # event JSON arrives on stdin
cmd=$(echo "$input" | jq -r '.tool_input.command')

if [[ "$cmd" == *"deploy --env prod"* ]]; then
  echo "Production deploys go through the release pipeline, not Claude." >&2
  exit 2                                            # 2 = block, stderr goes to Claude
fi
exit 0                                              # 0 = allow

Hook or prompt? The decision rule

Use a hook when the rule must hold every time and a single violation is costly: spending limits, identity checks, blocking destructive commands, redacting personal data, normalizing formats that downstream logic depends on. Use the prompt for things that are judgment or preference: tone, level of detail, how to phrase an apology. Hooks for style preferences are over-engineering; prompts for financial limits are under-engineering.

How this shows up on the exam

Questions describe a rule that is "usually" followed and ask how to make it reliable: the answer is a hook or a programmatic gate. Questions about inconsistent data formats from several tools point to PostToolUse normalization rather than prompt instructions. Watch for the reverse trap too: if the problem is a preference, the simpler prompt change is the better answer.

Revision summary
Hook pointInterceptsTypical use
Before a tool runs (PreToolUse)The outgoing tool call and its argumentsBlock policy violations (refund > $500), require prerequisites, redirect to escalate_to_human
After a tool runs (PostToolUse)The tool result, before the model reads itNormalize formats (Unix epoch, ISO 8601, numeric status codes → one schema), trim fields, redact
PRETOOLUSE HOOK · CLAUDE AGENT SDK (PYTHON)
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher

async def cap_refunds(input_data, tool_use_id, context):
    if input_data["tool_input"].get("amount", 0) > 500:
        return {"hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": "Refunds over $500 need a human. Call "
                "escalate_to_human with a structured summary."}}   # redirect, not just block
    return {}                                                     # empty = allow

options = ClaudeAgentOptions(hooks={
    "PreToolUse": [HookMatcher(matcher="mcp__support__process_refund", hooks=[cap_refunds])],
})
POSTTOOLUSE NORMALIZATION (ILLUSTRATIVE LOGIC)
async def post_tool(call, result, ctx):
    for k in ("created_at", "shipped_at"):
        result[k] = to_iso8601(result.get(k))               # 1727049600 → 2024-09-23T00:00:00Z
    result["status"] = STATUS_NAMES.get(result["status"], result["status"])  # 3 → "shipped"
    return result

In Claude Code the same events are configured in .claude/settings.json. A command hook that exits with code 2 blocks the tool call, and its stderr is fed back to Claude as the reason.

The one-line rule

Business rule must always hold → hook. Preference or style → prompt. Hooks give deterministic guarantees; prompts give probabilistic compliance.

Scenario

Three MCP tools return dates as 1727049600, "2024-09-23T00:00:00Z" and "09/23/24". The agent miscomputes return windows. Adding "be careful with date formats" to the prompt is weak. A PostToolUse hook that normalizes every timestamp to ISO 8601 removes the problem at the source.

Trap
  • "Add a stronger instruction" for a rule that must always hold.
  • The reverse: a hook to enforce a tone or style preference. That is over-engineering; use the prompt.

RememberMust always hold → PreToolUse hook. Clean up what the model reads → PostToolUse hook. Preferences → prompt.

TASK 1.6

Task decomposition strategies

In plain words

Decomposition means breaking a big task into smaller ones. There are two ways. If you know the steps in advance (review each file, then check how the files fit together), write them as a fixed sequence: prompt chaining. If you cannot know the steps until you start looking ("add tests to this old codebase"), let the agent plan, discover and re-plan as it goes: dynamic decomposition.

Splitting also fixes a common problem. Asked to review 14 files at once, a model gives some files careful attention and others only a glance.

New terms: prompt chaining, dynamic decomposition, attention dilution

Concepts in depth

Why decompose at all?

Task decomposition means splitting a large task into smaller subtasks that are each easier to do well. Models, like people, do better work on a focused question than on a sprawling one. Give Claude fourteen changed files and ask for "a review", and the result is uneven: detailed comments on the first few files, a skim of the rest, and sometimes contradictory verdicts on identical code in two places. This effect is called attention dilution. A bigger context window does not fix it, because the problem is how attention is spread, not whether the text fits.

There are two strategies, and the right one depends on whether you know the steps in advance.

Strategy 1: prompt chaining (a fixed pipeline)

Prompt chaining is a sequence of focused model calls written in your code. Each call has one job, and its output becomes input to the next. You design the steps once; the model does not choose them. Here is a pull-request review built as a chain: one local pass per file, then an integration pass that looks across files, then a merge step.

CHAINED PR REVIEW · PYTHON, ANTHROPIC SDK
LOCAL_REVIEW = """Review ONE file's diff. Report only bugs and security issues.
Return JSON: [{"line": int, "severity": "critical|major|minor", "issue": str}]"""

INTEGRATION_REVIEW = """You see per-file findings plus the changed function
signatures and their call sites. Report only cross-file problems: broken
contracts, mismatched types, data flowing between files incorrectly."""

def ask(system, content):
    r = client.messages.create(model=MODEL, max_tokens=2000, system=system,
                               messages=[{"role": "user", "content": content}])
    return r.content[0].text

def review_pr(diffs, signatures, call_sites):
    # Step 1: one focused call per file. Each file gets full attention.
    local = {path: ask(LOCAL_REVIEW, f"File: {path}\n\n{diff}")
             for path, diff in diffs.items()}

    # Step 2: one call that looks ACROSS files, using compact inputs.
    cross = ask(INTEGRATION_REVIEW,
                f"Per-file findings:\n{json.dumps(local)}\n\n"
                f"Changed signatures:\n{signatures}\n\nCall sites:\n{call_sites}")

    # Step 3: plain code merges and de-duplicates. No model needed.
    return merge_and_dedupe(local, cross)
  • Step 1 Each file is reviewed in its own call, so every file gets the same depth of attention.
  • Step 2 The integration pass receives summaries, signatures and call sites, not all fourteen raw diffs again. Otherwise it would reintroduce the dilution you just removed.
  • Step 3 Deterministic work stays in code. Not every step of a chain needs a model.

Chaining is predictable (same steps every time), testable (each step can be checked alone) and cheap (no planning overhead). It fits work whose shape is known: code review, document extraction, translate-then-check pipelines.

Strategy 2: dynamic adaptive decomposition

Some tasks cannot be planned in advance because the plan depends on what you find. "Add comprehensive tests to this legacy service" is a good example. Before you start you do not know which modules are risky, which are already tested, or which hidden dependencies will make some code hard to test. In dynamic decomposition the agent itself creates the subtasks, executes them, and revises the plan as it learns.

HOW AN ADAPTIVE PLAN EVOLVES · AGENT'S WORKING NOTES
Plan v1 (after a quick scan)
  1. Map entry points and module structure
  2. Find modules with no tests
  3. Write tests for the riskiest untested modules first

Discovered: billing/ has no tests and handles money; it calls a
  third-party tax API directly, so it cannot be tested offline.

Plan v2
  1. [done] Map structure
  2. [done] billing/ and refunds/ untested; utils/ is trivial, skip it
  3. NEW: introduce a TaxClient interface so billing/ can use a fake
  4. Tests for billing/ (rounding, currency, tax failure paths)
  5. Tests for refunds/ (partial refunds, already-refunded orders)

Discovered: refunds/ shares a date helper with a known timezone bug.
Plan v3: add 4b. regression test for the timezone bug before fixing it

The value is adaptability: step 3 in plan v2 did not exist until the agent discovered the hard dependency. The cost is less predictability and more model calls. Use it for open-ended investigation, root-cause hunts and legacy-code work.

Choosing between them

Ask one question: can I write the steps down before I start? If yes, use a chain; you get consistency and lower cost. If no, use dynamic decomposition. Many real systems mix them: a fixed outer pipeline (plan, execute, review) with an adaptive agent inside the "execute" step.

Prompt chaining: steps fixed in code one local pass per file file 1 file 2 … file 14 Integration pass cross-file data flow Merge & dedupe One finding list
Dynamic: the plan changes Plan v1 1 map structure 2 find untested modules 3 test riskiest first Discovers billing/ calls tax API directly Plan v2 1 ✓ map structure 2 ✓ billing/, refunds/ untested 3 NEW: add a TaxClient fake 4 tests for billing/
Choose by whether you can write the steps down before you start. A PR review always has the same shape, so the chain is fixed in code: cheap, consistent, testable. "Add tests to this legacy service" does not: step 3 of plan v2 only exists because of what the agent found along the way.

How this shows up on the exam

A question about a large review with uneven or contradictory results is about attention dilution. The fix is splitting into per-file passes plus an integration pass. Distractors include a larger context window, running the same review three times and keeping only findings that appear twice (which drops real but intermittent bugs), and asking developers to submit smaller PRs (which moves the burden to people). A question about an open-ended task with unknown structure points to dynamic decomposition rather than a fixed checklist.

Revision summary
Prompt chaining (fixed pipeline)Dynamic adaptive decomposition
ShapeKnown sequence of focused stepsSubtasks generated from what each step discovers
Use forPredictable, multi-aspect work: code review, document extractionOpen-ended investigation: "add comprehensive tests to a legacy codebase", root-cause hunts
ExamplePer-file local review → cross-file integration passMap structure → find high-impact areas → prioritized plan → revise as dependencies appear
StrengthConsistent, testable, cheapAdapts to surprises
CHAINED REVIEW FOR A 14-FILE PR
file 1 · local pass
file 2 · local pass
… file 14
→
Integration passcross-file data flow, contracts, call sites
→
Merge & dedupeone consistent finding list

A single pass over many files causes attention dilution: deep comments on some files, shallow ones on others, missed bugs, and contradictory verdicts on identical code.

Scenario

"Add comprehensive tests to this legacy service." You cannot list the steps up front: first map the code, find untested high-risk paths, and uncover hidden dependencies. Dynamic decomposition fits. A fixed "test every file in order" chain wastes effort on trivial files.

Trap
  • Reviewing a 14-file PR in one pass, then trying to fix the inconsistency with a bigger context window or a 2-of-3 vote. Split the work instead: per-file passes plus an integration pass.

RememberKnown shape → fixed chain. Shape discovered as you go → dynamic decomposition. Many files → split into passes.

TASK 1.7

Session state, resumption and forking

In plain words

A session is one saved conversation, with its full history. You can resume it later and pick up where you left off, like reopening a document. You can fork it: make a copy and try a different idea without disturbing the original, like a branch in git.

The catch: the history contains old copies of files. If the code has changed since, tell the agent exactly what changed. If most of it is out of date, start a fresh session with a short summary instead.

New terms: session, resume, fork, stale context

Concepts in depth

What a session is

A session is one agent conversation saved by the runtime: the full message history (prompts, Claude's turns, every tool call and tool result) plus a session ID that identifies it. Because the Messages API itself is stateless, a session is simply that stored history, which the Agent SDK or Claude Code sends again when you continue.

Sessions matter for long investigations. Analysing a large service can take hours of reading files and tracing calls. You do not want to pay for that exploration twice, and you do not want to lose it when you close the terminal. Sessions give you three operations: start, resume and fork.

Starting a session and capturing its ID

In the Agent SDK, the first message streamed back by query is a system message of subtype init. It carries the session ID. Save it if you might want to come back.

START AND RECORD A SESSION · PYTHON, CLAUDE AGENT SDK
from claude_agent_sdk import query, ClaudeAgentOptions

READ_ONLY = ClaudeAgentOptions(allowed_tools=["Read", "Grep", "Glob"])

async def analyse_service():
    session_id = None
    async for msg in query(
        prompt="Map the payments service: entry points, data flow, risky areas.",
        options=READ_ONLY,
    ):
        if getattr(msg, "subtype", None) == "init":
            session_id = msg.data["session_id"]     # keep this
    save("payments-audit", session_id)
    return session_id

Resuming: continue the same conversation

Passing resume=session_id loads the stored history, so Claude continues with everything it learned last time. The important judgment is what to tell it. The history still contains file contents as they were when they were read. If a teammate changed some of those files since, Claude has no way of knowing unless you say so.

RESUME AND POINT AT WHAT CHANGED · PYTHON
options = ClaudeAgentOptions(resume=load("payments-audit"),
                             allowed_tools=["Read", "Grep", "Glob"])

prompt = """Since our last session, PR #482 changed two files:
  - src/payments/refund.py   (new partial-refund path)
  - src/payments/ledger.py   (rounding moved here)
Re-read only those two files, then update your risk list. Everything else
you read earlier is unchanged."""

async for msg in query(prompt=prompt, options=options):
    print(msg)

Naming the changed files is the targeted fix. Without it, Claude either trusts stale reads or re-explores the whole service, wasting the very work the session was meant to keep.

Forking: branch from a shared starting point

Sometimes you want to try two different approaches from the same analysis, for example two refactoring strategies, without one influencing the other. A fork copies the session's history into a new session with a new ID. Each branch continues independently, and the original stays untouched. In the SDK you resume with fork_session=True:

FORK ONE BASELINE INTO TWO EXPERIMENTS · PYTHON
baseline = load("payments-audit")

strategies = {
    "extract-service": "Plan extracting refunds into its own service.",
    "strangler":       "Plan a strangler-fig migration inside the monolith.",
}

for name, task in strategies.items():
    opts = ClaudeAgentOptions(resume=baseline, fork_session=True,
                              allowed_tools=["Read", "Grep", "Glob"])
    async for msg in query(prompt=task, options=opts):
        record(name, msg)                  # each branch has its own new ID
  • resume Which stored session to load.
  • fork_session=True Do not append to that session; copy it into a new one. Without this flag, both experiments would write into the same history and contaminate each other.
baseline S1 maps the codebase resume → still S1 + "files X, Y changed" fork → new S2 try approach A fork → new S3 try approach B S1, S2, S3 never see each other's turns
Resume continues one conversation; fork copies it and starts a new one. Resume keeps the same session id and its history, so tell the agent what changed since. A fork shares everything up to the branch point, then each copy goes its own way, which lets you compare two approaches without either contaminating the other.

The same operations in the Claude Code CLI

SESSION COMMANDS · BASH
claude --continue                          # reopen the most recent session here
claude --resume                            # choose from a list of past sessions
claude --resume payments-audit             # resume a specific named session
claude --resume payments-audit --fork-session   # branch it into a new session
claude -p --resume "$SESSION_ID" "Re-check refund.py only"   # scripted, non-interactive

When to start fresh instead

Resuming is not always the best choice. After a large refactor, most of the file contents in the history are wrong. The model may keep relying on them even when told some files changed, and the stale content still takes up context. In that case, start a new session and give it a short structured summary of what still holds:

Context from the previous analysis (still valid after the refactor):
- Refund flow: API -> RefundService.create -> Ledger.post -> PaymentsGateway
- Known risk: currency rounding happens in two places (now consolidated)
- Open question: retries in PaymentsGateway are not idempotent
Files moved in the refactor; re-read anything you need from src/payments/.

The summary carries the conclusions without the outdated raw material.

How this shows up on the exam

The questions are about choosing the right operation. Prior context mostly valid: resume. A few files changed: resume and name them. Most of the history is stale: fresh session plus a summary. Two alternatives from the same baseline: fork. Common distractors are re-exploring everything from scratch (wasteful), resuming without mentioning the changes (stale), and forking when you only wanted to continue.

Revision summary
  • --resume <session-name> continues a specific named conversation, for example an investigation spread across days.
  • fork_session creates an independent branch from a shared baseline. Analyse the codebase once, then fork to compare two refactoring or testing strategies without them contaminating each other.
  • When resuming after code changed, tell the agent which files changed so it re-reads those specifically instead of re-exploring everything or trusting stale results.
  • When most earlier tool results are stale, start a new session with a structured summary. That is more reliable than resuming a history full of outdated file contents.
SituationChoose
Prior context is still mostly validResume (--resume name)
A few files changed sinceResume and state exactly which files changed
Large refactor landed; old reads are wrongFresh session + injected summary of key findings
Compare two approaches from the same analysisFork the session
Trap
  • Resuming after a large refactor and trusting the old file reads still in the history.
  • Forking when you only want to continue. A fork is for comparing alternatives.

RememberMostly valid → resume and name the changed files. Mostly stale → fresh session plus a summary. Comparing approaches → fork.

D2

Tool Design & MCP Integration

18% · primary in scenarios 1, 3 and 4

The model chooses tools by reading their names and descriptions. Most tool problems on the exam are fixed by better interfaces: clearer descriptions, narrower tools, structured errors and scoped access.

TASK 2.1

Tool interfaces with clear descriptions and boundaries

In plain words

Claude picks a tool by reading its name and description, the way you would pick a function by reading its documentation. If two tools have vague, similar descriptions ("gets customer info", "gets order details"), Claude will mix them up.

A good description says what the tool does, what input it expects (with an example), what it returns, and when to use it instead of the similar tool next to it. Improving descriptions is usually the first and cheapest fix when the wrong tool gets picked.

New terms: tool description, tool selection, misrouting

Concepts in depth

What a tool definition is, and what Claude actually sees

A tool is a function in your own code that Claude is allowed to ask for. Claude never runs it and never sees its source code. It only sees a short tool definition that you send with every request. The definition has exactly three parts:

  • name A short identifier such as lookup_order. Claude uses it to say which tool it wants. Names should be specific verbs plus nouns. A vague name like process or analyze_content pulls the model toward it for unrelated jobs.
  • description Plain-language documentation for the model. This is the main thing Claude reads when deciding whether to call the tool and which tool to call. Most tool-selection bugs are fixed here.
  • input_schema A JSON Schema describing the arguments: their names, types, formats and which are required. Claude fills these arguments in when it calls the tool. Good field descriptions inside the schema stop it from guessing formats.

Because the definition is all Claude knows, the definition is the interface. If two tools look alike on paper, they look alike to Claude, however different the code behind them is.

A complete, well-written pair of tool definitions

Here are two support tools that used to be confused. Each description answers the same five questions: what it does, what input it expects (with an example), what it returns, its limits, and when to use the neighbouring tool instead.

TOOL DEFINITIONS · PYTHON (CLAUDE API)
TOOLS = [
  {
    "name": "get_customer",
    "description": (
      "Find a customer account and return identity details. "
      "Input: an email address, phone number, or customer ID (format C-12345). "
      "Returns: customer_id, full name, email, phone, account status, "
      "and verified (true/false). "
      "Use this FIRST when you do not yet have a verified customer_id, "
      "or when the user asks about their account, contact details or login. "
      "Do NOT use it to look up orders; use lookup_order for anything about "
      "a specific purchase. If several accounts match, the result lists them all; "
      "ask the user for another identifier instead of choosing one."
    ),
    "input_schema": {
      "type": "object",
      "properties": {
        "identifier": {
          "type": "string",
          "description": "Email, E.164 phone (+14155550123) or customer ID C-12345"
        }
      },
      "required": ["identifier"]
    }
  },
  {
    "name": "lookup_order",
    "description": (
      "Look up ONE order by its order number. "
      "Input: order number in the form #12345 or ORD-12345, plus the verified "
      "customer_id that owns it. "
      "Returns: status, items, amounts in cents, ship and delivery dates. "
      "Use when the user mentions an order, delivery, return or refund for a "
      "specific purchase. Does not search by product name or date range. "
      "Do NOT use to identify a customer; call get_customer first if you only "
      "have a name."
    ),
    "input_schema": {
      "type": "object",
      "properties": {
        "order_number": {
          "type": "string",
          "pattern": "^(#|ORD-)[0-9]{5}$",
          "description": "Order number, e.g. #12345 or ORD-12345"
        },
        "customer_id": {
          "type": "string",
          "description": "Verified customer ID from get_customer, e.g. C-88213"
        }
      },
      "required": ["order_number", "customer_id"]
    }
  }
]
  • "Input: ..." Stating the format with an example means Claude passes #12345 rather than "the blender order". Fewer validation errors, fewer retries.
  • "Returns: ..." Tells Claude what it will learn, so it can judge whether this tool answers the user's question before calling it.
  • "Use this FIRST when..." Explicit selection guidance. This is the line that separates two similar tools.
  • "Do NOT use ... use X instead" A boundary. Naming the neighbouring tool gives Claude a direct alternative instead of leaving it to guess.
  • "If several accounts match..." An edge case. Describing it in the tool means the right behaviour (ask, don't guess) comes with the tool wherever it is used.
  • "pattern", "required" The schema enforces the shape. The description explains the meaning. You need both.

How Claude chooses between tools

When a request arrives, Claude reads the system prompt, the conversation and every tool definition together, then decides whether a tool would help and which one fits best. Nothing else is involved: there is no hidden routing table. That has three consequences.

Vague, overlapping descriptions user request “Where is order #12345?” plausible? plausible? get_customer "Retrieves customer info" lookup_order "Retrieves order details" Both look right Claude may pick either one
Differentiated: use when / not for user request “Where is order #12345?” ruled out fits get_customer use: identity, contact, account not for: orders lookup_order use: order #, shipping, refunds not for: identity One clear match → lookup_order
Claude chooses a tool only by reading its description. When two descriptions overlap, the same request fits both and the choice becomes a coin flip. Saying what each tool is for, and what it is not for, leaves one clear match.
  • Overlap causes misrouting. "Retrieves customer information" and "Retrieves order details" both match "where is my order, I'm Sam?". Claude has nothing to separate them, so it sometimes picks the wrong one.
  • The system prompt can override a good description by accident. If the prompt says "always analyze the content first", a tool named analyze_content becomes attractive because of the shared words, even when its description says it is for something else. Audit the prompt for words that echo tool names.
  • More tools make each choice harder. Every extra definition is another candidate to rule out. Task 2.3 covers keeping each agent's list short.

Fixing overlapping tools, from smallest change to largest

The exam usually asks for the most effective first step, so learn the order.

  1. Rewrite the descriptions to state purpose, inputs, outputs and boundaries, as above. Cheap, targeted, fixes the root cause.
  2. Rename and rescope a tool whose name is misleading: analyze_content becomes extract_web_results, with a description that says it only handles fetched web pages.
  3. Split a generic tool into focused ones with clear contracts. analyze_document, which tried to do everything, becomes extract_data_points, summarize_content and verify_claim_against_source. Each now has one obvious use.
  4. Merge or restructure (for example one lookup_entity tool). Sometimes a fine design, but a large change to make before trying descriptions.
SPLITTING A GENERIC TOOL · BEFORE AND AFTER
# before: one tool, many jobs, vague description
{"name": "analyze_document",
 "description": "Analyzes a document."}

# after: three tools, each with one job
{"name": "extract_data_points",
 "description": "Pull numeric facts (value, unit, date, page) from ONE loaded "
                "document. Use when you need figures to cite. Returns a list."}
{"name": "summarize_content",
 "description": "Write a 150-word neutral summary of ONE loaded document. "
                "Use for an overview, not for citing specific numbers."}
{"name": "verify_claim_against_source",
 "description": "Check whether a single claim is supported by a given document. "
                "Returns supported / contradicted / not_found with the quote."}

How this shows up on the exam

The typical stem: an agent keeps calling the wrong one of two similar tools. The correct answer improves the descriptions (what, inputs, outputs, when to use which). Distractors include adding few-shot examples (they cost tokens and treat the symptom), building a keyword-based routing layer (over-engineered), and merging tools (valid, but too big a first step). If the stem mentions the system prompt using a word that matches a tool name, the fix is to reword the prompt.

Revision summary

The description is the primary mechanism the model uses to select a tool. Minimal or overlapping descriptions cause misrouting between similar tools.

BEFORE → AFTER
// before: the model cannot tell these apart
get_customer:  "Retrieves customer information"
lookup_order:  "Retrieves order details"

// after
lookup_order:
  "Look up a single order by order number (format: #12345 or ORD-12345).
   Use when the user mentions an order, shipment, delivery, return or refund
   for a specific purchase. Returns status, items, amounts, ship/delivery dates.
   Do NOT use to find who a customer is; use get_customer for identity,
   contact details or account status. If only a name is given, call
   get_customer first."

A good description states

  • What it does and what it returns
  • Input formats, with an example query
  • Edge cases and limits
  • When to use it versus its nearest neighbour

Fixes when tools overlap

  • Rename + rescope: analyze_content → extract_web_results with a web-specific description.
  • Split generic tools into purpose-specific ones with defined contracts: analyze_document → extract_data_points, summarize_content, verify_claim_against_source.
  • Audit the system prompt for keyword-sensitive wording. "Always analyze the content first" can pull the model toward a tool named analyze_content regardless of its description.
Trap

Sample Q2 asks for the most effective first step. Better descriptions win. Few-shot examples add tokens without fixing the root cause. A keyword routing layer is over-engineered. Merging into one lookup_entity tool is a valid design but too large a first step.

RememberThe description is the routing signal. Say what the tool does, its inputs and outputs, and when to use it instead of its nearest neighbour.

TASK 2.2

Structured error responses for MCP tools

In plain words

Tools fail, and a good tool tells the agent why so it can react sensibly. A network timeout is worth retrying. A typo in the order number needs corrected input. "Outside the 30-day return window" is a business rule, so retrying is pointless; explain it to the customer. "Not authorised" means stop.

If every failure just says "error", the agent cannot tell these apart. It retries hopeless calls and gives up on fixable ones. Also, "found nothing" and "could not search" are different outcomes and must look different.

New terms: error category, retryable, isError

Concepts in depth

How a tool tells the agent that something went wrong

When an MCP tool runs, it sends back a result: a list of content blocks (usually text) plus a flag called isError. If isError is true, the agent knows the call failed. The text in the content is the only explanation it gets. Claude reads that text and decides what to do next: retry, fix its input, explain something to the user, or stop.

So an error message is not just for a human reading logs. It is input to the model's next decision. A message that says only "Operation failed" gives Claude nothing to decide with. It may retry something that can never succeed, or give up on something that would have worked a second later.

The four kinds of failure, and why they need different reactions

  • transient The system had a temporary problem: a timeout, a 503, a dropped connection. The same call may work in a moment. Right reaction: retry, ideally with a short wait (backoff), and only a few times.
  • validation The input was wrong: an order number in the wrong format, a missing field. Retrying the same call fails again. Right reaction: correct the input, or ask the user for the right value.
  • business The system worked, and the answer is "no" because of a rule: outside the 30-day return window, refund over the limit. Retrying is pointless. Right reaction: explain the policy to the customer, offer alternatives, or escalate.
  • permission The caller is not allowed to do this. Retrying is pointless and may look like an attack. Right reaction: stop, and escalate or request access.

Two extra fields make the agent's job easy: isRetryable (a plain yes/no) and a customerMessage (wording that is safe to show the user). Without them Claude has to guess from the wording.

Tool result isError: false isError: true Success [] = no match say "none found" Failure read errorCategory to choose reaction transient timeout, 503 Retry with backoff isRetryable: true validation bad order format Correct the input retry after fixing business window closed Explain the policy isRetryable: false permission not authorised Stop and escalate isRetryable: false
First separate “empty” from “failed”, then let the error category pick the reaction. Only transient errors are worth retrying as they are; validation errors need a corrected input first. Business and permission errors will fail every time, so the agent explains or escalates instead.

Building it: an MCP tool that returns structured errors

This server uses FastMCP, the high-level server class in the official MCP Python SDK. Raising ToolError inside a tool makes the server return a result with isError: true and the message as its text. We put a small JSON object in that message so the category is machine-readable.

ORDERS MCP SERVER WITH STRUCTURED ERRORS · PYTHON
import json, re
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError
from myapp import db                      # your own data-access layer

mcp = FastMCP("orders")
ORDER_RE = re.compile(r"^(#|ORD-)[0-9]{5}$")

def fail(category: str, code: str, message: str, retryable: bool,
         customer_message: str | None = None):
    # One helper so every error has the same shape
    raise ToolError(json.dumps({
        "errorCategory": category,        # transient | validation | business | permission
        "isRetryable": retryable,
        "code": code,
        "message": message,               # for the agent
        "customerMessage": customer_message,  # safe to show the user
    }))

@mcp.tool()
def lookup_order(order_number: str, customer_id: str) -> dict:
    """Look up one order by number (#12345 or ORD-12345) for a verified customer."""
    if not ORDER_RE.match(order_number):
        fail("validation", "BAD_ORDER_NUMBER",
             f"'{order_number}' is not #12345 or ORD-12345 format.", retryable=False)
    try:
        order = db.get_order(order_number, timeout=3)
    except TimeoutError:
        fail("transient", "DB_TIMEOUT", "Order database timed out after 3s.",
             retryable=True)
    if order is None:
        # Not an error: the search worked and found nothing
        return {"found": False, "order_number": order_number}
    if order.customer_id != customer_id:
        fail("permission", "NOT_OWNER",
             "This order belongs to a different customer.", retryable=False)
    return {"found": True, **order.summary()}

@mcp.tool()
def start_return(order_number: str, customer_id: str) -> dict:
    """Open a return for a delivered order inside the 30-day window."""
    order = db.get_order(order_number)
    if order.days_since_delivery > 30:
        fail("business", "RETURN_WINDOW_EXPIRED",
             f"Delivered {order.days_since_delivery} days ago; window is 30.",
             retryable=False,
             customer_message="This order is past our 30-day return window, "
                              "but I can check warranty options for you.")
    return {"return_id": db.create_return(order).id, "label_url": "..."}

if __name__ == "__main__":
    mcp.run()
  • fail(...) Every failure goes through one helper, so the agent always sees the same fields in the same places. Consistency is what makes errors usable.
  • ToolError Turns the exception into an MCP result with isError: true. The agent sees a failed call, not a crash of the whole server.
  • return {"found": False} A genuine "no such order" is a successful search with an empty answer. It is returned normally, not raised as an error.
  • customerMessage Only set where the agent will need to explain something to the user, such as a business rule.

Empty is not the same as failed

This distinction is tested often. Compare the two results the agent might receive:

TWO DIFFERENT OUTCOMES · WHAT THE AGENT RECEIVES
// 1. The search ran and nothing matched. Safe to tell the customer.
{ "isError": false,
  "content": [{ "type": "text",
                "text": "{\"found\": false, \"order_number\": \"#55555\"}" }] }

// 2. The search could not run. We do NOT know whether the order exists.
{ "isError": true,
  "content": [{ "type": "text", "text": "{\"errorCategory\": \"transient\",
    \"isRetryable\": true, \"code\": \"DB_TIMEOUT\", ...}" }] }

If the tool returned [] or "not found" in case 2, the agent would confidently tell a customer their order does not exist during a database outage. That is worse than any error message: it is a wrong answer that looks like a right one.

Who handles which error

In a multi-agent system, the agent closest to the failure should deal with what it can. A subagent retries transient errors itself (a couple of attempts with backoff). Only when it cannot recover does it report upward, and then it reports richly: the category, what it tried, and any partial results it did get. The coordinator should not have to re-discover what went wrong. Task 5.3 covers this hand-off in detail.

How this shows up on the exam

Typical stems: "the agent keeps retrying a refund that is outside policy", or "the agent tells customers no orders exist during an outage". Correct answers add structured error metadata (category, isRetryable, a clear message) or separate empty results from failures. Distractors: capping retries in the loop (blunt, also stops useful retries), telling the model in the prompt not to retry (same problem), or returning empty results instead of errors (hides the failure).

Revision summary

MCP tools signal failure with isError: true on the result. The content should tell the agent what kind of failure it is, because the right recovery differs.

CategoryExampleRetry?Agent should
TransientTimeout, 503YesRetry with backoff, locally
ValidationBad order-number formatAfter fixing inputCorrect the input or ask the user
BusinessOutside 30-day return windowNoExplain the policy kindly; offer alternatives or escalate
PermissionNot authorized for this accountNoStop; escalate or request access
{
  "isError": true,
  "content": [{ "type": "text", "text": JSON.stringify({
    "errorCategory": "business",
    "isRetryable": false,
    "code": "RETURN_WINDOW_EXPIRED",
    "message": "Order #12345 was delivered 41 days ago; returns close at 30.",
    "customerMessage": "This order is past our 30-day return window, but I can check warranty options."
  })}]
}
  • A uniform "Operation failed" leaves the agent guessing, so it retries things that will never succeed or gives up on things that would.
  • Empty is not failure. "Query succeeded, zero matches" and "could not reach the database" must look different.
  • Subagents retry transient errors themselves and only propagate what they cannot resolve, with partial results and a list of what was tried.
Trap
  • A generic "Operation failed" for every failure.
  • Returning [] when the database was unreachable.
  • Retrying business or permission errors that can never succeed.

RememberReturn a category, isRetryable and a clear message. An empty result is not an error, and an error must never look empty.

TASK 2.3

Distributing tools across agents and configuring tool_choice

In plain words

Like people, agents do better with a small, well-chosen toolbox. Give an agent 18 tools and it picks wrongly more often. Give a writing agent a search tool and it keeps searching instead of writing. So each agent gets only the tools its job needs.

tool_choice is a setting on each request that controls whether Claude must use a tool: auto (its choice), any (must use some tool), a named tool (must use that one), or none (no tools this time).

New terms: least privilege, scoped tool, tool_choice

Concepts in depth

Why fewer tools per agent gives better results

Every tool you give an agent is one more option it must consider on every turn. With 4 or 5 tools that fit its job, the right choice is usually obvious. With 18 tools, several look plausible for any request, and the agent picks wrongly more often. It also spends tokens reading definitions it will never need.

There is a second effect: agents use the tools they are given. A synthesis agent that also has web search will start searching whenever it feels unsure, instead of doing its actual job of writing from the findings it was handed. The tool list quietly shapes the behaviour.

The design principle is least privilege, borrowed from security: give each agent only the tools its role requires. It makes selection more accurate, behaviour more predictable, and mistakes less costly.

Giving each agent its own tool list in the Agent SDK

In the Claude Agent SDK, custom tools are plain Python functions wrapped with the @tool decorator and bundled into an in-process MCP server with create_sdk_mcp_server. Each subagent is declared with an AgentDefinition whose tools list says exactly which tools it may use. Tools from that server get full names of the form mcp__<server>__<tool>.

RESEARCH SYSTEM WITH SCOPED TOOLS · PYTHON (CLAUDE AGENT SDK)
import json
from claude_agent_sdk import (query, tool, create_sdk_mcp_server,
                              ClaudeAgentOptions, AgentDefinition)

@tool("search_web", "Search the web for one subtopic. Returns up to 8 results "
      "with title, url and snippet.", {"query": str})
async def search_web(args):
    hits = await search_client.search(args["query"], limit=8)
    return {"content": [{"type": "text", "text": json.dumps(hits)}]}

@tool("load_document", "Fetch a document (PDF or HTML article) by URL and return "
      "its text. Only accepts http(s) URLs to documents, not search pages.",
      {"url": str})
async def load_document(args):
    url = args["url"]
    if not url.startswith(("https://", "http://")) or "/search?" in url:
        return {"content": [{"type": "text", "text": "Rejected: not a document URL"}],
                "is_error": True}
    return {"content": [{"type": "text", "text": await fetch_text(url)}]}

@tool("verify_fact", "Check ONE short factual claim (a number, date or name) "
      "against a trusted index. Returns supported / contradicted / unknown "
      "with a source. Not for open-ended research.", {"claim": str})
async def verify_fact(args):
    verdict = await fact_index.check(args["claim"])
    return {"content": [{"type": "text", "text": json.dumps(verdict)}]}

research = create_sdk_mcp_server(name="research", version="1.0.0",
                                 tools=[search_web, load_document, verify_fact])

options = ClaudeAgentOptions(
    system_prompt="Coordinate research. Delegate; do not search yourself.",
    mcp_servers={"research": research},
    allowed_tools=["Task"],                    # coordinator only delegates
    agents={
        "searcher": AgentDefinition(
            description="Finds and loads sources for one assigned subtopic.",
            prompt="Return findings as JSON: claim, excerpt, url, published_at.",
            tools=["mcp__research__search_web", "mcp__research__load_document"]),
        "synthesizer": AgentDefinition(
            description="Merges structured findings into a cited draft.",
            prompt="Write only from the findings you are given. Keep every "
                   "claim-to-source link. Use verify_fact for quick checks.",
            tools=["mcp__research__verify_fact"]),   # scoped, not web search
    },
)

async for message in query(prompt="Impact of AI on creative industries",
                           options=options):
    print(message)
  • @tool(name, description, schema) Turns a Python function into a tool definition. The third argument is a simple schema: parameter names and Python types.
  • create_sdk_mcp_server Bundles tools into an MCP server that runs inside your process. No separate program to deploy.
  • allowed_tools=["Task"] The coordinator's own list. It can delegate through the Task tool but cannot search, so it cannot quietly do the subagents' work.
  • AgentDefinition(tools=[...]) Each subagent's toolbox. If you leave tools out, the subagent inherits all available tools, which defeats the point. Always list them for scoped roles.
  • load_document A constrained alternative to a generic fetch_url. It does the one job the searcher needs and rejects anything else, so the tool cannot be misused.
  • verify_fact A scoped cross-role tool. Synthesis is not a research role, but it often needs a quick fact check. A narrow tool covers that common case without handing over full web search.

The scoped-tool trade-off, in numbers

In the guide's research scenario, the synthesis agent sent every fact check back through the coordinator. Each check cost 2 to 3 extra round trips and added about 40% to total latency. But 85% of those checks were simple lookups. Giving synthesis verify_fact removes the round trips for that 85%. The remaining 15% (complex verification that needs real research) still goes through the coordinator, where the searcher can handle it properly.

Coordinator tools: Task only Task Search web_search load_document Synthesis verify_fact no web search Report write_report Synthesis fact checks 85% simple verify_fact, no round trip 15% complex via coordinator
Each agent gets only the tools its role needs. The coordinator can only delegate. Synthesis gets one narrow verify_fact tool for the 85% of checks that are simple lookups, so those skip the 2–3 extra round trips; the rare complex checks still go through the coordinator.

The wrong fixes are instructive. Giving synthesis full web search over-provisions it and invites the "searches instead of writing" problem. Batching all checks to the end creates a blocking dependency. Speculatively caching facts in advance cannot predict what will be needed.

tool_choice: controlling whether a tool must be called

tool_choice is a parameter on a Messages API request. Tool lists decide what an agent can do; tool_choice decides, for one request, whether it must use a tool and which one.

no must {"type": "none"} May not call any tool plain-text answer this turn {"type": "auto"} default May call a tool or reply normal conversational agent {"type": "any"} Must call some tool structured output, type unknown {"type": "tool", "name": …} Must call this exact tool force one step to run first extended thinking: none / auto only
tool_choice is a dial from “no tool allowed” to “this tool, now”. Each request picks one setting. auto is the normal default; any guarantees structured output when several schemas could apply; a named tool forces a specific first step.
THE FOUR MODES · PYTHON (CLAUDE API)
# 1. auto (default): Claude may call a tool or just reply in text
client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS,
    tool_choice={"type": "auto"}, messages=msgs)

# 2. any: Claude MUST call a tool, but chooses which one
#    e.g. three extraction schemas, document type unknown
client.messages.create(model=MODEL, max_tokens=1024,
    tools=[EXTRACT_INVOICE, EXTRACT_RECEIPT, EXTRACT_CONTRACT],
    tool_choice={"type": "any"}, messages=msgs)

# 3. tool: Claude MUST call this exact tool
#    e.g. metadata extraction must happen before enrichment
client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS,
    tool_choice={"type": "tool", "name": "extract_metadata"}, messages=msgs)

# 4. none: Claude may NOT call tools this turn (definitions stay in the request)
client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS,
    tool_choice={"type": "none"}, messages=msgs)
  • auto Normal conversational agents. Claude decides whether a tool helps.
  • any You need structured output every time, and more than one schema could apply. A text reply is impossible, but Claude still picks the right schema.
  • {"type":"tool","name":...} A specific step must happen now. Use it for the first step, then run later steps in follow-up requests with other settings.
  • none You want a plain answer this turn, for example a final summary, without removing tools from the request.

One restriction: with extended thinking turned on, only auto and none are accepted. Forcing a tool with any or a named tool returns an error.

How this shows up on the exam

Look for stems where an agent misuses a tool outside its role, has a long tool list and picks wrongly, or causes latency by routing simple checks through the coordinator. The right answers scope tools per role, swap generic tools for constrained ones, or add one narrow cross-role tool for the frequent case. For tool_choice questions, map the need: "must produce structured output, type unknown" is any; "this step must run first" is a forced named tool.

Revision summary
  • Fewer tools, better choices. 18 tools on one agent degrades selection compared with 4–5 focused ones.
  • Agents given tools outside their role misuse them. A synthesis agent with web search starts searching instead of synthesizing.
  • Constrained alternatives: replace a generic fetch_url with load_document that validates document URLs.
  • Scoped cross-role tools: give synthesis a narrow verify_fact for the common simple check; send deep verification through the coordinator.
tool_choiceBehaviourUse when
{"type":"auto"}Model may call a tool or reply in textNormal conversational agents
{"type":"any"}Must call some tool, model picks whichYou need structured output and several schemas could apply (document type unknown)
{"type":"tool","name":"extract_metadata"}Must call this exact toolA specific step must run first; do later steps in follow-up turns
{"type":"none"}May not call any toolYou want a plain-text answer this turn but keep the tool definitions in the request

With extended thinking on, only auto and none are allowed. Forcing a tool (any or a named tool) returns an error.

Scenario (sample Q9)

Synthesis bounces to the coordinator for every fact check, adding 2–3 round trips and 40% latency. 85% are simple lookups. Give synthesis a scoped verify_fact tool and keep the 15% complex checks on the coordinator path. Full web-search access over-provisions; batching the checks creates blocking dependencies; speculative caching cannot predict needs.

Trap
  • Giving every agent every tool "for flexibility".
  • Fixing latency by giving synthesis full web search. Give it a narrow tool for the common case instead.

Remember4–5 tools per role. Use narrow cross-role tools for the frequent case. any = must call some tool; named = must call that one.

TASK 2.4

Integrating MCP servers into Claude Code and agents

In plain words

MCP (Model Context Protocol) is like USB for AI tools: a standard plug. Someone writes an MCP server for GitHub once, and any MCP-compatible agent can use its tools.

In Claude Code you list the servers you want in a config file. A team puts shared servers in .mcp.json in the repository so everyone gets them, and keeps secrets such as API tokens out of the file by referring to environment variables. Personal servers go in your own config. Besides tools (actions), a server can offer resources: read-only content such as a list of database tables.

New terms: MCP server, .mcp.json, scope, environment variable, resource

Concepts in depth

What MCP is and which problem it solves

Before MCP, every agent framework had its own way of defining tools. A GitHub integration written for one agent had to be rewritten for the next. The Model Context Protocol is an open standard that fixes this. It defines how an AI application asks an external program "what can you do?" and "please do this".

Claude Code MCP client Your SDK agent MCP client same protocol for every pair: list tools · call tool · read resource stdio http orders server yours · local tools (actions) lookup_order resources (read) schema://tables Jira server community · remote tools (actions) create_issue resources (read) jira://projects
MCP is one plug shape between agents and integrations. Any MCP client can use any MCP server. A local server is started as a process and spoken to over stdio; a remote one is reached over HTTP. Servers offer tools (actions the agent asks for) and resources (read-only content it can browse).

There are two sides:

  • MCP server A program that wraps some system (GitHub, Jira, your order database) and offers capabilities over the protocol. You write or install it once.
  • MCP client The AI application that connects to servers: Claude Code, an Agent SDK agent, Claude Desktop. It discovers what each server offers and passes those capabilities to the model.

A server can offer three kinds of things. Know the difference between the first two for the exam:

  • tools Actions the model can call, such as create_issue or lookup_order. They take arguments and may change things.
  • resources Read-only content the application can load, each identified by a URI: a database schema, a list of open issues, a document tree. Resources let the agent see what exists without making a series of exploratory tool calls.
  • prompts Reusable prompt templates the server provides. In Claude Code they appear as slash commands. Less central for this exam.

When the client connects, it asks every configured server for its list of tools and resources. All of them become available at once, side by side with the built-in tools. That is why a project server and your personal server can be used in the same session.

A minimal MCP server with one tool and one resource

This server is written with FastMCP from the official Python SDK. The decorators turn ordinary functions into MCP capabilities. Function names, type hints and docstrings become the tool's name, input schema and description, so write the docstring as carefully as any tool description (task 2.1).

orders_server.py · PYTHON (MCP SDK)
from mcp.server.fastmcp import FastMCP
from myapp import db                     # your own data-access layer

mcp = FastMCP("orders")

@mcp.tool()
def lookup_order(order_number: str, customer_id: str) -> dict:
    """Look up ONE order by number (#12345 or ORD-12345) for a verified customer.
    Returns status, items, amounts in cents and delivery dates.
    Use get_customer first if you only have a name."""
    return db.get_order(order_number, customer_id).summary()

@mcp.resource("schema://orders/tables")
def order_tables() -> str:
    """Tables and columns in the orders database, one per line."""
    return "\n".join(f"{t.name}: {', '.join(t.columns)}" for t in db.tables())

if __name__ == "__main__":
    mcp.run()        # default transport: stdio (the client starts this process)
  • FastMCP("orders") Creates a server named orders. The name shows up in tool names such as mcp__orders__lookup_order.
  • @mcp.tool() Registers an action. Type hints become the JSON input schema; the docstring becomes the description the model reads.
  • @mcp.resource("schema://orders/tables") Registers read-only content at a URI. An agent that needs to write a query can read this once instead of calling a dozen "list columns" tools.
  • mcp.run() Starts the server. With stdio transport the client launches it as a child process and talks over standard input and output. Remote servers use HTTP instead.

Connecting servers to Claude Code: .mcp.json and scopes

Claude Code reads server configuration from three scopes. The scope decides who gets the server and whether it is shared through git:

  • project Stored in .mcp.json at the repository root and committed. Everyone who clones the repo gets the same servers. Use it for team tooling. Claude Code asks each developer to approve these servers before first use, because they came from the repo rather than from you.
  • local The default for claude mcp add. Stored in your ~/.claude.json under this project's entry. Only you, only in this project. Good for experiments or personal credentials.
  • user Also in ~/.claude.json, but available in every project you open. Good for personal tools you always want.
.mcp.json AT THE REPO ROOT · JSON
{
  "mcpServers": {
    "orders": {
      "command": "python",
      "args": ["tools/orders_server.py"],
      "env": { "ORDERS_DB_URL": "${ORDERS_DB_URL}" }
    },
    "jira": {
      "type": "http",
      "url": "https://mcp.internal.example.com/jira",
      "headers": { "Authorization": "Bearer ${JIRA_TOKEN}" }
    }
  }
}
  • "command" / "args" A local (stdio) server: Claude Code starts this process for you.
  • "type": "http" / "url" A remote server reached over HTTP. Nothing runs on your machine.
  • ${ORDERS_DB_URL}, ${JIRA_TOKEN} Environment-variable expansion. The file says which variable to use; each developer sets the real secret in their own environment. The token never enters git.

You can write the file by hand or use the CLI, which writes it for you:

ADDING SERVERS FROM THE COMMAND LINE · BASH
# team server, written to .mcp.json (commit it)
claude mcp add --scope project orders -- python tools/orders_server.py

# personal remote server, available in every project
claude mcp add --scope user --transport http notes https://mcp.example.com/notes

# personal server for this project only (local is the default scope)
claude mcp add scratch-db -- python ~/tools/scratch_db.py

claude mcp list            # everything configured, and from which scope

Inside a Claude Code session, resources can be pulled into the conversation with an @ mention of the server and resource, and server-provided prompts appear as slash commands.

User scope ~/.claude.json you, every project Project scope .mcp.json, in git whole team Local scope ~/.claude.json entry you, this repo only Session all servers merged into one list git repo · .mcp.json "Bearer ${JIRA_TOKEN}" filled in at runtime shell env or CI secret JIRA_TOKEN=… never committed
Scopes decide who gets a server; environment variables keep secrets out of git. Claude Code merges user, project and local servers into one session. The shared .mcp.json only names the variable, and each developer or CI job supplies the real value.

Using the same server from an Agent SDK agent

Because MCP is a standard, the same orders_server.py works in your own agent. You pass the same kind of configuration through mcp_servers:

SAME SERVER, SDK AGENT · PYTHON (CLAUDE AGENT SDK)
import os
from claude_agent_sdk import query, ClaudeAgentOptions

options = ClaudeAgentOptions(
    mcp_servers={
        "orders": {
            "command": "python",
            "args": ["tools/orders_server.py"],
            "env": {"ORDERS_DB_URL": os.environ["ORDERS_DB_URL"]},
        }
    },
    allowed_tools=["mcp__orders__lookup_order"],
)

async for message in query(prompt="Where is order #12345 for C-88213?",
                           options=options):
    print(message)

Build, reuse, and getting the agent to prefer your tool

  • Reuse before you build. For standard systems such as GitHub or Jira, use an existing community server. Write a custom server only for workflows specific to your team or company.
  • When the agent ignores your MCP tool. A common case: you add a powerful code-search MCP tool, but the agent keeps using the built-in Grep. The agent is choosing by description, and Grep's is clear. Fix it by describing what your tool can do that Grep cannot ("searches across all 40 repositories and returns symbol definitions with call sites"), not by forbidding Grep.

How this shows up on the exam

Common stems: "the whole team needs the same integration, and the token must not be committed" (project scope in .mcp.json plus ${ENV_VAR}); "a developer wants to try a server just for themselves" (local or user scope); "the agent makes many exploratory calls to learn what tables exist" (expose a resource); "should we build a Jira server?" (no, use a community one). Wrong answers include committing tokens, adding .mcp.json to .gitignore (then nobody gets the config), and asking every developer to configure the team server by hand.

Revision summary
ScopeFileShared via git?Use for
Local (default)~/.claude.json, under this project's entryNoPersonal server or credentials for this one project
Project.mcp.json in repo rootYesTeam tooling: GitHub, Jira, internal APIs
User~/.claude.jsonNoPersonal servers you want in every project
claude mcp add --scope project github -- npx -y @modelcontextprotocol/server-github
claude mcp add --scope user --transport http notes https://mcp.example.com/notes
claude mcp list        # what is configured, and from which scope
.mcp.json WITH ENV-VAR EXPANSION
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }   // secret stays out of git
    },
    "orders-api": {
      "type": "http",
      "url": "https://mcp.internal.example.com/orders",
      "headers": { "Authorization": "Bearer ${ORDERS_API_TOKEN}" }
    }
  }
}
  • Tools from all configured servers are discovered at connection time and available at once. A project server and a personal server work side by side.
  • Tools vs resources. Tools perform actions. Resources expose readable content catalogs (issue summaries, doc hierarchies, database schemas) so the agent can see what exists without exploratory tool calls.
  • If the agent keeps using built-in Grep instead of your more capable MCP search, improve the MCP tool's description of what it can do and return.
  • Prefer an existing community server for standard systems (Jira, GitHub). Build custom servers only for team-specific workflows.
  • Claude Code asks each developer to approve project-scoped servers from .mcp.json before first use.
Trap
  • Committing a token in .mcp.json instead of using ${ENV_VAR}.
  • Asking every developer to configure the same team server by hand at user scope.
  • Writing a custom server for Jira or GitHub when community servers exist.

RememberTeam server → .mcp.json plus env vars. Personal → local or user scope. Catalogs the agent should browse → resources.

TASK 2.5

Choosing built-in tools: Read, Write, Edit, Bash, Grep, Glob

In plain words

Claude Code and the Agent SDK come with built-in tools for working on code. Two are easy to confuse: Grep searches inside files for text ("where is processRefund called?"), and Glob finds files by name pattern ("all test files"). Read opens a file, Edit changes one specific piece of text, Write creates or replaces a whole file, and Bash runs commands.

Good agents explore step by step: search for a starting point, read it, follow the trail. They do not read every file up front.

New terms: Grep, Glob, Read, Edit, Write, Bash

Concepts in depth

What the built-in tools are

Claude Code, and agents built with the Claude Agent SDK, come with a set of ready-made tools for working with files and code. You do not define them; they are already there, and you enable or restrict them with settings such as allowed_tools. Each is a normal tool call under the hood: Claude sends a tool_use with arguments, the harness runs it, and the output comes back as a tool_result.

The exam expects you to know which tool fits which job, and why the wrong one causes trouble. The examples below show the arguments Claude sends for each.

Each tool, with an example call

EXAMPLE TOOL CALLS · JSON (ARGUMENTS CLAUDE SENDS)
// Grep: search INSIDE files for text or a regex
{ "name": "Grep",
  "input": { "pattern": "processRefund\\(", "glob": "**/*.ts",
             "output_mode": "content" } }

// Glob: find files by NAME or path pattern
{ "name": "Glob", "input": { "pattern": "src/**/migrations/*.sql" } }

// Read: show a file's contents (optionally a range of lines)
{ "name": "Read",
  "input": { "file_path": "/repo/src/refunds/service.ts", "offset": 40, "limit": 80 } }

// Edit: replace one exact, unique piece of text in a file
{ "name": "Edit",
  "input": { "file_path": "/repo/src/refunds/service.ts",
             "old_string": "if (amount > 500) {",
             "new_string": "if (amount > REFUND_LIMIT_CENTS) {" } }

// Write: create a new file, or replace a file's entire contents
{ "name": "Write",
  "input": { "file_path": "/repo/src/refunds/limits.ts",
             "content": "export const REFUND_LIMIT_CENTS = 50_000;\n" } }

// Bash: run a shell command (tests, builds, git)
{ "name": "Bash", "input": { "command": "npm test -- refunds" } }
  • Grep Answers "where does this text appear?" Use it for callers of a function, an error message, an import, a config key. It returns matching lines or file names, not whole files, so it is cheap on context.
  • Glob Answers "which files exist that match this name?" Use it for "all test files" (**/*.test.tsx) or "every migration". It never looks inside files.
  • Read Shows a file so Claude can understand it. Read whole files when you need the full flow; read a line range for a big file.
  • Edit Changes a specific snippet. old_string must match the file exactly and only once, so the tool knows which spot to change.
  • Write Creates a file or overwrites it completely. Right for new files; risky for small changes to large files, because the whole content is replaced.
  • Bash Runs commands. Use it for things that need execution (tests, builds, git), not for reading or searching files when a dedicated tool exists.

The classic confusion is Grep versus Glob. A memory aid: Grep greps contents; Glob globs names. Using Glob to find where processRefund is called finds nothing useful; using Grep to list test files is slow and noisy.

Glob: matches file names Glob "**/*.test.ts" src/ refunds/ service.ts service.test.ts orders/ api.ts api.test.ts returns: 2 file paths
Grep: matches text inside files Grep "processRefund" routes.ts import { processRefund } router.post("/refunds", …) service.ts const LIMIT = 50_000 export function processRefund( returns: matching lines
Glob looks at names; Grep looks inside. Use Glob to find files by path pattern (all tests, all migrations) and Grep to find where text appears (callers, error strings, imports). Neither loads whole files, so both are cheap on context; Read comes after, for the files that matter.

When Edit fails: non-unique anchors

Edit refuses to run if old_string appears more than once, because it cannot tell which occurrence you meant. Suppose "timeout": 30 appears four times in a config file. There are three sensible responses:

  1. Widen the anchor. Include enough surrounding lines to make the match unique (for example the section name above the line).
  2. Replace all, but only if every occurrence really should change.
  3. Read then Write. Read the full file, produce the corrected full content, and Write it back. This is the fallback the exam guide names.

Retrying the same Edit is never the answer: the file has not changed, so it fails the same way.

Exploring a codebase step by step

Reading every file up front fills the context with code that does not matter, and the important parts get less attention (task 5.4). Good exploration is incremental: find an entry point, read it, follow the trail. Here is how an agent should answer "How does a refund get processed, and where is the $500 limit enforced?"

INCREMENTAL EXPLORATION · WALK-THROUGH
1. Grep  pattern="refund" glob="src/**/routes*"     # find the entry point
         -> src/api/routes.ts:88   router.post("/refunds", refundController.create)

2. Read  src/api/refundController.ts                   # read only that file
         -> calls refundService.process(order, amount)

3. Grep  pattern="export .*process" path="src/refunds"  # follow the import
         -> src/refunds/service.ts:41

4. Read  src/refunds/service.ts offset=30 limit=60      # read the relevant range
         -> if (amount > 500) throw new LimitError(...)   # found the rule

5. Grep  pattern="LimitError"                           # who handles the error?
         -> src/api/errors.ts, src/escalation/handoff.ts

6. Glob  pattern="src/refunds/**/*.test.ts"             # find the existing tests

Six calls, a handful of files read, and a precise answer. Each step was chosen from what the previous step revealed.

Tracing usages through wrapper modules

Large codebases often have wrapper or "barrel" modules that re-export functions, sometimes under new names (export { processRefund as refund } from "./service"). Grepping only for processRefund misses callers that use refund. The reliable method: first list everything the wrapper exports (Read it, or Grep for export in it), then Grep for each exported name across the codebase.

How this shows up on the exam

Expect questions that describe a need ("find every place an error string is logged", "find all migration files", "Edit failed because the text appears several times") and ask for the right tool or fallback. Distractors swap Grep and Glob, use Bash with sed or cat where a dedicated tool fits, retry a failed Edit, or read the whole repository up front.

Revision summary
I need to…ToolExample
Find text inside filesGrepAll callers of processRefund, an error string, an import
Find files by name or pathGlob**/*.test.tsx, src/**/migrations/*.sql
See a whole fileReadFollow an import to understand a flow
Change a specific snippetEditRequires the old text to match uniquely
Create or fully replace a fileWriteNew file, or fallback when Edit's anchor is not unique
Run commandsBashTests, builds, git
  • Edit fails on non-unique matches. Fallback: Read the file, then Write the full new content.
  • Explore incrementally: Grep for entry points, Read to follow imports, trace the flow. Do not read every file up front.
  • Wrapper modules: list everything a module exports first, then Grep for each exported name to find all usages, including re-exports under different names.
Trap
  • Using Glob to search file contents, or Grep to find files by name.
  • Reading every file up front instead of following entry points.
  • Retrying Edit on an anchor that is not unique.

RememberGrep = contents. Glob = names. Edit needs a unique anchor: widen it, or Read then Write.

D3

Claude Code Configuration & Workflows

20% · primary in scenarios 2, 4 and 5

Most questions here are "where does this file go" and "which mechanism fits." Learn the file layout and the reason each mechanism exists: always-loaded context, conditional context, on-demand workflows, or headless automation.

FILE MAP · WHAT IS SHARED AND WHAT IS PERSONAL
~/.claude/                       personal · never in git
  CLAUDE.md                      your instructions, every project
  commands/*.md                  personal slash commands
  skills/<name>/SKILL.md          personal skills (use distinct names)
~/.claude.json                   user-scoped MCP servers

repo/                            shared · committed
  CLAUDE.md  (or .claude/CLAUDE.md)  project standards, always loaded
  .mcp.json                      team MCP servers, ${ENV} expansion
  .claude/
    rules/*.md                   topic rules; optional paths: globs
    commands/*.md                team slash commands  → /review
    skills/<name>/SKILL.md        team skills with frontmatter
  packages/api/CLAUDE.md         directory-level, loads for that subtree
TASK 3.1

CLAUDE.md hierarchy, scoping and modular organization

In plain words

CLAUDE.md is a plain text file of instructions that Claude Code reads automatically at the start of every session, like an onboarding note for a new teammate ("we use TypeScript; run the tests with npm test").

It can live in three places: your home folder (only you see it), the project root (the whole team, committed to git), or a sub-folder (applies when working there). Large projects split instructions into smaller topic files. The /memory command shows which instruction files are loaded right now.

New terms: CLAUDE.md, user / project / directory level, @import, /memory

Concepts in depth

What CLAUDE.md actually is

CLAUDE.md is an ordinary Markdown file. There is no special syntax to learn and nothing is compiled or validated. When a Claude Code session starts, Claude Code finds the CLAUDE.md files that apply to where you are working and adds their text to the context, alongside the system prompt. From then on Claude reads those instructions on every turn, exactly as if you had typed them at the start of the conversation.

Two consequences follow from "it is just text in the context". First, it is guidance, not enforcement. Claude follows CLAUDE.md very reliably, but it is still a prompt; a rule that must never be broken belongs in a hook or a permission setting (see 1.5). Second, it costs context on every request. A 2,000-line CLAUDE.md is read on every turn, whether or not it is relevant, so keep it focused on what applies to most work in the project.

Good things to put in CLAUDE.md: how to build, test and lint; the project's architecture in a few lines; naming and style conventions; "always" and "never" rules; where important things live. Bad things to put in it: long procedures you only run occasionally (make those skills, see 3.2) and rules that only apply to one kind of file (make those path-scoped rules, see 3.3).

The three levels, and who sees each one

Claude Code looks for CLAUDE.md files in three kinds of places. The difference between them is mostly about who shares the instructions.

  • ~/.claude/CLAUDE.md User level. Lives in your home directory, so it applies to every project you open on this machine. It is never in a git repository, so nobody else ever sees it. Use it for personal preferences: your editor habits, how verbose you like explanations, your own shortcuts.
  • ./CLAUDE.md or ./.claude/CLAUDE.md Project level. Lives in the repository root and is committed, so everyone who clones the repo gets the same instructions. This is where team standards belong.
  • packages/billing/CLAUDE.md Directory level. A CLAUDE.md inside a sub-folder. It is loaded when Claude works with files in that part of the tree, which keeps package-specific rules out of everyone else's context.

Organizations can also deploy a managed, organization-wide instruction file through policy settings, but for the exam the three levels above are what matter.

PROJECT LEVEL · ./CLAUDE.md (COMMITTED)
# Acme Shop monorepo

## Architecture
- packages/web: Next.js storefront (TypeScript, React 18)
- packages/api: Node REST API, Postgres via Prisma
- packages/billing: payment service (strict rules, see its own CLAUDE.md)

## Commands
- Install: pnpm install
- Test one package: pnpm --filter <package> test
- Lint + typecheck before you say a task is done: pnpm lint && pnpm typecheck

## Conventions
- TypeScript strict mode everywhere. No `any` without a comment explaining why.
- Function and file names: camelCase. React components: PascalCase.
- API errors use the shape in docs/standards/api-errors.md.
- Never edit files under generated/ ; regenerate them with pnpm codegen.

## Standards (imported)
@docs/standards/testing.md
@docs/standards/git-workflow.md
USER LEVEL · ~/.claude/CLAUDE.md (PERSONAL, NEVER SHARED)
# My preferences
- Explain your plan in 3-5 bullets before large edits.
- I use VS Code; give file paths as clickable relative paths.
- When you run tests, show me only the failing ones.
DIRECTORY LEVEL · packages/billing/CLAUDE.md
# Billing service
- Money is always integer cents (type Cents = number). Never use floats for money.
- Every external payment call goes through src/gateway.ts, which handles retries.
- Log payment events with logPayment(); never log card numbers or full emails.
@../../docs/standards/pci-logging.md

@imports: building CLAUDE.md from smaller files

A line that starts with @ followed by a path, such as @docs/standards/testing.md, tells Claude Code to pull that file's content in at that point. Relative paths are resolved from the file that contains the import. Imported files can import others, so you can build a small tree of standards documents.

Imports solve two problems. They let a team keep standards in normal documentation files that humans also read, instead of duplicating them inside CLAUDE.md. And they let each package choose only the standards that apply to it: the billing package imports the PCI logging rules, the web package does not, so web work never pays the context cost of payment rules.

.claude/rules/: one topic per file

As a project grows, a single CLAUDE.md turns into a long, hard-to-maintain document that everyone edits. The .claude/rules/ folder lets you split instructions into focused Markdown files, one per topic. A rules file with no frontmatter is loaded for every session, just like CLAUDE.md. A rules file with a paths list in its frontmatter loads only when Claude works on matching files; that is task 3.3.

.claude/rules/
  api-conventions.md    # always loaded: REST naming, pagination, error shape
  deployment.md         # always loaded: never push to main, release via tags
  testing.md            # paths: ["**/*.test.ts", "**/*.test.tsx"]  (loads only for tests)

How the levels combine

The levels do not replace each other. Everything that applies is loaded together: your user file, the project file, any rules files, and any directory file for the area you are working in. Claude sees all of them at once. That is why a new hire and a senior engineer can get different behaviour from the same repository: the senior engineer has extra instructions in a user file the new hire does not have.

Because these are instructions rather than settings, there is no strict "override" mechanism. If two files contradict each other, Claude has to guess. The practical rule is to put general rules at the project level, add only narrower specifics in directory files, and keep personal files to preferences that do not change project behaviour.

~/.claude/CLAUDE.mdyour preferences personalnot in git CLAUDE.md (repo root)+ @imported files in gitteam shares .claude/rules/*.mdone topic per file in gitteam shares packages/api/CLAUDE.mdonly when working there in gitteam shares all applicable files load together One session's context every file above, read side by side no override: conflicts make Claude guess
The levels add up; they do not replace each other. Every file that applies is loaded into the same context. The directory file (dashed) joins only when Claude works in that folder. Only the user file lives outside git, which is why a teammate can see different behaviour from the same repository.

/memory: seeing what is loaded

Type /memory in a Claude Code session to see which instruction files are loaded and to open one for editing. It is the first thing to check when "Claude does X for me but not for my colleague": run /memory on both machines and compare the lists. Very often the missing rule turns out to live in someone's ~/.claude/CLAUDE.md.

How this shows up on the exam

Expect "where should this instruction live?" questions. Team-wide and must be shared: project CLAUDE.md or .claude/rules/, committed. Personal: ~/.claude/CLAUDE.md. Only relevant to one package: that package's directory CLAUDE.md, or an @import from it. Behaviour differs between people: check /memory, and suspect user-level files. Wrong answers usually put team rules in a personal file, or cram every topic into one giant root file.

Revision summary
  • Three levels: user (~/.claude/CLAUDE.md), project (CLAUDE.md at root or .claude/CLAUDE.md), directory (a CLAUDE.md in a subfolder).
  • User-level is private. Instructions there are not in version control, so teammates never get them.
  • @import pulls other files into a CLAUDE.md, e.g. @docs/standards/testing.md. Each package can import only the standards that apply to it.
  • .claude/rules/ replaces one huge CLAUDE.md with focused files: testing.md, api-conventions.md, deployment.md.
  • /memory shows which memory files are loaded. Use it first when behaviour differs between people or sessions.
# packages/billing/CLAUDE.md
Billing service. Money is integer cents; never floats.
@../../docs/standards/api-errors.md
@../../docs/standards/pci-logging.md
Scenario

A new hire's Claude ignores the team's naming convention that works for everyone else. /memory shows the convention lives only in a senior engineer's ~/.claude/CLAUDE.md. Move it to the project CLAUDE.md (or a rules file) and commit it.

Trap
  • Team rules living in one person's ~/.claude/CLAUDE.md.
  • A 2,000-line root CLAUDE.md covering every topic, where focused .claude/rules/ files or @import would do.

RememberShared → project CLAUDE.md or .claude/rules/, committed. Personal → ~/.claude/. Debug with /memory.

TASK 3.2

Custom slash commands and skills

In plain words

A slash command or skill is a saved, reusable instruction you trigger by name, such as /review. Put it in the project's .claude folder to share it with the team, or in your home folder to keep it personal.

Settings at the top of a skill file change how it runs. context: fork runs it in a separate sub-session so its long output does not clutter your chat. allowed-tools limits what it may do. Rule of thumb: rules that always apply go in CLAUDE.md; procedures you run now and then become skills.

New terms: slash command, skill, frontmatter, context: fork, allowed-tools

Concepts in depth

Why reusable instructions exist

Some instructions are not rules that apply all the time. They are procedures you run now and then: "review this branch against our checklist", "prepare a release", "map this module". Typing the full procedure every time is slow and inconsistent; putting it in CLAUDE.md wastes context on every request, even when you are not doing that task. Slash commands and skills solve this. You write the procedure once in a file, and it only enters the context when it is used.

Anatomy of a slash command

A slash command is a Markdown file in a commands folder. The file name becomes the command name: .claude/commands/review.md gives you /review. The body of the file is the prompt Claude receives when you run the command. Optional YAML frontmatter at the top (between --- lines) adds settings.

.claude/commands/review.md · COMMITTED, SO THE WHOLE TEAM GETS /review
---
description: Review this branch against the team checklist
argument-hint: [focus-area]
allowed-tools: Read, Grep, Glob, Bash(git diff:*), Bash(git log:*)
---
Review the changes on the current branch compared with main.

Focus area from the user (may be empty): $ARGUMENTS

Steps:
1. Run `git diff main...HEAD` and list the changed files.
2. For each file, check against docs/review-checklist.md.
3. Report only: bugs, security issues, missing tests, broken API contracts.
   Skip formatting and naming; the linter handles those.
4. Output a table: file | line | severity (critical/major/minor) | issue | fix.
  • description A one-line summary shown in the command list when you type /. It helps people (and Claude) know what the command is for.
  • argument-hint Shown next to the command name as you type, so people know what to pass, for example /review security.
  • allowed-tools Which tools this command may use without asking. Here it can read and search, and run only git diff and git log. A review command has no reason to write files or run arbitrary shell commands, so it is not allowed to.
  • $ARGUMENTS Replaced by whatever the user typed after the command name. /review auth flow puts "auth flow" there. If nothing was typed, it is empty, which is why the prompt says "may be empty".

Where the file lives decides who gets it. .claude/commands/ inside the repository is committed and shared with everyone who clones it. ~/.claude/commands/ in your home folder is personal and works in every project you open.

Anatomy of a skill

A skill is a richer version of the same idea. Instead of a single file, a skill is a folder with a SKILL.md file inside, plus any supporting files the procedure needs: checklists, templates, scripts. Skills have two extra powers. Claude can load a skill automatically when the task matches the skill's description, without anyone typing its name. And a skill can run in a forked context, a separate sub-session whose long working output never enters your main conversation.

.claude/skills/analyze-module/ · FOLDER LAYOUT
.claude/skills/analyze-module/
  SKILL.md            # instructions + frontmatter (required)
  report-template.md  # supporting file the instructions refer to
  risk-criteria.md    # supporting file: what counts as "risky"
.claude/skills/analyze-module/SKILL.md
---
name: analyze-module
description: Deep-dive one module and report its structure, hotspots and risks.
  Use when asked to map, audit, explain or assess a module or package.
argument-hint: <module-path>
allowed-tools: Read, Grep, Glob
context: fork
---
Analyze the module at $ARGUMENTS.

1. Find its entry points and public exports.
2. Trace its dependencies, inside and outside the repo.
3. Find functions with no tests (search for their names in *.test.* files).
4. Rate risk using risk-criteria.md in this folder.

Return a report following report-template.md. Keep it under 60 lines:
the caller only needs the summary, not your working notes.
  • name The skill's identifier, and the name you type to run it (/analyze-module). Use lowercase words joined by hyphens.
  • description The most important field. Claude reads it to decide when the skill is relevant, so it should say both what the skill does and when to use it. A vague description means the skill is never picked up automatically, or is picked up at the wrong time.
  • argument-hint Tells the person what to pass. If they run the skill with nothing, the hint reminds them a module path is expected.
  • allowed-tools Limits what the skill can do. This one may only read and search, so even a badly-worded request cannot make it edit code or run shell commands. That is "limiting blast radius".
  • context: fork Runs the skill in an isolated sub-agent. All the file reads and intermediate notes stay in that sub-agent; only the final report comes back to your conversation. Use it for skills that produce a lot of exploratory output, which would otherwise fill your context and make later answers worse.
  • $ARGUMENTS Same as in commands: replaced by what the user typed after the skill name.

A related option, disable-model-invocation: true, stops Claude from triggering a skill on its own, so it only runs when a person types its name. That suits procedures with side effects, such as a deploy.

Without context: fork you: /analyze-module runs in main chat inside the main chat reads40 files 3,000 linesof notes summary at the end main context used
With context: fork you: /analyze-module brief only forked sub-session reads40 files 3,000 linesstay here summary only ~30 lines in main chat main context used
context: fork moves the noisy work out of your conversation. Both runs do the same reading. Without a fork, every file read and note lands in the main chat and crowds out what came before. With a fork, the work happens in a separate sub-session and only the short summary comes back.

Personalising a team skill without breaking it for others

Suppose the team has .claude/skills/deploy-check/ and you want a version with two extra steps. Editing the shared file changes it for everyone. Creating a personal copy with the same name in ~/.claude/skills/ creates two skills that compete for the same name. The clean answer is a personal copy with a different name, such as ~/.claude/skills/deploy-check-dhairya/, which you change freely.

Choosing: CLAUDE.md, rule, command or skill?

The instruction is…Put it inWhy
True for almost every task in the projectCLAUDE.mdAlways loaded; no one needs to remember to invoke it
True only for certain kinds of file.claude/rules/ with pathsLoads only when matching files are touched (3.3)
A short procedure people run by nameSlash commandOne file, simple, no context cost until used
A procedure with supporting files, noisy output, or one Claude should apply automaticallySkillFolder for resources, context: fork, auto-invocation from the description

Recent Claude Code versions treat commands and skills as the same mechanism underneath: a command file and a skill folder both give you a /name. The difference is what a skill adds on top.

CLAUDE.md testrule skill/release session starts edit api.ts edit Cart.test.tsx type /release – – – – –
Each mechanism enters the context at a different moment. A circle marks when it loads; the bar shows it staying in the conversation afterwards. CLAUDE.md is there from the first message, a path rule joins when a matching file is touched, and a skill or command only when someone (or Claude) invokes it.

How this shows up on the exam

Expect questions about location (team: .claude/; personal: ~/.claude/), about which frontmatter fixes which problem (output floods the conversation → context: fork; skill must not modify files → allowed-tools), and about choosing between CLAUDE.md and a skill. A common trap: allowed-tools restricts actions; it does nothing about the volume of output. Another: putting an always-on rule in a skill, which only loads when invoked.

Revision summary
Project (shared)User (personal)
Commands.claude/commands/~/.claude/commands/
Skills.claude/skills/<name>/SKILL.md~/.claude/skills/<name>/SKILL.md
SKILL.md FRONTMATTER
---
name: analyze-module
description: Deep-dive one module and report structure, hotspots and risks.
context: fork                     # run in an isolated sub-agent; only the summary returns
allowed-tools: Read, Grep, Glob   # restrict what the skill may do
argument-hint: <module-path>      # prompts the dev when invoked with no argument
---
Map the module at $ARGUMENTS. Return: entry points, dependencies,
untested paths, and the three riskiest functions with reasons.
  • context: fork keeps verbose output (codebase analysis) or exploratory noise (brainstorming) out of the main conversation.
  • allowed-tools limits blast radius, for example a skill that may only write files and never run shell commands.
  • To customise a team skill for yourself, create a personal copy with a different name in ~/.claude/skills/ so teammates are not affected.
  • Commands vs skills: .claude/commands/review.md and .claude/skills/review/SKILL.md both give you /review. A skill also gets a folder for supporting files, and Claude can load it automatically when the task matches its description.
Skill or CLAUDE.md?

CLAUDE.md = always loaded, universal standards. Skill = on-demand, task-specific workflow. A rule every edit should follow does not belong in a skill; a 40-line release checklist does not belong in CLAUDE.md.

Trap
  • Editing the shared team skill to suit yourself.
  • Putting an always-on rule in a skill, which only loads when invoked.
  • Expecting allowed-tools to reduce output volume. That is what context: fork does.

RememberProject skills and commands live in .claude/ and are committed. Personal ones live in ~/.claude/. Noisy → context: fork. Risky → allowed-tools.

TASK 3.3

Path-specific rules for conditional loading

In plain words

Some conventions belong to a type of file rather than a folder. Test files, for example, often sit next to their components all over the project.

A rule file in .claude/rules/ can say which files it applies to, using a pattern such as **/*.test.tsx (any file ending in .test.tsx, in any folder). Claude Code loads the rule only while it works on matching files. That saves space and avoids irrelevant advice.

New terms: path-scoped rule, glob pattern

Concepts in depth

The problem: conventions that follow file types, not folders

CLAUDE.md files are tied to places: the project root, or a specific folder. Many real conventions are tied to kinds of file instead. Test files usually sit next to the component they test, so they are scattered through dozens of folders. Database migrations, Terraform files, GraphQL schemas and Storybook stories are often the same. To cover those with directory CLAUDE.md files you would need one in every folder that contains a test, and you would have to keep them all in sync. Putting the rules in the root CLAUDE.md instead means every session pays for them, even sessions that never touch a test.

Path-scoped rules solve this. A rules file says which files it applies to, and Claude Code loads it only when Claude is working with a matching file.

How a path-scoped rule is written

A rule is a Markdown file in .claude/rules/. The optional frontmatter at the top holds a paths list of glob patterns. The body is the instruction text, exactly as you would write it in CLAUDE.md.

.claude/rules/react-tests.md
---
paths:
  - "**/*.test.tsx"
  - "**/*.test.ts"
---
# Writing tests
- Use React Testing Library. Query by role or label, never by test id.
- One behaviour per test; the test name states the behaviour.
- Build data with the factories in test/factories/, not inline objects.
- Mock network calls with msw handlers from test/handlers.ts.
.claude/rules/migrations.md
---
paths: ["db/migrations/**/*.sql"]
---
- Migrations are append-only. Never edit a migration that has been merged.
- Every migration needs a matching down migration in the same folder.
- Add indexes with CREATE INDEX CONCURRENTLY.

When Claude reads or edits src/cart/CartSummary.test.tsx, the first rule's pattern matches and its text is added to the context. When Claude edits src/cart/CartSummary.tsx (not a test), it does not load, so that work stays uncluttered. A rules file with no paths list is loaded in every session, just like CLAUDE.md.

Reading glob patterns

A glob is a short pattern that matches file paths. Two wildcards do almost all the work: * matches any characters within one folder name or file name, and ** matches any number of folders, including none. Paths are relative to the project root.

PatternMatchesDoes not match
**/*.test.tsxButton.test.tsx, src/ui/Button.test.tsx, a/b/c/X.test.tsxButton.tsx, Button.test.ts
*.mdREADME.md in the rootdocs/guide.md (it is in a sub-folder)
docs/**/*.mddocs/guide.md, docs/api/errors.mdREADME.md
src/api/**/*.tssrc/api/orders.ts, src/api/v2/users/get.tssrc/web/api.ts
terraform/**/*every file anywhere under terraform/infra/main.tf
src/**/*.{ts,tsx}both .ts and .tsx files under src/src/styles.css

The most common mistake is forgetting **/. The pattern *.test.tsx only matches test files in the project root, which is almost never what you want.

.claude/rules/testing.md paths: ["**/*.test.tsx"] src/ components/ Button.tsx Button.test.tsxmatch checkout/ Cart.tsx Cart.test.tsxmatch utils/ money.ts money.test.tsno: .ts e2e/ login.test.tsxmatch edit Cart.test.tsxrule loads edit money.tsnot loaded
A path rule follows the file pattern, not the folder. ** means "any folders", so test files in components/, checkout/ and e2e/ all match. money.test.ts does not, because the pattern asks for .tsx. Claude Code loads the rule only when it works on a matching file.

Path rules versus the alternatives

  • Directory CLAUDE.md Best when the convention belongs to one area of the tree, such as the billing package. Poor for file types spread across many folders.
  • Root CLAUDE.md Always loaded, so it works, but it wastes context on unrelated work, and Claude has to infer when the rule applies.
  • Skill Loads only when invoked or when its description matches. A convention that must be followed every time a test is touched should not depend on someone remembering to invoke a skill.
  • .claude/rules/ + paths Loads automatically and deterministically whenever a matching file is involved, and nowhere else. One file to maintain.

How this shows up on the exam

The signal is a convention for files that are spread across directories: tests next to components, migrations, Terraform, schema files. The answer is a .claude/rules/ file with a paths glob. Distractors are subdirectory CLAUDE.md files (bound to folders), one big root file (relies on inference and wastes tokens) and a skill (needs invoking).

Revision summary
# .claude/rules/testing.md
---
paths: ["**/*.test.tsx", "**/*.test.ts"]
---
Use React Testing Library. Query by role, not test id.
One behaviour per test. Use fixtures from test/fixtures/.

# .claude/rules/terraform.md
---
paths: ["terraform/**/*"]
---
Every resource gets owner and cost-center tags. No inline IAM policies.
  • Rules with a paths glob load only when Claude edits matching files, saving tokens and avoiding irrelevant guidance.
  • Glob rules beat subdirectory CLAUDE.md files for conventions that span directories, such as test files living next to their components everywhere.
Trap (sample Q6)

Tests sit beside components across the tree. Subdirectory CLAUDE.md files are bound to directories; one big root CLAUDE.md relies on inference; skills need invocation. Path-scoped rules are the deterministic, maintainable answer.

RememberA convention that follows a file pattern across directories → .claude/rules/*.md with paths globs.

TASK 3.4

Plan mode vs direct execution

In plain words

Plan mode makes Claude Code look and think before it changes anything: it reads the code, proposes a plan and waits for your approval. That is worth it for big or risky changes, such as splitting a large app into services or a migration across 45 files, where a wrong start wastes hours.

For a small, clear fix (one file, an obvious bug), let it work directly. A common combination: plan, approve, then execute.

New terms: plan mode, direct execution, Explore subagent

Concepts in depth

What plan mode is

Claude Code normally works by acting: it reads a file, edits it, runs the tests, edits again. Plan mode changes the rules for a while. In plan mode Claude may only look: read files, search with Grep and Glob, and ask you questions. It does not edit files or run commands that change anything. Its job is to understand the problem and come back with a written plan. Nothing changes in your repository until you approve that plan.

The value is in catching wrong directions early. A refactor that starts on the wrong design can produce dozens of edits that all have to be undone. Ten minutes of reading and planning is far cheaper than an hour of rework.

How to enter it

  • Shift+Tab In an interactive session, pressing Shift+Tab cycles through permission modes; one of them is plan mode, shown in the status line.
  • claude --permission-mode plan Starts a session already in plan mode.
  • Ask for it "Before changing anything, investigate and propose a plan" gets similar behaviour, but the mode is the reliable way, because in plan mode Claude cannot make changes rather than merely being asked not to.

The plan → approve → execute flow, step by step

A PLAN-MODE SESSION · ILLUSTRATIVE
You (plan mode): Move logging from our custom logger to pino across the API.

Claude: [reads src/lib/logger.ts, greps for "logger." -> 212 calls in 47 files,
         reads 3 representative call sites, checks package.json]

Claude: Questions before I plan:
  1. Keep the current log levels (verbose/info/warn/error), or map verbose -> debug?
  2. Should request IDs be added to every log line?

You: Map verbose to debug. Yes to request IDs.

Claude: Plan
  1. Add pino + pino-http; create src/lib/log.ts exporting a configured logger.
  2. Add request-ID middleware in src/app.ts; attach a child logger to req.
  3. Replace logger.verbose -> log.debug, others 1:1 (codemod, 47 files).
  4. Delete src/lib/logger.ts once no imports remain.
  5. Run tests + typecheck; update docs/logging.md.
  Risks: 6 call sites pass objects as the 2nd argument; handled manually.

You: [approve the plan]

Claude: [leaves plan mode and executes steps 1-5, editing files and running tests]

Notice the three phases. Explore: Claude reads enough to understand the scope (47 files, 212 calls) and the risky edge cases. Clarify and plan: it asks the questions only you can answer, then writes a concrete, ordered plan with risks. Execute: after you approve, it switches to normal mode and carries out the plan directly. You can also reject the plan or ask for changes before anything is touched.

plan mode · read-only 1 · ExploreRead · Grep · Glob 2 · Write the planquestions + risks 3 · You reviewapprove · edit · reject revise approve 4 · ExecuteEdit · Write · Bash Directsmall fix skips1–3
Plan mode puts a checkpoint before any file changes. Steps 1 and 2 can only read. Nothing is edited until you approve; "edit" or "reject" sends Claude back to revise the plan. Direct execution goes straight to step 4, which is right for a small, clear fix.

When to plan and when to just do it

The decision is about how much is unknown and how expensive a wrong start would be.

Signal in the taskModeReason
Architectural change: service boundaries, splitting a monolithPlanSeveral valid designs; the wrong one is very costly
Change touching dozens of files (library migration)PlanNeed to see the full scope and edge cases first
Multiple approaches with different infrastructure needsPlanA human should choose before work starts
Single-file bug with a clear stack traceDirectThe cause and the fix are already known
Small, well-specified additionDirectPlanning adds time without reducing risk

If the requirements already say the change is large or architectural, plan from the start. "Start directly and switch to plan mode if it gets complicated" sounds pragmatic but ignores what the task already told you.

The Explore subagent

Exploring a large codebase produces a lot of output: file listings, search results, file contents. If all of that lands in your main conversation, it fills the context and later work degrades (see 5.4). Claude Code has a built-in, read-only Explore subagent for this. Claude hands it a question such as "find every place request IDs are generated and how they flow to the logger". The Explore subagent does the searching in its own separate context and returns a short summary. Your main conversation receives only the summary.

Plan mode and the Explore subagent work well together. During planning, Claude delegates broad discovery to Explore, keeps the main context for decisions, and writes the plan from the summaries.

How this shows up on the exam

Look for the size and uncertainty signals: "monolith to microservices", "45+ files", "several approaches", "architectural decision" mean plan mode; "single file", "clear stack trace", "add one validation" mean direct execution. A question about verbose discovery filling the context points to the Explore subagent. Wrong answers include "let the implementation reveal the boundaries" and "start direct, switch later".

Revision summary
Signal in the taskMode
Architectural decision, service boundaries, monolith → microservicesPlan mode
Library migration touching 45+ filesPlan mode
Several valid approaches with different infra needsPlan mode
Single-file bug with a clear stack traceDirect execution
Add one date-validation conditionalDirect execution
  • Plan mode allows safe, read-only exploration and design before any change, which prevents expensive rework.
  • Combine them: plan the migration, approve the plan, then execute it directly.
  • The Explore subagent isolates verbose discovery and returns a summary, keeping the main context from filling up in multi-phase work.
Trap (sample Q5)

"Start direct and switch to plan mode if it gets complex" ignores that the complexity is stated in the requirements. "Let the implementation reveal the boundaries" risks late rework.

RememberComplexity stated up front (architecture, many files, competing approaches) → plan first. Small, clear, single-file → execute directly.

TASK 3.5

Iterative refinement techniques

In plain words

When Claude does not get something right the first time, how you give feedback matters. Showing beats telling: give 2–3 examples of an input and the exact output you want. Even better, give it tests that must pass.

If you are working in an unfamiliar area, ask Claude to interview you first, so you discover the questions you had not thought of. Put related fixes in one message; send unrelated ones separately.

New terms: input/output examples, test-driven iteration, interview pattern

Concepts in depth

Why the first attempt is often not quite right

When Claude's output misses the mark, the cause is usually not that Claude cannot do the task. It is that the request left room for more than one reasonable reading. Words like "clean", "properly", "handle edge cases" or "make it consistent" mean different things to different people. Repeating the same words more forcefully does not remove the ambiguity. The techniques in this task all work by replacing ambiguous description with something concrete that can only be read one way.

Technique 1: input/output examples

When you want a transformation (reformat data, rename things, convert one structure into another), show two or three concrete pairs of input and the exact output you expect, including at least one awkward case. Examples define the transformation precisely, including the parts you would forget to describe.

BEFORE · DESCRIPTION ONLY
Convert our log lines to JSON. Keep the important fields and normalise them.
AFTER · CONCRETE EXAMPLES
Convert each log line to one JSON object. Examples:

Input:  2026-10-04 14:03:11 WARN [orders] slow query 812ms user=42
Output: {"ts":"2026-10-04T14:03:11Z","level":"warn","svc":"orders",
         "msg":"slow query","duration_ms":812,"user_id":42}

Input:  2026-10-04 14:03:12 ERROR [auth] token expired
Output: {"ts":"2026-10-04T14:03:12Z","level":"error","svc":"auth",
         "msg":"token expired","duration_ms":null,"user_id":null}

Input:  garbage line without a timestamp
Output: {"ts":null,"level":"unknown","svc":null,"msg":"garbage line without a timestamp",
         "duration_ms":null,"user_id":null}

The examples answer questions the description never raised: timestamps become ISO 8601 in UTC, levels are lowercase, a duration becomes a number in a named field, missing values are null rather than absent, and unparseable lines are kept, not dropped.

Technique 2: test-driven iteration

When correctness can be checked by running code, write the tests first. The tests become an unambiguous specification, and each iteration gives Claude objective feedback instead of your impression.

TEST FIRST · PYTHON (PYTEST)
from migrate import convert_order

def test_null_discount_becomes_zero_cents():
    assert convert_order({"discount": None})["discount_cents"] == 0

def test_discount_string_is_parsed_to_cents():
    assert convert_order({"discount": "12.50"})["discount_cents"] == 1250

def test_missing_discount_key_is_treated_as_zero():
    assert convert_order({})["discount_cents"] == 0

def test_negative_discount_is_rejected():
    import pytest
    with pytest.raises(ValueError):
        convert_order({"discount": "-3"})

The loop is: Claude writes or changes the code, runs the tests, and you (or Claude) paste the exact failing output back. "Test 3 fails: KeyError 'discount'" is precise feedback; "it still doesn't handle nulls right" is not. Tests can cover behaviour, edge cases and even performance limits (for example "converts 100,000 rows in under 2 seconds").

1 · You write testsbehaviour · edge cases the spec 2 · Claude writes codeor changes it 3 · Run the tests all green? yes Done no 4 · Paste the exact failure next try
The tests are the specification, and their failures are the feedback. Each loop sends Claude a precise message such as "test 3 fails: KeyError 'discount'" instead of your impression, and the loop ends on an objective signal: every test passes.

Technique 3: the interview pattern

In an unfamiliar domain you may not know which questions matter. Instead of guessing at a full specification, ask Claude to interview you before it designs or builds anything. It will raise considerations you had not thought about.

I need a cache in front of our product-catalog API. Before proposing a design,
interview me. Ask one question at a time about anything that changes the design:
invalidation, consistency, failure modes, data size, traffic, cost. When you have
enough, summarise the requirements and wait for my confirmation.

Typical questions it will ask: How stale can a price be? What happens if the cache is down: serve stale, or go straight to the API? How many products, and how big is each? Who changes catalog data, and how often? Each answer removes a guess from the eventual design.

Technique 4: batching feedback correctly

When you have several things to fix, how you group them matters.

  • Interacting issues Fixes that affect each other go in one detailed message. For example, "change the date format", "update the parser that reads it" and "fix the test fixtures that contain dates" all touch the same data. Sent separately, each fix can undo or contradict the previous one.
  • Independent issues Unrelated problems ("typo in the README", "slow query in reports") can be fixed one at a time. Smaller, focused requests are easier to check.

How this shows up on the exam

Match the technique to the situation. Inconsistent interpretation of a described transformation → 2–3 input/output examples. Behaviour that can be verified by running code → tests first and iterate on failures. Unfamiliar problem space → interview pattern. Several related fixes → one combined message. The wrong answers are usually "rewrite the description in more detail" or "tell Claude to be more careful".

Revision summary
When prose is read inconsistently

Input/output examples

Give 2–3 concrete before/after pairs. Examples communicate a transformation better than descriptions.

When correctness is checkable

Test-driven iteration

Write tests first (behaviour, edge cases, performance), then iterate by pasting the failing output.

In unfamiliar domains

Interview pattern

Ask Claude to question you first: cache invalidation, failure modes, scale. It surfaces decisions you missed.

Batching feedback

Interacting vs independent

Fixes that affect each other go in one detailed message. Independent issues can be fixed one by one.

Scenario

A migration script mishandles nulls. Instead of "handle nulls properly," give a test case: input {"discount": null} → expected {"discount_cents": 0}.

Trap
  • Repeating "handle edge cases properly" more forcefully.
  • Sending five interacting fixes as five separate messages, so each change undoes the last.

RememberShow, don't describe. Examples and tests beat adjectives.

TASK 3.6

Claude Code in CI/CD pipelines

In plain words

Claude Code can run inside automated pipelines (CI/CD), for example to review every pull request. Nobody is there to answer its questions, so you run it in non-interactive mode with -p: it does the job, prints the result and exits.

For another program to read the result, ask for JSON output that matches a schema. The review criteria live in CLAUDE.md. And the reviewer should be a fresh instance, not the session that wrote the code.

New terms: CI/CD, -p (print mode), --output-format json, --json-schema

Concepts in depth

Interactive versus non-interactive Claude Code

When you type claude in a terminal, you get an interactive session: Claude works, asks for permission, asks clarifying questions and waits for your reply. A CI/CD pipeline (GitHub Actions, GitLab CI, Jenkins) has nobody to answer. If Claude stops to ask something, the job hangs until it times out.

The -p flag (long form --print) runs Claude Code non-interactively: it takes the prompt you pass, works through the task, prints the final result to standard output and exits. That is the mode for scripts and pipelines. Because nobody can approve tool use during the run, you decide up front which tools are allowed.

Getting output another program can read

A pipeline step usually needs to do something with Claude's answer: post comments, fail the build, open a ticket. Prose is hard for code to parse reliably. Two flags fix that.

  • --output-format json Prints one JSON object describing the run (the result, the session id, cost and timing) instead of plain text, so a script can parse it. stream-json emits events as they happen, for long jobs.
  • --json-schema '<schema>' Gives Claude Code a JSON Schema that the final answer must match. Your script can rely on the fields existing with the right types, for example every finding has a file, a line and a severity.
  • --allowedTools "Read,Grep,Glob" Pre-approves only these tools. A reviewer needs to read code, not edit it or run arbitrary commands, so give it read-only tools.
  • --max-turns 15 Caps the number of agent turns, which bounds the cost and time of a single run.

A complete PR review job

.github/workflows/claude-review.yml · GITHUB ACTIONS
name: claude-review
on:
  pull_request:
    types: [opened, synchronize]       # new PR, and every new push to it

permissions:
  contents: read
  pull-requests: write                 # needed to post review comments

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0               # full history so we can diff against main

      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Collect diff and prior findings
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          git diff origin/${{ github.base_ref }}...HEAD > pr.diff
          python .github/scripts/prior_findings.py ${{ github.event.number }} > prior.json

      - name: Run review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "$(cat .github/review-prompt.md)" \
            --output-format json \
            --json-schema "$(cat .github/review-schema.json)" \
            --allowedTools "Read,Grep,Glob" \
            --max-turns 15 > review.json

      - name: Post inline comments
        env:
          GH_TOKEN: ${{ github.token }}
        run: python .github/scripts/post_review.py ${{ github.event.number }} review.json
.github/review-prompt.md · THE PROMPT
You are reviewing a pull request. The diff is in pr.diff.
Review criteria are in CLAUDE.md under "Code review". Report only bugs,
security issues and missing tests; skip style.

prior.json lists findings already posted on this PR. Report a finding only if it
is new, or if a prior finding is still present in the latest code. Do not repeat
findings that were fixed.
.github/review-schema.json · SHAPE OF THE ANSWER
{
  "type": "object",
  "required": ["findings"],
  "properties": {
    "findings": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["file", "line", "severity", "issue", "fix"],
        "properties": {
          "file":     { "type": "string" },
          "line":     { "type": "integer" },
          "severity": { "enum": ["critical", "major", "minor"] },
          "issue":    { "type": "string" },
          "fix":      { "type": "string" }
        }
      }
    }
  }
}
.github/scripts/post_review.py · ILLUSTRATIVE
import json, os, subprocess, sys

pr_number, path = sys.argv[1], sys.argv[2]
run = json.load(open(path))
# The schema-shaped answer; the exact field name can differ between CLI versions.
answer = run.get("structured_output") or json.loads(run["result"])

repo = os.environ["GITHUB_REPOSITORY"]
sha = os.environ["GITHUB_SHA"]
for f in answer["findings"]:
    body = f"**{f['severity'].upper()}**: {f['issue']}\n\nSuggested fix: {f['fix']}"
    body += "\n\n<!-- claude-review -->"          # marker so the next run can find it
    subprocess.run([
        "gh", "api", f"repos/{repo}/pulls/{pr_number}/comments",
        "-f", f"body={body}", "-f", f"commit_id={sha}",
        "-f", f"path={f['file']}", "-F", f"line={f['line']}", "-f", "side=RIGHT",
    ], check=True)

Where the review criteria come from

Claude Code in CI reads the repository's CLAUDE.md just as it does on a laptop. That makes CLAUDE.md the natural place for the review criteria (what counts as a bug, which severity is which), testing standards and fixture conventions. Keeping them there means the CI reviewer and developers' local sessions apply the same standards, and changing a standard is a normal pull request.

Why a separate reviewer instance

If the same Claude session that generated the code also reviews it, it still has its own reasoning in context and tends to agree with itself. A CI job starts a fresh session that has never seen how the code was written, so it reviews what is actually there. This is the same principle as 4.6.

Re-runs without duplicate comments

The workflow runs on every push to the pull request. Without care, each run posts the same findings again and the PR fills with duplicates. The fix is in the prompt and the data: prior_findings.py collects comments carrying the claude-review marker into prior.json, and the prompt tells Claude to report only findings that are new or still unaddressed. Raising the severity threshold or skipping re-runs would hide real issues instead.

PR opened / pushed triggers CI job (GitHub Actions) claude -p fresh instance, no chat CLAUDE.mdcriteria prior.jsonseen before JSON (schema) findings.json post_review.py posts only new findings PR comments next run reads them
The reviewer is a fresh, non-interactive instance with two inputs. CLAUDE.md supplies the review criteria and prior.json lists what was already reported. The JSON output is posted by a script, and the posted comments feed the next run (dashed), so a new push only adds new or still-unfixed findings.

Test generation in CI

The same setup can generate tests. Two details make the output useful: include the existing test files in context, so Claude does not propose scenarios that are already covered, and document in CLAUDE.md what makes a test valuable and which fixtures to use. Nightly test generation is not blocking, so it can also use the Message Batches API (4.5) to halve the cost; a blocking pre-merge check should stay synchronous.

If you use GitHub, the anthropics/claude-code-action Action wraps the same CLI and handles much of the plumbing above.

How this shows up on the exam

"The CI job hangs" → -p. "We need machine-readable findings" → --output-format json with --json-schema. "Duplicate comments on every push" → include prior findings and ask for new or unresolved ones. "The reviewer misses its own mistakes" → independent instance. Watch for invented options such as CLAUDE_HEADLESS=true, a --batch flag or .claude/config.json with a commands array; none of them exist.

Revision summary
REFERENCE DESIGN · PR REVIEW JOB (SCENARIO 5)
PR opened / pusheddiff + changed files
→
claude -pindependent instance · CLAUDE.md gives criteria
→
JSON findings--output-format json + --json-schema
→
Post inline commentsdedupe vs prior findings
claude -p "Review this PR diff. Report only bugs and security issues per CLAUDE.md.
Previously reported findings are in prior.json; report only new or still-unaddressed ones." \
  --output-format json \
  --json-schema '{"type":"object","properties":{"findings":{"type":"array","items":{
     "type":"object","required":["file","line","severity","issue","fix"],
     "properties":{"file":{"type":"string"},"line":{"type":"integer"},
       "severity":{"enum":["critical","major","minor"]},
       "issue":{"type":"string"},"fix":{"type":"string"}}}}}}'
  • -p / --print = non-interactive: run, print, exit. Without it the job hangs waiting for input.
  • CLAUDE.md is the CI context: review criteria, testing standards, fixture conventions.
  • Session isolation: the session that wrote the code is a weak reviewer of it. Review in a separate instance.
  • On re-runs, include prior findings and ask for new or unresolved issues only, to avoid duplicate comments.
  • For test generation, include existing test files so Claude does not propose scenarios already covered, and document valuable-test criteria and fixtures in CLAUDE.md.
  • Constrain the job: --allowedTools "Read,Grep,Glob" for a read-only reviewer, --max-turns to bound cost. The anthropics/claude-code-action GitHub Action wraps the same CLI for PR workflows.
Trap
  • Options that name features that do not exist: CLAUDE_HEADLESS=true, a --batch flag, .claude/config.json with a commands array.
  • Reviewing in the session that wrote the code.
  • Using the Batch API for a blocking pre-merge check.

Rememberclaude -p + --output-format json + --json-schema, review criteria in CLAUDE.md, a separate reviewer instance, and prior findings in context.

D4

Prompt Engineering & Structured Output

20% · primary in scenarios 5 and 6

Three themes: say exactly what counts (criteria and examples), make the shape guaranteed (tool use with schemas), and check the meaning separately (validation, retries, independent review).

TASK 4.1

Explicit criteria to raise precision and cut false positives

In plain words

Words like "be careful" or "only important issues" mean different things to different readers, Claude included. Precise criteria work better: list exactly what to report (security holes, crashes) and what to skip (style, naming), and show an example of each severity level.

This matters because false alarms are expensive. Once developers see a few wrong review comments, they stop trusting all of them, including the correct ones.

New terms: explicit criteria, false positive, precision

Concepts in depth

Precision, recall and why false positives matter so much

Any automated reviewer makes two kinds of mistakes. A false positive is a finding that is not really a problem: the bot says "this comment is wrong" when the comment is fine. A false negative is a real problem the bot misses. Precision is the share of reported findings that are real; recall is the share of real problems that get reported.

For a review bot that comments on pull requests, precision matters more than it first appears. Developers read the comments, and each false alarm costs them time and patience. After a few bad comments they stop reading carefully, and then the true findings get ignored too. A bot with 95% precision and modest recall is useful. A bot that finds everything but is wrong a third of the time gets switched off. That is why the exam keeps returning to "cut false positives" as the goal.

Why vague instructions do not fix precision

The tempting fix is an adjective: "be conservative", "only report important issues", "only high-confidence findings". These feel like instructions, but they do not tell the model where the line is. "Important" to one reader is a security hole; to another it is an inconsistent variable name. Claude fills the gap with its own judgment, and that judgment varies from file to file and run to run.

Asking the model to score its own confidence from 1 to 10 and filtering on the score has the same weakness. The model has no measured basis for the number, so a "9" on a wrong finding is common. Self-reported confidence only becomes usable after it has been calibrated against labeled data (task 5.5).

What works is explicit criteria: a list of what to report, a list of what to skip, a precise test for borderline categories, and a definition of each severity level with a concrete example.

Anatomy of a review prompt with explicit criteria

SYSTEM PROMPT · PR REVIEW BOT
You review pull request diffs for the payments service. Your findings are posted
as inline comments, so every finding must be worth a developer's time.

<report>
Report a finding ONLY if it belongs to one of these categories:
1. Security: injection (SQL, shell, template), missing auth or ownership checks,
   secrets in code or logs.
2. Correctness: null/undefined dereference, off-by-one, wrong comparison,
   unhandled error path that loses data, money stored as float.
3. Concurrency: race conditions on shared state, missing transaction around
   multi-step writes.
4. Comment accuracy: flag a comment ONLY when the behaviour it describes
   contradicts what the code does. Do not flag comments that are terse,
   incomplete, or worded differently than you would write them.
</report>

<skip>
Do NOT report: naming, formatting, import order, missing docstrings,
"could be refactored", personal style preferences, or any pattern that is used
consistently elsewhere in this repository.
</skip>

<severity>
critical: exploitable security issue or silent data loss.
  Example: db.query(`SELECT * FROM orders WHERE id = ${req.query.id}`)
major: wrong result for a realistic input, or a crash in a normal path.
  Example: total = sum(i.price for i in items) / len(items)   # items may be empty
minor: wrong result only in rare edge cases, with no data loss.
  Example: date range check uses < where the spec says <=
</severity>

For each finding output: file, line, category, severity, issue (one sentence),
fix (one sentence). If nothing meets the criteria, output an empty list.
  • Opening context Says who reads the output and why that raises the bar. Giving the reason helps the model generalise to cases the lists do not name.
  • <report> A closed list of categories. Anything outside it is out of scope by default, which is what removes most false positives.
  • Comment accuracy test The borderline category gets a precise test ("contradicts what the code does") plus what does not count. This is the line that fixes the 40% false-positive scenario.
  • <skip> Naming the things to ignore is as important as naming the things to report. "Patterns used consistently in this repo" stops the bot fighting the team's own conventions.
  • <severity> Each level has a definition and a code example. Without examples, "major" and "minor" drift between runs; with them, classification becomes consistent.
  • Output contract A fixed set of fields per finding, and explicit permission to return nothing. Without "empty list is fine", models tend to find something to say.

The XML-style tags are not required syntax; they are a clear way to separate sections so the model (and the next engineer) can see where each rule lives.

Restoring trust when one category is noisy

Suppose comment-accuracy findings are wrong 40% of the time while the other categories are accurate. Developers do not separate the categories in their heads; they just learn "the bot is often wrong". The practical sequence is:

accepted (real) dismissed target security94% correctness91% comment accuracy58% 4 in 10 wrong
One noisy category drags down trust in all of them. Developers accept security and correctness findings over 90% of the time, but dismiss 42% of comment-accuracy findings. They do not keep score per category; they just learn "the bot is often wrong". Switch the noisy category off, rewrite its criterion, and switch it back on only when its measured precision reaches the target.
  1. Temporarily disable the noisy category so the accurate findings regain credibility.
  2. Rewrite its criterion into a precise test, and add an example of a terse but correct comment that must not be flagged.
  3. Measure precision per category on a sample of past PRs, using whether developers accepted or dismissed each finding.
  4. Re-enable the category once its precision matches the others.
PER-CATEGORY PRECISION FROM DEVELOPER FEEDBACK · PYTHON
from collections import Counter

# each record: {"category": "comment_accuracy", "outcome": "accepted" | "dismissed"}
def precision_by_category(feedback):
    accepted = Counter(f["category"] for f in feedback if f["outcome"] == "accepted")
    total = Counter(f["category"] for f in feedback)
    return {cat: accepted[cat] / total[cat] for cat in total}

# {'security': 0.94, 'correctness': 0.91, 'comment_accuracy': 0.58}
# -> disable comment_accuracy, fix its criterion, re-measure before re-enabling

How this shows up on the exam

Questions describe a reviewer or classifier that is noisy and offer fixes. The right answer names concrete criteria: what to report, what to skip, a precise test, severity examples. Wrong answers use adjectives ("be more conservative"), self-rated confidence thresholds, a bigger model, or a second model voting on the first. When the stem says one category is noisy and the others are fine, the answer usually combines disabling that category for now with rewriting its criterion.

Revision summary
Vague (does not work)Explicit (works)
"Check that comments are accurate.""Flag a comment only when the behaviour it claims contradicts what the code does."
"Be conservative." / "Only high-confidence findings.""Report: null derefs, injection, auth bypass, race conditions. Skip: naming, formatting, patterns used consistently in this repo."
"Rate severity appropriately.""Critical = data loss or security exposure, e.g. db.query(`…${req.query.id}`). Minor = …"
  • False positives cost more than missed nits. One noisy category makes developers distrust the accurate ones too.
  • Tactic: temporarily disable the high-false-positive category to restore trust while you improve its prompt.
  • Define severity levels with a concrete code example for each, so classification is consistent.
Scenario

Developers ignore the review bot because 40% of its "comment accuracy" findings are wrong, while other categories are accurate. Switch that category off for now, rewrite its criterion ("flag only when the comment contradicts the code"), add an example of a terse but correct comment, then switch it back on.

Trap
  • "Be conservative" or "only report high-confidence issues". Both are vague.
  • Asking for a 1–10 confidence score and filtering on it. Self-reported confidence is uncalibrated.

RememberName what to report and what to skip, with a concrete example for each severity.

TASK 4.2

Few-shot prompting for consistency and quality

In plain words

Few-shot prompting means putting a few worked examples in the prompt: "here is a tricky case, here is the right answer, and here is why". Examples teach format and judgment faster than paragraphs of rules, the way a new employee learns faster from three solved tickets than from a policy manual.

Pick examples for the cases where Claude was getting confused, not the easy ones.

New terms: few-shot examples, ambiguous case

Concepts in depth

What "few-shot" means

A shot is one worked example placed in the prompt. Zero-shot means instructions only. Few-shot means instructions plus a handful of examples, typically two to four, that show an input, the correct output, and ideally the reasoning that leads from one to the other.

Examples work because they remove ambiguity that prose cannot. A rule like "escalate when policy does not cover the request" leaves Claude to decide what "does not cover" means. One example of a competitor price-match request marked "escalate: policy only covers our own price drops" draws the line precisely. The model also copies the format of examples very reliably, so examples are the strongest tool for consistent output structure.

When to reach for examples

The exam's framing is: you have already written clear instructions, and results are still inconsistent between similar cases. That is the signal for few-shot. If the problem is something else, examples are the wrong fix:

  • The model picks the wrong tool because two tool descriptions overlap → fix the descriptions (task 2.1).
  • A rule must hold every single time, such as a refund limit → enforce it in code (task 1.4).
  • Output must match a schema exactly → use tool use with a JSON schema (task 4.3).

How to structure an example set

Good example sets share four properties:

  • Targeted Each example covers a case the model was getting wrong or that sits near a decision boundary. Easy cases teach nothing new.
  • Reasoned Each example states why the chosen action beats the plausible alternative. The reasoning is what lets the model generalise to cases you did not list.
  • Varied Examples differ in surface form (short and long inputs, different wording, different document layouts) so the model learns the rule, not the phrasing.
  • Consistent format Every example uses exactly the output format you want back. The model will mirror it.

Wrapping examples in XML-style tags such as <examples> and <example> keeps them clearly separated from instructions and from the real input. Claude is trained to pay attention to this kind of structure.

FEW-SHOT SET FOR A CODE REVIEWER · SYSTEM PROMPT EXCERPT
<examples>
<example>
<code>
const user = users.find(u => u.id === id);
return user.email;
</code>
<finding>
line: 2 | category: correctness | severity: major
issue: users.find returns undefined when no user matches; .email then throws.
fix: return user?.email ?? null, or throw a NotFound error explicitly.
</finding>
<why>Realistic input (unknown id) crashes a normal request path, so major.</why>
</example>

<example>
<code>
// Cache for 5 minutes; stale reads are acceptable for the catalogue.
const TTL_MS = 5 * 60 * 1000;
</code>
<finding>none</finding>
<why>Looks like it might hide a staleness bug, but the comment documents a
deliberate trade-off and matches the code. Acceptable; do not report.</why>
</example>

<example>
<code>
// Retries up to 3 times
for (let i = 0; i <= 3; i++) { await send(); }
</code>
<finding>
line: 1 | category: comment_accuracy | severity: minor
issue: Loop runs 4 times (0..3 inclusive), contradicting "up to 3".
fix: use i < 3, or update the comment to "4 attempts".
</finding>
<why>The comment's claim contradicts the behaviour, which is the test for
comment accuracy. Wording style alone would not qualify.</why>
</example>
</examples>

Look at what each example teaches. The first shows the exact output format and how severity is chosen. The second is the most valuable for precision: it is acceptable code that looks suspicious, and it teaches the model when not to report. The third pins down the comment-accuracy test from task 4.1 with a concrete contradiction.

Instructionsreport / skip criteria rules inprose <examples> 1 · real bug input: code output: finding why: severity 2 · looks bad, is fine input: code output: none why: deliberate 3 · edge case input: code output: finding why: claim vs code exactformat when NOTto report the precisetest Real inputthe PR diff to review answered inthe same shape
Each example earns its place by teaching something the instructions could not. The output rows show the exact format to copy. The tinted "why" rows carry the judgment that lets Claude generalise. Example 2, suspicious-looking code that is actually fine, is the one that cuts false positives.

Few-shot for extraction: vary the document structure

For extraction, the ambiguity is usually about where information lives. A citation can be inline ("Smith, 2021") or in a bibliography at the end; an invoice total can sit in a table or in a sentence. If every example uses the same layout, the model learns that layout and returns empty fields, or invents values, when it meets a different one.

EXTRACTION EXAMPLES WITH DIFFERENT LAYOUTS · ILLUSTRATIVE
<example>
<document>... as shown (Okafor et al., 2022), latency fell 40% ...</document>
<output>{"claim": "latency fell 40%", "source": "Okafor et al., 2022",
         "source_location": "inline citation"}</output>
</example>
<example>
<document>... latency fell 40% [3] ... References: [3] Okafor, Lee. 2022. ...</document>
<output>{"claim": "latency fell 40%", "source": "Okafor, Lee, 2022",
         "source_location": "numbered reference [3]"}</output>
</example>
<example>
<document>... latency fell 40% in our tests. (No citation given.)</document>
<output>{"claim": "latency fell 40%", "source": null,
         "source_location": null}</output>
</example>

The third example matters most: it shows that null is the correct answer when the source is absent, which directly reduces hallucinated citations.

Common mistakes

  • Many examples of the easy case and none of the hard ones.
  • Examples that show the answer without the reasoning, so the model copies surface features instead of the rule.
  • Examples whose format differs from the format you ask for, which produces mixed output.
  • Adding examples to fix a problem whose real cause is a vague tool description or a missing rule in code.

How this shows up on the exam

The stem usually says detailed instructions are already in place but results are inconsistent, or the model mishandles a specific kind of ambiguous case. The best answer adds a small number of targeted examples with reasoning. Distractors include longer instructions, a separate classifier model, or many generic examples. For extraction questions, look for "varied document structures" and "show null when absent".

Revision summary

When detailed instructions still give inconsistent results, few-shot examples are the most effective lever. They teach format and judgment, and they help the model generalise to cases you did not list.

  • Use 2–4 targeted examples aimed at the ambiguous cases, each showing why one action beat the plausible alternative.
  • Show the exact output format: location, issue, severity, suggested fix.
  • Include an example of acceptable code that looks suspicious, to cut false positives.
  • For extraction, show varied document structures (inline citations vs bibliography, tables vs narrative). This reduces hallucination and empty fields.
<example>
Request: "I want to return the blender but I also think I was charged twice."
Decision: lookup_order first, then check payments.
Why: both concerns hinge on order #; get_customer is unnecessary because the
session already holds a verified customer_id. Escalation not needed: both are
within policy and tools.
</example>
Trap
  • Ten examples of the easy case and none of the hard ones.
  • Examples that show the answer but not the reasoning.
  • Adding examples when the real problem is a vague tool description.

Remember2–4 examples aimed at the ambiguous cases, each showing why one choice beats the plausible alternative.

TASK 4.3

Structured output with tool use and JSON schemas

In plain words

Programs need data in a fixed shape, such as JSON with specific fields. The most reliable way to get it: define a tool whose input schema is exactly that shape, and have Claude call it. The tool's arguments are your data, and they always match the schema.

Make a field nullable (allowed to be empty) when the document might not contain it; otherwise Claude may invent a value to fill it. And remember that a correct shape does not mean correct content.

New terms: JSON schema, structured output, nullable field, enum

Concepts in depth

The problem: programs cannot read paragraphs

An extraction pipeline feeds another system: a database, an accounting tool, a dashboard. That system needs data in a fixed shape, for example an object with a vendor_name string and a line_items array. If you ask Claude "extract the invoice fields as JSON" in plain text, you usually get JSON, but not always: sometimes there is a sentence before it, a trailing comma, a missing field, or a field with a slightly different name. Each of those breaks the downstream parser.

There is a more reliable route. Claude's tool use feature already produces structured arguments that are checked against a schema. So you define a "tool" that you never actually run. Its input schema is the shape you want. When Claude "calls" it, the arguments are your data.

JSON Schema in five minutes

A JSON Schema is a JSON document that describes what other JSON must look like. Tool definitions use it for input_schema. The handful of keywords you need:

  • "type" The kind of value: "object", "array", "string", "integer", "number", "boolean", "null". A list such as ["string", "null"] means "either of these".
  • "properties" For an object: the allowed field names, each with its own schema.
  • "required" Field names that must be present. A required field must appear, but if its type allows null the value may be null.
  • nullable Not a keyword; it is the pattern "type": ["string", "null"]. It tells the model "if this is not in the document, say null". Without it, a required string forces the model to put something there, which is how invented PO numbers happen.
  • "enum" A fixed list of allowed values, such as document types. Adding "unclear" gives the model an honest answer for ambiguous input; adding "other" plus a free-text detail field keeps the list extensible without breaking the schema.
  • "items" For an array: the schema every element must match, for example each line item is an object with a description and an amount.
  • "description" Plain-language guidance attached to any field. The model reads it. Use it for formats ("ISO 8601 date") and rules ("integer cents, not dollars").

A complete extraction call

EXTRACTION WITH A FORCED TOOL · PYTHON, CLAUDE API
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"          # use your current model id

INVOICE_TOOL = {
    "name": "record_invoice",
    "description": "Record the fields of ONE invoice. Use null for any field "
                   "that does not appear in the document. Never guess.",
    "input_schema": {
        "type": "object",
        "required": ["vendor_name", "invoice_date", "po_number",
                     "line_items", "stated_total_cents", "document_type"],
        "properties": {
            "vendor_name":  {"type": "string"},
            "invoice_date": {"type": ["string", "null"],
                             "description": "ISO 8601 (YYYY-MM-DD); null if absent"},
            "po_number":    {"type": ["string", "null"]},
            "document_type": {"enum": ["invoice", "credit_note", "receipt",
                                       "unclear", "other"]},
            "document_type_detail": {"type": ["string", "null"],
                                     "description": "Only when document_type is other"},
            "line_items": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["description", "amount_cents"],
                    "properties": {
                        "description":  {"type": "string"},
                        "amount_cents": {"type": "integer"}
                    }
                }
            },
            "stated_total_cents": {"type": "integer"}
        }
    }
}

SYSTEM = """You extract data from invoices.
Normalize: dates to YYYY-MM-DD; money to integer cents (12.50 -> 1250).
If a value is not printed in the document, use null. Do not infer it."""

def extract(document_text: str) -> dict:
    resp = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        system=SYSTEM,
        tools=[INVOICE_TOOL],
        tool_choice={"type": "tool", "name": "record_invoice"},  # must call it
        messages=[{"role": "user",
                   "content": f"<document>\n{document_text}\n</document>"}],
    )
    for block in resp.content:
        if block.type == "tool_use" and block.name == "record_invoice":
            return block.input        # already a dict that matches the schema
    raise RuntimeError(f"No tool call; stop_reason={resp.stop_reason}")

Line by line:

  • tools=[INVOICE_TOOL] Tells Claude this "tool" exists. Nothing will ever execute it; it only defines the shape.
  • tool_choice Forces Claude to call record_invoice, so the reply is always structured. Without it (auto), Claude might answer in prose.
  • system Carries the normalization rules. The schema says "integer"; the prompt says "cents, not dollars". Shape and meaning work together.
  • <document> tags Separate the input clearly from instructions, so text inside the invoice is not mistaken for a command.
  • block.input The extracted data, already parsed into a Python dict. No json.loads, no syntax errors to handle.
Invoice text<document>…</document> user message messages.create tools=[record_invoice] tool_choice: forced response tool_use blockname: record_invoice block.input A Python dictvendor, items, total… Your validatorsums · dates · rules Shape guaranteed by schema Meaning your code
The schema guarantees the shape; only your code can check the meaning. Forcing the tool means every response carries a tool_use block whose input already matches the schema: right fields, right types, no stray text. Whether the line items add up or the date is plausible is a separate check (task 4.4).

Several schemas: letting Claude choose with "any"

If documents arrive unlabeled and you have one schema per document type, define all of them and set tool_choice to {"type": "any"}. Claude must call one of the tools, and it picks the one that fits. You read block.name to know which shape you received.

UNKNOWN DOCUMENT TYPE · PYTHON
resp = client.messages.create(
    model=MODEL, max_tokens=2048, system=SYSTEM,
    tools=[INVOICE_TOOL, RECEIPT_TOOL, CONTRACT_TOOL],
    tool_choice={"type": "any"},      # must call SOME tool; Claude picks which
    messages=[{"role": "user", "content": doc}],
)
call = next(b for b in resp.content if b.type == "tool_use")
handlers = {"record_invoice": save_invoice, "record_receipt": save_receipt,
            "record_contract": save_contract}
handlers[call.name](call.input)

Use a forced named tool when one specific step must run first, for example extract_metadata before an enrichment step, then continue the next steps in follow-up turns. One caveat: when extended thinking is enabled, only auto and none are allowed, so forced tool use is not available in that mode.

Syntax versus semantics

The schema guarantees syntax: the JSON is valid, the fields exist, the types are right. It does not guarantee semantics: whether the line items really sum to the total, whether the date was copied from the right place, whether "Acme Ltd" is the vendor or the customer. A perfectly shaped answer can still be wrong. That is why task 4.4 adds validation in code after extraction.

How this shows up on the exam

If a question describes JSON parse failures or missing fields, the answer is tool use with a schema, not "tell the model to output valid JSON". If it describes invented values, the answer is a nullable field plus "use null if absent". If documents vary in type, look for tool_choice: any with several schemas. If the output is well formed but numbers do not add up, the answer is validation, not a stricter schema.

Revision summary

Define an "extraction tool" whose input_schema is the shape you want. When Claude calls it, the tool_use.input is your structured data. This is the most reliable way to get schema-compliant JSON and removes syntax errors.

{
  "name": "extract_invoice",
  "description": "Record fields from one invoice. Use null when a field is absent.",
  "input_schema": {
    "type": "object",
    "required": ["vendor_name", "line_items", "stated_total", "document_type"],
    "properties": {
      "vendor_name":   { "type": "string" },
      "invoice_date":  { "type": ["string", "null"], "description": "ISO 8601; null if absent" },
      "po_number":     { "type": ["string", "null"] },
      "document_type": { "enum": ["invoice", "credit_note", "receipt", "unclear", "other"] },
      "document_type_detail": { "type": ["string", "null"], "description": "Fill when type is other" },
      "line_items": { "type": "array", "items": { "type": "object",
          "properties": { "desc": {"type":"string"}, "amount_cents": {"type":"integer"} } } },
      "stated_total":     { "type": "integer" },
      "calculated_total": { "type": "integer", "description": "Sum of line_items" },
      "conflict_detected":{ "type": "boolean" }
    }
  }
}
  • Nullable fields stop the model inventing values to satisfy a required field.
  • "unclear" handles ambiguity; "other" + detail string keeps categories extensible.
  • Put normalization rules in the prompt (dates to ISO, amounts to cents) alongside the strict schema.
  • tool_choice: "any" when several extraction schemas exist and the document type is unknown; forced {"type":"tool","name":"extract_metadata"} to run one step before enrichment.
Syntax vs semantics

Schemas guarantee valid JSON of the right shape. They do not guarantee that line items sum to the total or that a value landed in the right field. That needs validation (4.4).

Trap
  • "Respond with valid JSON only" in the prompt, then parsing text.
  • Marking every field required, which pressures the model to invent values.
  • Closed enums with no "unclear" or "other" option.

RememberTool use plus a schema guarantees the shape. Nullable fields stop invented values. Meaning still needs validation.

TASK 4.4

Validation, retry and feedback loops

In plain words

After extracting data, check it in code. Do the line items add up to the total? Is the date a real date? If not, ask Claude again and say exactly what was wrong ("line items sum to 410, but the total says 450"). Specific feedback fixes most misreadings.

But if the information simply is not in the document, no number of retries will find it. Flag it for a human instead.

New terms: validation, retry with feedback, semantic error

Concepts in depth

Two layers of checking

Task 4.3 used a schema to guarantee the shape of extracted data. This task adds the second layer: checking the meaning in ordinary code. Typical semantic checks are:

  • Arithmetic: line items should add up to the stated total.
  • Plausibility: an invoice date should be a real date, not in the future, and not decades old.
  • Cross-field rules: if document_type is "other", the detail field must be filled.
  • Format: a PO number should match your company's pattern if one is present.

These checks are deterministic and cheap, so they run on every document. When a check fails, you have a choice: retry the extraction with feedback, accept the value with a flag, or send the document to a person. The skill being tested is knowing which.

Expressing the checks with Pydantic

Pydantic is a popular Python library that turns a class definition into a validator. You declare fields with types, add custom validation methods, and call model_validate on a dict. It either returns a typed object or raises a ValidationError listing every problem in plain language. That list of problems is exactly what you will send back to Claude on a retry.

SEMANTIC VALIDATION · PYTHON, PYDANTIC
from datetime import date
from pydantic import BaseModel, field_validator, model_validator

class LineItem(BaseModel):
    description: str
    amount_cents: int

class Invoice(BaseModel):
    vendor_name: str
    invoice_date: date | None          # Pydantic parses "2026-09-28" into a date
    po_number: str | None
    document_type: str
    document_type_detail: str | None = None
    line_items: list[LineItem]
    stated_total_cents: int
    conflict_detected: bool = False

    @field_validator("invoice_date")
    @classmethod
    def not_in_future(cls, v):
        if v is not None and v > date.today():
            raise ValueError(f"invoice_date {v} is in the future")
        return v

    @model_validator(mode="after")
    def totals_match(self):
        calculated = sum(i.amount_cents for i in self.line_items)
        if calculated != self.stated_total_cents and not self.conflict_detected:
            raise ValueError(
                f"line_items sum to {calculated} cents but stated_total_cents is "
                f"{self.stated_total_cents}. Re-read the line items; if the document "
                f"itself is inconsistent, set conflict_detected to true.")
        return self
  • field_validator Checks one field in isolation, here that a date is not in the future.
  • model_validator(mode="after") Runs after all fields are parsed, so it can compare fields with each other. This is where the sum check lives.
  • conflict_detected An escape hatch for documents that really do contradict themselves. Some invoices are printed with a wrong total. If Claude has re-read carefully and the source is inconsistent, it should say so rather than "fix" the numbers to make them match.
  • error message text Written for Claude, not for a log file: it states the numbers and what to do next. Specific messages are what make retries succeed.

The retry-with-feedback loop

A useful retry includes three things: the original document, the output that failed, and the specific errors. Sending only "try again" gives the model nothing new to work with, so it usually repeats the same mistake.

Extractforced tool call input Validatesums · dates pass Savestatus: auto fail Retry with doc + output + exact errors ≤ 2 times still fails Human reviewor null
A retry is a loop with an exit, not a loop until it works. Each retry carries the document, the failed output and the exact error, so Claude has something new to work with. Misreads usually clear in one retry. If the value is simply not in the document, more retries can only invent one, so the loop stops and a person (or a null) takes over.
EXTRACT → VALIDATE → RETRY → HUMAN · PYTHON
import json
from pydantic import ValidationError

MAX_RETRIES = 2

def extract_validated(doc: str):
    messages = [{"role": "user", "content": f"<document>\n{doc}\n</document>"}]
    for attempt in range(MAX_RETRIES + 1):
        resp = client.messages.create(
            model=MODEL, max_tokens=2048, system=SYSTEM,
            tools=[INVOICE_TOOL],
            tool_choice={"type": "tool", "name": "record_invoice"},
            messages=messages)
        call = next(b for b in resp.content if b.type == "tool_use")
        try:
            return Invoice.model_validate(call.input), "auto"
        except ValidationError as err:
            problems = "\n".join(f"- {e['loc']}: {e['msg']}" for e in err.errors())
            # keep the conversation valid: answer the tool call, then give feedback
            messages.append({"role": "assistant", "content": resp.content})
            messages.append({"role": "user", "content": [{
                "type": "tool_result", "tool_use_id": call.id, "is_error": True,
                "content": (
                    "Validation failed for your previous extraction:\n"
                    f"{problems}\n\n"
                    f"Your previous output was:\n{json.dumps(call.input, indent=2)}\n\n"
                    "Re-read the document above and call record_invoice again. "
                    "If a value is truly not in the document, use null.")}]})
    return call.input, "human_review"   # still failing: likely not fixable by retrying

Here is what Claude actually receives on the first retry:

RETRY MESSAGE AS SENT
Validation failed for your previous extraction:
- (): Value error, line_items sum to 41000 cents but stated_total_cents is 45000.
  Re-read the line items; if the document itself is inconsistent, set
  conflict_detected to true.

Your previous output was:
{ "vendor_name": "Northwind Supplies", "line_items": [ ...4 items... ],
  "stated_total_cents": 45000, ... }

Re-read the document above and call record_invoice again. If a value is truly
not in the document, use null.

The document is already in the conversation from the first turn, so "the document above" is visible to Claude. Because the API is stateless, the full message list is sent again on every call.

When a retry helps, and when it cannot

Retries fix misreads: a row skipped in a table, a date copied in the wrong format, a value placed in the wrong field. The information is in the document; Claude just needs a second, guided look. Retries cannot fix absence. If the PO number is not printed anywhere, a third attempt can only invent one. The design rule is: retry a small number of times with specific feedback, then stop and route the document to a person (or accept null if the field is optional). Logging which failures were retried, and whether the retry worked, tells you which checks are worth retrying at all.

Feedback loops beyond a single document

The same idea scales up to improving the prompt over time. For a code-review bot, add a detected_pattern field to each finding, a short label such as "unchecked_null_return". When developers dismiss findings, you can group dismissals by pattern and see exactly which kinds of findings are noise. That tells you which criterion or example to change in the prompt, instead of guessing.

FINDING WITH A PATTERN LABEL · JSON
{ "file": "src/refunds.ts", "line": 88, "severity": "major",
  "detected_pattern": "unchecked_null_return",
  "issue": "findOrder may return null; .total is read without a check.",
  "fix": "Return 404 when findOrder returns null." }

How this shows up on the exam

Look for three things. First, the retry must include the specific errors, not just "try again". Second, recognize when the information is missing from the source; the right answer then stops retrying and routes to a human or accepts null. Third, a schema-valid result is not proof of correctness; options that rely on a stricter schema to catch arithmetic errors are wrong. Self-checking fields such as calculated_total next to stated_total, and a conflict_detected flag, are signs of a good design.

Revision summary
VALIDATION–RETRY LOOP
Extracttool_use + schema
→
ValidatePydantic / business rules
→fail
Retry with feedbackoriginal doc + failed output + exact errors
→still fails
Human reviewinfo likely absent
FailureWill a retry help?
Date in wrong format, wrong field placement, structural mistakesYes
Line items do not sum to stated total because the model misread a rowUsually
Value exists only in an external document that was not providedNo; route elsewhere
  • Self-checking fields: extract calculated_total next to stated_total; add conflict_detected when the source contradicts itself.
  • Feedback loops for reviews: add a detected_pattern field to each finding so you can analyse which patterns developers dismiss and tune the prompt.
Scenario

Retry 1 fixed the date format. Retry 2 still has no PO number, because the document has none. Stop: set it to null or route to review. A third retry can only invent one.

Trap
  • Retrying without telling the model what failed.
  • Retrying when the information is not in the source.
  • Treating a schema-valid result as a correct one.

RememberRetry with the specific error, the original document and the failed output. Retries fix misreads, not missing information.

TASK 4.5

Batch processing strategies

In plain words

The Message Batches API lets you send thousands of requests in one go. It costs half as much, but results can take up to 24 hours and there is no faster guarantee. Good for overnight jobs; never for something a person is waiting on.

Each request carries your own ID, custom_id, so you can match results to inputs and resend only the ones that failed.

New terms: Message Batches API, custom_id, SLA

Concepts in depth

Synchronous calls versus batches

A normal messages.create call is synchronous: you send one request and wait a few seconds for the answer. That is right whenever someone or something is waiting: a chat user, a CI job that blocks a merge, an agent loop that needs the result to choose its next step.

The Message Batches API is for work where nobody is waiting. You submit a large set of independent requests at once, Anthropic processes them in the background, and you collect the results later. In exchange for giving up speed you get about 50% lower cost and much higher throughput. The catch is timing: a batch can take up to 24 hours, and there is no guarantee it finishes sooner. There is no latency SLA.

What a batch request contains

Each entry in a batch is an ordinary Messages API request (model, max_tokens, system, messages, even tools) wrapped with a custom_id that you choose. Results do not come back in submission order, so the custom_id is how you match each result to its input. Use something meaningful, such as the document ID from your own system.

Each entry is one call. If Claude's response requests a tool, the batch does not run the tool and call Claude again; the result simply ends with stop_reason: "tool_use". So batches suit single-turn work (classify this, extract that, summarize this file) and do not suit multi-step agent loops. Forcing a tool for structured extraction still works, because you only need the tool call's arguments.

The full lifecycle in code

BATCH LIFECYCLE
createrequests + custom_id
→
in_progresspoll status
→
endedall requests resolved
→
resultssucceeded / errored / expired / canceled
→
resubmit failuresonly those custom_ids, with a fix
CREATE, POLL, COLLECT, RESUBMIT · PYTHON, CLAUDE API
import time
import anthropic

client = anthropic.Anthropic()

def make_request(doc_id: str, text: str) -> dict:
    return {
        "custom_id": doc_id,                      # your key for matching results
        "params": {
            "model": MODEL,
            "max_tokens": 2048,
            "system": SYSTEM,
            "tools": [INVOICE_TOOL],
            "tool_choice": {"type": "tool", "name": "record_invoice"},
            "messages": [{"role": "user", "content": f"<document>\n{text}\n</document>"}],
        },
    }

# 1. create
docs = load_todays_documents()                    # {doc_id: text}
batch = client.messages.batches.create(
    requests=[make_request(i, t) for i, t in docs.items()])

# 2. poll until every request has finished (succeeded or not)
while client.messages.batches.retrieve(batch.id).processing_status != "ended":
    time.sleep(60)

# 3. collect results by custom_id
extracted, failed = {}, {}
for r in client.messages.batches.results(batch.id):
    if r.result.type == "succeeded":
        call = next(b for b in r.result.message.content if b.type == "tool_use")
        extracted[r.custom_id] = call.input
    else:                                         # errored, expired or canceled
        failed[r.custom_id] = r.result.type

# 4. resubmit ONLY the failures, after fixing the cause
if failed:
    retry = []
    for doc_id in failed:
        for n, chunk in enumerate(split_into_chunks(docs[doc_id])):  # e.g. too long
            retry.append(make_request(f"{doc_id}#part{n}", chunk))
    client.messages.batches.create(requests=retry)
  • processing_status The batch-level state. "ended" means every request has a final outcome, not that every request succeeded.
  • r.result.type The per-request outcome. succeeded carries the normal message; errored carries an error (for example an input that was too long); expired means it was not processed within the 24-hour window; canceled means you cancelled the batch.
  • custom_id on resubmit The failed IDs tell you exactly what to resend. Resubmitting the whole batch would pay twice for the thousands that already worked.
  • split_into_chunks The fix must address the cause. Resending an over-long document unchanged fails again for the same reason.

Tune on a sample before the big run

Batches are cheap per request but slow to iterate on. If the prompt has a flaw, you find out a day later, across ten thousand documents. So refine the prompt and schema on a small, varied sample first, using synchronous calls for fast feedback. Only when first-pass success is high do you submit the full batch.

SLA arithmetic: picking a submission window

Suppose documents arrive continuously and the business promises results within 30 hours of arrival. You collect documents and submit a batch every W hours. Think about the worst-case document: it arrives just after a batch was submitted, so it waits up to W hours for the next submission, then up to 24 hours for processing. You also need a buffer B for validation and resubmitting failures.

wait for next submission batch processing, up to 24h slack for retries SLA 30h Every 4h28h · 2h slack Every 6h30h · no slack 0h6 1218 2430
Plan for the worst-case document: window + 24 hours + buffer. Time 0 is a document that arrives just after a batch was submitted. It waits a full window, then processing may take the full 24 hours. A 4-hour window finishes by hour 28 and leaves 2 hours to validate and resubmit failures; a 6-hour window uses the whole 30 hours and leaves nothing.

Worst case = W + 24 h + B, and it must be ≤ the SLA.

Window WW + 24 hSlack left in a 30 h SLAVerdict
12 h36 h−6 hBreaks the SLA
8 h32 h−2 hBreaks the SLA
6 h30 h0 hNo room for retries
4 h28 h2 hWorks, with a retry buffer

The key move is adding the full 24 hours, not the typical processing time. Batches often finish much faster, but an SLA has to hold in the worst case.

How this shows up on the exam

Match the workload to the API: anything blocking a person or a pipeline step (pre-merge review, live chat) uses synchronous calls; overnight reports, weekly audits and bulk backfills use batches. Expect a cadence question that needs the W + 24 h calculation. For failures, the right answer resubmits only the failed custom_ids with a fix. Distractors include "use batches to speed things up" (they are slower), resubmitting everything, or running multi-turn tool loops inside a batch.

Revision summary
Message Batches API

What you get

  • 50% lower cost
  • Up to 24 h processing, no latency SLA
  • custom_id correlates request ↔ result
  • Poll for completion
Limits

What you do not get

  • No multi-turn tool calling inside a request
  • No guaranteed order or speed
  • Unfit for anything a person is waiting on
WorkloadAPI
Blocking pre-merge checkSynchronous
Overnight tech-debt report, weekly audit, nightly test generationBatch

SLA arithmetic

Worst case = waiting for the next submission + up to 24 h processing + a buffer for validation and resubmits. For a 30 h SLA: 4 h windows → 4 + 24 = 28 h, leaving 2 h of slack. A 6 h window would hit 30 h with zero slack.

Failure handling

  • Resubmit only failed items, identified by custom_id, with a fix (e.g. chunk documents that exceeded the context limit).
  • Refine the prompt on a sample set first to maximise first-pass success before sending 10,000 documents.
Trap
  • Using batch for anything a person waits on: pre-merge checks, live chat.
  • Resubmitting the whole batch after a few failures.
  • Choosing a submission window without adding the 24 h worst case.

RememberBatch = 50% cheaper, up to 24 h, no latency SLA, matched by custom_id. Worst case = window + 24 h + buffer.

TASK 4.6

Multi-instance and multi-pass review

In plain words

People are bad at proofreading their own writing because they read what they meant, not what they wrote. Claude has a similar problem: the session that wrote the code tends to agree with its own reasoning. A separate, fresh Claude instance without that history makes a better reviewer.

Large reviews also work better in passes: look at each file on its own, then do one more pass on how the files work together.

New terms: independent reviewer, multi-pass review

Concepts in depth

Why a model is a weak reviewer of its own work

When Claude writes code in a session, the conversation holds its whole chain of reasoning: the assumptions it made, the approach it chose, the edge cases it decided not to worry about. If you then ask the same session to review the code, it reads the code through that reasoning. Assumptions that were wrong look reasonable, because they are the assumptions it already made. This is the same reason people miss typos in their own writing.

Instructions such as "now critically double-check your work" do not remove that context; the reasoning is still there in the conversation. Extended thinking does not remove it either. What helps is a reviewer that never saw the reasoning.

What an "independent instance" means

An instance here is simply a separate conversation with Claude. Because the API is stateless, a new call that does not include the generator's messages starts with no knowledge of how the code was written. It can be the same model. Independence comes from the context, not from using a different model.

Same session reviews itself one conversation Task Plan + assumptions Code it wrote "Now review it" review sees all of the above "Looks correct." blind spots shared
Fresh reviewer instance generator Plan Code ✕ not passed diff only fresh reviewer Criteria CLAUDE.md Diff "2 issues found." reads only the code
Independence comes from what the reviewer cannot see. The same model works as a reviewer as long as its conversation does not contain the author's plan. Only the diff, the criteria and the project conventions cross over, so wrong assumptions in the plan no longer look reasonable.

The reviewer gets only what a human reviewer would get: the diff or the files, the review criteria, and relevant project conventions. It does not get the author's plan or explanations.

GENERATOR AND INDEPENDENT REVIEWER · PYTHON, CLAUDE API
import anthropic

client = anthropic.Anthropic()

def generate(task: str) -> str:
    resp = client.messages.create(
        model=MODEL, max_tokens=4096,
        system="You are a senior Python engineer. Write the code for the task.",
        messages=[{"role": "user", "content": task}])
    return resp.content[0].text

def review(code: str, criteria: str) -> str:
    # A brand-new conversation: no task discussion, no author reasoning.
    resp = client.messages.create(
        model=MODEL, max_tokens=4096,
        system="You review code you did not write. Assume nothing about intent "
               "beyond what the code and criteria state.\n" + criteria,
        messages=[{"role": "user", "content": f"<code>\n{code}\n</code>"}])
    return resp.content[0].text

code = generate("Implement refund_order(order_id, amount_cents) with a $500 cap.")
findings = review(code, REVIEW_CRITERIA)      # criteria from task 4.1

In Claude Code the same principle applies: the CI review job runs claude -p as a fresh process (task 3.6), and inside a session a review can be delegated to a subagent, which starts with its own empty context.

Multi-pass review for large changes

Independence fixes bias. A second problem is attention dilution: when one prompt contains 14 files, the model reviews some carefully, skims others, and may even give contradictory verdicts on identical code in different files. A bigger context window does not help, because the issue is how attention is spread, not whether the text fits.

PR · 14 files a.ts b.ts c.ts … 14 local local local local pass 1 · one per file · in parallel summaries Integration passcross-file contracts locallocal Merge & dedupeone consistent list
Split a big review by job, not just by size. Every file gets a focused local pass, so none is skimmed, and the passes run at the same time. A separate integration pass sees only interface summaries and looks for problems between files. One merge step removes duplicates and contradictions before developers see anything.

The fix is to split the review into passes with different jobs:

  • Per-file passes Each file is reviewed on its own for local problems: null handling, error paths, injection. Every file gets full attention, and the passes can run in parallel.
  • Integration pass A separate pass looks only at how files interact: data flowing from one module to another, changed function signatures and their call sites, contracts between services. It receives a compact summary of each file's interface rather than every line.
  • Merge and dedupe Findings from all passes are combined into one list, removing duplicates and resolving contradictions, so developers see one consistent review.
PER-FILE PASSES IN PARALLEL + INTEGRATION PASS · PYTHON, ASYNC
import asyncio
import anthropic

aclient = anthropic.AsyncAnthropic()

async def ask(system: str, content: str) -> str:
    resp = await aclient.messages.create(
        model=MODEL, max_tokens=4096, system=system,
        messages=[{"role": "user", "content": content}])
    return resp.content[0].text

async def review_pr(files: dict[str, str]) -> dict:
    # Pass 1: one focused review per file, all running at the same time
    local = await asyncio.gather(*[
        ask(LOCAL_CRITERIA, f"<file path='{path}'>\n{src}\n</file>")
        for path, src in files.items()])

    # Pass 2: cross-file view built from short interface summaries
    summaries = await asyncio.gather(*[
        ask("Summarize this file's public functions, inputs, outputs and side "
            "effects in under 120 words.", src)
        for src in files.values()])
    integration = await ask(
        INTEGRATION_CRITERIA,   # data flow, signature changes, call sites
        "\n\n".join(f"## {p}\n{s}" for p, s in zip(files, summaries)))

    # Pass 3: merge into one consistent list
    return {"local": dict(zip(files, local)), "integration": integration}

Confidence in a verification pass

A further refinement is a verification pass: a separate instance checks each finding against the code and attaches a confidence value. Confidence can then decide which findings a human looks at first. The same warning as in task 5.5 applies: the numbers only mean something after you compare them with real outcomes, such as which findings developers accepted, and set thresholds from that data.

How this shows up on the exam

The correct answers are an independent reviewer instance without the generator's context, and per-file passes plus a cross-file integration pass for large PRs. Common distractors: asking the same session to "double-check", relying on extended thinking for self-review, moving to a larger context window, requiring two of three reviewers to agree (which suppresses real bugs that only one pass catches), or asking developers to split their PRs, which moves the burden to people without improving the system.

Revision summary
  • Self-review is weak. The generating session keeps its reasoning and tends to defend it. Instructions to "double-check" and extended thinking do not fix that.
  • Independent instance without the generator's context catches subtler issues.
  • Multi-pass: per-file local passes plus an integration pass for cross-file data flow (see 1.6).
  • Confidence per finding in a verification pass can route review attention, once calibrated.
Trap (sample Q12)

A bigger context window does not fix attention quality. Requiring 2-of-3 agreement suppresses real bugs that only appear intermittently. Making developers split PRs shifts the burden without improving the system.

RememberReview in a fresh instance. Split big reviews into per-file passes plus an integration pass.

D5

Context Management & Reliability

15% · appears in scenarios 1, 2, 3 and 6

Long sessions lose detail, tool output crowds out what matters, and multi-agent systems drop sources and errors at every hand-off. This domain is about keeping facts, failures and provenance intact.

TASK 5.1

Preserving critical information across long interactions

In plain words

In a long conversation, older messages are often summarized to save space, and summaries lose detail: "$742.10 refund by Friday" becomes "customer wants a refund".

The fix is to keep the hard facts (IDs, amounts, dates, promises) in a separate case-facts block that is sent with every request and never summarized. Also trim tool results down to the fields that matter, and put the most important information at the start, because models are weakest at noticing things buried in the middle of a long input.

New terms: summarization loss, case-facts block, lost in the middle

Concepts in depth

What "context" actually is on each request

The Claude API is stateless. It does not store your conversation between calls. Every time your program calls client.messages.create, it sends a complete package, and that package is everything Claude knows at that moment. People call this package the context. It is made of four parts:

  • system Standing instructions: the agent's role, policies and escalation rules. Sent on every request.
  • tools The tool definitions Claude may call. They also take up space in the context.
  • messages The conversation so far: user turns, assistant turns, tool calls and tool results, in order.
  • Your own injected blocks Anything your code decides to add, such as a block of case facts. Claude cannot tell the difference between "history" and "something your code added"; it only sees text.

Because your code builds this package from scratch on every turn, your code decides what Claude remembers. If a fact is not in the package, Claude does not know it. That is the single most useful idea in this task: memory problems are context-assembly problems, and you fix them in the code that assembles the context.

The context window has a maximum size, measured in tokens. Long support sessions and agent runs with many tool calls grow quickly, so programs usually shrink older history. The most common way is progressive summarization: every N turns, older messages are replaced by a short summary written by Claude. That keeps the package small, but it is also where details get lost.

The three ways important information goes missing

1. Summaries blur exact values. A summary is written to be short. "Customer was promised a refund of $742.10 for order #12345 by Friday 3 October" becomes "Customer is waiting on a refund". Each summary is a summary of the previous summary, so the loss compounds. Amounts, dates, percentages, order numbers and promises are exactly the details that disappear first, and exactly the ones a support agent must get right.

2. Lost in the middle. Models pay most reliable attention to the beginning and the end of a long input. A finding buried in the middle of 30 pages of aggregated results is more likely to be missed than the same finding at the top. This is not fixed by a bigger window; a bigger window just makes the middle larger.

3. Tool-result bloat. An order-lookup tool might return 40 fields: warehouse codes, internal flags, audit timestamps. The agent needs five. Every call appends all 40 to the history, so after ten lookups most of the context is noise. Noise costs tokens and dilutes attention.

how reliably Claude uses it easily missed high low start middle end Key findings section A section B
Models use the start and end of a long input most reliably; the middle is where findings get missed. Put a short key-findings block first and the details under clear headings after it. A bigger context window does not help, because it only makes the middle longer.

Fix 1: a case-facts block that is never summarized

Keep the hard facts in a small structured object, outside the message history. Update it in code whenever a tool returns something important, and render it into the system prompt on every request. The history can be summarized as aggressively as you like, because the facts no longer live there.

CASE FACTS · BUILT IN CODE, INJECTED EVERY TURN · PYTHON
from dataclasses import dataclass, field

@dataclass
class Issue:
    kind: str                     # "duplicate_charge", "damaged_item", ...
    order_id: str
    amount: float | None = None
    status: str = "open"          # open / resolved / escalated
    promised: str | None = None   # exactly what the customer was told

@dataclass
class CaseFacts:
    customer_id: str | None = None
    verified: bool = False
    issues: list[Issue] = field(default_factory=list)   # one entry per issue

    def render(self) -> str:
        lines = ["<case_facts>",
                 f"customer_id: {self.customer_id} (verified: {self.verified})"]
        for i, iss in enumerate(self.issues, 1):
            lines.append(f"issue {i}: {iss.kind} | order {iss.order_id} | "
                         f"amount {iss.amount} | status {iss.status} | "
                         f"promised: {iss.promised}")
        lines.append("</case_facts>")
        return "\n".join(lines)

def build_request(facts: CaseFacts, history: list[dict]) -> dict:
    system = BASE_POLICY + "\n\n" + facts.render() + (
        "\nThe case_facts block is authoritative. Quote amounts and dates from it.")
    return dict(model=MODEL, max_tokens=1024, system=system,
                tools=TOOLS, messages=history)

# after a tool result arrives, your code (not the model) updates the facts
facts.issues.append(Issue("duplicate_charge", "12345", amount=742.10,
                          promised="refund by Fri 3 Oct"))
  • CaseFacts Lives in your program, not in the conversation. It survives any amount of summarization because it is rebuilt from code each turn.
  • issues A list, one structured entry per issue. In a multi-issue session ("damaged blender and a double charge") each problem keeps its own order, amount and status, so details from one issue do not bleed into another.
  • promised Commitments made to the customer are facts too. Losing "by Friday" is how agents break promises.
  • render() Produces a short tagged block. Tags such as <case_facts> make it easy for Claude to find and easy for you to tell it "this block is authoritative".
one request, rebuilt by your code each turn System promptrole, policy Case factsnever summarized C-88213 · $742.10 · refund by Fri 3 Oct Tool definitionsnames, schemas Older turnssummary, lossy Recent turnsfull detail Tool results5 of 40 fields kept What summarizing does to a fact refund $742.10 by Fri 3 Oct summary wants a refund details lost
Your code assembles the whole package on every turn, so your code decides what Claude remembers. Hard facts live in a pinned case-facts block that is rebuilt from code each time. Older turns can then be summarized freely, which matters because a summary turns "refund $742.10 by Fri 3 Oct" into "wants a refund".

Fix 2: trim tool output before it enters the history

The model only needs the fields relevant to the task. Filter the tool result in code, ideally in one central place such as a PostToolUse hook (task 1.5) or the tool wrapper itself, so every call is trimmed the same way.

KEEP ONLY RETURN-RELEVANT FIELDS · PYTHON
KEEP = {"lookup_order": ["order_id", "status", "total", "delivered_at", "items"]}

def trim(tool_name: str, result: dict) -> dict:
    wanted = KEEP.get(tool_name)
    if wanted is None:
        return result
    return {k: result[k] for k in wanted if k in result}

# 40 fields in, 5 fields out; the other 35 never reach the context

Fix 3: put key findings first, and ask upstream for structure

When you hand Claude a large aggregated input, such as the outputs of five research subagents, layout matters. Put a short key-findings summary at the top, then the details under explicit section headers. The important points sit where attention is strongest, and the headers let the model navigate the rest.

LAYOUT FOR A LONG AGGREGATED INPUT · TEXT
## Key findings (read first)
1. Return window is 30 days from delivery, not from purchase.
2. Order #12345 was delivered 2026-09-12 (day 23 of 30).
3. Duplicate capture pi_91b confirmed by payments log.

## Section A: Order history
...
## Section B: Payment logs
...
## Section C: Policy excerpts
...

The same idea applies between agents. If a downstream agent has a tight context budget, ask the upstream agent to return structured data (key facts, citations, relevance scores, dates) rather than long prose with its full reasoning. A 300-token JSON record carries the same useful content as 3,000 tokens of narrative.

Why "send the full history" and "summarize" are both true

Beginners often find these two rules contradictory. They are not. Because the API is stateless, you must send whatever history Claude needs on every request; you cannot send only the latest message and expect Claude to remember the rest. When that history gets too long, you summarize the narrative parts. The facts are pulled out first into the case-facts block, so summarization can no longer damage them. Recent turns stay at full fidelity.

How this shows up on the exam

Look for symptoms such as "the agent quotes the wrong amount late in the conversation", "it forgets the second issue", or "it misses a finding that is in the input". The right answers extract facts into a persistent block, trim tool output, or reorder the input with key findings first. Distractors include switching to a larger context window (more room, same attention problem), summarizing more often (more loss), and telling the model in the prompt to "remember the details" (it cannot remember what is no longer in the package).

Revision summary

Three ways context goes wrong

  • Progressive summarization blurs numbers, dates, percentages and what the customer was promised ("refund $742.10 by Friday" becomes "customer wants a refund").
  • Lost in the middle: models handle the start and end of long inputs well and can miss findings in the middle.
  • Tool-result bloat: an order lookup returns 40+ fields when 5 matter, and every call adds more.
PROMPT LAYOUT FOR A LONG SUPPORT SESSION
System promptrole, policies, escalation criteria with examples
Case facts block · never summarizedcustomer_id C-88213 · order #12345 · $742.10 · delivered 2026-09-12 · promised: refund by Fri
Summary of older turnsnarrative only; the facts live above
Recent turns, full fidelitywith trimmed tool results (only return-relevant fields)
  • Extract transactional facts into a persistent case facts block sent with every request, outside the summarized history. For multi-issue sessions keep one structured entry per issue.
  • Trim tool output to relevant fields before it enters context (a PostToolUse hook is a good place).
  • For aggregated inputs, put a key-findings summary at the top and organise details under explicit section headers.
  • Ask upstream agents for structured data (key facts, citations, relevance scores, dates) instead of long prose and reasoning chains when downstream budgets are tight.
  • The API is stateless: send the complete conversation history each request to stay coherent.
Scenario

Thirty turns into a chat, the agent offers a $700 refund. It had confirmed $742.10, but the history is summarized every 10 turns and the summary rounded it. Pin the amount in a case-facts block that is never summarized.

Trap
  • Switching to a bigger context window.
  • Summarizing everything, including amounts, dates and promises.
  • Keeping full 40-field tool responses in the history.

RememberFacts go in a pinned case-facts block. Trim tool output. Put key findings first.

TASK 5.2

Escalation and ambiguity resolution

In plain words

Escalation means handing the case to a human. The agent should escalate when the customer asks for a person, when policy does not cover the situation, when an exception is needed, or when it cannot make progress.

It should not escalate just because the customer sounds upset, or because it "feels unsure"; those signals are unreliable. When a request is ambiguous (two customers called Priya Shah), the agent asks a clarifying question rather than guessing.

New terms: escalation criteria, policy gap, disambiguation

Concepts in depth

What escalation is, and why it is a design decision

Escalation means the agent stops trying to resolve the case itself and hands it to a human. A support agent that never escalates frustrates customers and makes costly mistakes on cases it should not handle. One that escalates too often defeats the purpose of automation; the scenario in the exam targets at least 80% first-contact resolution.

So the real question is where the line sits, and how the agent knows where it sits. If the line is only implied ("escalate when appropriate"), the agent guesses, and the guesses are inconsistent: sometimes it escalates easy cases, sometimes it struggles on with cases that needed a person. The exam's sample answer for this problem is to make the boundary explicit: written criteria in the system prompt, backed by a few worked examples of "escalate" versus "resolve".

The criteria that should trigger escalation

  • Explicit request for a human Honour it immediately. Do not investigate first or try to talk the customer out of it. Their request overrides the agent's opinion that it could solve the problem.
  • Policy gap The policy is silent or ambiguous about this situation, for example a competitor price-match when the policy only covers price adjustments on your own site. That is not a hard case to reason through; it is a decision the agent has no authority to make.
  • Exception needed The fair outcome requires breaking a rule, such as a refund outside the return window.
  • No meaningful progress The agent has tried the available tools and cannot move the case forward.

And the cases that should not trigger escalation:

  • Frustration alone An upset customer with a simple, in-scope issue should get acknowledgement and a fix. Offer to resolve it; escalate if they then repeat that they want a person.
  • Routine cases with evidence A standard damaged-item replacement with a photo is exactly what the agent is for.
Asked for a human? yes Escalate now no Policy silent, or exception needed? yes Escalate no Several customers match the lookup? yes Ask for an ID email, order # no Can the tools move it forward? no Escalate yes Resolve it upset? acknowledge repeats ask: escalate Never a branch condition sentiment · self-rated confidence
Escalation follows explicit criteria checked in order, not the agent's mood reading. An explicit request for a person wins immediately. Policy gaps, needed exceptions and dead ends escalate with a structured handoff. Ambiguous identity gets a clarifying question. Everything else is resolved, even when the customer is upset.

Writing the criteria and examples into the system prompt

Criteria tell Claude the rule; few-shot examples show how to apply it to borderline cases. Each example states the situation, the decision, and why, so the model learns the reasoning rather than memorising surface features.

SYSTEM PROMPT EXCERPT · ESCALATION POLICY
<escalation_policy>
Escalate with escalate_to_human when ANY of these is true:
1. The customer asks for a human, a manager or a person. Escalate at once;
   do not investigate first.
2. Policy does not cover the request (it is silent or ambiguous).
3. Resolving it requires an exception to policy.
4. You have tried the relevant tools and cannot make progress.

Do NOT escalate only because the customer is upset. Acknowledge the
frustration and offer to resolve in-scope issues yourself.
If a lookup returns more than one matching customer, ask for another
identifier. Never guess which account is theirs.
</escalation_policy>

<examples>
<example>
Customer: "This is ridiculous, my kettle arrived cracked!" (photo attached)
Decision: resolve. Offer a replacement.
Why: frustrated, but a standard damage claim with evidence is in scope.
</example>
<example>
Customer: "Amazon sells this for $40 less. Match it."
Decision: escalate.
Why: policy covers price adjustments on our own site only; competitor
matching is a policy gap, not a judgment call for the agent.
</example>
<example>
Customer: "Just put me through to a person."
Decision: escalate immediately with a summary of what is known so far.
Why: an explicit request for a human overrides everything else.
</example>
</examples>

The escalation tool and its handoff payload

Escalation is itself a tool call. Defining it as a tool with a required schema forces the agent to produce a complete, structured handoff instead of a vague "needs a human". The human agent usually does not read the transcript, so the payload must stand on its own.

ESCALATE_TO_HUMAN TOOL DEFINITION · MESSAGES API (PYTHON)
escalate_tool = {
    "name": "escalate_to_human",
    "description": (
        "Hand the case to a human agent. Use when the customer asks for a "
        "person, policy does not cover the request, an exception is needed, "
        "or you cannot make progress. The human will NOT read the "
        "conversation, so the summary must be complete."),
    "input_schema": {
        "type": "object",
        "required": ["reason_category", "issue_summary",
                     "actions_taken", "recommended_action"],
        "properties": {
            "reason_category": {"enum": ["customer_request", "policy_gap",
                                         "exception_needed", "no_progress"]},
            "customer_id": {"type": ["string", "null"]},
            "issue_summary": {"type": "string"},
            "facts": {"type": "object",
                      "description": "Order ids, amounts, dates"},
            "actions_taken": {"type": "array", "items": {"type": "string"}},
            "recommended_action": {"type": "string"},
            "customer_expectation": {"type": ["string", "null"]},
        },
    },
}
  • reason_category An enum mirrors the written criteria. It lets you measure why escalations happen and spot criteria that fire too often.
  • customer_id nullable A customer who asks for a human straight away may not be verified yet; null is honest, an invented id is not.
  • actions_taken, recommended_action Save the human from repeating the investigation, and from re-asking the customer.

Ambiguity: ask, don't guess

Ambiguity is different from escalation. When a lookup returns several matches, the agent has a gap in its information, not a gap in its authority. The right move is a short clarifying question that uses a second identifier.

DISAMBIGUATION DIALOGUE
Customer:  Hi, I'm Priya Shah, where is my order?
Agent:     [get_customer(name="Priya Shah") -> 2 accounts]
Agent:     I found more than one account under that name. Could you share
           the email address on the order, or the order number?
Customer:  priya.s@example.com
Agent:     [get_customer(email="priya.s@example.com") -> 1 account, verified]
           Thanks. Your order #55120 shipped yesterday ...

Picking "the most recent account" or "the one with an open order" is a guess that will sometimes expose one customer's data to another. Escalating is also wrong here: a human would just ask the same question.

Why sentiment and self-rated confidence are weak signals

Two tempting designs appear as distractors. Sentiment-based escalation measures how upset someone sounds, but mood does not track case complexity: a calm customer can have a policy-gap request, and an angry one can have a two-minute fix. Self-reported confidence ("rate your confidence 1–10, escalate below 6") is poorly calibrated; models are often confidently wrong exactly on the hard cases. A separate classifier model might eventually help, but it is over-engineered before you have tried explicit criteria and examples.

How this shows up on the exam

Questions describe an agent that escalates inconsistently, escalates easy cases, or misses policy gaps, and ask for the best fix. The proportionate answer is explicit criteria plus few-shot examples. Other recurring items: "customer asks for a human" means escalate immediately; "several matches" means ask for another identifier; and any option that routes on sentiment or self-rated confidence is almost always a distractor.

Revision summary
SituationCorrect behaviour
Customer explicitly asks for a humanEscalate immediately, no investigation first
Customer is frustrated, issue is simple and in scopeAcknowledge, offer to resolve; escalate if they repeat the request
Policy is silent or ambiguous (competitor price match when policy covers only own-site adjustments)Escalate: a policy gap, not just a hard case
Needs a policy exceptionEscalate
No meaningful progress possibleEscalate with a structured handoff
Lookup returns several matching customersAsk for another identifier (email, order #, postcode); never guess
Standard damage replacement with photo evidenceResolve autonomously
Unreliable escalation signals
  • Sentiment measures mood, not case complexity.
  • Self-reported confidence (1–10) is poorly calibrated; the agent is often confidently wrong on the hard cases.
  • A separate classifier is over-engineered before prompt criteria have been tried.
The fix pattern (sample Q3)

Explicit escalation criteria in the system prompt plus few-shot examples of escalate vs resolve. It targets the real cause, unclear decision boundaries, at proportionate cost.

RememberEscalate on an explicit request, a policy gap, a needed exception, or no progress. Never on sentiment or self-rated confidence. Several matches → ask, don't guess.

TASK 5.3

Error propagation across multi-agent systems

In plain words

In a team of agents, one failure should not sink the whole job, and it should not be hidden either. If a search subagent times out, it retries a couple of times itself. If that still fails, it reports back clearly: what failed, what it tried, and any partial results.

The coordinator can then try another route, or carry on and note the gap in the final report. The two worst behaviours are pretending nothing went wrong and crashing the whole job.

New terms: error propagation, partial results, coverage gap

Concepts in depth

What "error propagation" means

In a multi-agent system, work flows through layers: a tool fails inside a subagent, the subagent reports to the coordinator, and the coordinator writes the final output. Error propagation is the question of what each layer passes upward when something goes wrong. Two principles cover almost every exam question:

  • Never hide a failure If a source could not be searched, the layers above must know. Otherwise the final report looks complete when it is not.
  • Never let one failure kill everything One timed-out search should not throw away the results of the other four subagents.

The way to satisfy both is to recover locally where possible, then report what could not be recovered, in a structured form.

Four ways a subagent can report trouble

1. Empty result marked as success. The search timed out, so the subagent returns {"status": "ok", "results": []}. The coordinator reads that as "there is nothing on this topic" and the report silently omits it. This is the worst option, because it is invisible.

2. Generic failure. "Search unavailable." The coordinator knows something failed, but not what was attempted, whether any partial data exists, or what else could be tried. It can only give up or blindly retry.

3. Exception that ends the workflow. The subagent crashes, the coordinator does not catch it, and the whole research run is lost, including every subagent that succeeded.

4. Structured failure report. The subagent retries transient errors itself, and if it still cannot finish, it returns what failed, what it tried, any partial results and suggested alternatives. This is the right answer.

Hide it, or crash empty marked as success Search agent timed out ok, [ ] Coordinator Report topic missing exception ends the run Search agent raise Coordinator All results lost others discarded
Recover, then report Search agent retry ×2 status: partial_failure failure_type: timeout attempted: query, 2 tries partial_results: 1 alternatives: trade press Coordinator or Try another source or query Continue annotate the gap Final report coverage gap: music licensing
Recover locally, then report what you could not recover. Hiding the failure (the first case under Hide it, or crash) makes the report look complete when it is not; crashing (the second case) throws away the work that succeeded. A structured partial failure (Recover, then report) lets the coordinator try another source or carry on and state the gap.

The subagent side: retry locally, then report

Transient errors (timeouts, rate limits, 503s) usually succeed on a second or third attempt, so the subagent should retry them itself with a short backoff. The coordinator does not need to hear about problems that were fixed. Errors that retrying cannot fix (bad input, no permission) should not be retried at all.

SUBAGENT SEARCH WRAPPER · PYTHON
import time

class TransientError(Exception): ...
class PermanentError(Exception): ...

def search_with_report(query: str, source: str, retries: int = 2) -> dict:
    partial, last_error = [], None
    for attempt in range(retries + 1):
        try:
            results = SEARCH[source](query)          # may raise
            return {"status": "ok", "query": query, "source": source,
                    "results": results}              # [] here = genuinely nothing
        except TransientError as e:
            last_error = ("timeout", str(e))
            partial = SEARCH_CACHE.get((source, query), partial)
            time.sleep(2 ** attempt)                 # 1s, 2s, 4s
        except PermanentError as e:
            last_error = ("permanent", str(e))
            break                                    # retrying cannot help

    return {
        "status": "partial_failure" if partial else "failure",
        "failure_type": last_error[0],
        "detail": last_error[1],
        "attempted": {"query": query, "source": source, "retries": retries},
        "partial_results": partial,
        "alternatives": ["query trade-press archive", "narrow to EU market"],
        "coverage_gap": f"No complete results from {source} for: {query}",
    }
  • status Three distinct values. ok with an empty list means "searched, found nothing"; failure means "could not search". The two must never look the same.
  • failure_type Tells the coordinator whether trying again later is sensible.
  • attempted What was tried, so the coordinator does not repeat the same failing call.
  • partial_results Anything that did come back is kept, not thrown away.
  • alternatives, coverage_gap Give the coordinator options and a ready-made sentence for the final report.

The coordinator side: decide, continue, annotate

The coordinator receives one report per subagent. It should never abort because one failed. For each failure it has three choices: try an alternative route, re-delegate with a narrower query, or accept the gap and carry on. Whatever it chooses, the gap is recorded so it can appear in the output.

COORDINATOR CONSUMING REPORTS · PYTHON
findings, gaps = [], []
for report in subagent_reports:
    if report["status"] == "ok":
        findings += report["results"]
        continue
    findings += report.get("partial_results", [])
    retry = try_alternative(report["alternatives"])   # one targeted attempt
    if retry and retry["status"] == "ok":
        findings += retry["results"]
    else:
        gaps.append(report["coverage_gap"])

report_md = synthesize(findings, coverage_gaps=gaps)  # gaps go into the output

Coverage annotations in the final output

A coverage annotation is a short, honest statement in the final report about what is well supported and what is missing. Readers can then judge how far to trust each section.

EXAMPLE OUTPUT SECTION
## Coverage
Well supported (3+ independent sources): visual art, graphic design, film.
Partially covered: music. Licensing-economics sources timed out after
2 retries; findings rely on one 2025 trade survey.
Not covered: academic journals (database access denied).

How this shows up on the exam

The typical stem: "a subagent's search times out; what should it return?" The right option contains a structured error with failure type, the attempted query, partial results and alternatives, and the coordinator continues with an annotated gap. Wrong options: return an empty success, return a generic "search unavailable", raise an exception that stops the workflow, or retry forever. Remember the split of responsibilities: subagents handle transient retries themselves; coordinators decide what to do about what remains.

Revision summary
Subagent returns…VerdictWhy
Structured error: type, attempted query, partial results, alternativesRightCoordinator can retry differently, try another source, or proceed and annotate
"search unavailable" after silent retriesWrongGeneric status hides what was tried and what partially worked
Empty result marked successWrongSuppresses the failure; report looks complete but is not
Exception that ends the whole workflowWrongOne failure should not discard all the other work
{
  "status": "partial_failure",
  "failure_type": "timeout",
  "attempted": { "query": "AI music generation royalties 2025", "source": "web_search", "retries": 2 },
  "partial_results": [ { "claim": "...", "url": "...", "published_at": "2025-11-03" } ],
  "alternatives": ["query trade-press archive", "narrow to EU market"],
  "coverage_gap": "Music licensing economics"
}

The final report should carry coverage annotations: which findings are well supported and which areas have gaps because sources were unavailable.

Trap
  • A subagent returning "no results" after a timeout, so the failure looks like success.
  • The coordinator aborting the whole run because one source failed.
  • A generic "search failed" with no detail.

RememberRetry locally, then report the failure type, what was tried, partial results and alternatives. Annotate the gaps in the final output.

TASK 5.4

Context in large codebase exploration

In plain words

Exploring a big codebase fills the context with file contents. After a while the agent gets vague: it talks about "typical patterns" instead of the actual classes it found earlier.

Prevent this by writing key findings into a notes file the agent can re-read, sending narrow questions to subagents (which return short answers), and shrinking the conversation with /compact. For long multi-agent jobs, save progress to files so a crash does not lose everything.

New terms: scratchpad file, /compact, context degradation, manifest

Concepts in depth

Why long explorations degrade

When Claude Code or an SDK agent explores a large codebase, every Read, Grep and Bash result is appended to the conversation. A two-hour investigation can accumulate hundreds of file excerpts. Two things happen. First, the context fills up, and older material is compacted or summarized, losing specifics. Second, even before it is full, attention is spread across a mass of mostly irrelevant text.

The recognisable symptom: the agent starts answering in generalities. Instead of "RefundService.applyCredit calls LedgerClient.post without a retry", it says "refund services typically call a ledger". It has lost the concrete findings it made an hour ago and is filling the gap with typical patterns. Answers also become inconsistent from one question to the next.

The fixes all follow one principle: keep the main context small and keep important findings somewhere durable.

context used answers turn vague window limit /compact start 2 hours in all output in main context scratchpad + subagents
Everything the agent reads stays in the main context unless you move it out. Left alone, usage climbs into the zone where answers turn generic, and /compact only resets it partway. Writing findings to a scratchpad file and letting subagents do the noisy searching keeps the main context low for the whole session.

Technique 1: the scratchpad file

A scratchpad is an ordinary file in the repository where the agent writes down what it has learned, as it learns it. Files are outside the context window, so they are not summarized or forgotten. When a later question needs a finding, the agent re-reads the scratchpad instead of relying on its memory of the conversation.

NOTES/REFUND-FLOW.MD · WRITTEN BY THE AGENT AS IT EXPLORES
# Refund flow: findings
- Entry point: api/routes/refunds.ts -> RefundController.create
- RefundService.applyCredit (services/refund.ts:88) posts to LedgerClient
  WITHOUT retry. Suspected cause of missing ledger entries.
- Feature flag REFUND_V2 switches to services/refund_v2.ts (not yet traced)
- Tests: tests/refund.spec.ts covers happy path only

## Open questions
- Does refund_v2 share LedgerClient?

You can make this a habit in CLAUDE.md: "During investigations, record findings in notes/<topic>.md and re-read that file before answering follow-up questions."

Technique 2: delegate focused questions to subagents

A subagent runs in its own separate context. You give it a narrow question ("find every caller of LedgerClient.post"), it does all the noisy searching in its context, and only its short final answer comes back to the main conversation. The thousands of lines it read never touch the main context. In Claude Code the built-in Explore subagent exists for exactly this; you can also define your own.

DELEGATING DISCOVERY · PROMPT TO THE MAIN AGENT
Use a subagent to find every caller of LedgerClient.post and whether each
call is wrapped in retry logic. Return only a table: file, line, retried
(yes/no). Do not paste file contents.

Technique 3: summarize between phases, and /compact

Long work naturally falls into phases: map the structure, then analyse a subsystem, then propose changes. At the end of each phase, write a short structured summary and start the next phase (or its subagents) from that summary instead of the full transcript. The next phase gets the conclusions without the clutter.

Inside an interactive Claude Code session, /compact does a similar job on demand: it replaces the conversation so far with a summary, freeing space. Use it when the context is full of verbose discovery output you no longer need. Because compaction summarizes, write the important findings to a scratchpad first. /clear goes further and starts an empty conversation.

Technique 4: crash recovery with a state manifest

Long multi-agent runs can crash, time out or be interrupted. If each agent's progress lives only in its context, everything is lost. The fix is for each agent to export its state to a known file as it works, and for the coordinator to keep a manifest: one file listing every agent, its status and where its state is saved. On restart, the coordinator reads the manifest, skips finished agents, and injects saved state into the prompts of the agents that were mid-way.

STATE/MANIFEST.JSON
{
  "run_id": "audit-2026-10-04",
  "phase": "analysis",
  "agents": {
    "mapper":   {"status": "done",    "state": "state/mapper.json"},
    "security": {"status": "running", "state": "state/security.json",
                 "last_file": "src/auth/session.ts"},
    "tests":    {"status": "pending"}
  }
}
RESUMING FROM THE MANIFEST · PYTHON
import json, pathlib

manifest = json.loads(pathlib.Path("state/manifest.json").read_text())

for name, info in manifest["agents"].items():
    if info["status"] == "done":
        continue                                     # never redo finished work
    prior = ""
    if "state" in info:
        prior = pathlib.Path(info["state"]).read_text()
    prompt = (f"{TASKS[name]}\n\n<prior_state>\n{prior}\n</prior_state>\n"
              f"Continue from where the prior state ends "
              f"(last file: {info.get('last_file', 'none')}).")
    launch_agent(name, prompt)                       # state injected, not remembered
  • status Lets the coordinator skip completed agents instead of rerunning the whole job.
  • state Path to the agent's exported findings. A new agent instance has no memory of the old one, so this file is how its knowledge survives.
  • last_file A precise resume point, so the agent continues instead of restarting its scan.

How this shows up on the exam

Stems describe a long exploration where answers become vague or inconsistent, or a multi-agent run that crashed. Right answers: scratchpad files, subagents for focused discovery, summaries injected between phases, /compact, and manifests for recovery. Distractors: keep going in the degraded session, paste the whole repository into context, rely on a larger context window, or restart everything from scratch after a crash.

Revision summary

Symptom of degradation: late in a long session the model answers inconsistently and talks about "typical patterns" instead of the specific classes it found earlier.

  • Scratchpad files: the agent writes key findings to a file (e.g. notes/refund-flow.md) and re-reads it for later questions.
  • Delegate to subagents for focused questions ("find all test files", "trace refund flow dependencies"); the main agent keeps the high-level picture.
  • Summarize between phases and inject that summary into the next phase's subagents.
  • /compact shrinks context when it fills with verbose discovery output.
  • Crash recovery: each agent exports its state to a known location; on resume the coordinator loads a manifest and injects the state into agent prompts.
// state/manifest.json
{ "run_id": "audit-2026-10-04", "phase": "analysis",
  "agents": {
    "mapper":   { "status": "done",    "state": "state/mapper.json" },
    "security": { "status": "running", "state": "state/security.json", "last_file": "src/auth/session.ts" },
    "tests":    { "status": "pending" } } }
Trap
  • Carrying on in a degraded session.
  • Reading the whole repository into the main context.
  • Switching to a bigger context window as the fix.

RememberWrite findings to a scratchpad, delegate focused searches to subagents, summarize between phases, and /compact when the context is bloated.

TASK 5.5

Human review workflows and confidence calibration

In plain words

Automation needs a safety net. 97% overall accuracy sounds great, but it can hide 70% accuracy on one type of document. So before reducing human checks, measure accuracy for each document type and each field.

Send uncertain or contradictory items to people, and keep checking a random sample of the "confident" ones to catch new problems. A model's confidence score is only useful after you have tested it against known correct answers; that testing is called calibration.

New terms: human-in-the-loop, calibration, stratified sampling

Concepts in depth

Why extraction pipelines keep humans in the loop

An extraction pipeline (scenario 6) turns invoices, receipts and contracts into structured data that flows into other systems. Errors are costly: a wrong amount is paid, a wrong date breaks a contract deadline. So pipelines start with humans reviewing every result. Over time the goal is to review less, sending only the risky items to people. This task is about doing that safely: deciding which items need a human, and proving that the ones you skip are actually fine.

Aggregate accuracy can hide a weak segment

"97% accurate overall" sounds safe. But an average mixes very different kinds of documents. Suppose the pipeline processed 10,000 documents:

SegmentDocumentsAccuracyErrors
Typed invoices8,00099.4%48
Receipts1,50095%75
Handwritten receipts50070%150
Overall10,00097.3%273

The overall figure is excellent, yet more than half of all errors come from handwritten receipts, where nearly one in three results is wrong. Removing human review across the board would let those errors through. The same thing happens at field level: vendor names might be 99.9% right while due dates are 90% right. That is why you measure accuracy per document type and per field before reducing review.

What calibration means, concretely

Many pipelines ask the model to output a confidence per field, for example 0.0 to 1.0. A confidence score is only useful if it is calibrated: when the model says 0.9, it should be right about 90% of the time. Raw model confidence often is not; models tend to say "high" even when wrong.

To calibrate, you take a labeled validation set (documents where humans already know the correct answers), run the pipeline, and group results by the confidence the model reported. Then you compare stated confidence with actual accuracy:

Model saidFields in bucketActually correctReal accuracy
0.95 – 1.004,0003,96099%
0.85 – 0.951,2001,02085%
0.70 – 0.8560039065%
below 0.702009045%

Now the numbers mean something. If the business can tolerate 1% errors on auto-accepted fields, the evidence says: auto-accept only at 0.95 and above. The 0.85–0.95 bucket claims about 90% but delivers 85%, which you would never have known without the labeled set. The threshold is chosen from measured accuracy, not from what the model claims. Repeat the measurement per segment; handwritten receipts may need a different threshold, or always go to a human.

actually correct 100% 70% 40% 0.4 0.7 1.0 confidence the model reported perfect calibration accept ≥ 0.95 45% 65% 85% 99%
Calibration compares the confidence the model states with how often it is actually right, measured on labeled data. Points below the dashed diagonal are overconfident: fields scored 0.85–0.95 are right only 85% of the time. Choose the auto-accept threshold from measured accuracy (here 0.95, where accuracy reaches 99%), not from the model's own numbers.

Routing: who reviews what

REVIEW ROUTER · PYTHON
import random

THRESHOLD = {"invoice": 0.95, "receipt": 0.97}  # from calibration, per segment
ALWAYS_HUMAN = {"handwritten_receipt"}
AUDIT_RATE = 0.03                                # 3% of auto-accepted output

def route(doc) -> str:
    if doc.type in ALWAYS_HUMAN:
        return "human"
    if doc.conflict_detected or doc.type == "unclear":
        return "human"                           # contradictory or ambiguous source
    if min(f.confidence for f in doc.fields) < THRESHOLD[doc.type]:
        return "human"                           # weakest field decides
    if random.random() < AUDIT_RATE:
        return "audit"                           # sampled check of "confident" output
    return "auto_accept"
  • THRESHOLD per segment Comes from the calibration table, not from intuition. Different document types earn different thresholds.
  • conflict_detected / unclear Contradictory or ambiguous sources go to people regardless of confidence. Reviewer time is scarce; spend it where the machine is weakest.
  • min(...) A document is only as reliable as its least certain field.
  • AUDIT_RATE Some auto-accepted documents still get a human check. That is how you keep measuring the real error rate after review is reduced.
Extracted documents Always-human segment? (handwritten) no Source conflict or type unclear? no Weakest field below threshold? no any "yes" Human review queue Auto-accept most documents Audit 3% each type Where the audit samples land invoices receipt hand random stratified
Risky documents go to people; the rest are auto-accepted but still sampled. Checks run in order, and any "yes" sends the document to human review. A small audit of auto-accepted output keeps measuring the real error rate. Stratified sampling draws from every segment, whereas random sampling spends almost every audit on the dominant document type.

Stratified random sampling

If you only ever review low-confidence items, you never learn whether the high-confidence ones are actually right. A random audit of auto-accepted output fixes that. Stratified means you sample from each segment separately, in fixed proportions, rather than from the whole pile. With pure random sampling, 3% of 10,000 documents is 300 audits, and almost all would be typed invoices because they dominate the volume; the rare handwritten receipts might get five checks, too few to notice a problem. Stratifying guarantees every segment, including small ones, gets enough samples. It also catches new error patterns, such as a supplier who changes their invoice layout.

How this shows up on the exam

The classic stem: "accuracy is 97%; leadership wants to stop human review of high-confidence results; what first?" The right answer measures accuracy by segment and field and sets up stratified sampling. Distractors: approve because 97% beats the target, auto-accept on uncalibrated self-rated confidence, or run every document twice and accept matches (two runs of the same model often agree on the same mistake).

Revision summary
REVIEW ROUTING · EXTRACTION PIPELINE (SCENARIO 6)
Extraction+ field-level confidence
→
Routerthresholds calibrated on a labeled validation set
→
Human queuelow confidence, contradictory or ambiguous source
Auto-accept+ stratified random sample audited
  • Aggregate accuracy hides weak segments. 97% overall can mean 99% on invoices and 70% on handwritten receipts.
  • Before reducing human review, measure accuracy by document type and by field.
  • Stratified random sampling of high-confidence output keeps measuring the real error rate and catches new error patterns.
  • Field-level confidence is only useful after calibration against labeled data. Spend scarce reviewer time on low-confidence or contradictory cases.
Trap
  • Trusting aggregate accuracy.
  • Using raw self-reported confidence as a threshold before calibrating it.
  • Sampling only low-confidence items, so the auto-accepted error rate is never measured.

RememberMeasure accuracy per segment, calibrate thresholds on labeled data, and keep stratified sampling of auto-accepted output.

TASK 5.6

Provenance and uncertainty in multi-source synthesis

In plain words

Provenance means "where did this come from?". When combining many sources, every claim keeps its source and date attached; otherwise nobody can check the final report.

When two good sources disagree, report both and say who said what; do not quietly pick one. Dates matter too: 21% in 2024 and 38% in 2025 may be a trend, not a contradiction.

New terms: provenance, attribution, conflicting sources

Concepts in depth

What provenance is and why synthesis destroys it

Provenance is the record of where a piece of information came from: the source, its date, and where in the source it appears. In a research system (scenario 3), search subagents collect claims from many documents, analysis subagents extract data points, and a synthesis agent writes the final report. At every hand-off, the easiest thing to produce is plain prose, and prose sheds provenance. "38% of indie musicians use generative tools" arrives at the report with no way to tell who said it, when, or how they measured it.

Without provenance, nobody can verify the report, conflicting numbers cannot be explained, and a stale statistic looks as authoritative as a fresh one. The fix is structural: carry claims as records, not sentences, from the first subagent to the final output.

A data model that keeps the claim–source link

FINDING RECORD · PYTHON (PYDANTIC)
from datetime import date
from pydantic import BaseModel

class Source(BaseModel):
    url: str
    title: str
    publisher: str
    published_at: date
    location: str | None = None      # page, section, table number

class Finding(BaseModel):
    claim: str                       # one atomic statement
    value: str | None = None         # "38%", "$1.2B" when numeric
    excerpt: str                     # exact supporting quote
    source: Source
    data_collected: str | None = None # when the data was gathered
    method: str | None = None        # "online survey, n=1,204"
    topic: str
  • claim One fact per record. A paragraph with five facts cannot keep five separate sources.
  • excerpt The exact words from the source, so a reader or a verification step can check the claim against it.
  • source.published_at and data_collected Two different dates. A 2025 report may describe 2023 data. Both matter when comparing numbers.
  • method A survey of 1,204 artists and an estimate from industry revenue can both be "correct" and still disagree. Method explains why.

Subagents are instructed to return lists of Finding objects, and the synthesis prompt says: "Preserve every claim-to-source mapping. Never merge two claims into one sentence without citing both sources."

Merging findings and detecting conflicts

When records about the same topic arrive from different subagents, synthesis groups them. Records that agree reinforce each other. Records with different values are a conflict, and conflicts are kept, not resolved by quietly picking one.

GROUPING AND FLAGGING CONFLICTS · PYTHON
from collections import defaultdict

def merge(findings: list[Finding]) -> dict:
    by_topic = defaultdict(list)
    for f in findings:
        by_topic[f.topic].append(f)

    merged = {}
    for topic, items in by_topic.items():
        values = {f.value for f in items if f.value}
        sources = {f.source.publisher for f in items}
        merged[topic] = {
            "findings": items,
            "conflict": len(values) > 1,
            "status": "established" if len(sources) >= 2 and len(values) <= 1
                      else "contested" if len(values) > 1
                      else "single_source",
        }
    return merged

Before calling something a conflict, check the dates. 21% from a survey collected in 2023 and 38% from one collected in 2025 may be a trend: adoption grew. That is why the date fields exist. Without them, the report would wrongly present two accurate numbers as a contradiction.

each claim travels with its source 38% use AI Indie · 2025 21% use AI Label · 2024 $1.2B sales Trade · 2025 Synthesis agent Report established: $1.2B [Trade, 2025] contested: 21% [Label, 2024] 38% [Indie, 2025] a trend, not a contradiction 21% 38% 2024 2025
Carry claims as records with their source and date, all the way into the report. When two credible figures disagree, the report keeps both with attribution instead of picking one. Plotting them by date shows that 21% (2024) and 38% (2025) may simply be growth.

Presenting the result

The report separates well-established findings (several independent sources agree) from contested ones (credible sources disagree), keeps the methodological context, and shows each kind of content in the format that fits it: financial or statistical data as tables, news and narrative developments as prose, technical findings as lists.

EXAMPLE REPORT EXCERPT
## Well established
Generative tools are now common in commercial graphic design
(Design Council survey, 2025; Adobe industry report, 2025).

## Contested: adoption among independent musicians
| Value | Source                | Published  | Data collected | Method               |
|-------|-----------------------|------------|----------------|----------------------|
| 21%   | Label Assoc. report   | 2024-02-01 | 2023           | label member survey  |
| 38%   | Indie Artist Survey   | 2025-06-10 | 2025 Q1        | online, n=1,204      |
The gap may reflect growth between 2023 and 2025 as well as different
populations (label-signed vs independent artists). Both figures shown.

Notice what the synthesis agent did not do: it did not average the numbers, pick the newer one, or drop the topic because sources disagreed. It reported both, attributed and dated, and explained the possible reasons. If the decision about which figure to use matters, that decision belongs to the coordinator or a human, with full information.

How this shows up on the exam

Stems: "the final report has statistics with no citations", "two sources give different figures", "synthesis output loses which source said what". Right answers: structured claim records with source, excerpt and dates; preserve the mapping through synthesis; report conflicts with attribution; split established from contested. Distractors: choose the most recent or most "credible" number, average the values, omit conflicting statistics, or ask the synthesis agent to "cite sources" when it never received them.

Revision summary
{ "claim": "Generative tools used by 38% of indie musicians",
  "excerpt": "...38 percent of surveyed independent artists...",
  "source": { "url": "https://example.org/survey", "title": "Indie Artist Survey" },
  "published_at": "2025-06-10", "collected": "2025-Q1",
  "method": "online survey, n=1,204",
  "conflicts_with": [{ "value": "21%", "source": "Label Assoc. report", "published_at": "2024-02-01" }] }
  • Summaries lose attribution unless each claim keeps its claim → source mapping; synthesis must preserve and merge those mappings.
  • Conflicting credible numbers: report both with attribution. Do not pick one arbitrarily. Let the coordinator decide how to reconcile.
  • Dates prevent false conflicts: 21% in 2024 and 38% in 2025 may be a trend, not a contradiction.
  • Structure the report into well-established vs contested findings, keeping methodological context.
  • Render content by type: financial data as tables, news as prose, technical findings as lists.
Trap
  • Picking the newer or "more credible" number and dropping the other.
  • Summaries that lose the claim → source link.
  • Calling a trend a contradiction because the dates were dropped.

RememberEvery claim keeps its source and date. Conflicts are reported with attribution and stay visible.

S

The six scenarios, as system designs

You will get four. For each, know the reference architecture and the decisions the questions are likely to probe.
Scenario 1

Customer support resolution agent

D1D2D5

Agent SDK loop + MCP tools get_customer, lookup_order, process_refund, escalate_to_human. Target ≥ 80% first-contact resolution.

  • Gate: refund tools blocked until a verified customer ID exists
  • PreToolUse hook: refund > $500 → escalate
  • PostToolUse: normalize dates, trim order fields
  • Case-facts block; structured handoff
  • Explicit escalation criteria + few-shot
  • Multiple matches → ask for identifiers
Scenario 2

Code generation with Claude Code

D3D5

Team use for generation, refactoring, debugging, docs.

  • Project CLAUDE.md + @import; rules with paths globs
  • Team commands in .claude/commands/
  • Skills with context: fork, allowed-tools
  • Plan mode for architecture; direct for scoped fixes
  • Explore subagent, /compact, scratchpads
  • I/O examples, TDD, interview pattern
Scenario 3

Multi-agent research system

D1D2D5

Coordinator → search, analysis, synthesis, report subagents; cited output.

  • allowedTools includes Task; parallel Task calls in one turn
  • Broad decomposition, partitioned scope
  • Findings passed explicitly, as claim/source/date records
  • Scoped verify_fact for synthesis
  • Structured partial-failure errors; coverage gaps in report
  • Conflicts kept with attribution
Scenario 4

Developer productivity agent

D2D3D1

Agent SDK with Read, Write, Bash, Grep, Glob + MCP servers; explores legacy code, generates boilerplate.

  • Grep vs Glob; Edit then Read+Write fallback
  • Incremental exploration from entry points
  • MCP descriptions strong enough to beat Grep
  • Resources for catalogs (schemas, docs)
  • Dynamic decomposition for "add tests to legacy code"
  • Resume / fork sessions; manifests for recovery
Scenario 5

Claude Code in CI/CD

D3D4

Automated reviews, test generation, PR feedback with few false positives.

  • claude -p + --output-format json + --json-schema
  • Independent reviewer instance
  • Explicit report/skip criteria; severity examples
  • Per-file + integration passes
  • Prior findings in context to avoid duplicates
  • Sync for pre-merge; batch for nightly
Scenario 6

Structured data extraction

D4D5

Unstructured docs → schema-validated JSON → downstream systems.

  • Extraction tool schema; nullable fields; enum + unclear/other
  • tool_choice any / forced
  • Validation-retry with specific errors; know when retry is futile
  • calculated vs stated totals; conflict flags
  • Batches with custom_id; SLA windows
  • Calibrated confidence, stratified sampling, per-segment accuracy
⇢

Signal in the question → likely answer

Read the stem for one of these signals, then check the option that matches.
If the question says…Lean toward…
"must always", "financial", "compliance", "X% of the time it skips"Programmatic gate or hook, not prompt text
"most effective first step"Smallest change at the root cause (descriptions, criteria, examples)
Loop ends early / runs foreverBranch on stop_reason; append tool_result blocks
Answer cut off mid-sentencestop_reason: "max_tokens": truncated, not finished
Subagent output vague, missing earlier infoPass findings explicitly in its prompt
Coordinator cannot spawn subagents"Task" missing from allowedTools
Subagents run one after anotherEmit multiple Task calls in one response
Report misses whole subtopics, subagents fineCoordinator decomposition too narrow
Wrong tool picked between two similar toolsRicher, differentiated descriptions; rename/split
Agent retries hopeless calls / gives up on recoverable onesStructured errors: category + isRetryable
Agent has 15+ tools and misuses someScope tools per role; constrained alternatives
Need a tool call guaranteed, type unknowntool_choice: "any"
Need one specific step to run firstForced {"type":"tool","name":…}
Extended thinking + forced tool errorsOnly auto / none work with thinking
Shared MCP server, secret token.mcp.json + ${ENV_VAR}
Personal MCP server, one projectLocal scope (the claude mcp add default)
Agent prefers Grep over MCP toolImprove MCP tool description
Teammate does not get instructionsThey are in user-level config; move to project
Conventions for files spread across dirs.claude/rules/ with paths globs
Command for everyone who clones.claude/commands/
Skill output floods the conversationcontext: fork
Architecture / many files / multiple approachesPlan mode
CI job hangs waiting for input-p
Reviewer approves its own bugsIndependent instance
Big PR, inconsistent reviewPer-file passes + integration pass
Too many false positivesExplicit report/skip categories; disable noisy category for now
Inconsistent format despite instructionsFew-shot examples
Model invents missing valuesNullable fields + "use null if absent"
Retry still fails, data not in docStop retrying; route to human / fetch source
Cut cost, latency-tolerantMessage Batches API; sync for blocking
Numbers lost in long chatsPersistent case-facts block
"Customer asks for a human"Escalate immediately
Policy does not cover the requestEscalate (policy gap)
Two customers matchAsk for another identifier
Subagent timeoutStructured error with partial results; continue and annotate gaps
Model forgets earlier classes in long explorationScratchpad file, subagents, /compact
"97% accurate, can we drop review?"Segment by doc type/field; stratified sampling
Two sources disagreeKeep both with attribution and dates
?

Practice set

32 original questions written in the exam's style, grouped by domain; not taken from the exam. Answer each in your head before opening it.
D1 · Support agent · choose oneYour refund policy says amounts over $500 must go to a human. In testing, the agent follows this 98% of the time. What should you change?
  1. Move the rule to the top of the system prompt in capitals.
  2. Add a PreToolUse hook that denies process_refund above $500 and tells the agent to call escalate_to_human.
  3. Add five few-shot examples of large refunds being escalated.
  4. Lower the model temperature to zero.
Show answer ▾
B. A financial rule needs a deterministic guarantee. A, C and D all improve probabilistic compliance; 98% is still a failure in 1 of 50 cases. The hook also redirects, so the customer still gets help.
D1 · Research system · choose oneThe coordinator delegates to four subagents, but logs show each runs only after the previous one finishes, even though they are independent. What is the cause?
  1. Subagents share one context window and must queue.
  2. The coordinator issues one Task call per turn instead of several in a single response.
  3. allowedTools is missing "Task".
  4. The Agent SDK cannot run subagents in parallel.
Show answer ▾
B. Parallel execution happens when one coordinator response contains multiple Task tool calls. C would stop delegation entirely, not serialize it. A and D are false.
D1 · Sessions · choose oneYesterday you analysed a service in a named session. Overnight a teammate refactored 3 of its 40 files. You want to continue the analysis. Best approach?
  1. Resume the named session and tell Claude which 3 files changed so it re-reads them.
  2. Start a brand-new session and re-explore all 40 files.
  3. Resume and continue without mentioning the change.
  4. Fork the session twice and compare outputs.
Show answer ▾
A. Most prior context is still valid, so resume, and target re-analysis at the changed files. B wastes work; C trusts stale reads; D solves a different problem (comparing approaches).
D1 · Agent loop · choose oneYour agent loop runs for i in range(8) and returns whatever the last response said. Long tasks get cut off and short ones waste calls. What is the right design?
  1. Raise the limit to 25 iterations.
  2. Stop when the response text contains "done".
  3. Loop until stop_reason is "end_turn", run tools whenever it is "tool_use", and keep a generous cap only as a safety net.
  4. Ask the model to output {"finished": true} and stop on that.
Show answer ▾
C. The API already reports why the turn ended. A cap as the primary stop condition is the listed anti-pattern (A). B and D parse model text for control flow.
D1 · Handoff · choose oneHuman agents say escalated chats force them to re-ask the customer everything. The escalation call passes only reason: "needs human". Best fix?
  1. Escalate earlier in the conversation.
  2. Pass a structured handoff: customer ID, issue summary, root cause, evidence, amounts, what was tried and a recommended action.
  3. Paste the whole conversation as prose into the reason field.
  4. Ask the customer to summarise the issue again for the human.
Show answer ▾
B. The human does not see the transcript, so the payload must stand alone and be scannable. C buries the key numbers; A and D leave the information gap in place.
D1 · Enforcement · choose twoWhich two mechanisms guarantee that process_refund never runs before the customer's identity is verified?
  1. A system-prompt rule written in capitals.
  2. A prerequisite check in the tool handler that rejects the call unless the session holds a verified customer_id.
  3. Few-shot examples that show verification first.
  4. A PreToolUse hook that denies process_refund when no verified customer_id is in session state.
  5. Setting temperature to 0.
Show answer ▾
B and D. Both run in code on every call. A, C and E only make compliance more likely.
D1 · Multi-concern · choose oneA customer writes: "My blender arrived broken, I was charged twice, and I need to update my email." The agent fixes the blender and ends the chat. What should change?
  1. Tell the agent to handle one issue per conversation.
  2. Have the agent split the message into separate issues, investigate each against the same customer context (in parallel where independent), and reply once covering all three.
  3. Route each issue to a different human team.
  4. Ask the customer to open three tickets.
Show answer ▾
B. Decompose, investigate with shared context, then synthesize one reply. The other options push the work back onto the customer or onto humans.
D2 · MCP config · choose twoYour team wants everyone to use the same Jira integration in Claude Code. The API token must not be committed. Which two actions are correct?
  1. Configure the server in the project's .mcp.json using ${JIRA_TOKEN}.
  2. Ask each developer to add the server to their ~/.claude.json.
  3. Use an existing community Jira MCP server rather than writing a custom one.
  4. Put the token in .mcp.json and add the file to .gitignore.
  5. Describe the Jira API in CLAUDE.md so Claude can call it with Bash.
Show answer ▾
A and C. Project scope shares the config through git, env-var expansion keeps the secret out, and Jira is a standard integration with community servers. B is not shared; D stops sharing the config at all; E is fragile.
D2 · Errors · choose oneThe agent calls lookup_order five times in a row for an order that is past the return window, because the tool returns "Error: request failed". Best fix?
  1. Cap retries at two in the agent loop.
  2. Return a structured error with errorCategory: "business", isRetryable: false and a customer-friendly explanation.
  3. Return an empty result instead of an error.
  4. Tell the agent in the system prompt not to retry failed tools.
Show answer ▾
B. The agent cannot tell a policy decision from an outage. Structured metadata lets it stop retrying and explain the policy. A is a blunt cap; C hides the failure; D would also stop useful retries of transient errors.
D2 · Built-in tools · choose oneClaude must update a config value, but Edit fails because the line "timeout": 30 appears in four places in the file. What should it do?
  1. Use Bash with sed -i on every match.
  2. Read the full file, then Write the corrected full content.
  3. Use Glob to find a different file to edit.
  4. Retry Edit until it succeeds.
Show answer ▾
B. The documented fallback when Edit lacks a unique anchor is Read + Write. A changes all four, which may be wrong. (Including more surrounding text to make the anchor unique is also fine in practice.)
D2 · Tool scoping · choose oneYour synthesis subagent has web_search and keeps running new searches instead of writing. Best fix?
  1. Tell it in the prompt not to search.
  2. Remove web_search from its tools and, if needed, give it a narrow verify_fact tool.
  3. Merge synthesis into the search agent.
  4. Set tool_choice to {"type":"any"}.
Show answer ▾
B. Least privilege: an agent misuses tools outside its role. A is probabilistic, C blurs roles, and D forces a tool call, which makes things worse.
D2 · tool_choice · choose oneAn extraction pipeline has three tools: extract_invoice, extract_receipt and extract_contract. Documents arrive unlabeled, and every one must produce structured output. Which tool_choice?
  1. {"type":"auto"}
  2. {"type":"any"}
  3. {"type":"tool","name":"extract_invoice"}
  4. {"type":"none"}
Show answer ▾
B. any guarantees a tool call and lets the model pick the right schema. auto may reply in text; forcing one tool is wrong when the type is unknown.
D2 · Resources · choose oneBefore every query, your agent makes a dozen exploratory calls just to learn which database tables and columns exist. What reduces this most directly?
  1. Expose the schema catalog as an MCP resource the agent can read.
  2. Add more few-shot examples of correct queries.
  3. Increase max_tokens.
  4. Cache the agent's final answers.
Show answer ▾
A. Resources expose browsable content catalogs, so the agent can see what exists without exploratory tool calls.
D2 · Errors · choose oneA search tool returns [] both when nothing matches and when the database times out. During outages the agent tells customers "no orders found". Best fix?
  1. Retry every empty result three times.
  2. On timeout return isError: true with a transient category and isRetryable: true; keep [] for a genuine no-match.
  3. Tell the agent that empty results might be errors.
  4. Replace the tool with Bash database queries.
Show answer ▾
B. Empty and failed must look different. A wastes calls on real no-matches; C asks the model to guess.
D3 · Skills · choose oneA team skill that maps a module's dependencies dumps thousands of lines into the conversation, and later answers get worse. Best fix?
  1. Add context: fork to the skill's frontmatter.
  2. Move the skill's instructions into CLAUDE.md.
  3. Run /compact after each use.
  4. Restrict the skill with allowed-tools: Read.
Show answer ▾
A. Forked context runs the skill in an isolated sub-agent and returns only its result. C treats the symptom every time; B loads it always; D limits actions, not output volume.
D3 · CI · choose oneYour nightly review job re-runs on every new commit and posts the same comments again and again. What fixes it?
  1. Switch to the Message Batches API.
  2. Include the previous findings in context and ask for only new or still-unaddressed issues.
  3. Run the review in the same session that generated the code.
  4. Raise the severity threshold so fewer comments are posted.
Show answer ▾
B. Prior findings in context let Claude de-duplicate. D hides real issues; C makes reviews worse; A changes cost, not duplication.
D3 · Rules · choose oneTerraform conventions must apply to every *.tf file, and those files sit in a dozen directories. Where do the conventions go?
  1. A CLAUDE.md in each directory.
  2. .claude/rules/terraform.md with paths: ["**/*.tf"].
  3. A skill named terraform.
  4. ~/.claude/CLAUDE.md.
Show answer ▾
B. Path-scoped rules load whenever matching files are edited, wherever they live. A is hard to maintain, C needs invoking, D is not shared.
D3 · Skills · choose oneYou want a variant of the team's /deploy-check skill with extra steps only you need. What is the right move?
  1. Edit .claude/skills/deploy-check/SKILL.md and commit.
  2. Copy it to ~/.claude/skills/ under a different name and change the copy.
  3. Copy it to ~/.claude/skills/ under the same name.
  4. Add your steps to the project CLAUDE.md.
Show answer ▾
B. A personal copy with its own name leaves teammates unaffected. A changes it for everyone, C collides with the team skill, D loads your steps for everyone on every task.
D3 · Plan mode · choose oneA test fails with a clear stack trace pointing at one missing null check in one file. Which approach?
  1. Plan mode, then execute.
  2. Direct execution.
  3. Spawn an Explore subagent first.
  4. Write a skill for null checks.
Show answer ▾
B. Small, clear, single-file changes do not need a planning phase.
D3 · Refinement · choose oneYou described a log-line transformation in a paragraph, and Claude applies it inconsistently. Most effective next step?
  1. Rewrite the paragraph in more detail.
  2. Give 2–3 concrete input → output examples, including an edge case.
  3. Switch to plan mode.
  4. Ask Claude to be more careful.
Show answer ▾
B. Examples communicate a transformation better than prose.
D3 · CI · choose twoA CI job must run Claude Code non-interactively and produce machine-readable findings. Which two are correct?
  1. claude -p "<prompt>"
  2. Set CLAUDE_HEADLESS=true.
  3. --output-format json with --json-schema.
  4. claude --batch.
  5. Commit .claude/config.json with a commands array.
Show answer ▾
A and C. B, D and E are invented features. They are distractors from the exam guide.
D4 · Extraction · choose oneInvoices without a PO number come back with plausible but fake PO numbers. The schema marks po_number as a required string. Best fix?
  1. Make po_number nullable and instruct the model to return null when absent.
  2. Add a retry when the PO number fails a regex.
  3. Lower temperature.
  4. Remove po_number from the schema.
Show answer ▾
A. A required non-null field pressures the model to fabricate. B fails because the information is absent; retries cannot add it. D loses data you need when it exists.
D4 · Batch · choose oneDocuments arrive continuously; results are due within 30 hours. Batch processing may take up to 24 hours. Which submission cadence safely meets the SLA with room for resubmitting failures?
  1. Every 12 hours.
  2. Every 8 hours.
  3. Every 4 hours.
  4. Once a day.
Show answer ▾
C. Worst case is window + 24 h. 4 + 24 = 28 h leaves 2 h of buffer. 8 + 24 = 32 h already breaks the SLA.
D4 · False positives · choose twoDevelopers ignore your review bot. 40% of its "comment accuracy" findings are wrong; the other categories are accurate. Which two actions fit best?
  1. Temporarily disable the comment-accuracy category.
  2. Replace "check comments are accurate" with an explicit criterion: flag only when a comment's claim contradicts the code.
  3. Tell the model to "be conservative".
  4. Report only findings with self-rated confidence above 8/10.
  5. Switch to a larger model and change nothing else.
Show answer ▾
A and B. Restore trust now, then fix the vague criterion. C is vague, D is uncalibrated, and E does not address the cause.
D4 · Validation · choose oneExtraction output always passes the schema, but on 6% of invoices the line items do not add up to the stated total. Best fix?
  1. Make the schema stricter.
  2. Extract calculated_total next to stated_total, check them in code, and on a mismatch retry with the document, the previous output and the specific discrepancy. Set conflict_detected when the source itself is inconsistent.
  3. Drop line items from the schema.
  4. Raise max_tokens.
Show answer ▾
B. Schemas check shape, not meaning. Semantic checks plus targeted retries fix misreads; the conflict flag handles documents that contradict themselves.
D4 · Batch · choose oneA 10,000-document batch finishes with 280 failures, all "input too long". What next?
  1. Resubmit the whole batch.
  2. Chunk those 280 documents and resubmit only them, matched by custom_id.
  3. Run the 280 synchronously without changes.
  4. Move the whole pipeline to synchronous calls.
Show answer ▾
B. Resubmit only what failed, with a fix for the cause. C fails again for the same reason.
D5 · Escalation · choose oneA customer writes: "I just want to talk to a person." Their issue is a simple address change the agent could finish in one step. What should the agent do?
  1. Complete the address change first, then offer a human.
  2. Escalate to a human immediately, with a structured summary.
  3. Explain that it can handle this faster than a human.
  4. Check sentiment and escalate only if negative.
Show answer ▾
B. An explicit request for a human is honoured immediately, without investigating first. Offering to resolve applies when the customer is frustrated but has not asked for a person.
D5 · Human review · choose oneAn extraction pipeline is 97% accurate on 10,000 documents. Leadership wants to stop human review for high-confidence results. What should you do first?
  1. Approve it; 97% exceeds the target.
  2. Measure accuracy by document type and field, and set up stratified sampling of high-confidence output.
  3. Ask the model to self-rate confidence 1–10 and auto-accept above 8.
  4. Run every document twice and accept only matches.
Show answer ▾
B. Aggregates can hide a weak segment. Validate per segment and keep sampling to detect new error patterns. C uses uncalibrated self-reports.
D5 · Long sessions · choose oneThirty turns into a support chat, the agent offers a $700 refund. Earlier it confirmed $742.10. History is summarized every 10 turns. Best fix?
  1. Stop summarizing and keep the full history.
  2. Keep a persistent case-facts block (IDs, amounts, dates, promises) sent with every request, outside the summarized history.
  3. Use a model with a larger context window.
  4. Tell the agent to re-read the conversation before quoting amounts.
Show answer ▾
B. Facts that must survive go in a block that is never summarized. A eventually overflows, C does not fix attention, and D cannot recover what the summary already lost.
D5 · Ambiguity · choose oneget_customer("Priya Shah") returns two accounts. What should the agent do?
  1. Pick the account with the most recent order.
  2. Ask the customer for another identifier, such as an email or an order number.
  3. Escalate to a human.
  4. Continue with both accounts.
Show answer ▾
B. Never guess identity. A short clarifying question resolves it without escalation.
D5 · Exploration · choose oneTwo hours into exploring a large codebase, Claude starts describing "typical service patterns" instead of the classes it found earlier. What helps most from here?
  1. Keep going; it will recover.
  2. Have Claude write key findings to a scratchpad file, delegate focused searches to subagents, and /compact.
  3. Paste the whole repository into context.
  4. Ask Claude to be more specific.
Show answer ▾
B. Generic answers are a sign the context has degraded. Persist findings outside the context and keep the main context lean.
D5 · Provenance · choose oneOne source says 21% of indie musicians use generative tools (published 2024). Another says 38% (published 2025). What should the report do?
  1. Report 38% because it is newer.
  2. Average them to 29.5%.
  3. Report both with attribution and dates, and note that the gap may be a trend rather than a contradiction.
  4. Leave the statistic out because the sources conflict.
Show answer ▾
C. Keep both, attributed and dated. Dates often explain an apparent conflict.
✓

Hands-on labs and exam scope

The guide's four preparation exercises, condensed into checklists, plus what will not be tested.
Lab 1 · D1 D2 D5

Multi-tool agent with escalation

  • 3–4 MCP tools, two deliberately similar
  • Loop on stop_reason
  • Errors with category + isRetryable
  • Hook blocking amounts over a threshold → escalate
  • Test multi-concern messages
Lab 2 · D3 D2

Team Claude Code setup

  • Project CLAUDE.md
  • Rules with paths for API and tests
  • Skill with context: fork + allowed-tools
  • .mcp.json with env vars + a personal server
  • Compare plan mode vs direct on 3 task sizes
Lab 3 · D4 D5

Extraction pipeline

  • Schema: required, nullable, enum + other
  • Validation-retry; log retryable vs not
  • Few-shot for varied layouts
  • Batch of 100 docs; resubmit failures by custom_id
  • Field confidence → human routing; per-segment accuracy
Lab 4 · D1 D2 D5

Multi-agent research pipeline

  • Coordinator with Task; explicit context passing
  • Parallel Task calls; measure latency gain
  • Findings: claim, excerpt, source, date
  • Simulate a timeout; continue with partial results
  • Conflicting stats preserved with attribution
Out of scope (not tested)
Fine-tuning or training models · Claude internals, training, weights · Constitutional AI, RLHF
API auth, billing, account management · OAuth, key rotation · rate limits, quotas, pricing maths
Hosting MCP servers (infra, networking, containers) · cloud-provider-specific setup
Embeddings and vector databases · computer use · vision · streaming / SSE
Prompt caching internals (only know it exists) · tokenization details · benchmarks and model comparisons