Agents and Workflows
Agent SDK Construction and Hooks
Exam objective: Building and correcting Claude Agent SDK agent definitions, custom agent loops and harnesses, and hook configurations so that required actions execute deterministically rather than at the model's discretion.
What the exam tests
Building and fixing agents so that behavior you require actually happens: Agent SDK options and agent definitions, the agent loop (SDK-managed or your own), and hook configurations. The recurring judgment is whether something may be left to the model or must be enforced by code.
Key rules
Deterministic versus discretionary. System prompts, CLAUDE.md, skills, tool descriptions and subagent descriptions steer Claude. Hooks and permission rules are enforced by the harness.
The SDK loop. Claude responds, the SDK runs requested tools, results go back, and this repeats until a response has no tool calls. The run ends with a ResultMessage: check subtype before reading result. max_turns and max_budget_usd have no default limit. A single-shot query() raises after yielding an error result.
Your own loop. On the Messages API, loop while stop_reason == "tool_use": run the tools, then send the original messages, the assistant response and a user message of tool_result blocks. Report failures with is_error: true and limit retries. The client SDK tool runner (beta) does this for you; write the loop yourself for human approval or conditional execution.
Permission order. Hooks, deny rules, ask rules, permission mode, allow rules, canUseTool. allowedTools pre-approves and does not restrict. dontAsk denies anything that would prompt. A deny rule or hook deny holds even in bypassPermissions.
Hooks. Register them under hooks by event name, each with an optional matcher and callbacks.
async def guard(input_data, tool_use_id, context):
if "rm -rf" in input_data["tool_input"].get("command", ""):
return {"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Destructive command blocked"}}
return {} # no decision: normal permission flow
options = ClaudeAgentOptions(hooks={"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[guard], on_failure="block")]})
PreToolUsecan block or rewrite (updatedInput, a full replacement insidehookSpecificOutput).PostToolUseruns after the fact: audit, addadditionalContext, or replace output.- A
Stophook can returndecision: "block"with areasonto keep Claude working; checkstop_hook_activeto avoid endless blocking. - By default a crashing
PreToolUsecallback lets the call continue to the permission flow;on_failure="block"/onFailure: "block"changes that. - Matching hooks run in parallel; the most restrictive decision applies.
- Filesystem hooks in
settings.jsonload throughsettingSourcesand run alongside programmatic ones.
Agent definitions. AgentDefinition requires description (when to use it) and prompt (its system prompt). tools limits what it has; omitted, it inherits those available to subagents. A non-fork subagent gets no parent history or parent system prompt, so context travels in the Agent tool prompt. Only its final message returns.
Configuration. With no system prompt set, the SDK uses a minimal one; the claude_code preset (plus append) must be requested. Omitting settingSources loads user, project and local settings. Custom tools are named mcp__<server key>__<tool>.
Traps
- Adding "always" or "never" to a prompt when the requirement is mandatory.
- Treating
allowedToolsas an allowlist while runningbypassPermissions. - Putting checks in
canUseToolfor calls that are already auto-approved. - Writing a file path in a
matcher; it matches tool names. - Catching errors in a guard and returning
{}: that is not a failure, so blocking on failure never triggers. - Ending a manual loop because the first content block is text.
- Setting
settingSourcesexplicitly and forgetting"project", which drops project CLAUDE.md and hooks. - Assuming session resume or fork restores files.
Decide quickly
| Situation | Choice | Why |
|---|---|---|
| Action must follow every edit | PostToolUse hook | Runs in code on the event |
| Call must never happen | PreToolUse deny or deny rule | Applies in every mode |
| Headless, fixed tool set | allowedTools + dontAsk | Everything else that would prompt is denied; read-only calls may still run |
| Human decides unresolved calls | canUseTool | Last step of the evaluation |
| Must not finish before a condition | Stop hook with block and reason | Forces continuation |
| Noisy subtask | Subagent | Context isolation |
| Non-coding agent with own persona | Custom system prompt | Preset targets coding work |
| Try another approach, keep original | Fork the session | History is copied |