Skip to content

Claude Code

Subagents and hooks in Claude Code: split the work and add fixed rules

How to write a Claude Code subagent with its own context and a limited set of tools, and how to add hooks that run before or after a tool to enforce rules.

Talqeen wrote this article and no editor has reviewed it yet. Search engines do not see this page until it is reviewed.

Over time a Claude Code session grows: files read, test output, side discussions. Two tools help. A subagent takes a task into a separate context and returns a summary. A hook is a command that runs automatically on a given event, enforcing a rule that does not depend on the model remembering it.

Subagents

A subagent is a Markdown file in .claude/agents/ (or ~/.claude/agents/ for you only), starting with YAML frontmatter:

---
name: test-runner
description: Runs the tests and summarises what failed and its likely cause. Use it after every code change.
tools: Read, Grep, Glob, Bash
---

Run the tests related to the change. For each failing test give its name,
the line where it failed and a likely cause in one sentence. Edit no file.

  • description tells Claude Code when to hand the task to this agent.
  • tools limits the tools it may use. Leave it out and the agent inherits all the session's tools, so it is better to set it.
  • You can add model to pick a faster model for a simple task.

The subagent works in its own context window, so long test output does not fill your main conversation; only the summary comes back. The /agents command lists available agents and helps you create one.

Hooks

A hook is a shell command Claude Code runs on an event. Hooks live in .claude/settings.json. Useful events:

  • PreToolUse: before a tool runs; it can block it.
  • PostToolUse: after a tool runs, such as formatting a file after an edit.
  • UserPromptSubmit: when you send a prompt, before the model reads it.
  • Stop: when Claude Code finishes its reply.

Formatting after every edit:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "pnpm exec prettier --write ." }]
      }
    ]
  }
}

matcher selects the tools the hook runs for. In PreToolUse, exit code 2 blocks the tool, and the hook's message reaches Claude Code so it knows why.

Security first

A hook runs on your machine with your permissions, without asking. Read every hook before adding it, especially one that comes with a plugin or skill from a source you do not know; keep commands short and clear; avoid anything that downloads and runs code; and review the settings file in pull requests as you review code.