CertSafari
    Anthropic Claude Certified Developer – Foundations (CCDV-F) - December 7 onwards· Lessons

    Domain 1 · Lesson 2/24

    Agent SDK agent definitions, loops and hooks for deterministic control

    Agent SDK Construction and Hooks

    17 min read
    5.67% of exam
    5 sources
    Published 18 Nov 2026
    Docs as of 18 Nov 2026

    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.

    ResultMessage subtypes a harness must branch on
    SubtypeWhat happenedresult field available?
    successClaude finished the task normallyYes
    error_max_turnsHit the maxTurns limit before finishingNo
    error_max_budget_usdHit the maxBudgetUsd limit before finishingNo
    error_during_executionAn 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?

    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.

    Which setting actually constrains an agent
    SettingWhat it doesRestricts the agent?
    allowed_tools / allowedToolsAuto-approves the listed tools; other tools remain availableNo
    disallowed_tools / disallowedToolsBlocks the listed tools regardless of other settingsYes
    permission_mode / permissionModeControls how much human oversight applies; bypassPermissions approves calls that reach itLoosens rather than restricts
    AgentDefinition toolsLimits a subagent to the named tools, e.g. Read, Grep, GlobYes, for that subagent
    AgentDefinition promptInstructions and expertise for the subagentNo, 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.

    Sources123

    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.

    Registering a callback for every Bash tool call (Python)python
    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.

    A PreToolUse callback that reads the path from tool_input and denies writes to .env filespython
    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])]

    Checkpoint 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?

    Sources45

    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.

    Where a PreToolUse hook's output fields go
    FieldAudienceTypical use
    permissionDecisionThe SDK's permission flow"deny" prevents the tool call; "allow" skips the permission prompt
    permissionDecisionReason (on deny)Claude, as the rejection reasonExplain why the call was blocked so the model can adjust
    systemMessageThe userTell the operator a guard fired
    continue / continue_The SDKDecide 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.

    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?

    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?

    Sources54

    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.

    Lifecycle hooks and the guarantee each one gives
    EventFiresPython SDKTypical deterministic use
    PreToolUseBefore a tool call executes; can block itYesDeny destructive Bash commands
    PostToolUseAfter a tool call succeedsYesLog file changes to an audit trail
    UserPromptSubmitWhen a prompt is submitted, before Claude processes itYesInject additional context into prompts
    StopWhen Claude finishes respondingYesSave session state before exit
    PreCompactOn a conversation compaction requestYesArchive full transcript before summarizing
    SubagentStart / SubagentStopWhen a subagent is spawned / finishesYesTrack spawning and aggregate results
    PostCompactAfter compaction completesNoLog the generated summary
    SessionStart / SessionEndSession begins / terminatesNoInitialize 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.

    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?

    Sources45

    Sources

    (5)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 3.
      “Tool restrictions: subagents can be limited to specific tools, reducing the risk of unintended actions.”
      ↩︎ Agent definitions: tool access is configuration, not instruction
    4. 4.
      “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. 5.
      “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

    Ready to test yourself?

    Practise Anthropic Claude Certified Developer – Foundations (CCDV-F) - December 7 onwards in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.