CertPrep
Domain 1 · Lesson 1.2 · 5 min read

Building Agents with the Agent SDK and Hooks

Exam skillAgent SDK Construction and Hooks

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.

Build agents with the Agent SDK or your own loop so that the loop ends correctly, tool calls and results stay paired, tools and permissions match each role, and anything that must always or never happen is enforced by hooks and code rather than by prompt instructions.

What you need to know

The Claude Agent SDK gives you the same agent loop that powers Claude Code: tools, permissions, sessions, subagents, MCP and hooks. You can also write your own loop on the Messages API. Either way, the exam asks whether the agent is built correctly and whether required actions are deterministic.

A correct loop on the Messages API

messages = [{"role": "user", "content": task}]
for turn in range(MAX_TURNS):                      # safety cap
    resp = client.messages.create(model=MODEL, max_tokens=4096,
                                  system=SYSTEM, tools=TOOLS, messages=messages)
    messages.append({"role": "assistant", "content": resp.content})  # unchanged
    if resp.stop_reason != "tool_use":
        break                                       # end_turn, max_tokens, refusal...
    results = [run_tool(b) for b in resp.content if b.type == "tool_use"]
    messages.append({"role": "user", "content": results})  # every id answered, one message
  • Continue while stop_reason is tool_use; stop otherwise, and keep an iteration cap.
  • Append the assistant turn unchanged, including thinking blocks when thinking is on.
  • Answer every tool_use id with a tool_result in the next single user message. A missing or split result gives a 400 error, which retrying cannot fix.
  • Return failures as tool_result with is_error: true and a readable reason.

Agent SDK options that matter

OptionUse
allowed_tools / disallowed_toolsWhich tools run without asking, which never run
permission_modeDefault prompting, accept edits, plan, bypass
can_use_tool callbackDecide each call in code (for example, ask a human for production targets)
agentsSubagent definitions: description (when to use), prompt, own tool list
mcp_serversExternal MCP servers, or an in-process SDK server for your Python functions
setting_sourcesLoad project settings, CLAUDE.md and Skills from the filesystem; set it explicitly in headless jobs

MCP tools are named mcp__<server>__<tool>; list the exact name to allow one tool. A subagent is chosen by its description, and delegation needs the subagent tool in the main agent's allowed tools.

Hooks make actions deterministic

EventRunsTypical use
PreToolUseBefore a tool call; can deny or modify inputBlock destructive commands, redact data, require approval
PostToolUseAfter a tool callFormatting, audit logs, feedback to the model
UserPromptSubmitWhen a prompt arrivesAdd context, validate requests
StopWhen the agent tries to finishBlock stopping until tests have run
SessionStart / SessionEndSession boundariesSet-up checks, final audit writes

For Claude Code command hooks, exit code 2 blocks the action and sends stderr to the model; other non-zero codes are non-blocking errors. SDK hooks return a decision such as permissionDecision: "deny" with a reason.

In the exam

Items show agent definitions, loop code or hook configuration with a defect: a loop that never ends, unanswered tool calls, a rule left to the prompt, the wrong hook event, a missing tool permission or settings source. Pick the change that makes the required behavior deterministic. Distractors strengthen prompt wording, raise max_turns, retry 400s, or move prevention to PostToolUse.

Check your understanding

Question 1

Card numbers must be masked before text reaches the ticketing tool. Which control is reliable?

Show answer

Answer: C. Only a pre-call hook changes the input every time, before the tool runs.

Question 2

A custom loop sometimes runs forever. What is missing?

Show answer

Answer: A. The model signals completion through the stop reason; the cap is the safety net.

Question 3

A headless SDK job never uses the repo's Skills, which work in Claude Code. What should be checked first?

Show answer

Answer: D. The SDK loads filesystem configuration only from the sources it is told to use.

Apply it: Harden Juniper's refund agent

Exercise · about 20 minCase: Juniper Outdoor Co.

Juniper's Agent SDK agent has tools get_order, start_return, issue_refund and search_products. Policy: refunds over $250 need a supervisor; every refund is logged with the order number; customer card details must never reach the logs. A review found the agent sometimes ends a conversation without confirming the refund outcome to the customer.

  1. Configure tools and permissions for the agent.
  2. Choose hooks for each policy rule, naming the event.
  3. Fix the unconfirmed outcomes deterministically.
    Done when: no policy rule depends on the model remembering it.
Check your work
Show model answer

1. allowed_tools lists the four tools; issue_refund is gated by a can_use_tool callback that requests supervisor approval above $250. The search tool is read-only; no shell or file tools are allowed.

2. PreToolUse on issue_refund: deny without an approval token when the amount exceeds $250, with a reason the model can relay. PostToolUse on issue_refund: write an audit record (order number, amount, approver, result). PreToolUse on any logging or ticket tool: mask card numbers in the input.

3. A Stop hook that checks the session's last refund result was reported to the customer (for example, a flag the harness sets when the model sends the confirmation) and blocks stopping with a reason if not.

Key termsAgentic loopClaude Agent SDKHookIterationTool use

Sources