What you will be able to do
- Choose the hook event and decision that enforce a rule deterministically, instead of relying on the model to follow it
- Check hooks, Skills and CLAUDE.md into a repository so every developer's session starts with the same tooling
- Connect Claude to an external system such as a database through an MCP server instead of custom glue code
- Run Claude Code without a person at the keyboard, through claude -p, GitHub Actions and the Agent SDK
1.Hooks: actions that run every time
Anything you write in a prompt or in CLAUDE.md is guidance. The model reads it and usually follows it, but it decides each time. A hook is not up to the model. It is a shell command that Claude Code runs whenever a particular event fires, whatever the model has decided. Use a hook when a rule must hold every single time: formatting after every edit, a lint before a turn can end, or a destructive command that must never run.
A hook has three parts. The event says when it fires. The matcher narrows it to particular tools, for example Bash or Edit|Write. The handler is the command that runs. The event matters most, because it decides what the hook is able to do:
| Event | When it fires | Typical use |
|---|---|---|
| PreToolUse | Before a tool call executes; can block it | Deny a dangerous Bash command or an edit to a protected file |
| PostToolUse | After a tool call succeeds | Run a formatter on the file Claude just edited |
| Stop | When Claude finishes responding | Block the turn from ending until a check passes |
| SessionStart | When a session begins or resumes | Re-inject reminders, for example after compaction |
| Notification | When Claude Code sends a notification | Show a desktop alert when Claude needs your attention |
| Setup | On --init-only, or --init or --maintenance in -p mode | One-time preparation in CI or scripts |
To stop a command before it runs, use PreToolUse with matcher Bash. The hook receives the call as JSON, for example { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" } }. Your script inspects the command and, if it is not allowed, returns a deny decision:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Destructive command blocked by hook"
}
}Compare the alternatives for a rule like "never rm -rf outside the working directory". A CLAUDE.md instruction still depends on the model choosing to obey it. Plan mode blocks edits to every source file, which shuts down normal work instead of targeting the one dangerous command. Sending Bash calls to a restricted subagent still leaves a model in charge of the decision. Only the PreToolUse hook enforces the rule the same way every time.
Hooks become team-wide when they live in .claude/settings.json. That file applies to a single project and can be committed to the repo, so every developer who clones it gets the same hooks. A PostToolUse hook with matcher Edit|Write that runs jq -r '.tool_input.file_path' | xargs npx prettier --write formats every file Claude touches. A SessionStart hook with matcher compact puts key reminders back into context after compaction has summarized the session:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"
}
]
}
]
}
}Checkpoint 1 of 6· Fill the gap
Your team wants every file Claude edits or writes to be run through Prettier straight away. Which hook event completes this settings sample?
{
"hooks": {
" ? ": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
}
],
"Notification": [
{
"matcher": "",
"hooks": [{ "type": "command", "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'" }]
}
]
}
}PostToolUse fires after a tool call succeeds, so the file Claude just edited is on disk and ready to format. PreToolUse fires before the edit happens, so there would be nothing new to format. Stop fires once at the end of the turn, not after each edit. SessionStart fires only when a session begins or resumes.
Source: code.claude.comCheckpoint 2 of 6· Check yourself
A team lead needs a guarantee that Claude never runs rm -rf outside the working directory, and wants normal editing to keep working. Which approach enforces this every time?
A PreToolUse hook runs before the tool executes and can block the call no matter what the model decided. CLAUDE.md and subagent instructions are guidance that a model may or may not follow. Plan mode blocks all source edits, which stops normal work instead of targeting the one dangerous command.
“PreToolUse | Before a tool call executes. Can block it”Source: code.claude.com
Checkpoint 3 of 6· Exam question
A platform team wants Claude Code to automatically block any Bash tool call that includes rm -rf targeting a path outside the working directory, without relying on the model choosing to avoid it on its own. Which mechanism should they configure?
Correct answer: A — Configure a PreToolUse hook that inspects the Bash tool input and returns a deny decision before the command runs
- A. Correct. A PreToolUse hook is a deterministic shell command that runs before the matching tool executes and can return a blocking decision, so it enforces the rule regardless of what the model decides, which is exactly the guarantee hooks are designed to provide over relying on the model's judgment.
- B. Incorrect. Plan mode blocks all execution, not just the specific dangerous pattern, so it would stop every Bash command including safe ones, and it is not a targeted, permanent enforcement mechanism for this one rule.
- C. Incorrect. A CLAUDE.md instruction is guidance the model may follow, but it is not deterministic enforcement; the model could still misjudge or ignore the instruction under certain phrasing of a task.
- D. Incorrect. Delegating to a restricted subagent limits which tools that subagent can call, but it does not deterministically inspect and block a specific dangerous command pattern the way a PreToolUse hook does, and the main agent could still issue the command directly.
2.Skills and MCP servers as shared team tooling
Every developer's session starts from the same checked-in files. CLAUDE.md as implementation guidance holds the project's conventions. Next to it, hooks enforce rules and Skills package repeatable procedures. Together these three put the whole team on the same workflow without anyone having to configure it locally.
Agent Skills (SKILL.md) are reusable prompt packages. Checked into the repo, they become a team prompt library. A developer runs a procedure like the one below as /fix-issue 1234, and every teammate's run follows the same eight steps: read the issue, fix it, test, lint, commit and open a PR.
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.
1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PRMCP servers are how Claude reaches external systems. When a team wants Claude to query its PostgreSQL database during a session, the fitting approach is to configure an MCP server for that database. The server exposes tools, Claude discovers them through the protocol, and the team writes no tool-execution code of its own. The other options each fail in a specific way. A PreToolUse hook reacts to tool calls that are already happening but gives Claude no new tool. Unrestricted Bash access goes against the practice of permitting only specific tools you know are safe. A subagent whose prompt contains the schema knows about the database but has no way to query it.
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
// Natural language query - Claude writes the SQL
prompt: "How many users signed up last week? Break it down by day.",
options: {
mcpServers: {
postgres: {
command: "npx",
// dbhub.toml sets readonly = true, so execute_sql rejects writes
args: ["-y", "@bytebase/dbhub", "--config", "dbhub.toml"]
}
},
allowedTools: ["mcp__postgres__execute_sql"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}Two settings in that example limit what Claude can do. allowedTools lists the one tool the run may call, mcp__postgres__execute_sql. The server's own config sets readonly = true, so a write is rejected even if Claude produces one. Here access control sits in the integration, not in the prompt.
Checkpoint 4 of 6· Check yourself
During sessions, developers want to ask Claude questions that need live answers from the team's PostgreSQL database. What should the team set up so Claude can run those queries?
An MCP server connects Claude to an external system and exposes tools that Claude discovers through the protocol, so the team writes no tool-execution code of its own. A hook only reacts to tool calls that are already happening and gives Claude no new tool. A subagent that has the schema still can't query the database. Unrestricted Bash goes against allowing only tools you know are safe.
“MCP servers for external services, skills for workflows, subagents for delegated work”Source: code.claude.com
Checkpoint 5 of 6· Exam question
A team wants Claude Code to query their internal PostgreSQL database directly during a session, without the team writing custom tool-execution code themselves. Which approach fits the Model Context Protocol integration model?
Correct answer: A — Configure an MCP server for the database and let Claude discover its tools through the protocol
- A. Correct. MCP servers expose external systems like databases as a set of discoverable tools that Claude can call directly, which is the documented mechanism for connecting Claude to systems such as a PostgreSQL database without hand-writing tool execution code.
- B. Incorrect. Hooks run deterministic shell commands at lifecycle events for validation or logging; they are not designed to serve as the mechanism through which Claude discovers and calls a database's query capabilities.
- C. Incorrect. Granting unrestricted Bash access lets Claude shell out to a CLI client, but this bypasses the structured, discoverable tool interface MCP provides and removes the scoped, auditable tool boundary the team wants.
- D. Incorrect. Putting schema details in a subagent's system prompt gives Claude static knowledge about the database, not a way to actually execute queries against it; it still lacks the live tool connection MCP provides.
3.Running Claude Code in scripts and CI
Claude Code does not need someone at the keyboard. With claude -p you pass a prompt, get the result on standard output, and can pipe data in, as in git log --oneline -20 | claude -p "summarize these recent commits". Any shell script, cron job or CI step can use it this way. The Setup hook event covers one-time preparation for these runs: it fires on --init or --maintenance in -p mode.
In GitHub, the Claude Code GitHub Action runs Claude in your CI pipeline. Running /install-github-app from Claude Code installs the GitHub App, adds the authentication secret and opens a pull request with the workflow file. A workflow can run in one of two modes. With no prompt input, it waits for an @claude mention in an issue or PR and posts its progress as a comment. With a prompt input, Claude runs on the trigger alone, and its results go to the workflow run log unless the prompt tells it to post them.
jobs:
claude:
if: contains(github.event.comment.body, '@claude')
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
actions: read
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}The team's skill library carries over to CI. Put actions/checkout before the Claude step so the files in .claude/skills/ exist on the runner, then pass /skill-name as the prompt. Locally and in CI, the same skill runs the same procedure. To restrict tools in CI, pass flags through claude_args, for example --allowedTools naming the only tool the job may call.
Unattended runs have guardrails of their own. On issue and pull request events, the user who triggers a run must have write access to the repository. Bot actors are rejected unless they are listed in allowed_bots, which stops bots from triggering Claude in a loop. For automation outside GitHub Actions, the Claude Agent SDK is the building block; the GitHub Action itself is built on it. If you only want reviews, Code Review gives every PR an automatic review without you writing a workflow.
| Option | Where it runs | Best for |
|---|---|---|
| Routines | Cloud, Anthropic-managed by default | Tasks that must run while your computer is off, or on API calls and GitHub events |
| Desktop scheduled tasks | Your machine, via the desktop app | Tasks that need local files, tools or uncommitted changes |
| GitHub Actions | Your CI pipeline | Repo events like opened PRs, or cron schedules kept alongside your workflow config |
| /loop | The current CLI session | Quick polling while a session is open |
Checkpoint 6 of 6· Fill the gap
This review job runs on pull request events and should review every pull request as soon as it is opened or updated, without anyone commenting @claude. Which action input fills the blank?
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
plugin_marketplaces: "https://github.com/anthropics/claude-code.git"
plugins: "code-review@claude-code-plugins"
? : "/code-review:code-review --comment ${{ github.repository }}/pull/${{ github.event.pull_request.number }}"With a prompt input, the workflow runs in automation mode. Claude starts on the pull_request trigger alone and does not wait for an @claude mention. Without a prompt, it would wait for a mention in a comment. allowed_bots only controls which bot actors may trigger a run. You run a skill by passing /skill-name as the prompt, not through a separate input.
Practise it for real
Add one formatting hook and one blocking hook to a project, then run Claude Code headless.
1.In
.claude/settings.json, add a PostToolUse hook with matcherEdit|Writeand the commandjq -r '.tool_input.file_path' | xargs npx prettier --write.Why: Formatting becomes something that happens after every edit, not something you have to remember to ask for, and committing the file shares it with the team.
You should see: After Claude edits a badly formatted file, the file on disk is in Prettier's style.
2.Add a PreToolUse hook with matcher
Bashthat runs a script which, for a command containingrm -rf, prints the deny JSON withpermissionDecisionset todeny.Why: PreToolUse fires before the tool executes, so it is the event that can block the call.
You should see: When you ask Claude to run
rm -rf /tmp/build, the call is denied with the reason "Destructive command blocked by hook" and nothing is deleted.3.Ask Claude to delete the same path again, this time phrasing it as a direct order.
Why: This shows the hook overrides the model's choice, however the request is worded.
You should see: The command is denied again.
4.Run
git log --oneline -20 | claude -p "summarize these recent commits"in the repository.Why: This is the same non-interactive form that scripts and CI jobs use.
You should see: A summary is printed to standard output and no interactive session opens.
Stuck? Get a nudge
If the deny does not trigger, check that the matcher is Bash and the event is PreToolUse. A PostToolUse hook only runs after the command has already executed.
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://code.claude.com/docs/en/hooks-guideOfficial docs
“Run shell commands automatically when Claude Code edits files, finishes tasks, or needs input.”
↩︎ Hooks: actions that run every time“Before a tool call executes. Can block it”
↩︎ Hooks: actions that run every time“For one-time preparation in CI or scripts”
↩︎ Running Claude Code in scripts and CI“Before a tool call executes. Can block it”
↩︎ Exam trap 1“After a tool call succeeds”
↩︎ Prediction“PreToolUse | Before a tool call executes. Can block it”
↩︎ Checkpoint - 2.https://code.claude.com/docs/en/hooksOfficial docs
“.claude/settings.json | Single project | Yes, can be committed to the repo”
↩︎ Hooks: actions that run every time - 3.
“MCP servers for external services, skills for workflows, subagents for delegated work”
↩︎ Skills and MCP servers as shared team tooling“MCP servers for external services, skills for workflows, subagents for delegated work”
↩︎ Exam trap 2 - 4.https://code.claude.com/docs/en/agent-sdk/mcpOfficial docs
“dbhub.toml sets readonly = true, so execute_sql rejects writes”
↩︎ Skills and MCP servers as shared team tooling - 5.https://code.claude.com/docs/en/best-practicesOfficial docs
“Permission allowlists: permit specific tools you know are safe, like npm run lint or git commit”
↩︎ Skills and MCP servers as shared team tooling - 6.https://code.claude.com/docs/en/common-workflowsOfficial docs
“Pipe Claude into scripts for CI and batch processing”
↩︎ Running Claude Code in scripts and CI - 7.https://code.claude.com/docs/en/github-actionsOfficial docs
“run actions/checkout before the anthropics/claude-code-action step so the skill files are available on the runner, then pass /skill-name as the prompt”
↩︎ Running Claude Code in scripts and CI“rejects a bot actor unless you list it in allowed_bots, which keeps bots from triggering Claude in a loop”
↩︎ Running Claude Code in scripts and CI“Claude Agent SDK: custom automation outside GitHub Actions. The Claude Code GitHub Action is built on the SDK”
↩︎ Running Claude Code in scripts and CI“Automation mode: when the workflow provides a prompt input, Claude runs without waiting for a mention”
↩︎ Exam trap 3