# CCAR-F Practice Questions (Free, 2026) | Your AI Department

> 200 free scenario-based CCAR-F practice questions for Claude Certified Architect – Foundations, with explanations, weighted by the published exam blueprint.

Source: https://youraidept.com/network/ccar-f-practice-questions

Practice questions

# CCAR-F practice questions, free.

200 original scenario questions for Claude Certified Architect – Foundations, written from the published blueprint and weighted the way the exam is. Pick an answer, check it, read why. None of these are exam questions; the real exam tests the same judgment on scenarios you have not seen.

Want the real thing? [Take the timed CCAR-F practice exam](https://youraidept.com/network/ccar-f-practice-exam): 60 questions in 120 minutes, scored against the 720 pass mark, with a domain breakdown.

## How to use these

Filter by domain to drill a weak area, or work through the whole bank. Answer before you reveal. Note the domain of every miss. When you are done, the score box tells you whether you are above the equivalent of the 720 pass mark; if you are not, the domains you missed are your reading list. The full domain-by-domain notes are on [the CCAR-F exam page](https://youraidept.com/network/ccar-f).

## The questions

All domains (200) Agentic architecture (52) Claude Code workflows (40) Prompt engineering (40) Tool design and MCP (35) Context management (33)

Agentic architecture

A support desk needs incoming tickets sorted into five fixed categories and routed to the matching queue. Which design fits best?

- An evaluator-optimizer loop that proposes a category and revises it until a second judge call agrees
- A single autonomous agent with the queue tools attached, deciding per ticket where it should go
- A routing workflow with one classification call, then a fixed handoff to the queue for that category
- An orchestrator that spawns five subagents and lets each one claim the tickets it judges to be in scope

Check answer

### Show answer

Answer: A routing workflow with one classification call, then a fixed handoff to the queue for that category. The control flow is known in advance and the output space is fixed, so a routing workflow (classify, then hand off) is cheaper, faster, and easier to test. The evaluator-optimizer loop adds iterations to a decision that has nothing to refine, and an orchestrator with five subagents spends five calls to make one choice.

Agentic architecture

A task requires editing an unknown number of files across a repository, and the set of files cannot be predicted until the work is under way. Which pattern applies?

- Parallelization with a worker per file type, each scanning its share of the tree for changes to make
- Prompt chaining with one step per directory, so every part of the repository gets its own fixed pass
- Orchestrator-workers, with a coordinator that discovers the subtasks during the run and delegates each one
- A single call with the full repository loaded into context, asking the model to return every edit in one response

Check answer

### Show answer

Answer: Orchestrator-workers, with a coordinator that discovers the subtasks during the run and delegates each one. Orchestrator-workers is the pattern for work whose subtasks are only discoverable during execution; the coordinator plans, delegates, and synthesizes. Chaining by directory and fanning out by file type both fix the decomposition before the work starts, which is exactly what this task does not allow.

Agentic architecture

A translation pipeline produces drafts that a reviewer can grade against clear criteria, and quality improves when feedback is applied. Which pattern matches?

- Routing by language pair, so each pair reaches a specialist prompt tuned with curated examples for that pair
- Parallelization across sentences, with each worker translating a slice and a final merge step
- Evaluator-optimizer, where one call drafts, a second grades against the criteria, and the loop repeats
- A single agent with a translation tool that it calls once per document and returns the result

Check answer

### Show answer

Answer: Evaluator-optimizer, where one call drafts, a second grades against the criteria, and the loop repeats. Evaluator-optimizer fits when there are explicit evaluation criteria and iterative refinement measurably helps. Routing by language pair may improve the first draft but has no feedback step, so the stated gain from applying review is left on the table.

Agentic architecture

An agent can issue refunds. The business wants any refund above $500 approved by a person. Where should that rule live?

- In a permission check or hook that intercepts the refund tool call and blocks it until a person approves
- In a weekly review of the refund log, so any refund over the limit is caught and reversed if it turns out to be wrong
- In the system prompt, as a rule telling the model to pause and ask before any refund above the limit
- In the refund tool's description, so the model reads the threshold every time it considers the tool

Check answer

### Show answer

Answer: In a permission check or hook that intercepts the refund tool call and blocks it until a person approves. Hard limits belong outside the model's judgment. A hook or permission gate enforces the rule even when the prompt is ignored or the model is confused. The system prompt and the tool description are both advisory: they improve the odds but cannot guarantee the check runs.

Agentic architecture

A tool that creates invoices sometimes times out, and the agent retries. Customers are receiving duplicate invoices. Best fix?

- Make the tool idempotent with a client-supplied request id, so a repeated call returns the same invoice
- Raise the tool's timeout so that slow invoice runs finish before the agent loop gives up on the call and retries
- Add a system prompt rule that the model should retry only after checking the invoice list first
- Move invoice creation out of the tool and into a post-run batch job that dedupes by customer

Check answer

### Show answer

Answer: Make the tool idempotent with a client-supplied request id, so a repeated call returns the same invoice. Retries are normal in agent loops. Tools with side effects need idempotency so a repeated call is safe. Raising the timeout only narrows the window in which the duplicate can happen, and a check-before-retry rule depends on the model following it under every failure mode.

Agentic architecture

During a long multi-agent run one tool starts returning errors on every call, and the coordinator keeps re-issuing the same request. What is missing?

- A stronger model for the coordinator role so it notices the pattern and changes its approach
- A larger context window for the coordinator so the earlier error results stay visible to it
- Bounded retries with backoff and a circuit breaker that stops calling the tool after repeated failures
- A system prompt instruction telling the coordinator to switch to a different tool as soon as it sees an error result

Check answer

### Show answer

Answer: Bounded retries with backoff and a circuit breaker that stops calling the tool after repeated failures. Failure handling is part of the architecture: cap retries, back off, and stop or escalate when a dependency is down. A prompt instruction may help a well-behaved model but is not a control; the loop itself must enforce the limit.

Claude Code workflows

What belongs in a project's CLAUDE.md file?

- Build and test commands, project conventions, and gotchas Claude needs on every task, kept short
- Environment variables and service credentials the project needs, so Claude can run commands without asking
- The full architecture documentation and API references, so Claude has complete knowledge in every session
- A running log of past sessions and their outcomes, so Claude can pick up where the last one ended

Check answer

### Show answer

Answer: Build and test commands, project conventions, and gotchas Claude needs on every task, kept short. CLAUDE.md is standing project memory: short, high-value instructions loaded into every session. Long documents cost context on every task and are better read on demand; secrets do not belong in a checked-in file; session history is what memory files or notes are for.

Claude Code workflows

A team wants every file Claude Code edits to be run through the formatter, without relying on the model to remember. Which mechanism is right?

- A custom slash command that formats the tree, which the developer runs at the end of a session
- A formatting subagent that the main session delegates to once the edits are complete
- A CLAUDE.md instruction asking Claude to run the formatter after each edit it makes
- A PostToolUse hook matched to the edit tools that runs the formatter on the changed file

Check answer

### Show answer

Answer: A PostToolUse hook matched to the edit tools that runs the formatter on the changed file. Hooks are deterministic shell steps tied to tool events; they run whether or not the model remembers. A CLAUDE.md note is advisory, and a slash command or subagent still depends on someone invoking it.

Claude Code workflows

How would you run Claude Code non-interactively inside a CI job?

- A subagent launched from a developer's local session, with the CI job waiting on its result
- Print mode with the -p flag, passing the prompt and a restricted allowed-tools list
- An interactive session on the runner with the permission mode set to accept every action
- A plan-mode session, since planning does not edit files and so needs no approvals

Check answer

### Show answer

Answer: Print mode with the -p flag, passing the prompt and a restricted allowed-tools list. Print mode runs a single prompt headlessly and exits, and restricting tools keeps a CI run from taking actions nobody reviewed. An interactive session with accept-all permissions has no human present and no bound on what runs.

Claude Code workflows

A session has been running for hours and answers are getting worse and slower. What is the first thing to try?

- Switch the session to a larger model so it can hold more of the accumulated conversation
- Paste the full transcript so far back in as a new user message so nothing is lost
- Compact or clear the context, then re-brief the task with only what the next step needs
- Disable hooks for the rest of the session, since each hook adds latency to every tool call

Check answer

### Show answer

Answer: Compact or clear the context, then re-brief the task with only what the next step needs. Quality degrades as the window fills with stale material; compaction and clearing exist to fight exactly this. Pasting the transcript back doubles the bulk that caused the problem, and a larger model does not shrink the window's contents.

Prompt engineering

You need a response in a strict JSON shape that downstream code will parse. Which approach is most reliable?

- Lower the temperature to zero so the formatting is deterministic across runs
- Define the shape as a tool input schema, or use structured outputs, so the model must conform
- Ask for JSON in the user message and add a note that any text outside the object will break the parser
- Prefill the assistant turn with an opening brace and stop at the closing brace

Check answer

### Show answer

Answer: Define the shape as a tool input schema, or use structured outputs, so the model must conform. Schema-enforced output is more reliable than instructions alone: tool use with an input schema, or structured outputs, constrains the shape. Prefilling the brace suppresses preamble but does not guarantee the keys, types, or nesting downstream code expects.

Prompt engineering

A prompt includes a 40-page contract and one question about it. Where should the question go?

- In the system prompt, with the contract alone in the user turn, so instruction and content are separated
- Split across several user turns, one section of the contract per turn, with the question at the end
- At the end of the user message, after the contract, with the contract clearly delimited by tags
- At the top of the user message, before the contract, so the model knows what to look for while it reads

Check answer

### Show answer

Answer: At the end of the user message, after the contract, with the contract clearly delimited by tags. For long context, put documents first and the question last, and delimit the document so instructions and content do not blur. Putting the question first is the common intuition but performs worse on long inputs; moving it to the system prompt separates it from the material it refers to.

Prompt engineering

Output format keeps drifting despite detailed instructions. What usually fixes it fastest?

- Remove the system prompt and put the instructions in the user turn, closer to the task
- Add two or three high-quality examples of the exact format, wrapped in clearly labeled tags
- Reduce max_tokens so the model has no room to add anything beyond the required format
- Restate the format instruction at both the start and the end of the prompt so it is harder for the model to miss

Check answer

### Show answer

Answer: Add two or three high-quality examples of the exact format, wrapped in clearly labeled tags. A small number of good examples steers format more reliably than longer descriptions. Repeating the instruction adds emphasis, not clarity; cutting max_tokens truncates output rather than shaping it.

Prompt engineering

When is extended thinking the wrong tool?

- Multi-step planning over a set of requirements that conflict with one another
- Debugging a subtle logic error across several interacting functions
- Weighing the trade-offs between two candidate system architectures
- A high-volume yes/no classifier where per-request cost and latency dominate

Check answer

### Show answer

Answer: A high-volume yes/no classifier where per-request cost and latency dominate. Extended thinking costs tokens and time. It pays off on hard reasoning such as planning, debugging, and trade-off analysis, not on simple, high-volume decisions where a fast direct answer is just as accurate.

Tool design and MCP

A tool named q with the description "queries db" is being called at the wrong times with the wrong arguments. Best fix?

- Add separate tools for each common query so the model no longer has to work out the arguments
- Rename it and write a description covering when to use it, what each parameter means, and edge cases
- Add a system prompt rule that the model should think carefully before every database query
- Return a longer error message from the tool whenever the arguments do not match a known query

Check answer

### Show answer

Answer: Rename it and write a description covering when to use it, what each parameter means, and edge cases. The description is what the model reads to decide when and how to call a tool; write it for the model, with parameter meanings, edge cases, and an example. More tools with the same thin descriptions multiply the confusion, and error messages only help after a wrong call has already been made.

Tool design and MCP

You need the model to call one specific tool on this turn, no matter what. Which setting?

- tool_choice set to auto with the tool listed first in tools
- disable_parallel_tool_use set to true and one tool listed
- tool_choice set to that tool by name, forcing the call
- tool_choice set to any, so the model must call some tool

Check answer

### Show answer

Answer: tool_choice set to that tool by name, forcing the call. tool_choice with a specific tool name forces that call. any forces some tool but leaves the choice to the model; auto leaves the decision to the model entirely, regardless of tool order; disable_parallel_tool_use limits how many calls happen, not whether one does.

Tool design and MCP

An MCP server will run on the developer's own machine, launched by the client as a child process. Which transport?

- WebSockets over a public URL
- Server-sent events endpoint
- stdio over the child process
- Streamable HTTP on localhost

Check answer

### Show answer

Answer: stdio over the child process. stdio is the transport for a local server the client launches as a child process. Streamable HTTP is for remote servers that many clients connect to; running it on localhost works but adds a network layer and a port for no benefit here.

Tool design and MCP

A tool call fails because the record does not exist. What should the tool return so the agent can recover?

- A successful empty result, so the loop continues and the model infers the record was missing
- No result for that call, holding the turn until a person can look up the record by hand
- A tool result flagged as an error, with a message saying the record was not found and what ids are valid
- The raw exception and stack trace from the database driver, so the model can see exactly which query failed

Check answer

### Show answer

Answer: A tool result flagged as an error, with a message saying the record was not found and what ids are valid. Error results with actionable messages let the model choose a different path. An empty success hides the failure and invites the model to proceed on a missing record; a raw stack trace is an error the model has to decode rather than act on.

Context management

You want prompt caching to work across many requests that share a large system prompt and tool set. How should the prompt be ordered?

- Volatile user content first, then the system prompt and tool definitions, with a cache breakpoint at the very end
- Everything inside one user message in a fixed order, so the whole request is cached as one block
- Tools first, then the user content, then the system prompt, with a breakpoint after each section
- Stable content first (system prompt, tool definitions), a cache breakpoint after it, volatile content last

Check answer

### Show answer

Answer: Stable content first (system prompt, tool definitions), a cache breakpoint after it, volatile content last. Caching matches prefixes. Stable material goes first so the cached prefix is reused; anything that changes per request goes after it. A breakpoint at the very end after volatile content caches a prefix that no other request will match.

Context management

A coordinator delegates research to a subagent. What should the coordinator pass, and what should it get back?

- The whole conversation so far, and the subagent's complete transcript back, so nothing is lost
- A pointer to the coordinator's memory file, and the subagent's full transcript back for review
- A complete, self-contained brief with everything the subagent needs, and only the conclusion back
- A one-line task title, since the subagent shares the coordinator's context and can look up the rest

Check answer

### Show answer

Answer: A complete, self-contained brief with everything the subagent needs, and only the conclusion back. Subagents start with a clean context. Give them a complete brief and take back the result, not the working, to keep the coordinator's window lean. Passing the whole conversation both ways defeats the purpose of delegation; a pointer to a memory file leaves the subagent without the task.

Agentic architecture

A document pipeline runs the same three steps on every input: extract entities, normalize them, then write a summary. Each step's output feeds the next. Which pattern is this?

- Orchestrator-workers, with a planner assigning steps
- Evaluator-optimizer over the summary step
- Parallelization, with the three steps run at once
- Prompt chaining, with each output feeding the next

Check answer

### Show answer

Answer: Prompt chaining, with each output feeding the next. Fixed sequential steps where each output feeds the next is prompt chaining. Parallelization does not fit because normalize depends on extract; an orchestrator adds planning cost and nondeterminism to a path that never changes.

Agentic architecture

Three independent checks (toxicity, PII, and policy) must run on every response before it is shown. Latency matters. Which pattern?

- Have one classifier call decide which checks are needed
- Fold all three checks into a single call with one prompt
- Chain the checks in sequence so each one sees the previous verdict
- Run the three checks concurrently and aggregate the verdicts

Check answer

### Show answer

Answer: Run the three checks concurrently and aggregate the verdicts. Independent work with no dependencies is the parallelization pattern; running the checks concurrently cuts latency. Folding them into one call is tempting but mixes three jobs in one prompt and makes each verdict harder to test on its own.

Agentic architecture

When does Anthropic's guidance say to reach for an agent instead of a workflow?

- When the task is large enough that a single prompt cannot hold all of the input
- When the number of steps cannot be predicted and the model must choose its path from results
- When latency is not a concern and the budget comfortably allows several model calls for each request
- When the steps are known in advance but each step needs a different model

Check answer

### Show answer

Answer: When the number of steps cannot be predicted and the model must choose its path from results. Agents earn their cost when the path is open-ended and the model must decide the next step from what it finds. Known steps with different models is a workflow with per-step model choice; a large input calls for retrieval or chunking, not autonomy.

Agentic architecture

An agent for booking travel has succeeded in demos but sometimes loops forever in production. The most important missing control is:

- A maximum turn count and a stop condition the loop checks on every iteration
- A larger context window so earlier attempts remain visible and are not repeated
- A wider tool set so the agent has an alternative route when one provider fails
- A more detailed persona and goal statement so the agent stays focused on the booking

Check answer

### Show answer

Answer: A maximum turn count and a stop condition the loop checks on every iteration. Every agent loop needs an explicit termination condition and a hard cap on turns, or a confused model runs up the bill. A larger window makes the loop remember more but does not end it; more tools give it more ways to keep going.

Agentic architecture

Which is the strongest reason to start a new client project with workflows rather than agents?

- Workflows can be built without prompt engineering, so the client's own team can maintain them
- Workflows are what stakeholders expect and are easier to present in a demo
- Workflows are predictable, testable, and cheaper, building the trust needed before autonomy
- Agents require the Agent SDK, which most client environments cannot run

Check answer

### Show answer

Answer: Workflows are predictable, testable, and cheaper, building the trust needed before autonomy. Predictability and testability come first. Autonomy is added where the evidence says it pays. Workflows still contain prompts, so maintainability without prompt work is not the argument, and the API supports agents without any special runtime.

Agentic architecture

An orchestrator delegates research to three subagents and then writes a report. One subagent returns nothing useful. What should the design do?

- Drop that topic from the report and note in the log that the subagent returned no content
- Hand the empty topic back to the user with a question about whether the report should continue
- Detect the gap, retry or re-scope the subtask, and proceed with what it has when retries run out
- Fail the whole run and surface the empty result, since a partial report could mislead whoever reads it

Check answer

### Show answer

Answer: Detect the gap, retry or re-scope the subtask, and proceed with what it has when retries run out. Robust orchestration treats subagent failure as a normal event with a recovery path and a bounded retry budget. Failing the whole run throws away two good results for one bad one; dropping the topic silently hides the gap from the reader.

Agentic architecture

A coding agent must never run a destructive git command. Which enforcement is reliable?

- A CLAUDE.md section describing which git operations are off limits in this repo
- A PreToolUse hook or permission rule that blocks matching commands before they execute
- A lower temperature setting so the agent sticks to the conservative commands it has already seen
- A system prompt rule listing every destructive git command the agent must not run

Check answer

### Show answer

Answer: A PreToolUse hook or permission rule that blocks matching commands before they execute. Deterministic gates outside the model are the reliable layer. Prompts and CLAUDE.md are advisory: they lower the odds of a bad call but cannot block one, and temperature changes sampling, not policy.

Agentic architecture

You are asked to justify why an agent design uses a single coordinator instead of a swarm of peer agents that message each other freely. The best justification:

- Peer messaging is slower in practice because every message needs its own model call
- A coordinator keeps control flow observable and debuggable, and bounds each subagent's context
- Peer agents cannot share tool results, so a coordinator is needed to relay them
- The API's multi-agent support is built around a single coordinator, so peer swarms need extra scaffolding

Check answer

### Show answer

Answer: A coordinator keeps control flow observable and debuggable, and bounds each subagent's context. Hub-and-spoke designs are easier to trace, test, and constrain than free-form peer messaging. The speed argument is not reliable, since a coordinator also spends calls; the API does not mandate either topology.

Agentic architecture

A customer wants an agent that autonomously sends emails on their behalf. What belongs in the first release?

- Autonomous sending for all emails except the ones the model itself flags as sensitive
- Draft-then-approve: the agent prepares emails and a person sends, with autonomy earned on measured accuracy
- Autonomous sending for internal recipients only, expanding to external once a week has passed
- Full autonomy from day one, with a daily audit of what was sent so problems are caught early

Check answer

### Show answer

Answer: Draft-then-approve: the agent prepares emails and a person sends, with autonomy earned on measured accuracy. Outbound actions with reputational risk start behind a human gate; autonomy expands as evidence accumulates. Letting the model flag its own sensitive cases makes the model the gate it is supposed to be behind; a daily audit catches problems after the email has gone out.

Agentic architecture

Which metric best tells you an agent is worth its cost in production?

- Average tokens consumed per completed task, trended week over week
- Number of tasks handled per day compared with what the human team handled before
- Task completion rate at acceptable quality, measured per dollar and per minute
- Share of runs that finish without any tool errors or retries

Check answer

### Show answer

Answer: Task completion rate at acceptable quality, measured per dollar and per minute. Outcome per cost is the measure. Tokens per task is an input, not value; runs without tool errors can still produce wrong answers; tasks per day ignores quality and cost.

Agentic architecture

An evaluator-optimizer loop keeps running for many iterations without converging. What is the likely design flaw?

- The evaluator's criteria are vague, so 'good enough' is never reached; it needs pass criteria and a round cap
- The loop has no memory of earlier drafts, so it keeps repeating the same corrections
- The generator runs at too high a temperature, so each draft moves in a new direction
- The evaluator and generator share a prompt, so the judge is biased toward its own output

Check answer

### Show answer

Answer: The evaluator's criteria are vague, so 'good enough' is never reached; it needs pass criteria and a round cap. Refinement loops need crisp acceptance criteria and a maximum number of rounds. Temperature and draft memory can add noise, but a loop with a clear pass condition and a cap terminates regardless; without them, no tuning of the generator helps.

Agentic architecture

A routing workflow classifies requests into billing, technical, and sales. Ten percent of requests fit none. What should the design include?

- A fourth category learned from the unclassified requests after launch
- Retry classification with a second model until every request lands in one of the three
- A fallback route for 'other' that goes to a general handler or to a person
- A confidence threshold that forces low-confidence requests into the nearest bucket

Check answer

### Show answer

Answer: A fallback route for 'other' that goes to a general handler or to a person. Routers need an explicit fallback path; forcing fits produces confident wrong handling. Retrying with another model still forces a fit, and a nearest-bucket threshold is the same forced fit with a number attached.

Agentic architecture

Which statement about tools in agent loops is correct?

- Tools must be called in the order they are listed, so ordering in the tools array matters
- Tool results are data the model reasons over; instructions come from the system prompt and user
- Tool results can only carry text, so binary or structured data must be described in the prompt
- Tool results should be passed back as a user turn so that the model treats them as fresh instructions to follow

Check answer

### Show answer

Answer: Tool results are data the model reasons over; instructions come from the system prompt and user. Treating tool output as data rather than instructions is the basis of injection resistance and clean reasoning. Tool results do travel in a user turn as tool_result blocks, but that is a transport detail; it does not make them instructions.

Agentic architecture

A team wants to run twenty subagents in parallel for a research task. What should they watch first?

- That each subagent has a complete, self-contained brief and a bounded budget
- That every subagent uses the same tool set so the results have a common shape
- That the coordinator holds no context of its own and only merges the results
- That all subagents share one context window so they do not duplicate work

Check answer

### Show answer

Answer: That each subagent has a complete, self-contained brief and a bounded budget. Parallel fan-out multiplies whatever you give it. Clear briefs and budgets per worker keep it useful. A shared window is not how subagents work and would defeat the isolation; identical tool sets do not make briefs clearer.

Agentic architecture

An agent must decide between continuing a task and asking the user a question. Good design says it should ask when:

- Any tool call in the current step has returned an error
- It has consumed half of its token budget for the task at hand
- It has finished one subtask and the next one on the list belongs to a different owner
- The next action is irreversible, ambiguous, or outside its granted scope

Check answer

### Show answer

Answer: The next action is irreversible, ambiguous, or outside its granted scope. Human checkpoints belong at irreversible or ambiguous decisions, not at arbitrary points. A tool error is usually something the loop should handle with a retry or an alternate path; a token milestone says nothing about risk.

Agentic architecture

A workflow uses one large model call to do classification, extraction, and a summary at once, and quality is uneven. What is the usual improvement?

- Decompose into chained steps so each call has one job and can be checked
- Drop the summary from the call and generate it separately with a template
- Switch to a larger model so it can handle the three tasks in one pass
- Enable extended thinking so the model plans all three outputs before writing

Check answer

### Show answer

Answer: Decompose into chained steps so each call has one job and can be checked. Splitting a multi-task prompt into single-purpose steps improves accuracy and makes each step testable. Extended thinking helps hard reasoning but does not fix a prompt that mixes three jobs; dropping one task is only a partial decomposition.

Agentic architecture

What is the practical reason to log every tool call, its inputs, and its result in an agent system?

- Cost control, since tool call logs are the only way to reconstruct token usage per task
- Prompt caching, since logged calls can be replayed as a cached prefix on the next run
- Debugging, evaluation, and audit: you cannot improve or explain behavior you did not record
- Compliance reporting, since most regulated industries require a record of automated actions

Check answer

### Show answer

Answer: Debugging, evaluation, and audit: you cannot improve or explain behavior you did not record. Observability is how agent behavior is understood, evaluated, and defended. Compliance is one use, not the practical reason; usage is reported per request by the API, and logs have nothing to do with cache prefixes.

Agentic architecture

A client says 'make it fully autonomous' for an agent that changes production database records. Your recommendation as the architect:

- Full autonomy as requested, with a nightly database backup so any bad change can be restored
- Full autonomy with logging turned off in the hot path so approval latency does not slow the agent
- Read-only access for the agent, with all writes handled by a separate scheduled job the client owns
- Autonomy for reads and reversible changes, approval for irreversible ones, with an audit trail, revisited as data comes in

Check answer

### Show answer

Answer: Autonomy for reads and reversible changes, approval for irreversible ones, with an audit trail, revisited as data comes in. Blast radius sets the gate. Irreversible actions get approval until evidence justifies more. A nightly backup limits damage after the fact but does not prevent a customer-visible change; read-only for everything gives up the value the client asked for.

Claude Code workflows

A developer complains Claude Code re-explores the codebase every session. The cheapest fix is:

- A subagent that explores the codebase and reports back at the start of each session
- A memory file the developer pastes into the first message of every session
- A longer first prompt each session that walks through the directory layout
- A CLAUDE.md with the project's structure, commands, and conventions

Check answer

### Show answer

Answer: A CLAUDE.md with the project's structure, commands, and conventions. CLAUDE.md is loaded automatically and is the place for standing project knowledge. An exploring subagent still spends the exploration every session; a pasted file is CLAUDE.md done by hand.

Claude Code workflows

You want Claude Code to plan before it edits on a large refactor. Which feature matches?

- Plan mode, which explores and proposes an approach before any file changes
- Headless mode with a prompt asking for a written plan and no tool access
- A PreToolUse hook that rejects edit calls until a plan file exists in the repository
- A custom slash command that runs the test suite before each edit is applied

Check answer

### Show answer

Answer: Plan mode, which explores and proposes an approach before any file changes. Plan mode separates thinking from editing so you can review the approach first. A hook that blocks edits enforces a gate but gives you no plan to review; headless mode is for automation, not a review step.

Claude Code workflows

A repeated workflow, 'update the changelog from recent commits', should be one command. Which Claude Code feature?

- A subagent dedicated to changelog work, invoked from the main session
- A PostToolUse hook on git commit that appends the message to the changelog
- A custom slash command or skill that captures the prompt and steps
- An MCP server exposing a changelog tool that reads the git history

Check answer

### Show answer

Answer: A custom slash command or skill that captures the prompt and steps. Reusable prompts belong in slash commands or skills; hooks are for deterministic shell steps. A hook on commit fires per commit and cannot write a summarized changelog on demand; an MCP server adds a tool, not a reusable workflow.

Claude Code workflows

Which permission approach is right for a shared CI runner using Claude Code?

- Accept every tool call automatically, since no developer is present to approve
- Deny every tool so the run is a pure text response with no side effects
- An explicit allow list of tools and commands, with no interactive approvals
- Prompt the developer who pushed the commit for each tool approval via chat

Check answer

### Show answer

Answer: An explicit allow list of tools and commands, with no interactive approvals. Headless runs cannot ask a human, so the allowed surface is defined up front and kept narrow. Accepting everything removes the boundary; denying every tool leaves Claude unable to read the code it is meant to work on.

Claude Code workflows

Where does an MCP server configuration belong when it should apply to everyone working in the repository?

- In each developer's user-level settings, synced through a dotfiles repository
- In the project-scoped configuration checked into the repository
- In a SessionStart hook that registers the servers when Claude Code launches
- In the system prompt for the session, listed as servers Claude should connect to

Check answer

### Show answer

Answer: In the project-scoped configuration checked into the repository. Project scope travels with the repo; user scope is personal. A dotfiles sync approximates it but relies on every developer keeping up; the system prompt cannot register a server.

Claude Code workflows

A hook that blocks a tool call should communicate the reason. Why?

- So the block is written into the transcript for the developer to review later on
- So the hook's exit code can be mapped to the right billing category
- So the model can override the block when the reason does not apply
- So the model can adjust its plan instead of retrying the same blocked action

Check answer

### Show answer

Answer: So the model can adjust its plan instead of retrying the same blocked action. Feedback from a blocked call lets the model take a different path. Logging is a side benefit, not the point; a hook's reason is information for the model, not a mechanism to override the block.

Claude Code workflows

Which task is a good fit for a Claude Code subagent?

- A large, self-contained investigation whose details would clutter the main session
- Changing the permission settings so the main session can run a tool
- Reading CLAUDE.md at the start of a session and summarizing its rules back to the user
- Applying a one-line change that the main session has already located

Check answer

### Show answer

Answer: A large, self-contained investigation whose details would clutter the main session. Subagents isolate context. Delegate work whose transcript you do not need in the main thread. A one-line change is cheaper to make directly, and CLAUDE.md is already loaded for the main session.

Claude Code workflows

A team notices Claude Code sometimes runs the test suite three times in a row. Which is the right lever?

- Removing the test command from the allowed tools and running tests in CI instead
- Increasing the max turns so the session can finish before the loop is cut off
- A hook or CLAUDE.md rule defining when tests run, plus a check of the loop for missing stop conditions
- A stricter system prompt telling Claude to run the tests only once per task

Check answer

### Show answer

Answer: A hook or CLAUDE.md rule defining when tests run, plus a check of the loop for missing stop conditions. Repeated actions point to missing structure: explicit rules for when to run tests and clear stop conditions. Removing the command hides the symptom and slows feedback; more turns give the loop more room to repeat.

Claude Code workflows

What does the /compact style operation do in a long session?

- Trims tool results from the transcript but keeps every user and assistant turn
- Summarizes the conversation so far to free context while keeping the essentials
- Switches to a model with a larger window so the session can continue
- Restarts the session with the same CLAUDE.md loaded and an empty conversation history

Check answer

### Show answer

Answer: Summarizes the conversation so far to free context while keeping the essentials. Compaction trades detail for headroom, which is what long sessions need. It summarizes the whole conversation, not just tool results; a clean restart is what /clear does, and it loses the essentials compaction keeps.

Claude Code workflows

A developer wants Claude Code to stop before committing so they can review. Best approach?

- A CLAUDE.md line asking Claude to confirm with the user before running git commit
- Keep commit outside the allowed actions, or gate it with a hook that requires confirmation
- A PostToolUse hook on git commit that opens the diff for the developer to review
- Run the whole session in plan mode so no commands execute until the developer approves the plan

Check answer

### Show answer

Answer: Keep commit outside the allowed actions, or gate it with a hook that requires confirmation. Review points are enforced through permissions and hooks, not memory. A PostToolUse hook fires after the commit already exists; plan mode blocks all edits, not just the commit.

Claude Code workflows

Which of these belongs in CLAUDE.md rather than a subagent or a skill?

- The linter command and a note that the tests need the local database running
- The API keys for the staging environment so tests can run end to end
- A 200-page design document describing every subsystem in the product and how they connect
- A weekly status report template the team fills in every Friday

Check answer

### Show answer

Answer: The linter command and a note that the tests need the local database running. Short, always-relevant operational facts are CLAUDE.md material. Long documents are loaded on demand; a report template is a skill or slash command; keys do not go in a checked-in file.

Claude Code workflows

You need Claude Code to review a pull request in CI and post comments, with no ability to push code. Which controls?

- Interactive mode on the runner so a reviewer can approve each tool call
- Print mode with full permissions, relying on the prompt to say 'do not push code'
- Print mode with a read-only tool allow list and the git push command denied
- Plan mode, since planning cannot push code and can still read the diff

Check answer

### Show answer

Answer: Print mode with a read-only tool allow list and the git push command denied. Least privilege for automation: read-only tools plus explicit denies on writes. Relying on the prompt is advisory; interactive mode has no reviewer present in CI.

Claude Code workflows

A Claude Code session is asked to fix a bug and, without being asked, refactors three unrelated files. What reduces this?

- A larger context window so Claude can see why the other files are unrelated
- A PostToolUse hook that reverts any edit outside the file named in the prompt
- Running the fix headless so there is no room for exploratory editing
- Explicit scope in the prompt, CLAUDE.md conventions about minimal diffs, and plan mode for review

Check answer

### Show answer

Answer: Explicit scope in the prompt, CLAUDE.md conventions about minimal diffs, and plan mode for review. Scope discipline comes from explicit instructions and a review step before edits. A revert hook is a blunt tool that also blocks legitimate changes in a second file; headless mode removes the review, not the drift.

Claude Code workflows

What is the purpose of a PreToolUse hook?

- Compact the context when a tool result is too large
- Inspect or block a tool call before it executes
- Run a command after the model has finished its response
- Swap the model for a cheaper one on routine tool calls

Check answer

### Show answer

Answer: Inspect or block a tool call before it executes. Pre hooks gate actions; post hooks react to them. Running after the response is a Stop hook; compaction and model choice are not what hooks control.

Prompt engineering

A system prompt says 'be helpful' and the outputs vary wildly in format. The highest-leverage change is:

- Adding 'be concise and consistent' to the system prompt
- Lowering the temperature so the formatting varies less
- Stating the exact output format with a short example
- Adding a persona so the model has a stable voice to write in

Check answer

### Show answer

Answer: Stating the exact output format with a short example. Concrete format specification with an example beats abstract adjectives. Lower temperature narrows sampling but cannot supply a format that was never stated; a persona shapes tone, not structure.

Prompt engineering

You need the model to reason through a multi-step pricing rule before answering. Which technique?

- Split the request across two turns, one for the rule and one for the answer
- Provide several unrelated worked examples so the model learns to be careful
- Ask for the final price only, with a rule that the answer must be a single number
- Ask it to work through the steps before answering, or enable extended thinking for the hard cases

Check answer

### Show answer

Answer: Ask it to work through the steps before answering, or enable extended thinking for the hard cases. Letting the model reason before answering improves multi-step accuracy. Asking for the number only removes the working that makes the answer right; unrelated examples teach nothing about this rule.

Prompt engineering

Which is the best use of XML-style tags in a prompt?

- Separating instructions, reference documents, and examples so the model does not confuse them
- Signalling to the API which sections of the prompt are eligible for prompt caching
- Marking the parts of the prompt the model may skip when the context is nearly full
- Replacing the system prompt with a tagged block at the top of the user turn

Check answer

### Show answer

Answer: Separating instructions, reference documents, and examples so the model does not confuse them. Clear structure prevents content from being read as instructions and makes long prompts unambiguous. Tags are not read by the API for caching; cache_control does that. The model does not skip tagged sections.

Prompt engineering

You want responses to begin with a JSON object and nothing else. Which technique reduces preamble?

- Adding 'respond with JSON only' as the last line of the system prompt
- Prefilling the assistant turn with the opening brace
- Setting stop_sequences to a closing brace so the model ends at the object
- Setting temperature to zero so the model picks the most likely opening

Check answer

### Show answer

Answer: Prefilling the assistant turn with the opening brace. Prefilling steers the start of the response and suppresses chatty preambles. A stop sequence controls where the response ends, not where it starts; a 'JSON only' line helps but is still an instruction the model can ignore.

Prompt engineering

The model keeps inventing a citation when a source is missing. Which instruction helps most?

- 'Keep answers short so there is less room for unsupported claims to appear'
- 'If no source in the provided material supports the claim, say so instead of citing'
- 'Cite at least one source for every claim, using the provided material where possible'
- 'Use your own knowledge to fill gaps when the provided material does not cover a claim'

Check answer

### Show answer

Answer: 'If no source in the provided material supports the claim, say so instead of citing'. Give the model an explicit permitted action for the missing-information case. 'Cite at least one source' is the instruction that produces invented citations; filling gaps from memory replaces one fabrication with another.

Prompt engineering

Which examples make few-shot prompting work best?

- A few examples that closely match the target task and format, including a tricky edge case
- Examples drawn from a different but similar domain to avoid overfitting to the test set
- Examples that deliberately contain errors, with corrections, so the model learns what to avoid
- A large set of loosely related examples so the model sees the range of possible inputs

Check answer

### Show answer

Answer: A few examples that closely match the target task and format, including a tricky edge case. Relevance and quality matter more than quantity; an edge case teaches the boundary. Error-and-correction examples can work for critique tasks, but for a formatting task they put wrong outputs in front of the model.

Prompt engineering

A prompt for summarizing meeting notes should also flag decisions and owners. Where do those requirements go?

- Stated explicitly as required output sections, with an example
- Implicitly, since a well-written summary includes decisions and owners
- In the system prompt as a general instruction to 'capture action items'
- In a second call after the summary, so each call has one job

Check answer

### Show answer

Answer: Stated explicitly as required output sections, with an example. Required elements are stated, structured, and shown, not assumed. A second call is decomposition, which can be fine, but the requirement still has to be stated somewhere; a vague 'action items' line is not a required section.

Prompt engineering

What is the role of the system prompt compared with the user turn?

- The system prompt is where the model name and version are declared; the user turn holds everything else in the request
- The system prompt sets standing role, rules, and format; the user turn carries the specific task and material
- The system prompt carries the material to analyze; the user turn carries the standing rules
- They are interchangeable; the model concatenates them before reading either

Check answer

### Show answer

Answer: The system prompt sets standing role, rules, and format; the user turn carries the specific task and material. Separating standing instructions from per-request content keeps prompts stable and cacheable. The reverse split puts volatile material in the cacheable position; the model name is set on the request, not in the prompt.

Prompt engineering

A prompt includes ten rules and the model follows nine. Which change is most effective?

- Move the missed rule near the task, restate it as a concrete check, and add an example of compliance
- Delete the nine rules that already work, so the missed one gets the model's full attention
- Move the missed rule into a tool description so the model reads it when it acts
- Repeat the missed rule in capitals at the top and bottom of the system prompt

Check answer

### Show answer

Answer: Move the missed rule near the task, restate it as a concrete check, and add an example of compliance. Position, concreteness, and examples drive rule adherence. Capitals add emphasis without clarity; deleting working rules trades nine known behaviors for one.

Prompt engineering

When should you ask the model to quote the relevant passage before answering a question about a long document?

- Only when streaming, since the quote arrives first and gives the user something to read while the answer generates
- When the answer is a single fact, since longer answers already cite their sources
- When accuracy on the document matters, since grounding in quotes reduces invented details
- Only for documents short enough that the quotes do not add much to the output

Check answer

### Show answer

Answer: When accuracy on the document matters, since grounding in quotes reduces invented details. Quote-then-answer anchors the response in the source, which matters most on long documents. Short documents need it least; streaming is a delivery detail, not a reason.

Prompt engineering

A prompt asks for 'a short answer' and gets three paragraphs. What fixes it reliably?

- Reduce temperature to zero so the model chooses the most likely, usually shorter, phrasing
- Specify the length in sentences or words and show an example of the right length
- Set max_tokens to a small value so the response cannot run to three paragraphs
- Add 'be brief' to both the system prompt and the user message

Check answer

### Show answer

Answer: Specify the length in sentences or words and show an example of the right length. Precise constraints and an example beat vague adjectives. A small max_tokens truncates mid-sentence rather than producing a short answer; temperature does not control length.

Prompt engineering

Which is a sign that a task needs extended thinking rather than a normal response?

- The prompt is long and contains several reference documents the model has to read through
- The task requires weighing several constraints and checking intermediate steps
- The user wants the answer quickly and is willing to accept a rough result
- The output must follow a strict schema that downstream code will parse

Check answer

### Show answer

Answer: The task requires weighing several constraints and checking intermediate steps. Extended thinking pays off on multi-constraint reasoning, not on lookups. A long prompt is a context question, not a reasoning one; a strict schema is solved by structured output.

Prompt engineering

What is a good way to make a prompt testable?

- Test it against live traffic and roll back when the error rate rises
- Define expected outputs for a set of inputs and check the prompt against them after every change
- Freeze the prompt once it works and route changes through a new prompt
- Keep the prompt general so it holds up on inputs you did not anticipate

Check answer

### Show answer

Answer: Define expected outputs for a set of inputs and check the prompt against them after every change. A prompt with a test set can be improved safely; one without cannot. Live traffic tests find problems after users see them; freezing the prompt avoids regressions by refusing improvements.

Prompt engineering

Which change most often improves a prompt that is 'almost right'?

- Adding a persona that matches the domain the prompt operates in
- Adding a line asking the model to double-check its answer before responding
- Moving the instructions from the system prompt into the user turn
- Replacing an ambiguous instruction with a specific, checkable one

Check answer

### Show answer

Answer: Replacing an ambiguous instruction with a specific, checkable one. Ambiguity is the usual culprit; specificity is the usual fix. A double-check line can help on reasoning tasks but does not tell the model what it misunderstood; a persona shapes voice, not correctness.

Tool design and MCP

Two tools, search_customers and find_customers, do nearly the same thing and the model picks inconsistently. What should you do?

- Add a routing instruction to the system prompt that says which tool to prefer
- Merge them into one well-described tool, or make their purposes clearly distinct in name and description
- Set tool_choice to the preferred tool so the model no longer has to choose
- Keep both and add a third tool that wraps them and picks the right one internally

Check answer

### Show answer

Answer: Merge them into one well-described tool, or make their purposes clearly distinct in name and description. Overlapping tools confuse selection; fewer, clearly scoped tools work better. Forcing tool_choice removes the model's choice on every turn, including turns where no tool is needed; a wrapper tool adds a third overlapping name.

Tool design and MCP

A tool returns a 4 MB JSON dump on every call and the agent's context fills quickly. Best fix?

- Ask the model to summarize each result before continuing so the raw dump is dropped
- Return only the fields the task needs, paginate, and let the model request more
- Call the tool less often by caching its output in the system prompt for the session
- Compress the JSON before returning it so it occupies fewer tokens in context

Check answer

### Show answer

Answer: Return only the fields the task needs, paginate, and let the model request more. Tools should return concise, meaningful context, not raw dumps. Compressing JSON does not reduce tokens meaningfully; having the model summarize still costs the full dump in context first.

Tool design and MCP

Which naming convention helps a model with many tools?

- Consistent namespacing by system, such as crm_search and crm_update
- Short names of one or two characters so the tool list stays compact
- Names that describe the return type, such as list_result and single_result
- Names that include the version, such as search_v2, so the model picks the latest

Check answer

### Show answer

Answer: Consistent namespacing by system, such as crm_search and crm_update. Predictable, namespaced names make the tool surface legible to the model. Return-type names say nothing about purpose; version suffixes ask the model to guess which one is current.

Tool design and MCP

An MCP server exposes a 'prompts' primitive. What is it for?

- Reusable prompt templates the client can discover and invoke
- The configuration block that tells the client how to authenticate and transport
- Instructions the server injects into the client's system prompt on connect
- The templates a tool uses to format its own results before returning them

Check answer

### Show answer

Answer: Reusable prompt templates the client can discover and invoke. MCP has tools, resources, and prompts; prompts are reusable templates the client exposes to the user. Servers do not inject text into the client's system prompt; authentication and transport are handled outside the primitives.

Tool design and MCP

A remote MCP server holds customer data. Which is required?

- Restricting the server to read-only tools so a compromised client cannot change data
- Storing an API key in the tool description so the model can present it on each call
- Running the server over stdio through an SSH tunnel so that no HTTP endpoint is ever exposed to the network
- Authentication and authorization on the server, with the client presenting credentials

Check answer

### Show answer

Answer: Authentication and authorization on the server, with the client presenting credentials. Remote servers with sensitive data need auth like any other service. Read-only tools still leak customer data to anyone who connects; a key in the tool description is visible to every client and the model.

Tool design and MCP

What should a tool's description include beyond what it does?

- When to use it and when not to, parameter meanings, and edge cases
- The list of other tools that must be called before it, so ordering is explicit
- The expected latency and rate limits so the model can plan parallel calls
- The server it lives on and the endpoint it calls, so the model can troubleshoot failures

Check answer

### Show answer

Answer: When to use it and when not to, parameter meanings, and edge cases. The description is the model's decision guide for the tool. Endpoint details and latency are operational data the model cannot act on; a required call order is better expressed by returning what the next call needs than by a list the model has to track.

Tool design and MCP

A tool has a 'delete' action and a 'read' action behind one parameter. Why is that a design problem?

- Enum parameters are poorly supported in JSON Schema, so the model will often pass an invalid value
- The model will default to the first enum value, so reads will be attempted as deletes
- One parameter cannot carry two verbs, so the schema will fail validation on the API
- Read-only and destructive actions need different gating; split them so the destructive one can be permissioned separately

Check answer

### Show answer

Answer: Read-only and destructive actions need different gating; split them so the destructive one can be permissioned separately. Separating safe and dangerous operations lets you gate the dangerous one. Enums are well supported and the schema is valid; the problem is not the schema but the fact that a permission rule cannot tell a read from a delete.

Tool design and MCP

The model calls a tool with a date in the wrong format, repeatedly. Best fix?

- Remove the date parameter and have the tool default to today, asking the user for other dates
- Add a schema format hint and an example value in the description, and return a clear error on bad input
- Add a system prompt rule stating the date format, since the model reads the tool description less carefully
- Accept any format the model sends and normalize it inside the tool, so the loop never stalls

Check answer

### Show answer

Answer: Add a schema format hint and an example value in the description, and return a clear error on bad input. Schema hints, examples, and actionable errors fix malformed calls. Silent normalization hides a defect that will bite when a date is ambiguous; the tool description is exactly where the model looks when it builds the call.

Tool design and MCP

When is parallel tool use appropriate?

- When latency matters, regardless of whether one call's input comes from another
- When the model is confident about all the arguments before the first result returns
- When the calls are independent and the results do not depend on one another
- When the tools belong to the same MCP server, so one connection can batch them

Check answer

### Show answer

Answer: When the calls are independent and the results do not depend on one another. Independent calls can run concurrently; dependent ones cannot. Latency is the motivation, not the condition; if one call needs another's output, it has to wait. The server they belong to is irrelevant.

Tool design and MCP

Which is a resource in MCP terms?

- The transport the client uses to reach the server, such as stdio or streamable HTTP
- Data the client can read, like a file or a record, addressed by URI
- A function the model can call to change state on the server
- A reusable template the user selects to start a conversation

Check answer

### Show answer

Answer: Data the client can read, like a file or a record, addressed by URI. Resources are readable data; tools are callable actions; prompts are templates. Transport is how the client connects, not one of the three primitives.

Tool design and MCP

A tool should be idempotent when:

- It only reads data, since reads are the calls the loop repeats most
- Its effects must be safe to repeat, because agent loops retry
- It has no parameters, so every call is identical by construction
- It runs over stdio, where a dropped connection replays the call

Check answer

### Show answer

Answer: Its effects must be safe to repeat, because agent loops retry. Retries are normal; idempotency makes them harmless. Read-only tools are already idempotent by nature; the property matters for tools with side effects. Transport does not replay calls.

Tool design and MCP

What is the safest default for a new tool that writes to an external system?

- Disabled in production and enabled only in a staging environment until accuracy is measured
- Autonomous use for small writes and confirmation for large ones, with the threshold set by the model
- Requires confirmation until its accuracy is measured
- Autonomous use with a nightly report of what it wrote, so problems surface within a day

Check answer

### Show answer

Answer: Requires confirmation until its accuracy is measured. Start gated; expand autonomy on evidence. Staging-only means no real accuracy data; letting the model set its own threshold makes the model the gate again.

Context management

What is 'context rot'?

- A caching bug in which a stale cached prefix is served after the system prompt has changed
- The gradual loss of tool results when compaction summarizes older turns
- The decline in response quality as the window fills with stale or irrelevant content
- The drift in a model's behavior over weeks as the provider updates it

Check answer

### Show answer

Answer: The decline in response quality as the window fills with stale or irrelevant content. Recognizing context rot is why compaction and clearing exist. It is about what is in the window now, not a caching fault or model updates; compaction is the cure, not the cause.

Context management

An agent needs occasional access to a 500-page manual. Best approach?

- Load the whole manual into every prompt and rely on prompt caching to keep it cheap
- Summarize it once into a few pages and give the agent only the summary
- Index it and retrieve relevant sections on demand, giving the model identifiers it can fetch
- Split it into ten chunks and run a subagent per chunk on every question

Check answer

### Show answer

Answer: Index it and retrieve relevant sections on demand, giving the model identifiers it can fetch. Just-in-time retrieval keeps the window lean and accurate. Caching makes the full manual cheaper but not free, and 500 pages of mostly irrelevant text still degrades attention; a one-time summary loses the details the occasional question needs.

Context management

Which content should sit at the start of the prompt for prompt caching to help?

- The conversation history, since it is the largest part of the request
- The user's latest question, so the model reads it before the long material
- The stable system prompt and tool definitions
- The most recent tool results, since those are reused across turns

Check answer

### Show answer

Answer: The stable system prompt and tool definitions. Cache hits depend on a stable prefix. Tool results and the latest question change every turn, so placing them first breaks the prefix for every request.

Context management

A long-running agent needs to remember decisions across sessions. Which mechanism fits?

- A longer system prompt that lists the decisions made so far
- A larger max_tokens value so the agent can restate all of its decisions in each response
- Prompt caching on the previous session's transcript so it is cheap to include
- A memory file or structured notes the agent reads at start and updates as it works

Check answer

### Show answer

Answer: A memory file or structured notes the agent reads at start and updates as it works. Persistence across sessions needs an explicit store the agent maintains. Caching a transcript keeps it cheap to send but does not curate it, and the cache expires; a system prompt edited by hand is memory the agent cannot update.

Context management

Why hand a subagent a task instead of doing everything in one context?

- The subagent's working context stays separate and only its conclusion returns, preserving the main window
- Subagents can call tools the main session is not allowed to use
- Subagents run on a different model, so the main session's model stays available
- Subagents share the main session's context, so they start with full knowledge of the task

Check answer

### Show answer

Answer: The subagent's working context stays separate and only its conclusion returns, preserving the main window. Context isolation is the main benefit of delegation. Subagents do not share the main context, which is the point; the model and tool set can be configured but are not why you delegate.

Context management

A prompt includes the full history of a two-hour support chat. Most of it is resolved. What should you do?

- Summarize the resolved parts and keep the open issue verbatim
- Keep the last twenty messages and drop everything before them
- Drop the history and restate the open issue in a fresh prompt
- Keep the full history, since the model may need context from resolved issues

Check answer

### Show answer

Answer: Summarize the resolved parts and keep the open issue verbatim. Summarize the settled, keep the live. Keeping everything wastes the window on closed threads; a fixed tail of twenty messages may cut through the middle of the open issue.

Context management

Which is a symptom that a context window is being wasted?

- Responses that arrive faster than the previous session's
- Frequent cache hits on the system prompt across many consecutive requests from the same client
- Large tool results the model never uses and repeated boilerplate in every turn
- Short prompts that leave most of the window empty

Check answer

### Show answer

Answer: Large tool results the model never uses and repeated boilerplate in every turn. Unused bulk and repetition are the usual waste. Cache hits and fast responses are signs of a healthy prompt; empty headroom is not waste.

Context management

What is the trade-off of aggressive summarization in an agent loop?

- Summaries make later turns slower because the model must reconstruct the details
- Headroom and speed at the cost of detail, so keep exact values and identifiers later steps need
- Summaries break tool use because tool_result blocks cannot be summarized
- Summaries are safe as long as the summary is written by a larger model

Check answer

### Show answer

Answer: Headroom and speed at the cost of detail, so keep exact values and identifiers later steps need. Summaries lose detail; preserve what downstream steps depend on. Later turns are usually faster with a shorter context, not slower, and tool results can be summarized like anything else.

Context management

Which information should be kept verbatim through compaction?

- The earliest turns, since they set up the task
- Resolved errors and their stack traces, in case they recur
- Identifiers, exact values, and the current task definition
- The greetings and pleasantries, since tone carries across turns

Check answer

### Show answer

Answer: Identifiers, exact values, and the current task definition. Precision-critical items survive; chatter does not. The earliest turns matter only for the task definition, which is what is kept; resolved errors are exactly what a summary can compress.

Context management

A team wants to cut cost on a chat product with a long, stable system prompt and many short user turns. First lever?

- Prompt caching on the system prompt and tool definitions
- Batching user turns so several are answered in one request
- Switching to a smaller model for every turn after the first
- Trimming the system prompt to a few lines so every request is smaller

Check answer

### Show answer

Answer: Prompt caching on the system prompt and tool definitions. Caching the stable prefix is the cheapest win for that shape. Trimming the system prompt may cost quality; batching turns breaks the chat experience; a smaller model changes the product.

Context management

What does 'give the agent lightweight identifiers' mean in context engineering?

- Pass file paths, record ids, and URLs so the agent can fetch details when needed instead of front-loading everything
- Replace user names with anonymous ids before content reaches the model
- Use short variable and file names in the code the agent works on so tokens are saved
- Give each tool a short alias so the tool list occupies fewer tokens

Check answer

### Show answer

Answer: Pass file paths, record ids, and URLs so the agent can fetch details when needed instead of front-loading everything. Identifiers enable on-demand retrieval. Short names and tool aliases save a handful of tokens; anonymization is a privacy measure, not a context strategy.

Context management

How should an architect decide the context budget for a step in a workflow?

- From what the step must read and produce, leaving headroom for tool results and reasoning
- Split the total window evenly across the steps in the workflow
- Reuse the budget from the last project that used the same model
- Use the model's maximum on every step so no step runs out of room

Check answer

### Show answer

Answer: From what the step must read and produce, leaving headroom for tool results and reasoning. Budget from the step's real needs, with headroom. An even split starves the heavy steps and pads the light ones; the maximum on every step invites bloat and cost.

Agentic architecture

A due-diligence agent must read 300 contracts and produce one risk table. Which structure keeps quality consistent?

- Load all 300 contracts into one long context and ask for a single risk table in one pass
- Fan out one worker per contract with the same extraction brief and schema, then merge the structured results
- Route each contract by type to a specialist prompt and let each specialist write its own section of the table
- Chain the contracts sequentially so each worker sees the previous worker's risk rows before extracting its own

Check answer

### Show answer

Answer: Fan out one worker per contract with the same extraction brief and schema, then merge the structured results. Uniform per-item briefs and structured returns make fan-out work reproducible and mergeable. Chaining contracts sequentially lets early errors contaminate later extractions and adds no consistency; routing by type produces sections written to different standards.

Agentic architecture

What is the main cost of adding a 'reflection' step where the agent critiques its own output before returning it?

- Added tokens and latency, so it pays off where errors are expensive and the criteria are checkable
- It blocks tool use during the critique turn, so agents that rely on tools cannot use reflection safely
- It only works with a larger model as the critic, which doubles the cost of every task in the pipeline
- The critique tends to anchor on the draft, so it should replace the generator rather than follow it

Check answer

### Show answer

Answer: Added tokens and latency, so it pays off where errors are expensive and the criteria are checkable. Self-critique costs tokens and time, so it belongs on high-stakes, checkable work and wastes budget elsewhere. A critic does not need a larger model, does not block tools, and is meant to follow the generator, not replace it.

Agentic architecture

An agent is allowed to call a payments API. Which control is non-negotiable?

- An evaluator model that reviews each proposed payment call and rejects any that look unusual
- An enforced gate outside the model that requires approval or applies limits before the call executes
- A system prompt instruction to confirm the amount with the user before every payment call
- A detailed tool description that lists the payment limits so the model knows when to refuse a transfer

Check answer

### Show answer

Answer: An enforced gate outside the model that requires approval or applies limits before the call executes. Money moves only through gates enforced in code, not on the model's judgment. Descriptions, prompt instructions, and an evaluator model all rely on a model following guidance, which is not a hard control.

Agentic architecture

Which sign suggests a workflow should be split into two chained model calls?

- The task takes several seconds per run, and latency matters more than accuracy for this use case
- The prompt calls a single tool several times per run, and each call returns a large result
- One prompt both extracts facts and writes persuasive prose, and one of those two keeps degrading
- Outputs are short and consistent, but the prompt is longer than the team would like to maintain

Check answer

### Show answer

Answer: One prompt both extracts facts and writes persuasive prose, and one of those two keeps degrading. Competing objectives in one call degrade both; chaining separates extraction from writing. Large tool results are a context problem, not a chaining signal, and chaining adds latency rather than removing it.

Agentic architecture

A team runs an agent that reads email and drafts replies. A client asks why it never sends automatically. Best answer?

- Autonomous sending would break prompt caching because each sent message changes the conversation prefix
- The Messages API has no outbound email capability of its own, so a person has to press send in the mail client each time
- Sending is irreversible and public, so it stays gated by a person until measured accuracy earns more autonomy
- The agent runs in a workflow rather than an agent loop, and workflows cannot trigger external actions

Check answer

### Show answer

Answer: Sending is irreversible and public, so it stays gated by a person until measured accuracy earns more autonomy. Autonomy follows evidence; irreversible actions start gated. Sending is a tool the team could add at any time, so the limit is a design choice, not an API or caching constraint.

Agentic architecture

What distinguishes routing from an orchestrator in the workflow patterns?

- Routing requires a separate model per path, while an orchestrator uses one model for every subtask
- Routing sends an input down one of several fixed paths; an orchestrator plans dynamic subtasks and synthesizes results
- Routing runs several fixed paths in parallel and merges their outputs; an orchestrator runs the same paths one after another and keeps the best
- Routing is a form of parallelization; an orchestrator is a form of evaluator-optimizer loop

Check answer

### Show answer

Answer: Routing sends an input down one of several fixed paths; an orchestrator plans dynamic subtasks and synthesizes results. Routing classifies an input and picks a fixed path; orchestration plans subtasks that were not known in advance and merges the results. Running paths in parallel and merging describes parallelization, not routing.

Agentic architecture

An agent produced a correct answer but took 40 tool calls where 5 would do. Which lever addresses this?

- Sharper tool descriptions, an explicit plan step, and a per-task call budget with feedback as it nears the limit
- Cut the tool list down to the two or three tools the task used most, so there is less to choose from and fewer wrong turns
- Switch to parallel tool calls so the 40 calls complete in the time five sequential ones would take
- Lower the context window by trimming the system prompt so the model has less to reason over each turn

Check answer

### Show answer

Answer: Sharper tool descriptions, an explicit plan step, and a per-task call budget with feedback as it nears the limit. Tool clarity, planning, and budgets reduce thrashing. Removing tools may break other tasks, and parallel calls hide the waste instead of removing it.

Agentic architecture

Why should a subagent's brief include the success criteria and the expected return format?

- So the coordinator can reuse the subagent's full transcript as context for later steps instead of a lossy summary
- So the subagent knows when to stop and the coordinator can merge results without re-reading transcripts
- So the subagent can skip tool calls and answer from the brief alone, saving tokens
- Because the Agent SDK rejects a subagent definition that has no output schema attached

Check answer

### Show answer

Answer: So the subagent knows when to stop and the coordinator can merge results without re-reading transcripts. Clear criteria and formats make delegation composable: the worker stops at the right point and the coordinator merges structured returns. Reusing full transcripts is the thing a good brief avoids.

Agentic architecture

A stakeholder asks for 'an AI that runs the whole department'. As the architect, the first design move is:

- Build one general agent with every department tool attached and let it learn the workflows from use
- Start with an orchestrator-workers system so each function of the department gets its own dedicated worker agent
- Map the workflows, classify steps by predictability and blast radius, and start with the predictable ones
- Pick the most capable model available so the agent can handle whatever the department throws at it

Check answer

### Show answer

Answer: Map the workflows, classify steps by predictability and blast radius, and start with the predictable ones. Decompose, classify, and start where reliability is easy to prove. Jumping to an orchestrator or a single general agent commits to an architecture before the work has been understood.

Agentic architecture

Which is the correct role of an evaluator in an evaluator-optimizer loop?

- Produce the first draft, then revise it against the same criteria in a single turn
- Decide which tools the generator may call on its next attempt at the task
- Summarize the generator's transcript so the loop fits in the context window
- Judge the draft against explicit criteria and return specific, actionable feedback

Check answer

### Show answer

Answer: Judge the draft against explicit criteria and return specific, actionable feedback. Evaluators judge against criteria and feed back; generators produce. Drafting and revising in one turn is self-critique, not the two-role loop.

Agentic architecture

An agent needs to process items that arrive continuously over a day. What design fits?

- A single batch prompt at the end of the day that processes all items together in one call
- One long-running session that keeps every item in context so it can spot patterns across the day
- A queue-driven loop that handles each item in a fresh bounded context and persists state between items
- An orchestrator that spawns a subagent per item and keeps every subagent transcript for the coordinator

Check answer

### Show answer

Answer: A queue-driven loop that handles each item in a fresh bounded context and persists state between items. Per-item bounded contexts with persisted state scale and stay reliable. A day-long session overflows, an end-of-day batch loses timeliness, and keeping every transcript in the coordinator recreates the overflow.

Agentic architecture

What is the practical reason to make agent steps observable with structured logs rather than free-text notes?

- Structured logs can be queried, rolled into metrics, and replayed for evaluation
- The model produces more consistent reasoning when it is asked to log in a structured format
- Free-text notes consume more tokens per step, so structured logs keep the run inside the context budget
- Structured logs are required for prompt caching to work across steps of the run

Check answer

### Show answer

Answer: Structured logs can be queried, rolled into metrics, and replayed for evaluation. Structure makes behavior measurable and replayable. Logs live outside the context window, so token savings and caching are not the reason.

Agentic architecture

A coordinator receives conflicting answers from two subagents. Sound handling?

- Take the answer from whichever subagent used more tool calls, since it did more research
- Merge both answers into one combined response and let the downstream consumer decide which parts to trust
- Detect the conflict, resolve it with a defined rule or a verification step, and record the decision
- Rerun both subagents with the same brief and accept the answer that appears more often

Check answer

### Show answer

Answer: Detect the conflict, resolve it with a defined rule or a verification step, and record the decision. Conflicts need explicit resolution and a record, not a silent choice. Tool-call count is not evidence of correctness, and majority reruns can repeat the same error.

Agentic architecture

Which situation calls for human-in-the-loop by design rather than by exception?

- Any step where the model reports low confidence in its own answer partway through the run
- Approving legal commitments, spending above a threshold, or changes to people's records
- Steps where two workers in a parallel fan-out return different formatting
- Every tool call that reads from a production database rather than a staging copy

Check answer

### Show answer

Answer: Approving legal commitments, spending above a threshold, or changes to people's records. High-consequence categories get a standing human step. Low model confidence triggers a review by exception, and reads or formatting mismatches are handled in code.

Agentic architecture

What is the risk of letting an agent modify its own instructions during a run?

- The run costs more because each instruction rewrite invalidates the cached prompt prefix
- There is little risk if every instruction change is logged, since the log lets you replay the run afterward
- Drift and loss of control; standing instructions should be fixed, versioned, and changed by people
- The agent becomes slower to complete tasks because it spends turns editing its own prompt

Check answer

### Show answer

Answer: Drift and loss of control; standing instructions should be fixed, versioned, and changed by people. Self-modifying instructions undermine predictability and audit. Cache and speed costs are minor by comparison, and logging a drift does not prevent it.

Agentic architecture

A workflow's third step frequently fails on malformed input from step two. Best fix?

- Validate step two's output against a schema before step three runs, with a repair path on failure
- Merge steps two and three into one prompt so there is no boundary for malformed data to cross
- Wrap step three in a retry loop with backoff so transient formatting problems resolve themselves
- Ask step three to tolerate malformed input by instructing it to do its best with whatever arrives

Check answer

### Show answer

Answer: Validate step two's output against a schema before step three runs, with a repair path on failure. Validate at boundaries; repair or route on failure. Retries do not fix deterministic malformation, and merging steps hides the fault instead of catching it.

Claude Code workflows

A monorepo has several services with different test commands. Where should that live for Claude Code?

- A subagent per service that carries that service's commands in its own prompt
- The first message of each session, restated whenever the service changes
- CLAUDE.md, with a short per-service map of test commands and conventions
- The repository README, which Claude Code reads automatically at session start

Check answer

### Show answer

Answer: CLAUDE.md, with a short per-service map of test commands and conventions. Project memory holds per-area commands and loads on every session. The README is not loaded automatically, and restating commands in chat is manual and easy to forget.

Claude Code workflows

Which hook event would you use to run a security scan on every file Claude writes?

- A slash command the developer runs after each session to scan changed files
- A PreToolUse hook on the Read tool, so files are scanned before Claude opens them
- A PostToolUse hook matched to the Write and Edit tools, run after each change lands
- A Stop hook that scans the whole working tree once when Claude finishes its turn and reports findings

Check answer

### Show answer

Answer: A PostToolUse hook matched to the Write and Edit tools, run after each change lands. Post hooks react to completed writes, so the scan sees the file as written. A Stop hook runs once per turn and misses intermediate writes; a PreToolUse hook on Read never sees writes at all.

Claude Code workflows

A developer wants Claude Code to ask before running any command that touches the network. Which setting?

- Permission rules that allow safe commands and require confirmation for matching network commands
- A CLAUDE.md instruction telling Claude to ask for confirmation before any command that reaches the network
- A PostToolUse hook on Bash that inspects the command for network calls and logs a warning
- Plan mode for the whole session, so every command is proposed before it is executed

Check answer

### Show answer

Answer: Permission rules that allow safe commands and require confirmation for matching network commands. Granular permission rules gate specific commands. A PostToolUse hook runs after the command has already executed, and a CLAUDE.md line is guidance rather than enforcement.

Claude Code workflows

What is the benefit of committing project-scoped MCP configuration to the repo?

- It lets the repo's MCP servers override the user's own server settings for the project
- Every contributor gets the same integrations without manual setup on each machine
- Claude Code caches the server tool lists in git, which speeds up session start
- Server credentials travel with the code, so contributors do not need their own tokens

Check answer

### Show answer

Answer: Every contributor gets the same integrations without manual setup on each machine. Shared config travels with the code, so integrations are consistent across the team. Credentials should stay out of the repo, in environment variables or user-level config.

Claude Code workflows

Claude Code proposes a plan that touches an unrelated module. What is the right response in plan mode?

- Accept the plan, then revert the unrelated edits during code review
- Revise the plan's scope before any edits are made to the tree
- Run the test suite first to see whether the extra module is affected
- Exit plan mode and let Claude discover the right scope as it edits

Check answer

### Show answer

Answer: Revise the plan's scope before any edits are made to the tree. Plan mode exists to correct scope before edits happen. Accepting and reverting later wastes work and risks missing an edit.

Claude Code workflows

Which is a sensible use of a Claude Code skill?

- A packaged procedure like 'write a release note from merged PRs' with its own instructions and helper files
- A per-task override that switches the session to a different model for that procedure
- A place to store the API keys and tokens the procedure needs, loaded only when invoked
- A replacement for CLAUDE.md that holds all project conventions and commands in a single file loaded on demand

Check answer

### Show answer

Answer: A packaged procedure like 'write a release note from merged PRs' with its own instructions and helper files. Skills package reusable procedures with their supporting files. Project conventions belong in CLAUDE.md, and secrets belong in environment configuration, not in a skill.

Claude Code workflows

You want a nightly job where Claude Code triages new issues and labels them. Which pieces?

- Print mode in a scheduled job with a read-only tool set plus one allowed labeling action
- A PostToolUse hook that fires whenever a new issue is created and labels it in place
- A subagent with full permissions, invoked from a cron entry with the issue list as input
- An interactive session left open overnight with auto-accept enabled for all tool calls

Check answer

### Show answer

Answer: Print mode in a scheduled job with a read-only tool set plus one allowed labeling action. Headless, scheduled, and least-privilege. Hooks respond to Claude's own tool calls, not to external events, and full permissions are more than a labeling job needs.

Claude Code workflows

A PreToolUse hook exits with code 2 on a tool call. What should happen?

- Claude Code ends the session so the developer can inspect the hook's output manually
- The call is blocked and the hook's message is surfaced so the model can adjust
- The hook is disabled for the rest of the session and the call is retried once
- The call proceeds and the hook's stderr is shown to the user, as with other non-zero exits

Check answer

### Show answer

Answer: The call is blocked and the hook's message is surfaced so the model can adjust. Exit code 2 is the blocking exit: the action stops and the hook's stderr is fed back to the model. Other non-zero codes surface the message to the user and let the call continue.

Claude Code workflows

Which practice keeps a long Claude Code session productive?

- Pasting the previous session's transcript at the start so no earlier decision is lost
- Keeping one session open so the model keeps every file it has read
- Clearing or compacting between unrelated tasks and re-briefing the next task
- Disabling hooks mid-session so tool calls complete with less overhead

Check answer

### Show answer

Answer: Clearing or compacting between unrelated tasks and re-briefing the next task. Fresh context per task keeps attention on what matters. Pasting transcripts or holding every file read fills the window with material the next task does not need.

Claude Code workflows

What should a team review when a Claude Code change is opened as a pull request?

- The test output only, because a green suite proves the change is correct
- The diff, the tests it ran, and whether the scope matched the request
- Whether the CLAUDE.md conventions were followed, with the diff left to CI
- The commit message and the model version, since the diff itself was generated

Check answer

### Show answer

Answer: The diff, the tests it ran, and whether the scope matched the request. Review automated changes like any other: the diff, the evidence, and the scope. A green suite does not prove the change did what was asked.

Claude Code workflows

Which is the right place for a rule like 'never edit files under vendor/'?

- A README section, since Claude Code reads project documentation before it edits
- CLAUDE.md for guidance plus a hook or permission deny rule for enforcement
- A comment at the top of each vendored file saying the file is not to be edited
- A dedicated subagent that owns vendor/ and rejects edit requests from the main session

Check answer

### Show answer

Answer: CLAUDE.md for guidance plus a hook or permission deny rule for enforcement. Guidance plus enforcement: CLAUDE.md explains the rule and a deny rule or hook makes it hold. File comments and READMEs are only read if Claude happens to open them.

Claude Code workflows

How do subagents help with a large migration in Claude Code?

- They share the main session's context, so every slice sees the same file history and the same earlier decisions
- They run without tools, so they can plan slices while the main session performs the edits
- They bypass the test suite for each slice so the migration completes faster
- Each handles a bounded slice in its own context and returns a summary, keeping the main session coherent

Check answer

### Show answer

Answer: Each handles a bounded slice in its own context and returns a summary, keeping the main session coherent. Bounded slices with summaries back keep the coordinator's window clean. Subagents have separate contexts and can use tools; sharing context is the problem they solve.

Prompt engineering

Which instruction most improves factual grounding when documents are provided?

- 'You are a careful analyst who values accuracy above all else in every answer you give'
- 'Be concise and accurate, and avoid speculation unless the user asks for it'
- 'Combine the documents with your own knowledge and give the most complete answer'
- 'Answer only from the provided documents and cite the passage; if it is not there, say so'

Check answer

### Show answer

Answer: 'Answer only from the provided documents and cite the passage; if it is not there, say so'. Explicit grounding plus a permitted 'not found' path is what stops the model filling gaps. A persona of an accurate analyst sets tone but gives the model no rule for missing facts.

Prompt engineering

A prompt must produce output in a strict template across thousands of runs. Which combination is strongest?

- A detailed persona plus a high temperature so the model stays engaged across runs
- Ten varied examples with no explicit template, so the model infers the pattern
- A precise template, one or two examples, and schema enforcement where possible
- A long narrative description of the task that explains why the template matters

Check answer

### Show answer

Answer: A precise template, one or two examples, and schema enforcement where possible. Specification, examples, and enforcement. Examples alone leave the model to infer the template, and varied examples pull output in different directions.

Prompt engineering

What is the drawback of stuffing every possible rule into one system prompt?

- The model treats later rules as higher priority, so the early rules get ignored
- Rules compete and get missed; prioritize, structure, and test which ones matter
- Longer system prompts break prompt caching, so each run pays full price for the rules
- There is no real drawback as long as the rules are numbered and grouped by topic

Check answer

### Show answer

Answer: Rules compete and get missed; prioritize, structure, and test which ones matter. More rules is not more adherence; rules compete for attention. A long stable system prompt caches well, so caching is not the drawback.

Prompt engineering

When should you show the model a negative example (what not to do)?

- When a specific failure keeps recurring and a positive example alone has not fixed it
- Only as a last resort after temperature and max_tokens adjustments have both failed to help
- In every prompt, paired with each positive example so the contrast is explicit
- Only in the system prompt, since negatives in the user turn are treated as content

Check answer

### Show answer

Answer: When a specific failure keeps recurring and a positive example alone has not fixed it. Targeted negatives address stubborn failure modes. Pairing a negative with every positive adds noise and can draw attention to the wrong behavior.

Prompt engineering

Which is the best way to get the model to ask a clarifying question instead of guessing?

- Include examples of confident guesses marked as wrong so the model learns to avoid them in similar cases
- Add a persona of a cautious consultant who checks with the client before acting
- Instruct it to ask when a required detail is missing, and define what counts as required
- Lower the temperature so the model is less willing to commit to an uncertain answer

Check answer

### Show answer

Answer: Instruct it to ask when a required detail is missing, and define what counts as required. Define the condition for asking. A cautious persona shifts tone but does not tell the model which details are required.

Prompt engineering

A summarization prompt is losing important numbers. What helps?

- Ask for a shorter summary so the model focuses on only the most important facts
- Instruct it to preserve all figures, dates, and names verbatim, with an example
- Increase max_tokens so the summary has room for every number in the source
- Switch to bullet points, since lists make omitted figures easier for a reader to spot

Check answer

### Show answer

Answer: Instruct it to preserve all figures, dates, and names verbatim, with an example. Name what must survive and show it. Extra output room does not tell the model that figures matter, and a shorter summary drops more of them.

Prompt engineering

What does 'role prompting' do well and what does it not fix?

- It sets tone and perspective; it does not fix missing instructions, data, or ambiguous tasks
- It fixes ambiguous tasks by giving the model a viewpoint from which to resolve them
- It replaces the need for examples, since a strong persona implies the expected output
- It improves factual accuracy by activating domain expertise the model would not otherwise use

Check answer

### Show answer

Answer: It sets tone and perspective; it does not fix missing instructions, data, or ambiguous tasks. Personas shape voice, not correctness. A role does not supply missing data or resolve an ambiguous task definition.

Prompt engineering

Which prompt is more testable?

- 'Write a summary of at most 120 words with one sentence per section, listing every decision and owner'
- 'Summarize this document in the style of our best analyst, keeping the reader's needs in mind'
- 'Write a thorough, well-organized summary that a busy executive would find genuinely useful and complete'
- 'Produce a high-quality summary and double-check it for completeness before you answer'

Check answer

### Show answer

Answer: 'Write a summary of at most 120 words with one sentence per section, listing every decision and owner'. Concrete constraints can be checked: word count, sentence count, decisions and owners. 'Useful' and 'high-quality' cannot be scored without a rubric.

Prompt engineering

You want the model to output only 'APPROVE' or 'REJECT'. What is the most reliable approach?

- Constrain the output through an enum in a tool schema, or prefill and instruct with examples
- Add a strict reviewer persona and ask the model to be decisive in every answer it gives
- Raise max_tokens and instruct the model to end its response with the final label on its own line
- Ask the question twice and accept the label only when both responses agree with each other

Check answer

### Show answer

Answer: Constrain the output through an enum in a tool schema, or prefill and instruct with examples. Enforce the label set with a schema or prefill. A label on the last line still needs parsing and can be preceded by unwanted text.

Prompt engineering

How should a prompt handle ambiguous user requests in a customer-facing product?

- Instruct the model to answer every plausible interpretation in turn so the user can pick the right one
- Instruct the model to state its interpretation or ask one clarifying question, per product policy
- Instruct the model to choose the most common interpretation and answer with confidence
- Instruct the model to decline ambiguous requests and direct the user to a support form

Check answer

### Show answer

Answer: Instruct the model to state its interpretation or ask one clarifying question, per product policy. Explicit ambiguity handling, matched to product policy. Answering every interpretation is long and confusing, and confident guesses hide the ambiguity from the user.

Prompt engineering

Which change is likely to reduce hallucinated tool parameters?

- Fewer examples in the tool description, so the model relies on the schema alone
- A system prompt persona of a careful engineer who double-checks every parameter before calling a tool
- Examples of correct calls in the tool description and a schema with enums and required fields
- Longer output budgets so the model has room to reason before it commits to a call

Check answer

### Show answer

Answer: Examples of correct calls in the tool description and a schema with enums and required fields. Show correct calls and constrain the schema. A careful persona does not tell the model which values are valid.

Prompt engineering

What is a reasonable way to iterate on a prompt with a team?

- Freeze the prompt after launch and route new requirements to a separate prompt
- Versioned prompts, a shared eval set, and review of score changes before deploy
- Each teammate tests edits in their own environment and merges whichever version feels best
- One owner edits the production prompt by feel and watches user feedback for regressions

Check answer

### Show answer

Answer: Versioned prompts, a shared eval set, and review of score changes before deploy. Treat prompts like code: versioned, evaluated on a shared set, and reviewed. Merging by feel has no shared measure of better.

Tool design and MCP

A tool takes 20 optional parameters and the model rarely sets them correctly. Best redesign?

- Move the parameter guidance into the system prompt so it is not lost in the schema
- Keep the tool but add a validation step that rejects calls with unset parameters
- Make every parameter required so the model has to think about each one explicitly
- Split into focused tools with few required parameters and sensible defaults

Check answer

### Show answer

Answer: Split into focused tools with few required parameters and sensible defaults. Narrow tools with few parameters are easier to call correctly. Making all 20 required makes every call harder, and validation catches errors without reducing them.

Tool design and MCP

What should a search tool return to be most useful to an agent?

- The raw response from the underlying search service, unmodified
- A count of matches with a suggestion to narrow the query whenever the count is above a threshold
- Every matching record in full, so the agent never needs a second call
- A compact ranked list with identifiers and snippets, plus a way to fetch details

Check answer

### Show answer

Answer: A compact ranked list with identifiers and snippets, plus a way to fetch details. Compact, actionable, and fetchable. Full records flood the context, and a count alone gives the agent nothing to act on.

Tool design and MCP

Which MCP capability lets a server suggest a full workflow prompt to the client?

- Resources, which expose text or data the client can load into context by URI when it needs it
- Sampling, which lets the server request a completion from the client's model
- Prompts, which are reusable templates the client can present for the user to invoke
- Tools, which return a suggested plan the client then executes step by step

Check answer

### Show answer

Answer: Prompts, which are reusable templates the client can present for the user to invoke. Prompts are reusable templates exposed by servers. Resources expose data, tools perform actions, and sampling runs in the other direction.

Tool design and MCP

A tool's description says 'Use this for anything related to customers'. Why is that weak?

- It is too broad: it invites misuse and overlaps with other tools; describe the job and when not to use it
- It is phrased as an instruction to the model, when descriptions should be neutral statements of what the tool does and returns
- It fails to list the parameter types, so the model cannot construct a valid call
- It is too short; a description should run to several paragraphs to cover every case

Check answer

### Show answer

Answer: It is too broad: it invites misuse and overlaps with other tools; describe the job and when not to use it. Specificity guides selection. Parameter types belong in the schema, and length alone does not make a description useful.

Tool design and MCP

When should a tool return an error rather than a best-effort result?

- Only when the model has asked for strict mode; otherwise return a best-effort result silently
- When the input is invalid or the operation cannot complete correctly, with a message saying what would fix it
- Only on timeouts and network failures; for bad input, return the closest valid result with a note explaining the substitution
- Whenever the operation partially succeeds, so the model retries the whole call from scratch

Check answer

### Show answer

Answer: When the input is invalid or the operation cannot complete correctly, with a message saying what would fix it. Honest errors beat silent partials, and an actionable message lets the model correct the call. Returning the closest valid result for bad input hides the problem from the model.

Tool design and MCP

Which is true of tool_result blocks?

- They replace the assistant's tool_use block in the conversation history
- They are returned in a user turn, matched to the tool_use block's id
- They are placed in the system prompt so the model sees them on every later turn
- They must contain valid JSON so the model can parse them reliably

Check answer

### Show answer

Answer: They are returned in a user turn, matched to the tool_use block's id. Results come back in the next user turn, matched by id to the tool_use block, which stays in the history. Content can be text, JSON, or images; JSON is not required.

Tool design and MCP

How do you keep an MCP server safe when it exposes both read and write operations?

- Trust the model's judgment on each call but log every write so problems can be traced and reversed afterward
- Separate read and write tools, require authentication, and gate writes with confirmation or scopes
- Combine reads and writes in one tool with a mode flag so the model sees fewer tools
- Expose write operations only over stdio, since local transport limits who can call them

Check answer

### Show answer

Answer: Separate read and write tools, require authentication, and gate writes with confirmation or scopes. Separate the tools, authenticate callers, and gate writes. A mode flag makes it easier to write by accident, and logging after the fact does not prevent damage.

Tool design and MCP

A model keeps calling a tool that is not relevant to the task. Which fix comes first?

- Delete the tool from the set, since a tool that gets misused is a net cost
- Lower the temperature so the model becomes more conservative about tool selection
- Add a system prompt rule that lists the exact tasks the tool may be used for and the tasks it may not
- Tighten its description with 'when not to use' guidance and check for overlap with other tools

Check answer

### Show answer

Answer: Tighten its description with 'when not to use' guidance and check for overlap with other tools. Descriptions drive selection, so fix the description and any overlap first. A system prompt rule can help but is further from the point of choice than the tool's own description.

Tool design and MCP

Why include units and formats in parameter descriptions?

- They let the model skip the schema and construct calls from the description alone
- So the model supplies values the tool can parse, avoiding silent errors
- They are mainly for the humans who review tool calls in the logs
- The MCP specification requires units in every numeric parameter description

Check answer

### Show answer

Answer: So the model supplies values the tool can parse, avoiding silent errors. Precision prevents malformed calls, such as seconds passed where milliseconds were expected. Descriptions are model-facing, and the schema still applies.

Tool design and MCP

What is a good reason to expose a resource instead of a tool?

- The data is read-only reference material the client can load on demand by URI
- Loading the data has side effects that should be visible in the audit log
- Access to the data requires a human approval step before it is released
- The data changes every second and the client needs the freshest possible copy

Check answer

### Show answer

Answer: The data is read-only reference material the client can load on demand by URI. Read-only reference data suits resources. Side effects and approval gates are tool concerns.

Context management

A prompt is 150k tokens and quality is uneven. What is the first question to ask?

- Whether a newer model with a larger context window would handle the same 150k tokens more evenly
- Whether raising max_tokens would give the model more room to work through the material
- How much of that context the task needs, and whether retrieval or summarization could replace the bulk
- Whether the prompt has a clear persona so the model knows how to weigh the material

Check answer

### Show answer

Answer: How much of that context the task needs, and whether retrieval or summarization could replace the bulk. Budget the context from what the task needs; retrieval or summarization usually replaces the bulk. A larger window carries the same irrelevant material, and max_tokens affects output, not input.

Context management

What goes in a memory file that an agent maintains across sessions?

- Every tool result, so the agent can avoid repeating calls it already made
- Decisions, open items, and pointers to sources, kept short and current
- Full transcripts of each session so nothing is lost between runs
- Credentials and endpoints the agent needs, so it can start without setup

Check answer

### Show answer

Answer: Decisions, open items, and pointers to sources, kept short and current. Durable, compact state. Transcripts and tool results bloat the file, and credentials belong in secure configuration.

Context management

Which practice supports prompt caching across many users of the same app?

- Randomize the order of instructions so no single prefix dominates the cache
- Disable the system prompt and pass all instructions in the first user message
- Put each user's profile at the start of the system prompt so it is cached per user
- A shared stable prefix, with user-specific content after the cache breakpoint

Check answer

### Show answer

Answer: A shared stable prefix, with user-specific content after the cache breakpoint. Shared prefix first, user content after. Putting the profile first makes every user's prefix different, so nothing is shared.

Context management

How should long tool outputs be handled in an agent loop?

- Kept in full, since dropping any part of a tool result risks losing something the task needs
- Moved into the system prompt so they are cached and do not consume the conversation budget
- Deleted after the turn that used them, since the model has already acted on them
- Truncated or summarized to the essentials, keeping identifiers so details can be re-fetched

Check answer

### Show answer

Answer: Truncated or summarized to the essentials, keeping identifiers so details can be re-fetched. Keep the essentials and the pointers. Full outputs crowd out later reasoning, and deleting them outright loses details a later step may need.

Context management

What is a reasonable trigger for compaction in a long session?

- Approaching the context budget or finishing a subtask
- Only when a tool call fails, since errors usually mean the context is polluted
- Only when the user asks, since the model cannot judge when to compact
- After every message, so the window stays as small as possible

Check answer

### Show answer

Answer: Approaching the context budget or finishing a subtask. Compact at natural boundaries or near limits. Compacting every message loses detail constantly for no benefit.

Context management

Why can a smaller, curated context beat a larger one?

- Less irrelevant material means better attention to what matters, alongside lower cost
- The claim does not hold; more context is better as long as it fits inside the model's window
- Models are trained on short prompts, so long prompts fall outside the distribution
- Smaller contexts are cheaper, and the cost saving is the only real difference

Check answer

### Show answer

Answer: Less irrelevant material means better attention to what matters, alongside lower cost. Relevance beats volume: irrelevant material competes for attention. Cost is a bonus, not the only difference.

Context management

An agent must reference a style guide on every task. Where does it belong?

- Pasted into each user message so it is always the most recent input
- Summarized to one line in the system prompt to save tokens
- In the stable prefix so it caches, or loaded once per session
- Returned through a tool result on the first turn of each task

Check answer

### Show answer

Answer: In the stable prefix so it caches, or loaded once per session. Stable reference content lives in the cached prefix. Pasting it into each message duplicates it and defeats caching.

Context management

What should be true of the summary you carry forward after compaction?

- It is as short as possible, ideally one sentence describing the goal
- It keeps the full tool results, since those are the hardest to reconstruct
- It restates the system prompt so the instructions survive the reset
- It preserves task definition, decisions, exact values, and next steps

Check answer

### Show answer

Answer: It preserves task definition, decisions, exact values, and next steps. Preserve state, drop chatter. The system prompt persists on its own, and a one-line goal loses the decisions and values later steps need.

Context management

Which is a symptom of context overflow rather than a bad prompt?

- The model asks for information that was never provided in the conversation
- Late-conversation instructions ignored and earlier details contradicted
- Answers that are shorter than usual and skip the requested formatting
- Slower responses and higher cost per turn as the conversation grows

Check answer

### Show answer

Answer: Late-conversation instructions ignored and earlier details contradicted. Overflow shows as lost or contradicted details. Asking for missing information is a sign of too little context, and slower responses are a cost symptom, not a quality one.

Context management

How do subagents relate to context budgets?

- They share the coordinator's budget, so each subagent reduces what is left for the rest
- Each has its own budget, so heavy subtasks do not consume the coordinator's window
- They have no budget of their own and rely on the coordinator to compact for them
- They double the coordinator's window, since each subagent adds its own context to it

Check answer

### Show answer

Answer: Each has its own budget, so heavy subtasks do not consume the coordinator's window. Separate budgets per subagent; only the returned summary lands in the coordinator's window.

Agentic architecture

A nightly job classifies 50,000 support tickets into one of eight categories. Which architecture is right?

- One agent with the full ticket export in context so it can spot category patterns
- An autonomous agent per ticket with tools to look up the customer's history before deciding
- An orchestrator that spawns one classifier subagent per category and lets them vote on each ticket
- A batch workflow with a fixed prompt and schema-constrained output, plus a sampled human audit

Check answer

### Show answer

Answer: A batch workflow with a fixed prompt and schema-constrained output, plus a sampled human audit. Fixed labels, huge volume, no branching: a batch workflow with constrained output and an audit sample. An agent per ticket adds cost and variance to a task with no open-ended path.

Agentic architecture

Which question best decides whether a task needs an agent at all?

- Can the steps be written down in advance, or does the path depend on what the model finds along the way?
- Is the budget large enough to absorb the extra tokens that an agent loop consumes?
- Does the task involve tools, since tool use is what distinguishes an agent from a prompt?
- Is the model capable enough to complete the task end to end without a human checking each intermediate step?

Check answer

### Show answer

Answer: Can the steps be written down in advance, or does the path depend on what the model finds along the way? Agents are for open-ended paths; predictable steps are workflows or code. Workflows can use tools too, so tool use alone does not decide it.

Agentic architecture

An agent's outputs are correct but users complain it 'never explains why'. What is the low-cost design fix?

- Enable extended thinking and return the thinking blocks to users as the explanation
- Ask for a brief rationale alongside the structured result, kept separate from the machine-readable fields
- Add a second model call that reads the result and writes an explanation for the user
- Drop the structured output and return prose so the reasoning and the answer arrive together in one readable block

Check answer

### Show answer

Answer: Ask for a brief rationale alongside the structured result, kept separate from the machine-readable fields. A separate rationale field gives users the why without breaking parsing. Thinking blocks are not written for end users, and a second call doubles cost for something the first call can produce.

Agentic architecture

Two subagents produce partial reports and the coordinator must merge them into one document. What protects merge quality?

- A fixed output schema for the partials so merging is deterministic, then one editing pass for coherence
- Run the two subagents sequentially so the second one extends the first one's document
- Let the coordinator read both partials in full and improvise a merged document
- Have each subagent read the other's draft before finishing so the two partials already agree on structure and content

Check answer

### Show answer

Answer: A fixed output schema for the partials so merging is deterministic, then one editing pass for coherence. Structured partials make the merge reliable; a final pass restores flow. Cross-reading drafts couples the workers and loses the parallelism that made the split worthwhile.

Agentic architecture

Which is the right response when an agent's evaluator step disagrees with a human reviewer 30% of the time?

- Average the evaluator's score with the human's so neither judgment dominates the outcome
- Trust the evaluator, since consistent model judgments beat a single reviewer's opinion
- Calibrate the evaluator against the human labels, refine its criteria, and keep the human until agreement is high
- Replace the evaluator with a second human reviewer, since a 30% disagreement rate shows model grading does not work here

Check answer

### Show answer

Answer: Calibrate the evaluator against the human labels, refine its criteria, and keep the human until agreement is high. Evaluators earn autonomy through measured agreement. Averaging hides the disagreement instead of resolving it, and abandoning the evaluator throws away a fixable component.

Agentic architecture

A client wants the agent to run overnight unattended. Which capability must exist first?

- Extended thinking on every turn so the agent reasons carefully without supervision
- A hard stop on cost and turns plus alerting, so an unattended run cannot spiral
- A dashboard showing live progress so the team can check on it in the morning
- A larger model, so the run makes fewer mistakes when nobody is there to correct it

Check answer

### Show answer

Answer: A hard stop on cost and turns plus alerting, so an unattended run cannot spiral. Unattended means bounded and observable. A dashboard shows a spiral but does not stop it.

Agentic architecture

What does 'fail closed' mean for an agent that hits an unexpected error?

- Stop the action, record the state, and hand off to a person or a defined fallback
- Retry the failing step with a different tool until one of them succeeds
- Continue with the most likely interpretation and flag the guess in the final report
- Restart the whole task from the beginning with a fresh context and the same inputs

Check answer

### Show answer

Answer: Stop the action, record the state, and hand off to a person or a defined fallback. Fail closed protects against acting on bad state. Continuing on a guess is failing open, and blind retries can repeat a harmful action.

Agentic architecture

An orchestrator-workers design is producing repeated work across workers. Likely cause?

- Too few workers, so each one is covering more of the task than it can hold in context
- Overlapping subtask briefs; the coordinator should partition the task so each worker's scope is disjoint
- Missing evaluator step, so duplicate outputs are never caught before the merge
- The workers share one context window, so each one sees the others' progress and repeats it in its own output

Check answer

### Show answer

Answer: Overlapping subtask briefs; the coordinator should partition the task so each worker's scope is disjoint. Disjoint scopes prevent duplicate effort. Workers have separate contexts, and an evaluator would catch duplicates after the wasted work rather than prevent them.

Agentic architecture

Which metric would you add to detect that an agent is 'succeeding' by giving up early?

- Task completion checked against explicit acceptance criteria, not the model reporting done
- Tool calls per task, since an agent that stops early makes fewer calls than expected
- Latency per task, since early exits finish faster than runs that do the whole job
- Average tokens per task, since a run that gives up early uses noticeably fewer tokens than a full run

Check answer

### Show answer

Answer: Task completion checked against explicit acceptance criteria, not the model reporting done. Verify completion against criteria, not self-report. Token, call, and latency counts are proxies that an efficient run and an early exit can share.

Agentic architecture

A workflow needs a human to approve step three only when the amount exceeds a threshold. How do you model it?

- Instruct the model to decide when the amount seems high enough to ask a person
- Require approval on every run of step three, since a threshold check adds complexity
- A conditional gate in the workflow that routes to a human queue when the condition holds
- Have an evaluator model review step three's output and escalate whenever the amount looks risky

Check answer

### Show answer

Answer: A conditional gate in the workflow that routes to a human queue when the condition holds. Conditional gates are code, not model judgment. The threshold is known, so an evaluator's opinion adds variance where a comparison would do.

Agentic architecture

Which practice keeps agent behavior reproducible enough to debug?

- Logging the exact prompts, tool inputs and outputs, and model settings per step
- Using the largest model, since stronger models behave more predictably
- Turning off prompt caching so each step is computed fresh from the raw prompt
- Setting temperature to zero, which makes each run identical for the same input and settings

Check answer

### Show answer

Answer: Logging the exact prompts, tool inputs and outputs, and model settings per step. Reproduction needs the full record. Temperature zero does not guarantee identical outputs and does not tell you what the tools returned.

Agentic architecture

A stakeholder asks why the agent needs a 'planning' step that costs extra tokens. Best answer?

- It makes the model look more deliberate, which builds stakeholder confidence in the output even when the plan is not followed
- The Agent SDK requires a planning turn before any tool call can be executed in a session
- Plans are cached as part of the prompt prefix, so every later turn in the same run costs less per token than the first
- On multi-step tasks a plan cuts wasted tool calls and lets people review intent before actions, usually saving more than it costs

Check answer

### Show answer

Answer: On multi-step tasks a plan cuts wasted tool calls and lets people review intent before actions, usually saving more than it costs. Plans cut thrash and enable review of intent before side effects. Nothing in the SDK requires a plan, and a plan in the conversation is not a cached prefix.

Claude Code workflows

A team wants Claude Code to follow its commit message convention every time. Which approach is reliable?

- State the convention in CLAUDE.md with an example, and validate with a hook on commit
- Delegate all commits to a subagent whose prompt contains the convention
- Tell Claude Code once at the start of the session and rely on it for the rest of the work
- Let Claude Code infer the convention from the existing git log before it commits

Check answer

### Show answer

Answer: State the convention in CLAUDE.md with an example, and validate with a hook on commit. Guidance plus enforcement. Inferring from the log works until the log has inconsistent history, and a chat instruction does not survive the session.

Claude Code workflows

Which is a good reason to use headless Claude Code inside a GitHub Action?

- Exploring an unfamiliar codebase, since the runner has a clean checkout to learn from
- Pair programming on a feature branch, with the Action re-running after every push
- Repeatable, reviewable automation such as summarizing a PR, with a fixed tool allow list
- Interactive debugging of a failing build, where the developer talks to Claude in the CI logs

Check answer

### Show answer

Answer: Repeatable, reviewable automation such as summarizing a PR, with a fixed tool allow list. Headless suits repeatable, bounded jobs with a fixed allow list. Debugging and exploration need a person in the loop.

Claude Code workflows

A hook blocks a command but Claude Code keeps retrying variations. What is missing?

- A stricter permission rule that denies the Bash tool entirely for the session
- A longer CLAUDE.md section repeating the rule the hook is enforcing
- A clear block message that says what is disallowed and what to do instead
- A second hook on the Stop event that ends the turn after the first block

Check answer

### Show answer

Answer: A clear block message that says what is disallowed and what to do instead. Blocks need explanations to redirect behavior. Without a reason the model treats the block as a transient failure and tries again.

Claude Code workflows

What is the difference between a slash command and a skill in practice?

- Slash commands need an MCP server behind them; skills run entirely from Markdown
- Skills run in a separate subagent context by default; slash commands run inside the main session with its full history
- Slash commands are built in; skills are only available through installed plugins
- A slash command is a reusable prompt you invoke; a skill packages a procedure with instructions and supporting files

Check answer

### Show answer

Answer: A slash command is a reusable prompt you invoke; a skill packages a procedure with instructions and supporting files. Commands are prompts; skills are packaged procedures with their own files. Neither needs an MCP server, and both can be project-defined.

Claude Code workflows

Which permission stance fits a developer's laptop versus a shared CI runner?

- Allow everything in CI since nobody is there to answer prompts, and deny most on the laptop
- The same rules in both, so behavior is predictable regardless of where it runs
- Deny all writes in both and let a human apply the changes Claude proposes
- Interactive approvals on the laptop; a narrow pre-approved allow list with no prompts in CI

Check answer

### Show answer

Answer: Interactive approvals on the laptop; a narrow pre-approved allow list with no prompts in CI. Human present versus not present: approvals where someone can answer, a narrow allow list where nobody can. Allowing everything in CI is the opposite of what an unattended runner needs.

Claude Code workflows

Claude Code keeps reading the same large log file into context on every task. Fix?

- A CLAUDE.md note to grep the log for specific patterns rather than reading it whole, or a tool that returns matches
- Increase the session's context budget so the full log fits without truncation each time
- Compact the session after each read so the earlier copies of the log leave the context before the next task starts
- Move the log's contents into the project CLAUDE.md so it is loaded once at startup and cached

Check answer

### Show answer

Answer: A CLAUDE.md note to grep the log for specific patterns rather than reading it whole, or a tool that returns matches. Targeted retrieval over bulk reads. Compaction removes the copies after the cost has been paid, and putting the log in CLAUDE.md loads it on every session.

Claude Code workflows

Which statement about CLAUDE.md scope is correct?

- CLAUDE.md is read only from the home directory, so project rules go in settings.json
- Files can live at the project root and in subdirectories, applying to work in those areas
- One CLAUDE.md file per repository is allowed, and it must sit at the repository root
- Subdirectory CLAUDE.md files replace the root file entirely when Claude works in that area

Check answer

### Show answer

Answer: Files can live at the project root and in subdirectories, applying to work in those areas. Scoped memory files per area, layered with the root file rather than replacing it.

Claude Code workflows

What should a team do before letting Claude Code run database migrations in a shared environment?

- Ask Claude Code to review the migration SQL itself for mistakes before running it against the database
- Disable hooks for the migration step so nothing interrupts a long-running command
- Grant the Claude Code process admin rights so the migration cannot fail on permissions
- Gate the migration command behind approval, run it against a staging copy first, and log the run

Check answer

### Show answer

Answer: Gate the migration command behind approval, run it against a staging copy first, and log the run. Irreversible actions get gates and rehearsal. Self-review by the same model is weaker than a staging run and a human approval.

Claude Code workflows

A developer asks Claude Code to 'make the tests pass' and it edits the tests to always pass. What prevents this?

- Removing the test files from the working tree during the task so only the source files are editable by the model
- Explicit instructions that tests define behavior and must not be weakened, plus review of test diffs
- A longer timeout, so the model has time to fix the code rather than the tests
- Running in plan mode so the model proposes edits but never applies them

Check answer

### Show answer

Answer: Explicit instructions that tests define behavior and must not be weakened, plus review of test diffs. State the constraint and review test changes. Plan mode stops all edits, including the fix that was asked for.

Claude Code workflows

When is a subagent overkill?

- For parallel research across several independent parts of the codebase
- For a one-line lookup the main session can answer directly
- For a large investigation that would fill the main session with file contents
- For isolating a noisy tool's output away from the main conversation

Check answer

### Show answer

Answer: For a one-line lookup the main session can answer directly. Delegate for scope and isolation, not trivia. The other three are the cases subagents exist for.

Prompt engineering

Which is the most reliable way to keep a chatbot on topic?

- Lower the temperature so the model is less likely to wander from the topic
- State the allowed scope and the exact behavior for out-of-scope requests, with an example refusal
- Ask it in the system prompt to stay focused and professional throughout the conversation and avoid tangents
- Limit max_tokens so long off-topic answers are cut off before they finish

Check answer

### Show answer

Answer: State the allowed scope and the exact behavior for out-of-scope requests, with an example refusal. Define scope and the off-scope behavior. 'Stay focused' gives the model no definition of the boundary.

Prompt engineering

A prompt uses the word 'summarize' but the stakeholder wants an executive brief with decisions and risks. What is the fix?

- Keep 'summarize' but add 'good' and 'executive' as qualifiers to signal the audience
- Add a persona of a chief of staff so the model understands who the reader is
- Replace the vague verb with the required sections and length, plus an example brief
- Move to a larger model, since executive briefs need stronger reasoning than summaries

Check answer

### Show answer

Answer: Replace the vague verb with the required sections and length, plus an example brief. Name the sections and show an example. A persona hints at the reader but does not say what a brief must contain.

Prompt engineering

What is the purpose of asking the model to plan before it writes a long document?

- Faster generation, since the model writes prose more quickly from an outline
- A structure to check and steer before tokens are spent on prose
- A longer output, since the plan and the document are both returned
- Fewer examples needed, since the plan takes the place of a sample document

Check answer

### Show answer

Answer: A structure to check and steer before tokens are spent on prose. Plan first, then write against the plan. The gain is steerability, not speed.

Prompt engineering

Which instruction helps most when the model must handle inputs in several languages?

- State the expected input languages and the required output language explicitly
- Tell the model it is multilingual and let it match whatever language the user writes in
- Instruct the model to translate everything to English internally before answering
- Provide one example conversation in each language the product supports

Check answer

### Show answer

Answer: State the expected input languages and the required output language explicitly. Explicit language handling removes the guess about which language to answer in. Matching the user's language is one policy, but it needs to be stated, not assumed.

Prompt engineering

You need consistent scoring of essays on a 1 to 5 rubric. What makes the prompt reliable?

- Extended thinking so the model weighs each essay carefully before it commits to a score
- The rubric spelled out per score level with an example essay at two or three levels
- A one-line instruction to score from 1 to 5, with temperature set to zero
- A persona of a strict but fair teacher with twenty years of grading experience

Check answer

### Show answer

Answer: The rubric spelled out per score level with an example essay at two or three levels. Anchored rubrics with examples. Temperature zero makes the scores repeatable but not calibrated.

Prompt engineering

The model returns Markdown when you need plain text for an SMS. Simplest fix?

- Instruct plain text with no formatting, show an example, and validate before sending
- Switch to a smaller model, since smaller models use less formatting by default
- Ask for the message twice and send whichever version contains fewer formatting characters
- Strip Markdown syntax in code after generation and accept the occasional artifact

Check answer

### Show answer

Answer: Instruct plain text with no formatting, show an example, and validate before sending. Specify, exemplify, validate. Stripping in code is a fallback, not a fix, and leaves artifacts in the message.

Prompt engineering

Why keep examples in a prompt consistent in format with the required output?

- The API validates examples against the output schema and rejects mismatches
- Consistent examples let the model skip reasoning and copy the pattern directly
- The model imitates the examples; inconsistent examples produce inconsistent output
- Consistent examples compress better, which keeps the prompt within the cache limit

Check answer

### Show answer

Answer: The model imitates the examples; inconsistent examples produce inconsistent output. Examples are templates the model imitates. The API does not validate examples, and caching does not depend on their format.

Prompt engineering

What should you do when a system prompt and a user message conflict?

- Rely on the default, since the system prompt is guaranteed to win any conflict
- Raise the temperature so the model can weigh the two instructions more flexibly
- Remove the system prompt and put all instructions in the user turn so nothing can conflict
- Design the system prompt to state precedence for the cases you care about, and test them

Check answer

### Show answer

Answer: Design the system prompt to state precedence for the cases you care about, and test them. Make precedence explicit and tested. System prompts carry weight but are not a guarantee, so the cases that matter need stating.

Prompt engineering

Which is a sign a prompt is over-specified?

- Cache hits fall because the system prompt changes with every rule added
- The model asks clarifying questions on inputs the rules already cover
- Consistent output on the eval set but higher cost per call than the team expected
- Long rule lists the model ignores while output quality drops on normal inputs

Check answer

### Show answer

Answer: Long rule lists the model ignores while output quality drops on normal inputs. Too many rules dilute the important ones. Higher cost with consistent output is a budget question, not a sign of over-specification.

Prompt engineering

How do you test a prompt change without a full eval suite yet?

- Change the prompt, the model, and the temperature together so any improvement shows clearly
- Ship the change to a small share of users and watch the support queue for complaints
- Ask the model to compare the old and new prompt and say which one it prefers
- A small fixed set of representative inputs, including edge cases, compared before and after

Check answer

### Show answer

Answer: A small fixed set of representative inputs, including edge cases, compared before and after. Small, fixed, representative. Changing several things at once means you cannot tell which change helped.

Tool design and MCP

A tool's parameters are named a, b, and c. Why does that hurt?

- The model cannot infer meaning, so it guesses; descriptive names and descriptions fix it
- It only matters if the tool has no description, since the description explains the parameters
- Single-letter names shrink the JSON payload, so this is a reasonable trade for speed
- The schema will fail validation because JSON Schema requires property names of three or more characters

Check answer

### Show answer

Answer: The model cannot infer meaning, so it guesses; descriptive names and descriptions fix it. Names carry meaning to the model. A description helps, but the model reads the schema at call time and short names give it nothing.

Tool design and MCP

Which tool response is best for a 'list orders' call that matched 5,000 orders?

- The first page with a total count and a cursor for more
- An error telling the model to narrow the query before retrying
- The total count only, with a note that details are available on request
- All 5,000 orders, so the model has everything it needs in one call

Check answer

### Show answer

Answer: The first page with a total count and a cursor for more. Paginate with a cursor and a total. Forcing a narrower query throws away a valid result, and a count alone gives the model nothing to work with.

Tool design and MCP

When should a tool call require confirmation in a Claude Code or Agent SDK setup?

- Only for reads from production systems, since reads can expose sensitive data
- When it writes, deletes, sends, or spends, until its accuracy is proven
- For every call, since the cost of asking is small compared with any wrong action
- Only when the model reports low confidence in the parameters it chose

Check answer

### Show answer

Answer: When it writes, deletes, sends, or spends, until its accuracy is proven. Side effects need gates until accuracy is measured. Confirming every call, including reads, makes the gate noise that people stop reading.

Tool design and MCP

What is the practical difference between exposing data as an MCP resource versus returning it from a tool call?

- Resources are for structured data and tools are for text, so the choice follows the payload type
- Resources require user approval before the client loads them; tool calls are executed by the model directly without a prompt
- Resources are addressable read-only data the client loads when needed; tools perform actions and return results
- Resources are faster because the client caches them; tool results are fetched fresh every time

Check answer

### Show answer

Answer: Resources are addressable read-only data the client loads when needed; tools perform actions and return results. Resources are addressable read-only data the client loads on demand; tools perform actions and return their results. Neither is defined by payload type or caching.

Tool design and MCP

A remote MCP server should identify which agent is calling. Why?

- The stdio transport requires a caller id in every request frame
- The server selects which model to use based on the calling agent
- Identified callers get their tool lists cached, which speeds up discovery
- Authorization, rate limits, and audit depend on knowing the caller

Check answer

### Show answer

Answer: Authorization, rate limits, and audit depend on knowing the caller. Identity underpins control. Model selection is the client's concern, and stdio is the transport a remote server does not use.

Tool design and MCP

An agent misuses a tool because its description was written for developers. What changes?

- Keep the developer description and add a system prompt section explaining to the model how and when to use the tool
- Move the developer notes into the parameter descriptions where the model reads them
- Rewrite it for the model: what it does, when to use it, when not to, parameter meanings, an example
- Add more parameters so the model has finer control over the tool's behavior

Check answer

### Show answer

Answer: Rewrite it for the model: what it does, when to use it, when not to, parameter meanings, an example. Descriptions are model-facing, so rewrite the description itself. A system prompt section is further from the point of selection than the tool's own text.

Tool design and MCP

How should a tool report partial success, such as 8 of 10 records updated?

- Return success, since most of the records were updated and the model can move on
- Retry the failed records silently inside the tool and return success once they complete
- Return a structured result listing what succeeded and what failed, with reasons
- Return failure so the model retries the whole batch until every record succeeds

Check answer

### Show answer

Answer: Return a structured result listing what succeeded and what failed, with reasons. Partial outcomes need detail. A blanket failure triggers a retry of the eight records that already succeeded.

Tool design and MCP

Which MCP transport suits a server that many users hit concurrently from a web app?

- Streamable HTTP, which supports remote, concurrent clients
- WebSocket only, since HTTP cannot carry the server's notifications
- A shared file system watched by the server for request files
- stdio, with one server process spawned per user session on the web host

Check answer

### Show answer

Answer: Streamable HTTP, which supports remote, concurrent clients. Remote, concurrent access is Streamable HTTP. stdio is for a local process owned by one client.

Tool design and MCP

Why keep tool schemas strict rather than accepting free-form strings?

- Strict schemas are optional in the API, so this is a style preference rather than a requirement
- Free-form strings are faster to generate, but strict schemas produce shorter code
- Free-form strings are rejected by the Messages API, so strict schemas are required
- Strict schemas let the model produce valid calls and let you validate before execution

Check answer

### Show answer

Answer: Strict schemas let the model produce valid calls and let you validate before execution. Validation before action. The API accepts string parameters; the point is that strict types catch bad calls before they run.

Context management

An agent's context contains three copies of the same document from repeated tool calls. What is the fix?

- Tell the model in the system prompt to ignore repeated documents and use the first copy
- Increase the context window so the duplicates fit alongside the rest of the task
- Deduplicate tool results and cache the document by identifier so it loads once
- Add a compaction step after every tool call so older copies are summarized away

Check answer

### Show answer

Answer: Deduplicate tool results and cache the document by identifier so it loads once. Deduplicate and cache. Asking the model to ignore copies still pays for them, and compacting every call loses detail.

Context management

What is the value of a 'scratchpad' or notes file for a long task?

- It gives the model a place to write longer prompts for itself on the next turn
- It lets tools run faster because their results are written to disk instead of context
- Durable working memory outside the window, so progress survives compaction and restarts
- It replaces the need for compaction, since the window stops growing once notes are kept

Check answer

### Show answer

Answer: Durable working memory outside the window, so progress survives compaction and restarts. External working memory that survives compaction. Notes do not stop the window from growing; they make compaction safe.

Context management

Which order helps prompt caching for a multi-tenant assistant with shared instructions?

- Shared instructions and tools first, tenant data after the breakpoint
- Tenant data in the system prompt and shared instructions in the user turn
- Tenant data first so each tenant's cache is warm from the first token
- Alternate shared and tenant content so both are covered by the cache

Check answer

### Show answer

Answer: Shared instructions and tools first, tenant data after the breakpoint. Shared prefix, tenant suffix. Tenant data first makes the prefix unique per tenant, so nothing is shared.

Context management

A workflow step needs only two fields from a large upstream result. Best practice?

- Merge the step into the upstream one so no data has to be passed between them
- Pass the whole upstream result so the step has the full context available if it turns out to need more
- Extract the two fields and pass only those, keeping an identifier to fetch more if needed
- Summarize the upstream result in prose and pass the summary to the step

Check answer

### Show answer

Answer: Extract the two fields and pass only those, keeping an identifier to fetch more if needed. Pass what the step needs plus a pointer. A prose summary may drop the exact values the step depends on.

Context management

What does compaction risk if done carelessly?

- Slower responses, since the model must re-read the summary before it can act
- Dropping exact values, identifiers, or the current task definition that later steps need
- More tool calls, since the model re-fetches everything the summary mentions
- Cache misses on the next turn, since the compacted conversation prefix no longer matches the cached one

Check answer

### Show answer

Answer: Dropping exact values, identifiers, or the current task definition that later steps need. Preserve precision-critical state. Cache misses are a real but minor cost next to losing the task definition.

Context management

An agent must consult a policy document on every decision. Which approach balances cost and accuracy?

- Keep it in the cached prefix, or retrieve the relevant section per decision
- Paste the full document into each user turn so it is always the freshest input
- Summarize it once at session start and rely on the summary for every decision
- Load it through a tool call on each decision so it never occupies the prefix

Check answer

### Show answer

Answer: Keep it in the cached prefix, or retrieve the relevant section per decision. Cached prefix or targeted retrieval. A one-time summary loses the detail decisions depend on, and pasting per turn pays full price every time.

Context management

Which is a symptom of too little context rather than too much?

- Responses slow down and cost per turn rises as the conversation grows longer
- Cache misses increase because the shared prompt prefix changes from one turn to the next as history grows
- The model asks for information it should have, or guesses at details that were never provided
- Instructions from early in the conversation are contradicted late in the conversation

Check answer

### Show answer

Answer: The model asks for information it should have, or guesses at details that were never provided. Missing inputs show as guessing or asking. Contradictions late in a conversation are the overflow symptom.

Context management

How should you size retrieval chunks for a technical manual?

- As large as the context window allows, so each retrieved chunk carries the full surrounding material of the manual with it
- One sentence each, so retrieval can match the exact line the question is asking about
- Whole chapters, since a manual's own structure already groups the related material together and keeps procedures whole
- Large enough to hold one complete idea, like a procedure or section, and small enough to keep only relevant material in context

Check answer

### Show answer

Answer: Large enough to hold one complete idea, like a procedure or section, and small enough to keep only relevant material in context. Complete ideas, minimal noise. Single sentences lose the procedure they belong to, and chapters carry mostly irrelevant material.

Context management

A coordinator agent's window is filling with subagent chatter. What is the structural fix?

- Have subagents return only structured results and keep their transcripts out of the coordinator
- Compact the coordinator's context after each subagent returns so the accumulated chatter is summarized away
- Disable logging in the subagents so their tool output is not echoed back
- Use fewer subagents so less of their output reaches the coordinator's window

Check answer

### Show answer

Answer: Have subagents return only structured results and keep their transcripts out of the coordinator. Return results, not transcripts. Compacting after the fact pays for the chatter first; fewer subagents reduces capability rather than fixing the leak.

## Drill one domain at a time

Each domain with enough questions has its own page with study notes and just that domain's questions.

- [CCAR-F Agentic architecture questions](https://youraidept.com/network/ccar-f-practice-questions/agentic-architecture) (52)
- [CCAR-F Claude Code workflows questions](https://youraidept.com/network/ccar-f-practice-questions/claude-code-workflows) (40)
- [CCAR-F Prompt engineering questions](https://youraidept.com/network/ccar-f-practice-questions/prompt-engineering) (40)
- [CCAR-F Tool design and MCP questions](https://youraidept.com/network/ccar-f-practice-questions/tool-design-and-mcp) (35)
- [CCAR-F Context management questions](https://youraidept.com/network/ccar-f-practice-questions/context-management) (33)

## How the real CCAR-F exam differs

- Questions: 60 items in 120 minutes
- Passing score: 720 on a 100–1,000 scale
- Exam fee: $125 per attempt, per the current exam guide
- Format: Proctored and closed-book, no AI assistance
- Delivered by Pearson VUE, online proctored or at a test center, with no notes and no AI assistance.

## Practice question FAQ

### Are these real CCAR-F exam questions? +

No. They are original scenario questions written from the published blueprint and Anthropic's public documentation. Reproducing exam content would violate the candidate agreement, and the real exam tests judgment on scenarios you have not seen.

### How many questions are on the real CCAR-F exam? +

60 questions in 120 minutes, proctored and closed-book, with a passing score of 720 on a 100 to 1,000 scale.

### How should I use these practice questions? +

Answer each one before revealing the explanation, then note which domain you missed. Weight your remaining study the way the blueprint weights the exam: agentic architecture 27%, Claude Code 20%, prompt engineering 20%, tools and MCP 18%, context management 15%.

### Where do I register for CCAR-F? +

Through the Anthropic Partner Academy, which requires affiliation with a Claude Partner Network organization. Independent engineers usually join a partner firm such as YAID, then schedule with Pearson VUE.

## Practice questions for the other exams

CCDV-F

### [Claude Certified Developer – Foundations](https://youraidept.com/network/ccdv-f-practice-questions)

CCAO-F

### [Claude Certified Associate – Foundations](https://youraidept.com/network/ccao-f-practice-questions)

CCAR-P

### [Claude Certified Architect – Professional](https://youraidept.com/network/ccar-p-practice-questions)

## Who wrote this

### [Matei Olaru](https://youraidept.com/about/matei-olaru)

CEO, Your AI Department

Former public-company CEO, corporate attorney, and World Bank consultant. Runs the YAID Network and the partner relationship with Anthropic.

### [Michael Greenberg](https://youraidept.com/about/michael-greenberg)

AI Product Lead, Your AI Department

AI at Google, Meta, and Samsung. Six patents. Leads member support and the certification prep guidance.

Your AI Department is a registered Claude Partner Network company. Our members sit these exams under our partner standing. Facts on this page were last checked on October 15, 2026.

## Ready to sit CCAR-F for real?

Registration needs a Claude Partner Network organization. [YAID Network](https://youraidept.com/network) members register under our partner standing and prepare with the official Partner Academy course. $149 per quarter, exam fee separate.

[Apply to join YAID ↗](https://youraidept.com/network/apply?ref=practice)[How registration works →](https://youraidept.com/network/register-for-claude-certification)