What you will be able to do
- Trace one Agent SDK agent loop from prompt to ResultMessage and spot where a harness can step in
- Fix an agent or subagent definition whose tool access depends on what the prompt asks for rather than on configuration
- Register a hook callback with the right event and matcher, and return a decision that reliably blocks or allows the action
- Say where a hook's permissionDecisionReason and systemMessage end up, and why exit code 1 does not block a tool call
- Pick the lifecycle hook that guarantees a required side effect, such as PreCompact for archiving a transcript
Key concept
Hook (deterministic interception point) — A hook is a callback your code registers on an agent lifecycle event. The SDK runs it every time that event fires, so it can block, modify or record the action no matter what the model chose to do. When a hook is the control and an instruction to the model is only guidance, the required behaviour is guaranteed.
1.The agent loop your harness drives
An Agent SDK agent runs a loop, and the code that wraps it is the only part you fully control. Claude receives the prompt along with the system prompt, tool definitions and history. It answers with text, tool calls or both. The SDK runs each requested tool and sends the results back to Claude for the next decision. The cycle repeats until Claude produces a response with no tool calls. Every part of that loop that depends on the model is a judgement the model makes. Anything that must happen on every run has to live in your options, your hooks or the code that reads the message stream.
The harness sees the run as a stream of typed messages. A SystemMessage with subtype "init" opens the session. Each content block in Claude's response arrives as its own AssistantMessage, and each tool result returns as a UserMessage. A ResultMessage closes the loop with the final text, token usage, cost and session ID. In Python you tell message types apart with isinstance(). In TypeScript you check message.type, and content blocks sit at message.message.content.
A finished loop is not necessarily a successful one. The ResultMessage carries a subtype: success means Claude finished normally. error_max_turns and error_max_budget_usd mean the run hit the maxTurns or maxBudgetUsd limit first. Neither of those carries a result field. A single-shot query() yields that error result and then raises, so wrap the loop in a try block. A few trailing system events can arrive after the result, so read the stream to the end rather than breaking as soon as the result appears. Turn limits cap runaway cost but never perform work: a run cut short by maxTurns has simply stopped. Diagnosing loops that thrash or never finish is covered in agent pattern diagnosis.
| Subtype | What happened | result field available? |
|---|---|---|
| success | Claude finished the task normally | Yes |
| error_max_turns | Hit the maxTurns limit before finishing | No |
| error_max_budget_usd | Hit the maxBudgetUsd limit before finishing | No |
| error_during_execution | An error interrupted the loop (for example, a cancelled request) | No |
Checkpoint 1 of 9· Check yourself
Your harness runs an Agent SDK agent with maxTurns set to 10. On one run Claude is still calling tools when it reaches the limit. What should the harness code that reads the message stream do?
Ending the loop does not mean the run succeeded. Hitting maxTurns produces an error_max_turns subtype with no result field, and turn limits only stop the run without doing any of the remaining work. Trailing system events can also arrive after the ResultMessage, so the harness should read the stream to the end.
“Check the subtype field to determine whether the task succeeded or hit a limit.”Source: code.claude.com
Sources1
2.Agent definitions: tool access is configuration, not instruction
The options object defines what an agent can do, and three tool settings are easy to mix up. allowed_tools / allowedTools auto-approves the tools it lists. It does not remove the others. Tools left off the list are still available, and calls to them that need approval go on to the permission mode and canUseTool. disallowed_tools / disallowedTools blocks the tools it lists, whatever the other settings say. permission_mode / permissionMode sets how much human oversight applies.
bypassPermissions also short-circuits canUseTool. Calls are approved before the callback is consulted, so the callback runs for only a handful of calls. Checks that must see every call belong in a PreToolUse hook, because hooks are evaluated before deny rules, ask rules and the mode. The full rule order is covered under least-privilege permission rules.
Subagent definitions follow the same rule. You pass them through the agents option as AgentDefinition entries. description tells Claude when to delegate, prompt sets the subagent's behaviour, tools sets what it can call, and model can override the model. A reviewer whose prompt says "never modify files" but whose tools include Edit can still edit. The prompt is advice; tools=["Read", "Grep", "Glob"] is a limit the subagent cannot exceed. Each subagent also runs in its own conversation, and only its final message returns to the parent.
| Setting | What it does | Restricts the agent? |
|---|---|---|
| allowed_tools / allowedTools | Auto-approves the listed tools; other tools remain available | No |
| disallowed_tools / disallowedTools | Blocks the listed tools regardless of other settings | Yes |
| permission_mode / permissionMode | Controls how much human oversight applies; bypassPermissions approves calls that reach it | Loosens rather than restricts |
| AgentDefinition tools | Limits a subagent to the named tools, e.g. Read, Grep, Glob | Yes, for that subagent |
| AgentDefinition prompt | Instructions and expertise for the subagent | No, it is guidance only |
Checkpoint 2 of 9· Match them up
A team is locking down an agent and its reviewer subagent. Match each setting to what it actually does to the agent's tool access.
Tap a term, then the definition that fits it.
Of these, only disallowed_tools and a subagent's tools list actually limit what can be called. allowed_tools only auto-approves the tools it lists, permission_mode can loosen oversight (bypassPermissions approves the calls that reach it), and a subagent's prompt is advice the subagent is not forced to follow.
“Tools not listed are still available, and calls to them that need approval fall through to the permission mode and canUseTool.”Source: code.claude.com
3.Registering hooks: events, matchers and callbacks
A hook registration has three parts: an event, a matcher and one or more callbacks. The hooks option takes event names such as PreToolUse as keys. Each value is an array of matchers, and each matcher pairs an optional filter pattern with the callbacks to run. When an event fires, the SDK collects the hooks registered for it, the matchers decide which ones run, and each callback that runs returns a decision.
options = ClaudeAgentOptions(
hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[my_callback])]}
)For tool hooks, the matcher is tested against the tool name and nothing else. "Bash" and "Write|Edit" are exact names. A pattern containing any other character is treated as an unanchored JavaScript regular expression, so mcp__memory__.* matches every tool from the memory server. A matcher such as "/etc/.*" is a valid regex that no tool name will ever match, so the hook never fires. To guard a path, match the file tools by name and inspect tool_input inside the callback.
async def protect_env_files(input_data, tool_use_id, context):
# Extract the file path from the tool's input arguments
file_path = input_data["tool_input"].get("file_path", "")
file_name = file_path.split("/")[-1]
# Block the operation if targeting a .env file
if file_name.lower() == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot modify .env files",
}
}
# Return empty object to allow the operation
return {}Every callback receives three arguments. The first is the input data, typed per event: PreToolUseHookInput carries tool_name and tool_input, and every input carries session_id, cwd and hook_event_name. When a hook fires inside a subagent, agent_id and agent_type are filled in. An audit hook on an orchestrator reads those fields to tell which calls a subagent made. In Python they are optional on the tool events and required on SubagentStart and SubagentStop. The second argument, the tool use ID, links the PreToolUse and PostToolUse events for one call. The third, the context, carries an AbortSignal in TypeScript and is reserved in Python.
Each matcher also accepts timeout and onFailure (on_failure in Python). By default, a callback that fails does not stop the action. Setting onFailure to "block" makes a crashed or timed-out guard block the action instead of letting it through. For a guard that has to be airtight, that setting matters as much as the deny logic.
Checkpoint 3 of 9· Fill the gap
The protect_env_files callback must run before every file write or edit, so that it can deny writes to .env files. Which matcher value completes this registration?
"PreToolUse": [HookMatcher(matcher=" ? ", hooks=[protect_env_files])]For tool hooks, the matcher is tested only against the tool name. You therefore match the Write and Edit tools by name, and the callback reads file_path from tool_input to decide whether to deny. A pattern based on a path or file name is still a valid regex, but no tool name matches it, so the hook never fires.
Source: code.claude.comCheckpoint 4 of 9· Check yourself
A PreToolUse guard denies Bash commands that touch production. Its callback calls a policy service, which sometimes hangs until the callback times out. Its matcher sets only matcher and hooks. When the callback times out, what happens to the Bash call it was guarding?
By default, a callback that fails does not stop the action, so a guard that crashes or times out lets the call through. For a guard that has to be airtight, set onFailure (on_failure in Python) to "block" on the matcher. A failed callback then blocks the action.
“What a failed callback does. Set "block" to block the action when a callback fails.”Source: code.claude.com
4.Returning a decision that actually blocks
Blocking a dangerous tool call requires the right event and the right output. Only PreToolUse runs before the tool executes and can stop it. PostToolUse fires after the call has succeeded, so a deleted directory is already gone, and asking the agent to restore it is cleanup, not prevention. UserPromptSubmit fires when a prompt is submitted and inspects that prompt. It never sees the rm -rf the model decides to run three turns later.
The reliable signal is an explicit deny. A command hook, which is a script registered in settings, blocks by exiting 2 or by printing JSON with permissionDecision: "deny". Any other non-zero exit only shows a hook error notice in the transcript, and the command runs anyway. An SDK callback has no exit code. It returns the hookSpecificOutput object shown above. Returning an empty object makes no decision, and the normal permission flow continues.
A denying hook can send text to two places. permissionDecisionReason on a deny goes to Claude as the explanation for the rejection, so the model knows why the call failed and can pick another approach. systemMessage is a top-level output field accepted on every event, and it shows a message to the user. Another top-level field, continue (continue_ in Python), decides whether the agent keeps running after the hook.
| Field | Audience | Typical use |
|---|---|---|
| permissionDecision | The SDK's permission flow | "deny" prevents the tool call; "allow" skips the permission prompt |
| permissionDecisionReason (on deny) | Claude, as the rejection reason | Explain why the call was blocked so the model can adjust |
| systemMessage | The user | Tell the operator a guard fired |
| continue / continue_ | The SDK | Decide whether the agent keeps running after this hook |
Checkpoint 5 of 9· Match them up
A PreToolUse guard has just caught an rm -rf call. Match each part of the hook's output to the effect it has.
Tap a term, then the definition that fits it.
Only a deny in permissionDecision stops the call. The reason sent with it is the text Claude reads. systemMessage goes to the user, not to Claude, and continue controls whether the agent keeps running. Returning an empty object leaves the call to the normal permission flow.
“systemMessage shows a message to the user, and continue (continue_ in Python) determines whether the agent keeps running after this hook”Source: code.claude.com
Checkpoint 6 of 9· Exam question
A PreToolUse hook denies a call and returns both permissionDecisionReason and systemMessage. Which statement describes where each value goes?
Correct answer: A — permissionDecisionReason is sent to the model as the tool rejection, while systemMessage is displayed to the user
- A. Correct. The reason tells Claude why the call was blocked so it can adapt, and systemMessage is a user-facing note, not model context.
- B. Incorrect. systemMessage is for the user, not the model; model-facing context uses additionalContext or the denial reason.
- C. Incorrect. The roles are reversed here: the decision reason is what Claude receives, and the system message is shown to the user.
- D. Incorrect. A deny only blocks that tool call; the session continues and Claude receives the rejection reason as the tool result.
Checkpoint 7 of 9· Exam question
A DevOps agent in a CI job occasionally proposes rm -rf on directories outside the workspace, even though its system prompt forbids it. Security wants a guarantee that such commands never execute. Which design provides that guarantee?
Correct answer: C — Register a PreToolUse hook on Bash that matches destructive patterns and returns a permissionDecision of deny for those commands
- A. Incorrect. The hook runs at the right point, but exit code 1 is a non-blocking error: the warning is logged and the Bash command still executes. Only exit code 2 or an explicit deny decision stops the call, so nothing is guaranteed.
- B. Incorrect. PostToolUse fires after the command has finished, so the directories outside the workspace are already deleted. Asking the agent to restore them is a reaction, not a guarantee that the command never executes.
- C. Correct. PreToolUse runs before the Bash call, and a deny permissionDecision stops it. Claude receives the reason as the tool result, so the destructive command never executes. This is enforced in code rather than by the model's judgment.
- D. Incorrect. UserPromptSubmit only sees the text a user submits. The rm -rf commands are generated by the model mid-loop, so they never appear in a prompt and this hook does not inspect or block them.
5.Choosing the lifecycle event for a required side effect
Tool calls are not the only thing that must happen every time. Archiving, auditing and cleanup also need a guarantee. Pick the event that fires at the exact moment the work is needed. Do not rely on an instruction the model may skip, or on an event that only happens to occur nearby. Events also fire at different rates. SessionStart and SessionEnd fire once per session. UserPromptSubmit, Stop and StopFailure fire once per turn. PreToolUse and PostToolUse fire on every tool call.
Stop fires when Claude finishes responding, not when compaction runs, so the history may already have been summarized before a Stop hook sees it. A lower turn limit stops the task early with error_max_turns and archives nothing. An instruction file is guidance the model may not follow, and asking a summary to be verbatim defeats compaction. PreCompact fires on every compaction request, before the summary is written, so its callback can copy the transcript to durable storage first.
| Event | Fires | Python SDK | Typical deterministic use |
|---|---|---|---|
| PreToolUse | Before a tool call executes; can block it | Yes | Deny destructive Bash commands |
| PostToolUse | After a tool call succeeds | Yes | Log file changes to an audit trail |
| UserPromptSubmit | When a prompt is submitted, before Claude processes it | Yes | Inject additional context into prompts |
| Stop | When Claude finishes responding | Yes | Save session state before exit |
| PreCompact | On a conversation compaction request | Yes | Archive full transcript before summarizing |
| SubagentStart / SubagentStop | When a subagent is spawned / finishes | Yes | Track spawning and aggregate results |
| PostCompact | After compaction completes | No | Log the generated summary |
| SessionStart / SessionEnd | Session begins / terminates | No | Initialize telemetry, clean up resources |
The Python and TypeScript SDKs support different sets of hook events, which affects how you build the harness. PreToolUse, PostToolUse, Stop, PreCompact and the subagent events work in both. SessionStart, SessionEnd, PostCompact and many newer events are TypeScript-only. A Python harness that needs session-start setup must do it in its own code before calling query(), because it cannot register a SessionStart hook.
Checkpoint 8 of 9· Match them up
An operations team lists side effects that must happen on every run of their agent. Match each lifecycle event to the requirement it is the right place to enforce.
Tap a term, then the definition that fits it.
Each requirement belongs on the event that fires at the moment the work is needed. Only PreToolUse runs early enough to block a tool call. PostToolUse runs after the call succeeds. UserPromptSubmit runs before Claude sees the prompt. Stop fires when Claude finishes responding, not when compaction runs, so archiving before a summary belongs on PreCompact.
“PreCompact | Yes | Yes | Conversation compaction request | Archive full transcript before summarizing”Source: code.claude.com
Checkpoint 9 of 9· Exam question
A long-running research agent hits context limits and the SDK auto-compacts it. Compliance requires the full pre-summary transcript to be archived each time. Which approach does this deterministically?
Correct answer: D — Register a PreCompact hook whose callback copies the transcript to durable storage before older history is summarized
- A. Incorrect. Summarization instructions steer the compactor but still produce a summary; they cannot guarantee a verbatim copy exists.
- B. Incorrect. Compaction happens mid-session when context nears its limit, and Stop fires only when execution finishes, so archives would be missed.
- C. Incorrect. This sacrifices task completion to dodge compaction instead of archiving, and long tasks would simply end with error_max_turns.
- D. Correct. PreCompact fires before compaction occurs (with a manual or auto trigger), giving code a deterministic point to archive the full transcript.
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://code.claude.com/docs/en/agent-sdk/agent-loopOfficial docs
“Claude continues calling tools and processing results until it produces a response with no tool calls.”
↩︎ The agent loop your harness drives“Check the subtype field to determine whether the task succeeded or hit a limit.”
↩︎ The agent loop your harness drives“Hit the maxTurns limit before finishing”
↩︎ The agent loop your harness drives“disallowed_tools / disallowedTools blocks listed tools, regardless of other settings.”
↩︎ Agent definitions: tool access is configuration, not instruction“You can use hooks to intercept, modify, or block tool calls before they run.”
↩︎ Key concept“Tools not listed are still available, and calls to them that need approval fall through to the permission mode and canUseTool.”
↩︎ Exam trap 1“Tools not listed are still available, and calls to them that need approval fall through to the permission mode and canUseTool.”
↩︎ Prediction - 2.
“To check the approved calls too, put your callback’s checks in a PreToolUse hook”
↩︎ Agent definitions: tool access is configuration, not instruction - 3.https://code.claude.com/docs/en/agent-sdk/subagentsOfficial docs
“Tool restrictions: subagents can be limited to specific tools, reducing the risk of unintended actions.”
↩︎ Agent definitions: tool access is configuration, not instruction - 4.https://code.claude.com/docs/en/agent-sdk/hooksOfficial docs
“For tool hooks, that field is the tool name.”
↩︎ Registering hooks: events, matchers and callbacks“agent_id and agent_type are populated when the hook fires inside a subagent.”
↩︎ Registering hooks: events, matchers and callbacks“Set "block" to block the action when a callback fails.”
↩︎ Registering hooks: events, matchers and callbacks“systemMessage shows a message to the user”
↩︎ Returning a decision that actually blocks“Archive full transcript before summarizing”
↩︎ Choosing the lifecycle event for a required side effect“For tool hooks, that field is the tool name.”
↩︎ Exam trap 2“systemMessage shows a message to the user”
↩︎ Exam trap 4“Archive full transcript before summarizing”
↩︎ Exam trap 5“What a failed callback does. Set "block" to block the action when a callback fails.”
↩︎ Checkpoint“systemMessage shows a message to the user, and continue (continue_ in Python) determines whether the agent keeps running after this hook”
↩︎ Checkpoint“PreCompact | Yes | Yes | Conversation compaction request | Archive full transcript before summarizing”
↩︎ Checkpoint - 5.https://code.claude.com/docs/en/hooksOfficial docs
“JavaScript regular expression, unanchored”
↩︎ Registering hooks: events, matchers and callbacks“Before a tool call executes. Can block it”
↩︎ Returning a decision that actually blocks“Blocking error: your hook exits 2.”
↩︎ Returning a decision that actually blocks“For "deny", shown to Claude.”
↩︎ Returning a decision that actually blocks“Deny and ask rules are still evaluated regardless of what the hook returns”
↩︎ Returning a decision that actually blocks“per turn: UserPromptSubmit, Stop, and StopFailure”
↩︎ Choosing the lifecycle event for a required side effect“Non-blocking error: your hook exits with any other code, or fails in some other way”
↩︎ Exam trap 3“Non-blocking error: your hook exits with any other code, or fails in some other way”
↩︎ Prediction