Software Engineeringunpacked

Claude Agent SDK hooks and sessions: control every tool call, then resume, fork or start fresh

In the Claude Agent SDK, hooks are callbacks that run your code on agent events. A PreToolUse hook sees every tool call before it runs and can allow, deny, ask or defer it, or change its input; a PostToolUse hook sees the result and can rewrite what Claude reads. Sessions are the saved conversation: continue the latest, resume one by ID, fork it to try an alternative, or start fresh with a summary when the old tool results are stale.

Video · Claude Agent SDK Hooks: PreToolUse and PostToolUse Explained (CCAR-F) · 4:35

Video · Claude Agent SDK Sessions: Resume, Fork or Start Fresh? (--resume, fork_session) (CCAR-F) · 4:37

Hooks: your code on every agent event

Hooks are "callback functions that run your code in response to agent events". You register them in options.hooks: each key is an event, each value a list of matchers, and each matcher a list of callbacks. Two details shape everything else:

The events you'll use most are PreToolUse (before a tool call), PostToolUse (after a successful one), UserPromptSubmit, Stop, SubagentStart/SubagentStop and PreCompact. Several more exist only in TypeScript.

PreToolUse: allow, deny, ask or defer

from claude_agent_sdk import ClaudeAgentOptions, HookMatcher

async def refund_gate(input_data, tool_use_id, context):
    amount = input_data["tool_input"].get("amount", 0)
    if amount > 100:
        return {"hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": "Refunds over $100 need a person. Hand off with a summary.",
        }}
    return {}  # allow, unchanged

options = ClaudeAgentOptions(hooks={
    "PreToolUse": [HookMatcher(matcher="mcp__cogwheel-backend__issue_refund", hooks=[refund_gate])],
})
Decision Effect Who sees the reason
{} The call goes ahead unchanged Nobody: there's no reason to give
allow Skips the permission prompt (deny and ask rules still apply) Debug log only
deny The call is blocked Claude, so it can change course
ask The user must confirm The user
defer The turn ends with stop_reason: "tool_deferred", so the call can be resumed later Debug log only

When several hooks answer differently, "deny takes priority over defer, which takes priority over ask, which takes priority over allow". A hook can also rewrite the call with updatedInput, paired with allow or ask; it replaces the whole input, so return a new object rather than editing the original. This is how guardrails in code are built.

PostToolUse: fix what Claude reads

A PostToolUse hook fires after the tool has run, with both tool_input and tool_response. Its updatedToolOutput replaces what Claude sees, for any tool. A common use, and one the exam guide names: normalize data from different MCP tools, such as Unix timestamps, ISO dates and amounts in cents, into one format before the model reasons about it.

async def normalize_payments(input_data, tool_use_id, context):
    return {"hookSpecificOutput": {
        "hookEventName": "PostToolUse",
        "updatedToolOutput": to_dates_and_dollars(input_data["tool_response"]),  # your converter
    }}

hooks = {"PostToolUse": [HookMatcher(matcher="^mcp__payments__", hooks=[normalize_payments])]}

Remember the limit: "updatedToolOutput only changes what Claude sees. The tool has already run". To stop an action, use PreToolUse.

Sessions: continue, resume, fork or start fresh

A session is "the conversation history the SDK accumulates while your agent works": your prompt, every tool call and result, every response, saved to disk automatically. Capture its ID from the result message:

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query

session_id = None
async for message in query(prompt="Audit the refund code", options=ClaudeAgentOptions()):
    if isinstance(message, ResultMessage):
        session_id = message.session_id

resume = ClaudeAgentOptions(resume=session_id)                     # later: pick up where it stopped
branch = ClaudeAgentOptions(resume=session_id, fork_session=True)  # try another way, original untouched
Situation Choice
Carry on in the same directory, one user continue_conversation=True (CLI: claude -c)
Several sessions, one per user or workstream resume=session_id (CLI: claude -r <name>)
Explore an alternative, keep the original intact resume + fork_session=True (CLI: --fork-session)
The old tool results are out of date A fresh session, with a structured summary of findings and decisions in the prompt

Two cautions. Sessions persist the conversation, not the filesystem: a fork that edits files changes them for everyone in that directory. And a resumed session still believes its old tool results; when the code or data has changed a lot, the exam guide's answer is that "starting a new session with a structured summary is more reliable than resuming with stale tool results". If only a little changed, resume and tell the agent which files changed. For the same ideas in Claude Code itself, see Claude Code hooks and Claude Code best practices.

Hooks and sessions on the Claude Certified Architect exam

Domain 1 of the CCAR-F exam tests hooks in task 1.5 (PostToolUse hooks that normalize tool results, interception hooks that block policy violations, hooks for deterministic guarantees versus prompts for probabilistic ones) and sessions in task 1.7 (named resumption, fork_session for parallel exploration, a fresh session with a summary when prior tool results are stale). New to the SDK? Start with the Claude Agent SDK tutorial.

More in all articles.

Sources: Hooks (Agent SDK); Hooks reference; How the agent loop works; Work with sessions (Agent SDK); CLI reference; Claude Certified Architect Foundations exam guide v1.0, task statements 1.5 and 1.7.

FAQ

What are hooks in the Claude Agent SDK?

Callback functions that run your code in response to agent events, such as PreToolUse before a tool call and PostToolUse after it. They run in your application process, outside the agent's context window, so they cost no context.

What can a PreToolUse hook return?

An empty object to allow the call unchanged, or a permission decision: allow, deny (the reason is shown to Claude), ask (the user confirms) or defer (the turn ends and the call can be resumed later). When hooks disagree, deny wins, then defer, then ask, then allow.

How do I resume a Claude Agent SDK session?

Take session_id from the result message and pass it as resume in the options of the next query. continue_conversation resumes the most recent session in the current directory instead.

What does fork_session do?

Used with resume, it starts a new session with a copy of the original history and its own ID, so you can explore an alternative while the original stays unchanged. It copies the conversation, not the files on disk.