Claude Code Slash Commands and Skills (SKILL.md Frontmatter)

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 7 min read🎯 Official objective 3.2

👋 In plain words: If your team keeps typing the same long instruction ('review this using our checklist…'), you can save it as a slash command or a skill that anyone can run. This lesson covers where to save them so the team shares them, and how a few settings keep them safe and tidy.

Custom slash commands and skills package repeatable workflows for your team. The exam checks where they live, how they are shared, and how frontmatter controls isolation, permissions and arguments (Task Statement 3.2).

📖 What You’ll Learn: You will be able to create shared commands and skills and control their isolation, permissions and arguments with frontmatter.

🔑 Key terms

  • Slash command: A saved prompt you run by typing /name, for example /review.
  • Skill: A reusable workflow in a SKILL.md file that Claude can run when needed, with its own settings.
  • Frontmatter: Settings at the top of a file, between two --- lines.
  • context: fork: Runs the skill in a separate side conversation, so its output doesn't clutter yours.
  • allowed-tools: Limits which tools the skill may use.

📖 The story in this lesson

Ravi's team reviews every pull request against the same 10-point checklist. He turns it into a shared /review command and an 'explore-codebase' skill for new joiners.

💡 Think of it like this

A slash command is a speed-dial button: one press runs a long instruction. A skill is a trained helper with a job description, a toolbox it is allowed to use, and its own desk, so it doesn't spread papers over yours.

⌨️ Commands: project vs personal

  • .claude/commands/review.md — project command, committed, available to everyone who clones the repo.
  • ~/.claude/commands/ — personal commands, not shared.
⚠️ Watch out: Commands are not defined in CLAUDE.md, and there is no .claude/config.json commands array.

🌍 Real-world example: One /review for the whole team

Ravi saves the checklist as .claude/commands/review.md and commits it. Every tester who pulls the repository can type /review. His personal /standup command stays in ~/.claude/commands/.

🎯 Skills and SKILL.md

---
name: explore-codebase
description: Map an unfamiliar area of the codebase and summarise entry points
context: fork
allowed-tools: Read, Grep, Glob
argument-hint: <directory or feature to explore>
---
Explore $ARGUMENTS. Return: purpose, entry points, key data flows, risks.
FrontmatterWhat it doesUse when
context: forkRuns the skill in an isolated sub-agent contextVerbose output (codebase analysis) or exploratory brainstorming would pollute the main session
allowed-toolsRestricts tools during the skillPrevent destructive actions (e.g. allow only file writes, no Bash)
argument-hintPrompts for required parametersUsers often invoke the skill without arguments

🌍 Real-world example: A safe explorer for new joiners

The explore skill produces long file listings, so it runs with context: fork and keeps the main chat clean. It may only read and search, never edit or run commands. Its argument hint reminds people to say which folder to explore.

---
name: explore-codebase
context: fork
allowed-tools: Read, Grep, Glob
argument-hint: <folder or feature>
---

📘 Personal variants

To customise a team skill for yourself, create a copy under a different name in ~/.claude/skills/. Editing the team skill — even locally — affects others or gets shadowed.

🌍 Real-world example: Ravi's stricter review

Ravi wants an extra security check in his own reviews. Instead of editing the team's command, he copies it to ~/.claude/skills/ under a new name, review-strict. The team version stays unchanged for everyone else.

📄 Skills vs CLAUDE.md

Skills are invoked on demand for task-specific workflows; CLAUDE.md is always loaded for universal standards. Conventions that must always apply belong in CLAUDE.md or rules, not in a skill.

🌍 Real-world example: Always-on rules vs on-demand jobs

'Never commit secrets' must apply all the time, so it goes in CLAUDE.md. 'Generate a release-notes draft' is needed once a sprint, so it is a skill that runs only when someone asks for it.

🚫 Common beginner mistake: Defining commands inside CLAUDE.md, or in a made-up config file. Commands are Markdown files in .claude/commands/.

🛠️ Try it yourself (about 8 minutes)

  1. Create .claude/commands/hello.md containing 'Summarise the README in 3 bullet points.'
  2. Start Claude Code in that repository.
  3. Type /hello and run it.
  4. Commit the file so teammates get it too.

✅ You are done when: /hello appears in the command list and prints a 3-bullet summary.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. Where does a project slash command that every developer gets on clone belong?

  • A. .claude/commands/ in the repo
  • B. CLAUDE.md
  • C. .claude/config.json
  • D. ~/.claude/commands/
Show answer

Answer: A. Project-scoped and version-controlled. D is personal. B holds instructions, not commands. C doesn't exist.

Question 2. A skill should only write files and never run Bash. Which frontmatter enforces this?

  • A. context: fork
  • B. paths
  • C. argument-hint
  • D. allowed-tools: Write, Edit (or similar, excluding Bash)
Show answer

Answer: D. It restricts the tools available during the skill. A isolates context. C prompts for arguments. B belongs to rules.

Question 3. Developers often run /migrate-schema with no arguments and get poor output. What helps?

  • A. Plan mode
  • B. context: fork
  • C. A longer CLAUDE.md
  • D. argument-hint: <table-name> <target-version> in the skill frontmatter
Show answer

Answer: D. It prompts for the required parameters. A, B and C don't address missing arguments.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Create .claude/commands/review.md with your team's review checklist and run it.
    ✅ Done when: A teammate can run /review after pulling the repository, and it follows your checklist.
  2. Task 2: Create a skill with context: fork, allowed-tools and argument-hint, and run it with and without arguments.
    ✅ Done when: Running the skill without arguments shows the argument hint, and its output does not flood the main conversation.
  3. Stretch: make a personal variant of a team skill under a different name in ~/.claude/skills/.
    ✅ Done when: Your personal variant has a different name, and the team skill still behaves exactly as before.

❓ Frequently Asked Questions

🤔 Where do team slash commands live?

In .claude/commands/ in the repository, so everyone gets them after cloning.

🤔 What does context: fork do?

It runs the skill in an isolated sub-agent context so its output does not crowd the main conversation.

🤔 How do I stop a skill running shell commands?

List only the tools it needs in allowed-tools, leaving out Bash.

🤔 Skill or CLAUDE.md?

Use a skill for on-demand, task-specific workflows and CLAUDE.md for standards that must always apply.

🏁 Summary

  • .claude/commands = team; ~/.claude/commands = personal.
  • context: fork isolates, allowed-tools restricts, argument-hint prompts.
  • Personal variants get a different name at user level.
📝 Test yourself: Mock Test 1 · Mock Test 4 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Claude Code Plan Mode vs Direct Execution and Iterative Refinement.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

CLAUDE.md Configuration Guide: Hierarchy, @import and Path-Specific Rules

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 8 min read🎯 Official objectives 3.1 and 3.3

👋 In plain words: CLAUDE.md is a plain text file where you write instructions Claude Code reads every time, such as 'use pytest' or 'never edit generated files'. Where you put that file decides who gets the rules. This lesson shows how to set it up so the whole team gets the same behaviour.

CLAUDE.md is how you give Claude Code persistent project knowledge. The exam tests where instructions live, who receives them, and how to keep them modular so the right conventions load at the right time (Task Statements 3.1 and 3.3).

📖 What You’ll Learn: You will be able to set up CLAUDE.md files so the right conventions reach every teammate and load only when they are relevant.

🔑 Key terms

  • CLAUDE.md: A Markdown file of standing instructions that Claude Code loads automatically.
  • User level: ~/.claude/CLAUDE.md on your own machine. Only you get these rules.
  • Project level: CLAUDE.md in the repository. Everyone who clones it gets these rules.
  • @import: A line in CLAUDE.md that pulls in another file's contents.
  • Path-specific rule: A rule file in .claude/rules/ that loads only when Claude edits matching files.

📖 The story in this lesson

A new tester joins Ravi's team and Claude Code ignores the team's test conventions on their laptop. The reason: Ravi had put the rules in his personal CLAUDE.md.

💡 Think of it like this

CLAUDE.md levels are like notices in a company. A sticky note on your own monitor (user level) is for you alone. A notice on the office board (project level) reaches everyone. A sign on the lab door (directory or path rules) applies only to people working in that room.

🏛️ The three-level hierarchy

LevelLocationShared with team?
User~/.claude/CLAUDE.mdNo — only you
Project./CLAUDE.md or ./.claude/CLAUDE.mdYes, via git
Directorypackages/api/CLAUDE.mdYes; applies when working there
⚠️ Watch out: “New team members don’t get our conventions” → the conventions are in a user-level file. Move them to the project CLAUDE.md.

🌍 Real-world example: The rules the new hire never got

Ravi moves 'Use Playwright fixtures, never hard-coded waits' from ~/.claude/CLAUDE.md into the repository's CLAUDE.md and commits it. The next morning the new tester pulls the repository and Claude follows the rule on their laptop too.

CLAUDE.md configuration hierarchyUser level~/.claude/CLAUDE.md · ~/.claude/skills · ~/.claude/commandsonly you — not sharedProject level./CLAUDE.md (+ @imports) · .claude/commands · .claude/skills · .mcp.jsonwhole team via gitDirectory levelpackages/payments/CLAUDE.mdwhen working in that folderPath-scoped rules.claude/rules/testing.md → paths: [“**/*.test.tsx”]only for matching filesAll applicable files load together into the session — run /memory to see exactly which onesTeam conventions belong at project level; a new teammate never receives your user-level file
Figure: where each CLAUDE.md and rule file lives, and who receives it. Swipe sideways to see the whole diagram.

📎 Keep it modular with @import

# packages/payments/CLAUDE.md
Payments service conventions.
@docs/standards/pci.md
@docs/standards/error-handling.md

Each package imports only the standards relevant to it, instead of loading everything everywhere.

🌍 Real-world example: Payment rules only where they matter

The payments package needs PCI security rules, but the storefront doesn't. The payments CLAUDE.md imports only the files it needs, so storefront work never loads irrelevant rules.

# packages/payments/CLAUDE.md
@docs/standards/pci.md
@docs/standards/error-handling.md

📏 .claude/rules/ and path-specific rules

Split a huge CLAUDE.md into topic files such as testing.md, api-conventions.md and deployment.md in .claude/rules/. Add YAML frontmatter with paths globs so a rule loads only when Claude edits matching files:

---
paths: ["**/*.test.tsx", "**/*.test.ts"]
---
Use React Testing Library. One behaviour per test. No snapshot tests.

Path-scoped rules beat directory CLAUDE.md files when matching files are scattered (tests next to components, Terraform in many service folders), and they save context because irrelevant rules never load.

🌍 Real-world example: Test rules that follow the test files

ShopNest's test files sit next to the code they test, in dozens of folders. One rule file with a paths pattern applies the testing conventions wherever a test file lives, and only when Claude edits a test.

---
paths: ["**/*.spec.ts"]
---
Use page objects. One behaviour per test.

🧠 Debug with /memory

When two developers see different behaviour, run /memory in each session to see exactly which memory files are loaded. It is the first diagnostic for hierarchy problems.

🌍 Real-world example: Why do our laptops behave differently?

Two testers get different results from the same request. Each runs /memory and compares the list of loaded files. One laptop still has an old personal rule file that overrides the team setup.

🚫 Common beginner mistake: Putting team rules in your personal ~/.claude/CLAUDE.md. Only you get them. Team rules belong in the repository.

🛠️ Try it yourself (about 8 minutes)

  1. In a test repository, run /init in Claude Code to create a CLAUDE.md.
  2. Add one rule, such as 'Write tests with pytest'.
  3. Run /memory and find your file in the list.
  4. Ask Claude to write a small test and check it follows the rule.

✅ You are done when: /memory shows the project CLAUDE.md and the generated test follows your rule.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. Your packages/payments/CLAUDE.md should include the PCI standards file but not the frontend style guide. What's the cleanest method?

  • A. @import the PCI standards file in that package's CLAUDE.md
  • B. Copy-paste the PCI text into it
  • C. Create a skill
  • D. Put everything in the root
Show answer

Answer: A. Selective, modular imports. B duplicates text that will drift. D loads irrelevant rules everywhere. C isn't always-on.

Question 2. Test files sit next to their sources throughout the repo. What's the best way to apply testing conventions automatically?

  • A. Root CLAUDE.md
  • B. A CLAUDE.md in each folder
  • C. A /test command
  • D. A .claude/rules/testing.md with paths: ["**/*.test.*"]
Show answer

Answer: D. Glob-scoped rules follow file types wherever they are. B is impractical for scattered files. C needs manual invocation. A loads the rules always and relies on inference.

Question 3. What's the key difference between a skill and CLAUDE.md?

  • A. CLAUDE.md can't be shared
  • B. Skills are invoked on demand for specific tasks; CLAUDE.md holds always-loaded standards
  • C. Skills can't restrict tools
  • D. Skills are always loaded
Show answer

Answer: B. D is reversed. A: project CLAUDE.md is shared. C: allowed-tools restricts them.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Run /init in a repository, then move one team convention from your user-level file into the project CLAUDE.md.
    ✅ Done when: A teammate who pulls the repository gets the convention without changing their own machine, and /memory shows the project file.
  2. Task 2: Create .claude/rules/testing.md with a paths glob for test files and confirm it loads only when you edit a test.
    ✅ Done when: The testing rule appears when you edit a test file and does not appear when you edit an unrelated source file.
  3. Stretch: split a long CLAUDE.md into three rule files and use @import for one shared standards document.
    ✅ Done when: The original CLAUDE.md is shorter, the three rule files each cover one topic, and the imported file loads where you expect.

❓ Frequently Asked Questions

🤔 Why doesn't my teammate get my CLAUDE.md rules?

They are probably in ~/.claude/CLAUDE.md, which is personal. Put team rules in the project CLAUDE.md.

🤔 What does @import do in CLAUDE.md?

It pulls another file's contents into CLAUDE.md, so each package can include only the standards it needs.

🤔 When should I use .claude/rules with paths?

When conventions apply to files spread across many folders, such as all test files.

🤔 How do I see which memory files are loaded?

Run /memory in the Claude Code session.

🏁 Summary

  • User-level = personal; project-level = team.
  • @import for modular standards; .claude/rules/ for topic files.
  • paths globs load conventions only for matching files, wherever they live.
  • /memory shows what’s loaded.
📝 Test yourself: Mock Test 1 · Mock Test 4 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Claude Code Slash Commands and Skills (SKILL.md Frontmatter).

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

MCP Integration in Claude Code: Scopes, Resources and Built-in Tools

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 8 min read🎯 Official objectives 2.4 and 2.5

👋 In plain words: MCP lets Claude Code plug into your team's systems, such as GitHub, Jira or a database, the same way for everyone. This lesson covers where to configure those connections, how to keep passwords out of Git, and which built-in tool to use for searching code.

The Model Context Protocol (MCP) connects Claude to your systems. The exam checks that you can configure servers at the right scope, keep secrets out of git, use resources to cut wasted calls, and pick the right built-in tool (Task Statements 2.4 and 2.5).

📖 What You’ll Learn: You will be able to configure MCP servers at the right scope, keep secrets out of git, and pick the right built-in tool for each job.

🔑 Key terms

  • MCP (Model Context Protocol): A standard that connects Claude to tools and data, like USB for AI.
  • .mcp.json: A file in your repository listing the MCP servers your whole team shares.
  • Environment variable: A secret or setting stored on your machine, for example GITHUB_TOKEN, not in the code.
  • Resource: Read-only content an MCP server offers, such as a list of database tables.
  • Grep / Glob: Built-in tools. Grep searches inside files; Glob finds files by name.

📖 The story in this lesson

Ravi wants every ShopNest developer's Claude Code to reach the team's GitHub and Jira, without anyone committing a password to the repository.

💡 Think of it like this

MCP is like a universal power socket. Any appliance (server) with the standard plug works in any room (Claude client). .mcp.json is the house wiring plan everyone shares. Your personal desk lamp stays in your own room, ~/.claude.json.

🔌 Project scope vs user scope

ScopeFileUse for
Project.mcp.json in the repo (committed)Shared team servers (GitHub, Jira, internal docs)
User~/.claude.jsonPersonal or experimental servers
{
  "mcpServers": {
    "github": {
      "command": "github-mcp-server",
      "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }
    }
  }
}

Environment-variable expansion (${GITHUB_TOKEN}) keeps credentials out of version control. Tools from all configured servers are discovered when Claude Code connects and are available at the same time.

🌍 Real-world example: Sharing GitHub without sharing the token

Ravi commits .mcp.json with the GitHub server, and the token written as a variable. Each developer sets their own GITHUB_TOKEN locally. Ravi's experimental weather server stays in his personal ~/.claude.json.

{"mcpServers": {"github": {"command": "github-mcp-server",
  "env": {"GITHUB_TOKEN": "${GITHUB_TOKEN}"}}}}

🛠️ Tools vs resources

  • Tools perform actions (search tickets, create an issue).
  • Resources expose content catalogues — issue summaries, documentation trees, database schemas — so the agent can see what exists without exploratory tool calls.

If the agent keeps choosing built-in Grep over your more capable MCP search tool, improve the MCP tool’s description. For standard systems like Jira, prefer a maintained community server; build custom servers for team-specific workflows.

🌍 Real-world example: 12 calls to find the tables

Claude made 12 exploratory calls just to learn which database tables exist. Ravi exposes the table list as an MCP resource instead. Claude can now see it straight away and goes straight to the right table.

MCP architecture in Claude CodeClaude Code (host)built-in: Read · Write · EditBash · Grep · GlobMCP clientdiscovers tools fromall servers at startGitHub server (team).mcp.json in the repotoken via ${GITHUB_TOKEN}Notes server (personal)~/.claude.jsononly on your machineRemote docs serverStreamable HTTPtools + resources (catalogues)stdiostdioHTTPTools = actionsResources = what existsPrompts = user templates
Figure: Claude Code's MCP client connects to team, personal and remote servers at the same time. Swipe sideways to see the whole diagram.

🛠️ Choosing built-in tools

NeedTool
Search file contents (callers, error strings, imports)Grep
Find files by name or path pattern (**/*.test.tsx)Glob
Load a whole fileRead
Create or overwrite a fileWrite
Targeted change via unique anchor textEdit (fallback: Read + Write when the anchor isn’t unique)
Run commands and testsBash

Explore incrementally: Grep for entry points, then Read along imports. To trace usage through wrapper modules, list all exported names first, then Grep for each.

🌍 Real-world example: Finding every test that creates a user

Ravi needs every *.spec.ts file that calls createUser(. First Glob, to find files by name pattern. Then Grep, to search inside those files for the text. Reading every file one by one would waste time and context.

🚫 Common beginner mistake: Writing an API token directly in .mcp.json. Use environment-variable expansion, so the committed file contains no secrets.

🛠️ Try it yourself (about 10 minutes)

  1. In a test repository, create .mcp.json with one server that uses ${MY_TOKEN}.
  2. Set MY_TOKEN in your terminal, not in the file.
  3. Start Claude Code and run /mcp to see the server.
  4. Check with git diff that no real token appears.

✅ You are done when: /mcp lists the server and the committed file contains only the variable name.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. Where should a shared team GitHub MCP server be configured, and how is its token handled?

  • A. .mcp.json with the token inline, but git-ignored
  • B. ~/.claude.json with the token inline
  • C. CLAUDE.md
  • D. Project .mcp.json committed, using ${GITHUB_TOKEN} env expansion
Show answer

Answer: D. Project scope makes it shared, and env expansion keeps secrets out of git. B is personal scope and the token is inline. C isn't where servers are configured. A is no longer shared, and it's a fragile secret-handling pattern.

Question 2. You need to find every file named *.spec.ts, then find which of them call createUser(. Which tools, in order?

  • A. Grep, then Glob
  • B. Bash ls only
  • C. Glob, then Grep
  • D. Read all files
Show answer

Answer: C. Glob matches path patterns, and Grep searches contents. A reverses their roles. D is wasteful. B can't search contents well.

Question 3. The agent makes 12 exploratory calls to discover which database tables exist. What's the better design?

  • A. Increase max_tokens
  • B. Put the full DB dump in the prompt
  • C. Add a list_everything tool
  • D. Expose the schema catalogue as an MCP resource
Show answer

Answer: D. Resources expose catalogues without needing exploratory calls. C is a blunt tool that may be huge. B wastes context and goes stale. A is unrelated.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Create a project .mcp.json that uses ${GITHUB_TOKEN} and a personal server in user scope. Confirm both appear with /mcp.
    ✅ Done when: /mcp lists both servers, and your committed .mcp.json contains no real token.
  2. Task 2: Find all callers of one function with Grep and all test files with Glob in a repo you know.
    ✅ Done when: You recorded the exact Grep and Glob patterns you used and how many matches each returned.
  3. Stretch: expose a list of documents as an MCP resource and compare the number of tool calls before and after.
    ✅ Done when: You counted tool calls before and after adding the resource, and the count went down.

❓ Frequently Asked Questions

🤔 Where do shared MCP servers go?

In the project's .mcp.json, committed to the repository, with secrets supplied through environment-variable expansion.

🤔 What is an MCP resource?

Read-only content the server exposes, such as a catalogue or schema, so the agent can see what exists without exploratory calls.

🤔 What is the difference between Grep and Glob?

Grep searches inside files for text. Glob finds files whose names or paths match a pattern.

🤔 What if Edit cannot find a unique match?

Read the whole file, then Write the corrected content.

🏁 Summary

  • Team servers in .mcp.json with ${ENV}; personal servers in ~/.claude.json.
  • Resources for catalogues, tools for actions.
  • Grep = contents, Glob = paths, Edit needs unique anchors.
📝 Test yourself: Mock Test 2 · Mock Test 3 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with CLAUDE.md Configuration Guide: Hierarchy, @import and Path-Specific Rules.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

MCP Tool Error Handling: isError, Error Categories and Retries

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 7 min read🎯 Official objective 2.2

👋 In plain words: Tools fail: servers time out, inputs are wrong, rules forbid an action. If a tool just says 'Operation failed', Claude can't tell whether to retry, fix something, or explain to the user. This lesson shows how to return errors that help Claude recover sensibly.

When a tool fails, the agent can only recover sensibly if it knows why. A generic “Operation failed” leads to pointless retries of policy violations and early surrender on simple timeouts. This is Task Statement 2.2.

📖 What You’ll Learn: You will be able to design MCP tool errors that let Claude retry what is worth retrying and explain or escalate the rest.

🔑 Key terms

  • MCP server: A small program that offers tools (and data) to Claude through the Model Context Protocol.
  • isError: A flag on a tool result saying 'this call failed'.
  • Transient error: A temporary failure, such as a timeout, that may work if you try again.
  • Business error: The action broke a rule, such as a refund outside the 30-day window. Retrying won't help.
  • Retryable: Whether trying again could succeed.

📖 The story in this lesson

ShopNest's refund tool can fail in four ways: the payment server is slow, the date was typed wrongly, the order is outside the 30-day window, or the bot lacks permission. Each failure needs a different response.

💡 Think of it like this

A good error is like a helpful shop assistant. 'Sorry, the till is rebooting, try again in a minute' (temporary). 'That date isn't valid, please use DD/MM' (fix the input). 'We can't refund after 30 days' (a rule). 'Only the manager can do that' (permission). 'Error' on its own helps nobody.

🚨 The isError pattern

MCP tools signal failure with isError: true in the tool result. Put structured metadata in the content:

{
  "isError": true,
  "content": [{"type": "text", "text": "{\"errorCategory\": \"business\", \"isRetryable\": false, \"message\": \"Refund window is 30 days; this order was delivered 41 days ago.\", \"customerMessage\": \"This order is outside our 30-day refund window.\"}"}]
}

🌍 Real-world example: A refund outside the window

Instead of throwing a raw error, the refund tool returns a result with isError set, a category, whether a retry could work, and a message the bot can pass on to the customer.

{"isError": true, "errorCategory": "business", "isRetryable": false,
 "customerMessage": "This order is outside our 30-day refund window."}

🚨 Four error categories

CategoryExampleRetryable?Agent should…
TransientTimeout, 503YesRetry with backoff
ValidationBad date formatYes, after fixing inputCorrect and retry
BusinessPolicy limit exceededNoExplain or escalate
PermissionNot authorisedNoEscalate or request access

🌍 Real-world example: Four failures, four responses

A timeout: retry after a short wait. A date in the wrong format: correct it and retry. Outside the refund window: explain to the customer, no retry. No permission: escalate to a human. One category field lets Claude choose correctly every time.

🚨 Empty result is not an error

“No orders found for this customer” is a successful query with zero matches. A database timeout is an access failure. Reporting empty results as errors triggers retries; reporting failures as empty results hides problems.

🌍 Real-world example: 'No orders' vs 'database down'

A new customer has no orders, so the search correctly returns an empty list as a success. On another day the database times out, which is an error. When ShopNest once reported both as 'no orders', customers were told they had never ordered while the database was down.

📘 Local recovery in multi-agent systems

Subagents should handle transient failures themselves and propagate only what they can’t resolve — with what they attempted and any partial results — so the coordinator can decide what to do next.

🌍 Real-world example: The subagent retries first

A search subagent hits a timeout. It retries twice by itself, which works most of the time. Only when it still fails does it report to the coordinator, saying what it tried and including the 3 results it did get.

🚫 Common beginner mistake: Returning an empty list when a tool actually failed. It hides the failure, and Claude will confidently say 'nothing found'.

🛠️ Try it yourself (about 8 minutes)

  1. List three ways a tool you use could fail.
  2. Label each one transient, validation, business or permission.
  3. Write the JSON error for the business case, including a customer-friendly message.

✅ You are done when: each failure has a category and a retryable yes or no, and the JSON includes isError.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. An MCP tool times out. What should it return?

  • A. A Python stack trace
  • B. A result with isError: true and structured metadata (category transient, retryable)
  • C. An empty array
  • D. Nothing; let the client hang
Show answer

Answer: B. It's structured and actionable. C disguises a failure as "no data". A is noisy and possibly leaks internals. D is broken behaviour.

Question 2. A search returns no matching orders for a valid customer. How should the tool report this?

  • A. As an error with isRetryable: true
  • B. By throwing a timeout
  • C. As a successful result with an empty list
  • D. As a permission error
Show answer

Answer: C. A valid query with zero matches is a success. Treating it as an error (A, D, B) triggers pointless retries or escalation.

Question 3. Which error should not be retried?

  • A. Network timeout
  • B. 503 Service Unavailable
  • C. Rate limited
  • D. "Refund exceeds the 30-day policy window"
Show answer

Answer: D. A business-rule violation: retrying won't change the outcome, so explain it or escalate. A, B and C are transient.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: List three failures your own tools can produce and classify each as transient, validation, business or permission.
    ✅ Done when: Each failure is assigned exactly one category and marked retryable or not retryable, with a reason.
  2. Task 2: Write the JSON error body for a business-rule failure, including a customer-friendly message.
    ✅ Done when: Your JSON includes isError, errorCategory, isRetryable and a message a customer could read without confusion.
  3. Stretch: make a subagent retry a transient error locally and report partial results to the coordinator only if it still fails.
    ✅ Done when: A simulated timeout is retried inside the subagent, and only a persistent failure reaches the coordinator with partial results.

❓ Frequently Asked Questions

🤔 What is the isError flag in MCP?

A field on the tool result that tells the client and Claude the tool call failed.

🤔 Which errors should not be retried?

Business-rule violations and permission errors. Retrying cannot change their outcome.

🤔 Is no results an error?

No. A valid query that matches nothing is a successful result with an empty list.

🤔 Why is 'Operation failed' a bad error message?

It hides whether the failure is temporary, caused by bad input or a policy, so the agent cannot choose a sensible recovery.

🏁 Summary

  • Return isError plus errorCategory, isRetryable and a readable message.
  • Business and permission errors are not retryable.
  • Empty ≠ failure.
📝 Test yourself: Mock Test 2 · Mock Test 3 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with MCP Integration in Claude Code: Scopes, Resources and Built-in Tools.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

Claude Tool Design: Descriptions, Tool Distribution and tool_choice

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 8 min read🎯 Official objectives 2.1 and 2.3

👋 In plain words: When Claude can use several tools, it picks one mostly by reading each tool's name and description. Vague descriptions make it pick the wrong tool, and too many tools make picking harder. This lesson shows how to write tools Claude chooses correctly.

Claude decides which tool to call mostly from the tool’s name and description. Weak descriptions are the number-one cause of misrouting, and too many tools make selection worse. This lesson covers Task Statements 2.1 and 2.3.

📖 What You’ll Learn: You will be able to write tool descriptions that Claude selects reliably and choose the right tool_choice setting for a task.

🔑 Key terms

  • Tool definition: The name, description and input schema you give Claude for each tool.
  • Input schema: A JSON description of the inputs a tool accepts, such as order_id as a string.
  • Misrouting: Claude calling the wrong tool for a request.
  • tool_choice: A setting that controls whether Claude may, must, or must not call a tool.

📖 The story in this lesson

ShopNest's support bot has two tools that keep getting mixed up: get_customer and lookup_order. Customers asking 'where's my order?' sometimes get their profile details instead.

💡 Think of it like this

Tool descriptions are the labels on kitchen drawers. If two drawers both say 'stuff', the cook opens the wrong one. Label them 'knives: for cutting' and 'spoons: for stirring, not cutting', and the right drawer opens every time.

📘 Write descriptions that differentiate

A good tool description states what the tool does, the accepted input formats, example queries, edge cases, what it returns, and when to use it rather than a similar tool.

{
  "name": "lookup_order",
  "description": "Fetch ONE order by order number (format: # followed by 5 digits, e.g. #12345) for a customer already verified with get_customer. Use for order status, items, totals and delivery dates. Do NOT use for customer profile, address or loyalty questions — use get_customer. Returns {order_id, status, items[], total, delivered_at}.",
  "input_schema": {"type": "object",
    "properties": {"customer_id": {"type": "string"}, "order_id": {"type": "string"}},
    "required": ["customer_id", "order_id"]}
}
  • Overlapping tools? Rename and rescope (analyze_content → extract_web_results), or split a generic tool into purpose-specific ones (extract_data_points, summarize_content, verify_claim_against_source).
  • Check the system prompt for keyword-triggered rules (“whenever the user says account, call get_customer”) that override good descriptions.
⚠️ Watch out: For “most effective first step” to fix misrouting, improving descriptions beats few-shot examples, routing classifiers and tool consolidation — they all cost more and don’t fix the root cause.

🌍 Real-world example: Fixing 'Gets data'

The old description of lookup_order was 'Gets order data'. Asha rewrites it to say what the tool is for, the order-number format, and when to use get_customer instead. Wrong tool calls drop sharply, and no classifier or extra infrastructure was needed.

"description": "Fetch ONE order by order number (#12345). Use for status, items, delivery date. NOT for profile or address questions: use get_customer."

🛠️ How many tools per agent?

Giving an agent 18 tools instead of 4–5 increases decision complexity and lowers selection reliability. Agents also misuse tools outside their speciality (a synthesis agent running web searches). Scope tools to the role, and add a narrow cross-role tool (e.g. verify_fact) only for frequent needs, routing complex cases back through the coordinator. Replace generic tools with constrained ones — fetch_url → load_document, which validates the URL.

🌍 Real-world example: From 18 tools to 5

ShopNest's first bot had 18 tools, including web search and file upload, and it often chose oddly. Asha gives the support agent only the 5 tools it needs. The rarely-used tools move to other agents, and tool selection becomes reliable.

🛠️ tool_choice options

ValueBehaviourTypical use
"auto"Model may answer in text or call a tool (default)General agents
"any"Model must call some toolGuarantee structured output when several extraction schemas exist
{"type":"tool","name":"X"}Model must call XForce extract_metadata first, then continue in follow-up turns
"none"No tool callsPure text responses
💡 Tip: Real-world note (Nov 2026). The newest Claude models (Opus 5.5, Sonnet 5.5, Fable 5.1+) reject forced any/named tool_choice with an error; there you use auto plus strict: true tools or structured outputs. For the exam, answer as the official exam guide teaches.

🌍 Real-world example: Forcing the first step

For invoice processing, ShopNest must always run extract_metadata first. Following the exam guide, they force that tool on the first call, then let Claude choose freely in later turns. For normal chat, auto lets Claude answer in plain text when no tool is needed.

tool_choice = {"type": "tool", "name": "extract_metadata"}
🚫 Common beginner mistake: Adding a routing classifier or many few-shot examples before fixing the tool descriptions. Descriptions are the cheapest fix and target the root cause.

🛠️ Try it yourself (about 8 minutes)

  1. Pick two similar functions from a project you know.
  2. Write a one-line description for each, as Claude would see it.
  3. Add the input format, an example, and 'use X instead when …' to each.
  4. Ask a colleague which tool fits three sample requests, using only your descriptions.

✅ You are done when: your colleague picks the right tool for all three requests.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. Two tools have the descriptions "Gets data" and "Gets info". What's the best first fix for misrouting?

  • A. Merge them
  • B. Add 8 few-shot examples
  • C. Add a routing classifier
  • D. Rewrite the descriptions with purpose, input formats, example queries, edge cases, and when to use each versus the other
Show answer

Answer: D. Descriptions are the main signal for tool selection, so this is the cheap fix at the root cause. C is over-engineering. A is valid sometimes, but it's more effort than a "first step". B adds tokens without fixing the cause.

Question 2. An agent has 18 tools and selects poorly. What's the best design move?

  • A. Use tool_choice: "any"
  • B. Add more tools for coverage
  • C. Increase the temperature
  • D. Give each specialised agent the 4–5 tools its role needs
Show answer

Answer: D. Fewer, role-scoped tools improve selection reliability. B makes it worse. A forces a call, not the right one. C adds randomness.

Question 3. analyze_content and analyze_document keep being confused. Content-analysis is only ever used for web search results. What's the best change?

  • A. Set tool_choice to auto
  • B. Add "IMPORTANT" to one description
  • C. Delete both
  • D. Rename it to extract_web_results with a web-specific description
Show answer

Answer: D. Renaming and rescoping removes the overlap. C loses capability. B is cosmetic. A is already the default and doesn't help.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Rewrite two one-line tool descriptions from your own project using the purpose, inputs, examples and boundaries pattern.
    ✅ Done when: Each rewritten description names its inputs with an example, says when to use it instead of a similar tool, and states what it returns.
  2. Task 2: Split a generic analyze_document tool into three purpose-specific tools with clear input and output contracts.
    ✅ Done when: Your three tools have distinct names, non-overlapping purposes and defined input and output fields.
  3. Stretch: test tool_choice auto versus any on the model you use and note how it behaves.
    ✅ Done when: Your notes record what happened with each tool_choice setting, including any error the model returned.

❓ Frequently Asked Questions

🤔 How does Claude choose which tool to call?

Mainly from each tool's name and description, so descriptions must explain purpose, inputs and when to use the tool over similar ones.

🤔 How many tools should an agent have?

Ideally four or five relevant to its role. Large tool sets make selection less reliable.

🤔 What does tool_choice any do?

It forces Claude to call some tool rather than reply with text, while letting it pick which one.

🤔 Do new Claude models support forced tool_choice?

The newest models reject forced any and named tool_choice. Use auto with strict tools or structured outputs there, but answer exam questions as the exam guide teaches.

🏁 Summary

  • The description is the selection signal — make it differentiate.
  • Give each agent 4–5 role-relevant tools.
  • auto = may call; any = must call some tool; forced = must call that tool.
📝 Test yourself: Mock Test 2 · Mock Test 3 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with MCP Tool Error Handling: isError, Error Categories and Retries.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

Task Decomposition and Session Management in Claude Code

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 7 min read🎯 Official objectives 1.6 and 1.7

👋 In plain words: Big tasks go better when you break them into steps, but there are two ways to do it: a fixed checklist, or a plan you adjust as you learn. This lesson also covers how to continue yesterday's work in Claude Code without starting from zero.

How you split work determines whether Claude stays focused or drowns in context. The exam asks you to choose the right decomposition pattern and the right way to continue work across sessions.

📖 What You’ll Learn: You will be able to choose the right decomposition pattern for a task and the right way to continue work across Claude sessions.

🔑 Key terms

  • Decomposition: Splitting a big task into smaller steps.
  • Prompt chaining: A fixed sequence of steps decided in advance, where each step's output feeds the next.
  • Dynamic decomposition: Planning the next step based on what you just discovered.
  • Session: One Claude Code conversation, with its history. It can be resumed later.
  • Fork: Copying a session into two independent branches, to try two approaches from the same starting point.

📖 The story in this lesson

Ravi has two jobs this week. He needs to review a 9-file pull request, which is predictable, and to add tests to ShopNest's old, untested payment service, which is not.

💡 Think of it like this

Prompt chaining is following a recipe: you know every step before you start. Dynamic decomposition is cooking with whatever is in the fridge: you open it, see what's there, and decide the next step.

✍️ Prompt chaining vs dynamic decomposition

Prompt chaining (fixed pipeline)Dynamic decomposition
Steps are known in advanceNext steps depend on what you discover
e.g. review each file against a checklist, then an integration passe.g. “add tests to this legacy codebase”, “find why billing is slow”
Predictable, cheap, testableAdaptive; plan → investigate → re-plan

🌍 Real-world example: Recipe or fridge?

Checking 9 changed files against the same checklist is a recipe, so Ravi uses a fixed chain. 'Add tests to the payment service' is a fridge job: he doesn't know what's inside until Claude explores the code, so the plan has to adapt.

🔍 Large code reviews: per-file plus integration

Reviewing many files in one pass dilutes attention: some files get deep feedback, others shallow, and identical code can get contradictory verdicts. Split the review into per-file passes for local issues plus a separate integration pass for cross-file data flow. A bigger context window doesn’t fix this — attention quality is the problem, not space.

🌍 Real-world example: The review that missed file 7

Reviewing all 9 files in one go, Claude gave detailed notes on the first files and only a line each on the rest. Ravi switches to one pass per file plus a final pass that checks how data moves between the files. Every file now gets the same attention.

📘 Open-ended tasks

For “add comprehensive tests to a legacy service”: map the structure, identify high-impact or high-risk areas, create a prioritised plan, then adapt it as dependencies are discovered.

🌍 Real-world example: Testing the legacy payment service

Claude first maps the service and finds the refund calculation handles money but has no tests. It plans: refunds first, then currency conversion, then logging. When it discovers a hidden dependency on a tax module, it updates the plan instead of following the old one blindly.

💾 Resume, fork or start fresh?

SituationUse
Continue yesterday’s named investigation; context still mostly valid--resume <session-name> — and tell the agent which files changed
Compare two approaches from the same analysisfork_session
Earlier tool results are largely staleStart fresh and inject a structured summary
⚠️ Watch out: Resuming without mentioning changed files lets the agent reason from stale results; re-exploring everything is wasteful. Name the changed files for targeted re-analysis.

🌍 Real-world example: Back to work after the weekend

On Monday, Ravi resumes Friday's named session and says: 'Since Friday, refund.py and tax.py changed.' Claude re-checks only those two files. To compare two refactoring ideas, he forks the session. After a major rewrite he starts fresh with a short summary instead.

claude --resume payment-tests
🚫 Common beginner mistake: Resuming an old session without saying what changed. Claude will reason from out-of-date file contents, so name the changed files.

🛠️ Try it yourself (about 8 minutes)

  1. List five tasks from your current work.
  2. Label each one 'recipe' (fixed chain) or 'fridge' (dynamic).
  3. For one recipe task, write the fixed steps.
  4. For one fridge task, write only the first exploration step.

✅ You are done when: every task is labelled, with a one-line reason why.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. "Review this PR": each of 9 files should get the same checklist, followed by a cross-file data-flow check. Which decomposition fits?

  • A. Three random full-PR passes with voting
  • B. Dynamic adaptive decomposition
  • C. A single pass with a larger context
  • D. Prompt chaining: per-file passes, then an integration pass
Show answer

Answer: D. Predictable, multi-aspect work suits a fixed chain. B suits open-ended investigation. C: attention gets diluted. A: voting suppresses real but intermittent findings.

Question 2. Yesterday you analysed a module in a named session. Overnight, teammates changed 3 of its 40 files. What's the best way to continue?

  • A. Use the Batches API
  • B. Start over and re-read all 40 files
  • C. --resume <name> and tell the agent which 3 files changed so it re-analyses them
  • D. Resume without mentioning the changes
Show answer

Answer: C. Most of the prior context is still valid, so resume and point at what changed. B is wasteful. D risks stale conclusions. A is irrelevant.

Question 3. You want to compare two refactoring strategies starting from the same codebase analysis. Which feature fits?

  • A. fork_session
  • B. /memory
  • C. /compact
  • D. --print
Show answer

Answer: A. Forking creates independent branches from a shared baseline. C shrinks context. D is non-interactive mode. B inspects memory files.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Classify five tasks from your own work as prompt chaining or dynamic decomposition.
    ✅ Done when: Each of your five tasks is labelled, with a one-line reason that mentions whether its steps are known in advance.
  2. Task 2: Plan a review of a 12-file pull request as per-file passes plus an integration pass.
    ✅ Done when: Your plan lists every file pass plus a separate integration pass, and says what the integration pass checks.
  3. Stretch: in Claude Code, resume a named session after changing two files and tell it exactly which files changed.
    ✅ Done when: Claude re-analyses only the two changed files and does not re-read the whole codebase.

❓ Frequently Asked Questions

🤔 What is prompt chaining?

A fixed sequence of focused steps, such as reviewing each file and then running an integration pass. It suits predictable work.

🤔 When should I use dynamic decomposition?

For open-ended tasks where the next steps depend on what you discover, such as adding tests to a legacy codebase.

🤔 Does a bigger context window fix inconsistent reviews?

No. The problem is attention dilution, so split the review into focused passes.

🤔 When should I fork a session?

When you want to compare two approaches starting from the same analysis.

🏁 Summary

  • Predictable multi-aspect work → prompt chaining; open-ended work → dynamic decomposition.
  • Big reviews → per-file passes plus an integration pass.
  • Resume when context is valid, fork to compare approaches, start fresh with a summary when it is stale.
📝 Test yourself: Mock Test 1 · Mock Test 2 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Claude Tool Design: Descriptions, Tool Distribution and tool_choice.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

Claude Agent SDK Hooks, Prerequisite Gates and Human Handoffs

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 8 min read🎯 Official objectives 1.4 and 1.5

👋 In plain words: You can tell Claude 'always verify the customer before a refund', and it will usually obey, but usually is not good enough for money. Hooks and gates are code that enforces rules every time. This lesson shows when a rule belongs in code instead of in a prompt.

Prompt instructions are probabilistic: even a well-written rule fails a small percentage of the time. When a business rule must always hold — verify identity before a refund, never refund over a limit — the exam expects programmatic enforcement (Task Statements 1.4 and 1.5).

📖 What You’ll Learn: You will know when to enforce rules in code instead of prompts, and how pre-tool interception and PostToolUse hooks do it.

🔑 Key terms

  • Prompt instruction: A rule written in words for Claude. It works most of the time, not every time.
  • Hook: Your code that runs automatically before or after a tool call, and can block, change or clean up that call.
  • Prerequisite gate: A check that blocks a tool until an earlier step has succeeded.
  • PostToolUse hook: A hook that runs after a tool and tidies its result before Claude sees it.
  • Handoff: Passing a case to a human agent, with a summary of what happened so far.

📖 The story in this lesson

ShopNest's support bot can issue refunds. Asha's rules: never refund before the customer is verified, and send any refund over $500 to a human. This lesson turns both rules into code.

💡 Think of it like this

A prompt is like a sign saying 'Staff only' on a door: most people obey. A hook is the lock on that door: nobody gets through without a key. For money, identity and safety, use the lock.

✍️ Prompt guidance vs programmatic enforcement

Prompt guidanceProgrammatic enforcement
ExamplesSystem-prompt rules, few-shot examplesHooks, prerequisite gates, removing tools
GuaranteeProbabilistic (non-zero failure rate)Deterministic
Use forStyle, preferences, judgementMoney, identity, compliance, destructive actions

🌍 Real-world example: The 1-in-200 mistake

Asha's system prompt says 'verify identity before refunds'. In testing, about 1 refund in 200 still skipped verification. For tone of voice that would be fine. For money it isn't, so she moves the rule into code, where it holds every single time.

🚧 Prerequisite gates

A gate blocks a downstream tool until an upstream step has succeeded — for example, process_refund is rejected unless get_customer returned a verified customer ID in this session.

def guard(tool_name, tool_input, session):
    if tool_name in {"lookup_order", "process_refund"} and not session.verified_customer_id:
        return deny("Verify the customer with get_customer first.")
    if tool_name == "process_refund" and tool_input["amount"] > 500:
        return redirect("escalate_to_human", reason="Refund above $500 needs approval")
    return allow()

🌍 Real-world example: No refund without verification

The gate checks the session before process_refund runs. If get_customer hasn't returned a verified ID yet, the call is refused with a clear message, and Claude then asks the customer for their details first.

🪝 The two hook patterns the exam tests

  • Tool-call interception (pre-tool) — inspects outgoing calls and blocks or redirects policy-violating ones (refunds over a threshold, rm -rf, writes to production paths).
  • PostToolUse — transforms tool results before the model sees them, e.g. normalising Unix epochs, ISO-8601 strings and numeric status codes from different MCP servers into one format, or trimming verbose results to the relevant fields.

🌍 Real-world example: Blocking big refunds and tidying dates

A pre-tool hook sees process_refund for $750 and redirects it to escalate_to_human. A PostToolUse hook converts the warehouse system's Unix timestamps, such as 1731000000, into readable dates before Claude reads them, so Claude never confuses two date formats.

if tool == "process_refund" and amount > 500:
    return redirect("escalate_to_human")
Agent SDK hook interception flowClauderequests atool callPre-tool hookallow · deny ·redirectTool / MCPserver runsPostToolUse hooknormalise dates ·trim fieldsallowedclean result back to ClaudeDenied / redirectede.g. refund > $500 → escalate_to_humandenyHooks = deterministicPrompts = probabilistic
Figure: pre-tool hooks block or redirect calls; PostToolUse hooks clean results before Claude sees them. Swipe sideways to see the whole diagram.

📘 Multi-concern requests

“My item arrived broken, I was double-charged, and my address is wrong” is three concerns. Decompose them, investigate each (in parallel where possible) using shared context, then send one combined resolution. Having several issues is not, by itself, a reason to escalate.

🌍 Real-world example: Three problems in one message

A customer writes: 'Broken kettle, charged twice, and my address is wrong.' The bot splits this into three issues, checks each (in parallel where it can), and sends one reply that covers all three. Three routine issues are still routine: no escalation needed.

🤝 Structured human handoffs

Human agents usually can’t see the bot transcript. When escalating, pass a structured summary: customer ID, the issue, the root cause found, actions already taken, amounts, and the recommended next step.

🌍 Real-world example: A handoff a human can act on

Escalating the $750 refund, the bot sends: customer ID C-1042 (verified), order #48213, kettle arrived broken, photo received, refund of $750 requested, above the $500 limit, recommend approving. The human agent acts in 30 seconds without reading the whole chat.

🚫 Common beginner mistake: Trying to fix an important rule by making the prompt louder ('ALWAYS verify!!!'). If the rule must hold every time, enforce it in code.

🛠️ Try it yourself (about 10 minutes)

  1. Write a Python function guard(tool_name, amount, verified).
  2. Return 'deny' if the tool is process_refund and verified is False.
  3. Return 'escalate' if the amount is over 500.
  4. Test it with three cases: unverified, $499 verified, and $501 verified.

✅ You are done when: the three cases return deny, allow and escalate, in that order.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. Identity must be verified before any refund. What's the strongest implementation?

  • A. Few-shot examples
  • B. A post-hoc audit log
  • C. A system-prompt rule
  • D. A programmatic gate that rejects process_refund unless get_customer returned a verified ID in this session
Show answer

Answer: D. A deterministic guarantee for a financial operation. A and C are probabilistic. B detects the problem afterwards; it doesn't prevent it.

Question 2. What does a PostToolUse hook typically do in this exam's context?

  • A. Blocks dangerous outgoing tool calls
  • B. Compacts the conversation
  • C. Transforms or normalises tool results before the model processes them
  • D. Selects which tool to call
Show answer

Answer: C. It runs after the tool, on the result. A describes pre-call interception. D is the model's job. B is a different mechanism.

Question 3. When should you choose a hook over a prompt instruction?

  • A. Whenever you want shorter prompts
  • B. When a business rule needs a guaranteed outcome
  • C. Never; hooks add latency
  • D. Only for logging
Show answer

Answer: B. Hooks give deterministic compliance. A is a side benefit, not the reason. C and D are wrong.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Write pseudo-code for a gate that blocks process_refund until get_customer has verified the customer.
    ✅ Done when: Your gate denies the refund call when verification is missing and allows it once get_customer has returned verified.
  2. Task 2: Add a threshold rule that redirects refunds over $500 to escalate_to_human.
    ✅ Done when: A refund of $501 is redirected to escalation, while a refund of $499 goes through unchanged.
  3. Stretch: write a PostToolUse function that converts Unix epochs and ISO-8601 strings into one date format.
    ✅ Done when: Both 1731000000 and '2024-11-07T17:20:00Z' come out of your function in the same format.

❓ Frequently Asked Questions

🤔 When should I use a hook instead of a prompt instruction?

When a rule must hold every time, such as identity checks, refund limits or blocking destructive commands. Prompts are probabilistic.

🤔 What does a PostToolUse hook do?

It transforms a tool's result before Claude sees it, for example normalising formats or trimming irrelevant fields.

🤔 Should a multi-issue request be escalated?

Not automatically. Split it into separate concerns, investigate each, and send one combined resolution.

🤔 What should a human handoff include?

Customer ID, the issue, the root cause found, actions taken, amounts involved and the recommended next step.

🏁 Summary

  • “Must always” → hooks and gates. “Should usually” → prompts.
  • Pre-tool interception blocks or redirects calls; PostToolUse normalises results.
  • Escalations carry a structured handoff summary.
📝 Test yourself: Mock Test 1 · Mock Test 2 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Task Decomposition and Session Management in Claude Code.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

Multi-Agent Orchestration with Claude: Coordinators and Subagents

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 9 min read🎯 Official objectives 1.2 and 1.3

👋 In plain words: Some jobs are too big for one agent, so you split them across a team: a coordinator agent hands out pieces to helper agents and combines what they find. This lesson shows how that team is organised and the mistakes that leave gaps in the result.

Multi-agent systems split a large job across specialised agents. The exam focuses on the coordinator–subagent pattern used by the Claude Agent SDK, and on the mistakes that make such systems produce incomplete or unattributed results (Task Statements 1.2 and 1.3).

📖 What You’ll Learn: You will be able to design a hub-and-spoke Claude system that delegates to subagents, passes context explicitly and runs subagents in parallel.

🔑 Key terms

  • Coordinator: The 'manager' agent that splits the task, hands out pieces, and combines the results.
  • Subagent: A helper agent with one focused job and only the tools it needs.
  • Hub-and-spoke: A layout where every message goes through the coordinator. Helpers never talk to each other directly.
  • Task tool: The Agent SDK tool a coordinator uses to start a subagent.
  • Context: Everything Claude can see in the current conversation.

📖 The story in this lesson

ShopNest wants a report comparing delivery companies before peak season. A coordinator agent hands out searching, contract reading and report writing to three subagents, then puts the report together.

💡 Think of it like this

Think of a newsroom. The editor (coordinator) assigns stories to reporters (subagents). Reporters don't swap notes directly: everything goes through the editor, who checks it, fills gaps and publishes one paper. And a new reporter knows nothing about the story until the editor briefs them.

🕸️ Hub-and-spoke architecture

A coordinator agent decomposes the task, decides which subagents to invoke, delegates, aggregates results and handles errors. Subagents never talk to each other directly — every message goes through the coordinator. That gives you observability, consistent error handling and controlled information flow.

  • Select subagents per query. A simple factual question should not run the full search → analysis → synthesis → report pipeline.
  • Partition the scope. Give each subagent distinct subtopics or source types so work isn’t duplicated.
  • Refine iteratively. The coordinator checks the synthesis for gaps, re-delegates targeted queries, and re-runs synthesis until coverage is sufficient.
⚠️ Watch out: When a report misses whole areas of a topic but every subagent “succeeded”, the root cause is the coordinator’s too-narrow decomposition — not the search or synthesis agents.

🌍 Real-world example: The report that forgot half the market

ShopNest's report covers only express couriers. Every subagent 'succeeded'. The coordinator's log shows why: it only asked about 'express delivery' and 'same-day delivery', never budget or freight carriers. The gap came from the coordinator's split of the task, not from the helpers.

Coordinator and subagent hub-and-spoke architectureCoordinator agentdecomposes · delegates with Taskaggregates · handles errorsSearchweb sourcesDocumentanalysisSynthesis+ verify_fact onlyReportwriter↓ prompt with explicit context↑ structured results + sourcesParallel = several Task callsin ONE coordinator response✗ No direct subagent-to-subagent messages, and subagents do not inherit the coordinator’s history
Figure: hub-and-spoke — every message flows through the coordinator. Swipe sideways to see the whole diagram.

🤖 Spawning subagents in the Agent SDK

  • Subagents are spawned with the Task tool. The coordinator’s allowedTools must include "Task", or it cannot delegate.
  • Each subagent type is configured with an AgentDefinition: a description, a system prompt and tool restrictions.
  • To run subagents in parallel, the coordinator emits several Task calls in one response — not one per turn.

🌍 Real-world example: Running three helpers at once

To save time, the coordinator asks for three Task calls in one response: search, contracts and pricing. They run in parallel. If it made one call per turn, they would run one after another and the report would take three times as long.

allowedTools: ["Task", "Read"]   # without "Task" the coordinator cannot delegate

🤖 Subagents start with an empty context

Subagents do not inherit the coordinator’s conversation and don’t share memory between invocations. Anything a subagent needs must be in its prompt.

{
  "task": "Synthesise findings on EU battery regulation",
  "quality_bar": "Two independent sources per claim; flag conflicts",
  "findings": [
    {"claim": "Battery passport required from Feb 2027",
     "excerpt": "...",
     "source_url": "https://example.org/reg",
     "published": "2025-08-14"}
  ]
}

Structured data that separates content from metadata (URL, document, page, date) keeps attribution intact across handoffs. Write coordinator prompts as goals and quality criteria, not step-by-step procedures, so subagents can adapt to what they find.

🌍 Real-world example: The writer with nothing to write about

The report-writer subagent receives only 'Write the comparison report' and produces vague text. It never saw the search results, because subagents don't see the coordinator's conversation. The fix is to put the findings, with their source links, into the subagent's prompt.

{"task": "Compare carriers", "findings": [{"claim": "Carrier A: 2-day delivery", "source_url": "https://example.com/a"}]}
🚫 Common beginner mistake: Assuming a subagent 'knows' what the coordinator learned. It starts with an empty context, so pass everything it needs in its prompt.

🛠️ Try it yourself (about 10 minutes)

  1. Pick a research question, such as 'Which three test frameworks suit our web app?'.
  2. Write down how a coordinator would split it into three subagent jobs.
  3. For each job, list the tools it needs, three at most.
  4. Write the JSON the coordinator would pass to the final writer subagent.

✅ You are done when: you have three non-overlapping jobs with tools listed, and a JSON brief that includes sources.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. A research report on "renewable energy policy" covers only solar subsidies. Every subagent completed its assignment successfully. Coordinator logs show the subtasks "solar tax credits", "solar feed-in tariffs" and "rooftop solar rebates". What's the root cause?

  • A. The analysis agent filters out wind sources
  • B. The synthesis agent drops content
  • C. The search agent's queries are too narrow
  • D. The coordinator's decomposition was too narrow
Show answer

Answer: D. The subagents did exactly what they were assigned; the assignments themselves missed wind, hydro, grid and so on. A, B and C blame agents that worked correctly within their scope.

Question 2. A subagent receives the task "Synthesise the findings" and produces generic text. Why?

  • A. It needs context: fork
  • B. Subagents can't read JSON
  • C. Its model is too small
  • D. It doesn't automatically inherit the coordinator's history, so the findings must be in its prompt
Show answer

Answer: D. Context must be passed explicitly. C: the model isn't the issue; it has no input to work from. B: false. A: context: fork is a Claude Code skill option and isolates context further, which doesn't help here.

Question 3. A subagent should run in parallel with two others. Where do the three Task calls go?

  • A. In three consecutive coordinator turns
  • B. In separate sessions started by a cron job
  • C. In a single coordinator response
  • D. In a batch request
Show answer

Answer: C. Several tool calls in one response run concurrently. A serialises them. B and D aren't how the SDK parallelises subagents.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Sketch a coordinator with three subagents for a research task and list the tools each subagent gets (no more than five).
    ✅ Done when: Every subagent has a one-line role and no more than five tools, and no tool is given to a subagent that does not need it.
  2. Task 2: Write the JSON you would pass to a synthesis subagent, including claim, excerpt, source URL and date for two findings.
    ✅ Done when: Your JSON keeps content and metadata in separate fields, so a synthesis agent could cite each claim correctly.
  3. Stretch: write a coordinator prompt that states goals and quality criteria without step-by-step instructions.
    ✅ Done when: Your coordinator prompt states the goal and at least three quality criteria, and contains no numbered step-by-step instructions.

❓ Frequently Asked Questions

🤔 Do subagents see the coordinator's conversation?

No. Subagents start with isolated context, so the coordinator must put everything they need in their prompt.

🤔 How do I run subagents in parallel?

Have the coordinator emit several Task tool calls in a single response instead of one per turn.

🤔 Why route everything through the coordinator?

It gives you observability, consistent error handling and control over what information each agent sees.

🤔 What causes a report to miss whole topics?

Usually the coordinator decomposed the topic too narrowly, even though each subagent completed its own task.

🏁 Summary

  • All communication flows through the coordinator.
  • "Task" must be in the coordinator’s allowedTools; parallel = multiple Task calls in one turn.
  • Pass context explicitly, as structured data with source metadata.
  • Missing coverage with “successful” subagents → narrow decomposition.
📝 Test yourself: Mock Test 1 · Mock Test 2 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Claude Agent SDK Hooks, Prerequisite Gates and Human Handoffs.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

Claude Agentic Loop: stop_reason, Tool Results and Anti-Patterns

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 9 min read🎯 Official objective 1.1

👋 In plain words: A chatbot answers once. An agent keeps working: it asks for a tool, gets the result, and decides what to do next until the job is done. The agentic loop is the small piece of code that keeps this going and knows when to stop.

Every Claude agent — whether you write it yourself or use the Agent SDK — is built on one loop: ask Claude, run the tools it requests, give it the results, repeat. Get the stop condition wrong and your agent either quits mid-task or never finishes. This is Task Statement 1.1 of the exam.

📖 What You’ll Learn: You will be able to write a Claude agentic loop that continues on tool_use, stops on end_turn and returns tool results correctly.

🔑 Key terms

  • Agentic loop: Code that repeatedly sends the conversation to Claude, runs any tools it asks for, and sends back the results.
  • stop_reason: A field in every Claude response that says why it stopped, for example tool_use or end_turn.
  • tool_use: Claude's request to run a tool, including the tool name and inputs.
  • tool_result: Your reply that carries the tool's output back to Claude, matched by tool_use_id.
  • end_turn: The stop reason meaning Claude has finished its answer.

📖 The story in this lesson

A ShopNest customer asks the support bot: 'Where is order #48213?' To answer, the bot must call lookup_order, read the result, and then reply. That takes two trips to Claude, and the agentic loop manages both.

💡 Think of it like this

The loop is like a manager and an assistant. The manager (Claude) says 'fetch me the order file'. The assistant (your code) fetches it and puts it on the desk. This repeats until the manager says 'done, here is the answer'. The assistant must listen for 'done', not guess from the manager's tone.

🔁 The loop, step by step

  1. Send the conversation (and tool definitions) to the Messages API.
  2. Inspect stop_reason on the response.
  3. If it is "tool_use": run each requested tool and append one user message containing every tool_result block, matched by tool_use_id.
  4. Call Claude again with the updated history.
  5. Stop when stop_reason is "end_turn".
messages = [{"role": "user", "content": user_question}]
while True:
    resp = client.messages.create(model=MODEL, max_tokens=4096,
                                  tools=TOOLS, messages=messages)
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason != "tool_use":       # "end_turn" (also handle max_tokens, refusal)
        break
    results = []
    for block in resp.content:
        if block.type == "tool_use":
            results.append(run_tool(block))      # returns a tool_result dict
    messages.append({"role": "user", "content": results})   # ALL results, ONE message

🌍 Real-world example: Two trips to answer one question

Trip 1: Claude replies with stop_reason tool_use and asks for lookup_order with order 48213. Your code runs the lookup and sends back a tool_result. Trip 2: Claude reads 'shipped, arriving Friday', writes the answer, and the stop_reason is end_turn. The loop stops.

trip 1 -> stop_reason: tool_use  (run lookup_order)
trip 2 -> stop_reason: end_turn  (show the answer)
Claude agentic loop flow1. Your codesends messages+ tool definitions2. Clauderesponds via theMessages APICheckstop_reasonReturn thefinal answer3. Run every tool_useappend ALL tool_resultblocks in ONE user messageend_turntool_usenext iteration✗ Never stop on assistant text, phrases like “DONE”, or a bare iteration cap
Figure: the agentic loop — keep looping while stop_reason is tool_use, stop on end_turn. Swipe sideways to see the whole diagram.

📘 Why the model chooses the next step

In an agent, Claude reasons about which tool to call next from the context, including the results it has just seen. That is the difference from a pre-configured decision tree, where code fixes the sequence. Tool results must be appended to the history, otherwise the model cannot use them and will often request the same tool again.

🌍 Real-world example: The bot adapts to what it finds

The lookup shows order 48213 was delivered yesterday, but the customer says it never arrived. Nobody coded that path. Claude decides by itself to call get_delivery_photo next. That flexibility is what makes it an agent rather than a fixed script.

⚠️ Termination anti-patterns (exam favourites)

⚠️ Watch out: All of these are wrong as the primary stop mechanism:
  • Stopping when the response “contains text” — Claude often writes a sentence and a tool call in the same turn.
  • Parsing phrases such as “DONE” or “Is there anything else?” — natural-language signals are brittle.
  • A fixed iteration cap — fine as a safety backstop, never as the loop logic.

🌍 Real-world example: The bug that stopped too early

A ShopNest developer stopped the loop whenever Claude's reply contained text. Claude wrote 'Let me check that order for you' and asked for a tool in the same reply. The loop stopped, the tool never ran, and the customer got half an answer. Checking stop_reason fixes it.

🛑 Other stop reasons you should know

stop_reasonMeaningWhat to do
end_turnClaude finishedReturn the answer
tool_useClaude wants tools runRun them, append results, loop
max_tokensOutput was cut offRaise the limit or continue
stop_sequenceA custom stop sequence was hitHandle per your design
pause_turnLong server-tool turn pausedSend the response back to continue
refusalClaude declinedHandle gracefully

🌍 Real-world example: When the answer gets cut off

Asked for a long returns-policy summary, the bot's reply stops mid-sentence. The stop_reason is max_tokens, meaning Claude hit the length limit. The fix is to raise the limit or ask Claude to continue, not to show the customer a broken sentence.

🚫 Common beginner mistake: Sending each tool result back as a separate message. When Claude asks for three tools in one turn, all three results go back together in one user message.

🛠️ Try it yourself (about 10 minutes)

  1. Install the SDK with pip install anthropic and set your API key.
  2. Define one fake tool, get_order_status, that always returns 'shipped'.
  3. Ask Claude 'Where is order 123?' and print stop_reason after each call.
  4. Send the tool result back and call Claude again.

✅ You are done when: your console prints tool_use and then end_turn, and the final answer mentions 'shipped'.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. Which loop condition is correct for a manual Claude agentic loop?

  • A. Loop until the assistant message contains no text
  • B. Loop until the model says "DONE"
  • C. Loop while stop_reason == "tool_use", stop on "end_turn"
  • D. Loop exactly 5 times
Show answer

Answer: C. stop_reason is the structured signal for whether the model wants a tool run. A: Claude often sends text and tool_use in the same turn. B: parsing natural language is brittle. D: a fixed cap can be a safety backstop, but it's never the primary stop condition.

Question 2. After executing the three tool calls Claude requested in one turn, how should you return the results?

  • A. Three separate user messages, one per result
  • B. Put the results in the system prompt
  • C. One assistant message with the results
  • D. One user message containing three tool_result blocks, each with its tool_use_id
Show answer

Answer: D. All results for a turn go back in one user message, matched by ID. A: splitting them breaks the turn structure and discourages parallel calls. B and C: results are user-role content, not system or assistant content.

Question 3. What best distinguishes an agent from a workflow?

  • A. In an agent the model decides the next action from context; in a workflow, code defines the path
  • B. Workflows can't use tools
  • C. Agents never need a system prompt
  • D. Agents use bigger models
Show answer

Answer: A. Model-driven decision-making is what makes it an agent. D: model size doesn't matter here. B: workflows use tools all the time. C: agents need system prompts too.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: Implement the loop from this lesson with one tool (get_weather returning fixed data) and print stop_reason on every iteration.
    ✅ Done when: Your script prints tool_use and then end_turn, and the final answer uses the tool's data.
  2. Task 2: Deliberately break it by stopping on 'response contains text'. Find a prompt where Claude writes a sentence and a tool call together and observe the failure.
    ✅ Done when: You can show a transcript where the broken loop stops early, and explain in one sentence why stop_reason fixes it.
  3. Stretch: add handling for max_tokens and refusal stop reasons with a clear message to the user.
    ✅ Done when: A response cut off by max_tokens or a refusal produces a clear message instead of a crash or a silent empty answer.

❓ Frequently Asked Questions

🤔 What stop_reason means Claude wants a tool run?

tool_use. Run every tool_use block in the response and send all results back in one user message.

🤔 Why not stop when the response contains text?

Claude often writes a short sentence and a tool call in the same turn, so text alone does not mean the task is finished.

🤔 Is an iteration cap wrong?

A cap is a good safety backstop, but it should never be the main way the loop decides it is done.

🤔 What happens if I forget to append tool results?

Claude cannot see the results, so it usually asks for the same tool again and the loop repeats.

🏁 Summary

  • Loop on stop_reason == "tool_use"; stop on "end_turn".
  • Return every tool result for a turn in a single user message.
  • Never terminate on text content, phrases or a bare iteration count.
📝 Test yourself: Mock Test 1 · Mock Test 2 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Multi-Agent Orchestration with Claude: Coordinators and Subagents.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.

The 6 CCAR-F Exam Scenarios Explained

📚 Exam guide v1.0 (July 2026)🔄 Checked against official sources: 11 Nov 2026✏️ Updated: 12 Nov 2026⏱️ 9 min read🎯 Exam overview

👋 In plain words: Every exam question sits inside one of six realistic situations, called scenarios. If you already know the six settings, you spend exam time thinking instead of reading. This lesson walks through each one with a familiar example.

The CCAR-F exam shows you four of six scenarios, picked at random. Each scenario frames about 15 questions, so knowing the setup in advance saves you minutes of reading and helps you spot what each question is really testing.

📖 What You’ll Learn: You will know the six production scenarios the CCAR-F exam draws from and the exam skills each scenario tests.

🔑 Key terms

  • Agent: A program where Claude decides the next step itself, for example which tool to call.
  • Tool: A function you let Claude call, such as lookup_order.
  • Claude Code: Anthropic's coding assistant that works in your terminal and repository.
  • CI (continuous integration): The automated pipeline that builds and tests code on every change.
  • Structured extraction: Turning messy documents into clean, predictable data such as JSON.

📖 The story in this lesson

ShopNest happens to use Claude in all six ways the exam describes: a support bot, Claude Code for developers, a research assistant, developer tooling, CI code review and invoice extraction. Each scenario below is shown as it happens at ShopNest.

💡 Think of it like this

Scenarios are like the six rooms of a house you will be asked about. If you have walked through every room once, a question about the kitchen makes sense straight away.

🎬 Scenario 1: Customer Support Resolution Agent

An Agent SDK agent handles returns, billing disputes and account issues through MCP tools such as get_customer, lookup_order, process_refund and escalate_to_human, targeting 80%+ first-contact resolution.

What it tests: prerequisite gates (verify before refund), interception hooks for thresholds, multi-concern requests, structured errors, escalation calibration, handoff summaries and preserving case facts in long conversations.

🌍 Real-world example: ShopNest's refund bot

A customer writes: 'My blender arrived broken, refund me.' Asha's bot must first verify the customer with get_customer, then check the order with lookup_order, and only then call process_refund. Questions here test that order of steps and when to hand over to a human.

🎬 Scenario 2: Code Generation with Claude Code

A team uses Claude Code for generation, refactoring, debugging and documentation with custom slash commands and CLAUDE.md.

What it tests: the CLAUDE.md hierarchy, .claude/rules/ with path globs, commands vs skills, skill frontmatter, plan mode vs direct execution, iterative refinement and context degradation.

🌍 Real-world example: A team-wide coding setup

ShopNest's developers want Claude Code to follow the same coding rules for everyone. Questions here ask where those rules live (CLAUDE.md files), how to share custom commands, and when to plan before editing many files.

🎬 Scenario 3: Multi-Agent Research System

A coordinator delegates to search, document-analysis, synthesis and report subagents to produce cited reports.

What it tests: decomposition breadth, explicit context passing, parallel Task calls, scoped tools, error propagation, conflicting sources and provenance.

🌍 Real-world example: Researching delivery partners

ShopNest asks Claude to compare five delivery companies. A coordinator agent splits the job: one helper searches, one reads contracts, one writes the report. Questions here test how the helpers get their information and how sources stay cited.

🎬 Scenario 4: Developer Productivity with Claude

An Agent SDK assistant explores codebases and automates chores using built-in tools (Read, Write, Edit, Bash, Grep, Glob) and MCP servers.

What it tests: built-in tool selection, incremental exploration, MCP scoping and resources, tool descriptions that beat built-ins, session resume and fork.

🌍 Real-world example: Finding where checkout breaks

A new developer asks Claude to find every place the checkout code calls the payment service. Questions here test which built-in tool fits: Grep to search file contents, Glob to find files by name, Read to open a file.

🎬 Scenario 5: Claude Code for Continuous Integration

Claude Code reviews pull requests and generates tests in CI, with a focus on actionable, low-false-positive feedback.

What it tests: -p, --output-format json + --json-schema, CLAUDE.md as CI context, independent reviewers, explicit criteria, multi-pass review and batch-vs-synchronous decisions.

🌍 Real-world example: Ravi's pull-request reviewer

Ravi adds Claude Code to the CI pipeline so every pull request gets an automatic review. Questions here test non-interactive mode, JSON output that can become PR comments, and how to avoid noisy or duplicate comments.

claude -p "Review this diff for bugs only" --output-format json

🎬 Scenario 6: Structured Data Extraction

Unstructured documents are turned into JSON validated against schemas and passed downstream.

What it tests: tool_use with JSON schemas, nullable fields, enum design, validation-retry loops, batch processing, confidence calibration and human-review routing.

🌍 Real-world example: Reading supplier invoices

ShopNest receives 2,000 PDF invoices a month. Claude extracts vendor, date and total into JSON for the accounting system. Questions here test schemas that don't invent missing values, retries after validation errors, and when a human should check.

🚫 Common beginner mistake: Reading every scenario description in full for every question. Read it carefully once, because every question in that block assumes you remember it.

🛠️ Try it yourself (about 8 minutes)

  1. For each of the six scenarios, write the name of a real system at your workplace that is similar.
  2. Mark the two scenarios closest to your daily work.
  3. Start your revision with those two.

✅ You are done when: each scenario has a real-life match in your notes, and you have chosen your two strongest.

🧪 Exam-Style Practice Questions

Try these before opening the answers. They use the same scenario style as the real exam.

Question 1. A customer message says: "My order arrived damaged, I was double-charged, and I want to change my email." What's the best agent strategy?

  • A. Answer the easiest issue first and end the session
  • B. Handle only the first issue and ask them to open new tickets
  • C. Split into three items, investigate each (in parallel where possible) using shared context, then give one unified reply
  • D. Escalate, because it's multi-issue
Show answer

Answer: C. Decompose, investigate, then synthesise. A and B give a poor experience and miss resolution targets. D: having several issues doesn't make a case complex.

Question 2. "Add comprehensive tests to this 200k-line legacy codebase." What's the best approach?

  • A. Ask for 1,000 tests in one prompt
  • B. Use only the Message Batches API
  • C. Generate tests file by file alphabetically
  • D. Map the structure, find high-impact or high-risk areas, make a prioritised plan, and adapt it as dependencies are discovered
Show answer

Answer: D. Dynamic decomposition for an open-ended task. C ignores priority. A is unrealistic and unfocused. B is a delivery mechanism, not a strategy.

Question 3. The synthesis output should show readers which sections rest on thin evidence because a source failed. What should you add?

  • A. Nothing; keep it clean
  • B. Remove the affected sections
  • C. Coverage annotations marking well-supported findings versus gaps from unavailable sources
  • D. A generic disclaimer
Show answer

Answer: C. Be transparent about uncertainty where it applies. A hides it. D isn't specific. B loses useful partial information.

📝 Assignment

Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.

  1. Task 1: For each scenario, write one sentence describing a system you have built or seen that is similar.
    ✅ Done when: Each of the six scenarios has one sentence describing a real or familiar system, so you can picture it on exam day.
  2. Task 2: Map each scenario to its two most-tested domains without looking back at the lesson.
    ✅ Done when: Your mapping matches the lesson for at least five of the six scenarios when you compare it afterwards.
  3. Stretch: draft one exam-style question of your own for Scenario 6 with four options and an explanation.
    ✅ Done when: Your question has one clearly correct answer, three plausible distractors, and an explanation of why each distractor is wrong.

❓ Frequently Asked Questions

🤔 How many scenarios appear on the CCAR-F exam?

Four, picked at random from a bank of six. Each frames roughly 15 questions.

🤔 Which scenario is best for QA engineers?

Scenario 5, Claude Code for Continuous Integration, and Scenario 6, Structured Data Extraction, are closest to test-automation work.

🤔 Do I need to memorise the tool names in the scenarios?

No, but knowing the setup (for example get_customer before process_refund) saves reading time and helps you spot what a question tests.

🤔 Do the mock tests use the same scenarios?

Yes. The five mock tests on this site rotate through all six scenarios so you meet each one at least twice.

🏁 Summary

  • Scenarios 1, 3 and 6 lean on Domains 1, 4 and 5; Scenarios 2, 4 and 5 lean on Domains 2 and 3.
  • Read the scenario once, carefully — every question in that block assumes you remember it.
  • Our five mock tests rotate through all six scenarios so you meet each at least twice.
📝 Test yourself: Mock Test 1 (30 scenario-based questions in 60 minutes, with explanations).

Next, continue with Claude Agentic Loop: stop_reason, Tool Results and Anti-Patterns.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.