Learning resourcesReviewed · Anthropic

Claude Agent SDK: Intercept and control agent behavior with hooks

This guide teaches Python and TypeScript developers to control Claude agents with hooks, but safeguards only cover the events and tools they handle. It explains permission decisions, tool input and output changes, logging and session events, including SDK differences and callback failure behavior.

Researched 23 Nov 2026

In short.

This Claude Agent SDK guide helps Python and TypeScript developers add checks around agent actions, but incomplete tool coverage or callback error handling can leave intended restrictions unenforced. It documents approval decisions, input and output changes, background logging and event-specific timeouts. Its file-protection example clearly exposes the limits of matching only selected tools and path formats. No examples were executed; security effectiveness, performance and operating costs are not established.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage is limited to the complete captured page at https://code.claude.com/docs/en/agent-sdk/hooks.md. It includes event support, configuration, callback behavior, examples, troubleshooting and notices about path coverage, failure handling, asynchronous output and version compatibility. Linked documentation, SDK source code, package releases, licensing terms and external service documentation are excluded. No examples, integrations or agent sessions were run; documented behavior has not been independently verified.

The overview

Identity

Intercept and control agent behavior with hooks is a Claude Agent SDK documentation page at [https://code.claude.com/docs/en/agent-sdk/hooks.md]. It teaches callback functions that run when an agent requests a tool, receives a result, stops or encounters another supported event.

The resource is a programming guide with paired Python and TypeScript examples. It is not a standalone application or a ready-made security policy.

Assessment

The guide is useful when an application needs explicit checks, approvals or logging around Claude's actions. It connects the basic event model to practical details such as modifying arguments, handling failed callbacks and diagnosing hooks that do not fire.

Its strongest caution is that a small callback is not comprehensive protection. The documented .env guard misses Bash writes and Windows paths, and a crashing guard normally falls back to ordinary permission evaluation unless configured otherwise.

Users

The main audience is developers embedding Claude agents in Python or TypeScript applications. Relevant needs include reviewing tool requests, recording tool activity, adding approval steps, changing tool arguments and tracking subagents.

Beginners need familiarity with asynchronous functions and SDK options to adapt the examples. Experienced developers will find the event support table, decision precedence, cancellation behavior and version requirements particularly relevant.

Capabilities

PreToolUse callbacks can allow, deny, request approval for or defer a tool call, and can replace its input. PostToolUse callbacks can add context or replace the output Claude receives. Other events support logging failures, tracking subagents, observing compaction and handling notifications.

TypeScript exposes more callback events than Python, including SessionStart, SessionEnd, PostToolBatch and several configuration and workspace events. The page also demonstrates HTTP notifications and Slack webhooks; these require application code and external endpoints.

Using it

Requirements

The examples assume an existing Claude Agent SDK application. Python examples use claude_agent_sdk, ClaudeAgentOptions, HookMatcher and ClaudeSDKClient. TypeScript examples use @anthropic-ai/claude-agent-sdk and query(). Installation steps, authentication requirements and general runtime requirements are not established here.

Blocking an action when a callback fails requires TypeScript Agent SDK v0.3.317 or later, or Python Agent SDK v0.2.177 or later. Claude Code must also support that option. Python does not expose SessionStart and SessionEnd as SDK callback events; the page describes settings-based shell hooks as an alternative.

Mechanism

An event triggers collection of registered hooks, matcher filtering and callback execution. Tool-event matchers inspect tool names rather than file paths; callbacks must inspect arguments themselves. Other events use different matching fields, and Stop ignores matchers.

Callbacks receive event data, a tool-use identifier where applicable and context. Decisions belong inside hookSpecificOutput. For conflicting PreToolUse decisions, deny takes priority over defer, then ask, then allow. Returning an empty object makes no permission decision.

Matching hooks run in parallel, so they must not depend on completion order. Normally the agent waits for callbacks. Background output lets it proceed immediately, but cannot block operations, modify them or inject context.

Setup

Define a callback and register it under the exact event name in the hooks option. Python uses HookMatcher entries; TypeScript uses matcher objects containing callback arrays. A Write|Edit matcher targets those tools, while omitting the matcher applies the callback to every occurrence of the event.

For a guard that must block on callback failure, configure onFailure as block in TypeScript or on_failure as block in Python. Return an empty object for an intentional no-op; falling through without a return counts as failure. If the existing session did not register the hooks, the page says to start a new session.

Shell hooks from settings can also participate when the corresponding settingSources or setting_sources entry is enabled. Inspect which settings sources the application loads, since callback registration alone does not describe every hook that may run.

Example

The opening example registers a PreToolUse callback for Write and Edit. It reads file_path, splits it on forward slashes and compares the final filename with .env without regard to letter case. A match returns a deny decision and an explanatory reason; other inputs return an empty object.

This illustrates targeted interception, with explicit limits. The check misses Windows backslash paths, and a Bash command can write the same file without triggering this matcher. The page points to sandbox configuration for restricting Bash writes. The example was not executed.

Assessment & evidence

Limitations

On most events, an exception, invalid output or missing return does not block the action by default. A failed PreToolUse guard lets the request reach normal permission evaluation. The block-on-failure option has exceptions: Stop, SubagentStop, TaskCompleted and TeammateIdle ignore it, and PermissionRequest depends on whether the failure arrives before canUseTool answers.

A PostToolUse hook runs after execution. Replacing the output Claude sees cannot prevent the tool's already completed effects. Likewise, prepending a directory to a path in the redirection example does not establish filesystem isolation.

Timeout behavior varies by event. A PreToolUse timeout blocks the tool call, while a Stop timeout counts as no decision. Timeouts use seconds in HookMatcher, but asyncTimeout uses milliseconds. Hooks may not fire when a session reaches max_turns, so they should not be assumed to provide guaranteed final cleanup.

Reasoning

Hooks are a plausible fit when application code must inspect a specific agent event and return an explicit decision. That assessment follows from the documented callback inputs and outputs; it is not a measured security result.

The choice between a blocking callback and background work matters. Permission checks need a synchronous decision before execution, while background logging can avoid waiting. Input changes also require care: updatedInput replaces the complete input, and pairing it with defer discards the change.

Alternatives

The page identifies permission rules and canUseTool callbacks as related ways to manage approvals, sandbox configuration for restricting Bash writes, and settings-based shell hooks for events missing from Python's callback API. These are adjacent mechanisms whose suitability depends on the required control. Their linked documentation was not assessed, and the page offers no comparison with other agent frameworks.

Evidence

The evidence consists of the complete documentation page at [https://code.claude.com/docs/en/agent-sdk/hooks.md], captured as selected-page.txt. It contains explanations, an event support table, Python and TypeScript examples, troubleshooting guidance and compatibility notices.

The source revision is sha256:5ac6b7a5978e55cc8f92d5d95249a849733989f93694c5f9b55319e77c51baf7. No code was executed. Runtime behavior, security completeness, performance and production reliability remain unverified.

Access & freshness

Costs

The page supplies no prices, token usage figures or operating-cost estimates. Total cost is unknown. Its HTTP logging and Slack examples introduce external services, but their charges are not stated. Callback latency and resource consumption are also unmeasured.

Rights

The captured page does not state a redistribution licence for its documentation or code examples. Reuse and redistribution rights are unknown from this evidence. SDK licensing and service terms are not established by this page either.

Freshness

The page was captured on 23 November 2026 at 06:13:20.411 UTC. No publication or last-updated date is supplied, so the capture timestamp does not establish when individual features were introduced.

Compatibility depends on both SDK and Claude Code versions. The page records version-dependent changes to timeouts, cancellation and message delivery, alongside minimum versions for individual features. For example, classifierContext requires TypeScript Agent SDK v0.3.236 or later. Compatibility with a particular installation was not assessed.

Actions

Before adopting a guard, identify every tool and path format that can perform the operation you want to restrict. Adapt the matcher and argument checks accordingly, and confirm the event exists in your chosen SDK. For file restrictions, account for the documented Bash and Windows gaps.

Validate normal decisions, thrown errors, missing returns, timeouts and conflicting hooks in your own environment. Check the required versions before relying on block-on-failure behavior. Keep observability separate from enforcement: background logging cannot block actions, and systemMessage delivery varies by event and version.

Evidence for this report

selected-page.txtselected · checked 2026-11-23