PROJECT · AGENT SDK HOOKS

Agent SDK Hooks: How to Add Reliable Controls Around AI Agent Tool Use

A hook is developer-written code that runs at a fixed point in an agent's lifecycle. A beginner-friendly walkthrough of PreToolUse and PostToolUse hooks: blocking a risky refund before it executes, enforcing an AML prerequisite, and normalizing messy tool results before the model reads them, with heavily commented Python.

A hook is developer-written code that runs at a fixed point in an agent's lifecycle. This project builds both hook points from scratch: a PreToolUse hook that refuses a refund before any money moves, an AML prerequisite that reads session state instead of trusting the model, and a PostToolUse hook that turns three messy tool results into one schema before the model reads them.

AI agents are useful because they can do more than answer questions.

They can call tools, inspect results, and take actions in outside systems. That is also what makes them risky. A customer-support agent might issue refunds. A finance agent might start a transfer. A coding agent might edit files or run shell commands. Once an agent can affect real systems, prompt instructions alone are not enough. Some rules need to be enforced by application code.

That is the job of Agent SDK hooks. A hook is developer-written code that runs at a specific point in an agent's execution lifecycle. In plain English: a hook is a checkpoint. When the agent is about to use a tool, or has just received a tool result, the application can run your code to inspect, block, modify, log, or clean up what is happening.

Hooks matter because the language model is probabilistic, while ordinary application code is deterministic. A probabilistic system can behave slightly differently from one run to another. A deterministic system follows explicit logic: if the same input reaches the same code path, the same rule is applied. Hooks use this kind of deterministic logic around the model's decisions.

the model PreToolUse allow · block · rewrite the tool runs PostToolUse clean · log the cleaned result goes back to the model probabilistic APPLICATION CODE — DETERMINISTIC the side effect is real from here
Fig. 1 · Where hooks sit. A PreToolUse hook runs after the model has chosen a tool but before that tool executes. A PostToolUse hook runs after it executes but before the model sees the result. Everything inside the dashed box is ordinary application code, which is why it behaves the same way every run.

The practical lesson is simple: prompt instructions are useful for shaping behaviour, and hooks are better for enforcing rules that should not be bypassed.

Sign in to view this build.

Create a free account to access the full build walkthrough on kevinsomany.com.

Loading…

Sign in or create an account.

Enter your email and we will send you a sign-in link. No password needed.

or continue with