Claude Code project setup: CLAUDE.md, settings, hooks, MCP
Set up a repository for Claude Code with four files: CLAUDE.md, .claude/settings.json, one hook and .mcp.json. What belongs in each, with documented examples.
At a glanceFive small Claude Code hooks with a test script: protect files, block risky commands, format after edits, check before stopping, and log every command.
TestedAll five scripts were run on Linux with sample input; the results shown are the real exit codes. Not run inside a live session or on Windows.
An instruction file asks. A hook enforces. When a rule in your project has no exceptions, such as never editing a generated folder, writing it in capital letters does not make it certain. A hook does, because Claude Code runs it every time, whatever the model decided. This guide gives you five small hooks and, more usefully, a way to test them without waiting for an agent to make the mistake.
Three facts cover most of what you need:
tool_input.file_path. For a shell command it includes tool_input.command.jq to read JSON. On macOS install it with brew install jq. On Windows the scripts run under Git Bash, which comes with Git for Windows; install jq with your package manager.Event: PreToolUse, for the Edit and Write tools. Save as .claude/hooks/protect-files.sh. It follows the example in Anthropic's guide, with one more pattern for a generated folder:
#!/bin/bash
# PreToolUse on Edit|Write: refuse changes to files that must not be touched.
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}" # Windows paths arrive with backslashes
PROTECTED=(".env" "package-lock.json" "/.git/" "/src/gen/")
for pattern in "${PROTECTED[@]}"; do
if [[ "$FILE_PATH" == *"$pattern"* ]]; then
echo "Blocked: $FILE_PATH matches protected pattern '$pattern'. Ask the user before changing it." >&2
exit 2
fi
done
exit 0
The line that replaces backslashes matters on Windows. The reference says file paths arrive there with backslash separators, even when the script runs under Git Bash, and that a check written with forward slashes then never matches, so the edit goes through as if there were no hook.
The message is written for Claude, not for you. Tell it what to do next, here "ask the user", so it does not just try another route to the same file.
Event: PreToolUse, for the Bash tool. Save as .claude/hooks/block-commands.sh:
#!/bin/bash
# PreToolUse on Bash: stop a short list of commands that are hard to undo.
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
BLOCKED=("git push --force" "git push -f" "git reset --hard" "rm -rf /" "rm -rf ~" "drop table")
lowered=$(echo "$COMMAND" | tr '[:upper:]' '[:lower:]')
for pattern in "${BLOCKED[@]}"; do
if [[ "$lowered" == *"$pattern"* ]]; then
echo "Blocked: this command contains '$pattern'. Explain what you wanted to do and let the user run it." >&2
exit 2
fi
done
exit 0
Event: PostToolUse, for Edit and Write. Save as .claude/hooks/format-on-edit.sh:
#!/bin/bash
# PostToolUse on Edit|Write: format the file that was just changed.
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
[ -f "$FILE_PATH" ] || exit 0
case "$FILE_PATH" in
*.json)
# jq rewrites the file with standard indentation, and fails on invalid JSON.
if formatted=$(jq . "$FILE_PATH" 2>&1); then
printf '%s\n' "$formatted" > "$FILE_PATH"
else
echo "$FILE_PATH is not valid JSON: $formatted" >&2
exit 2
fi
;;
# Add your own formatters here, for example:
# *.py) ruff format "$FILE_PATH" ;;
# *.ts|*.tsx|*.js) npx prettier --write "$FILE_PATH" ;;
esac
exit 0
The JSON branch does two jobs. It tidies the file, and if the file is not valid JSON it exits with 2, so Claude is told at once and can repair it. The two commented lines show where your own formatters go; they were not run for this article.
A hook that succeeds is silent. Claude Code shows nothing in the conversation, so check the file itself the first time.
Event: Stop, which fires when Claude tries to end its turn. Save as .claude/hooks/check-before-stop.sh:
#!/bin/bash
# Stop: the turn may not end while the project check fails.
INPUT=$(cat)
# If this hook already sent Claude back to work once, let it stop this time.
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
exit 0
fi
CHECK="${PROJECT_CHECK:-npm test --silent}" # replace with your project's check
if ! output=$($CHECK 2>&1); then
echo "The check '$CHECK' failed. Fix it before finishing:" >&2
echo "$output" | tail -n 20 >&2
exit 2
fi
exit 0
The first if is the important part. Without it, a check that cannot pass would send Claude back to work again and again. The guide says Claude Code overrides a Stop hook after eight blocks in a row, and recommends exactly this test of stop_hook_active so your hook gives way first.
Keep the check fast. It runs every time Claude finishes a turn, so a type check or a small test group suits it better than a ten-minute suite.
Event: PostToolUse, for Bash. Save as .claude/hooks/log-commands.sh:
#!/bin/bash
# PostToolUse on Bash: keep a plain record of every command that ran.
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
LOG="${CLAUDE_PROJECT_DIR:-.}/.claude/command-log.txt"
printf '%s\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$COMMAND" >> "$LOG"
exit 0
After a long unattended session, this file answers "what did it actually run?" in seconds. Add .claude/command-log.txt to .gitignore.
Make the scripts executable, then put this in .claude/settings.json:
chmod +x .claude/hooks/*.sh
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
]
},
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-commands.sh" }
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-on-edit.sh" }
]
},
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/log-commands.sh" }
]
}
],
"Stop": [
{
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-before-stop.sh" }
]
}
]
}
}
The matcher chooses which tools a hook applies to; Edit|Write means either. $CLAUDE_PROJECT_DIR is the project root, so the paths work wherever Claude Code is started from. Committing this file gives the whole team the same hooks. Inside a session, /hooks lists what is registered.
A hook you have not tested is a hope. Because the contract is only "JSON in, exit code out", you can test it from the shell. Save this as test-hooks.sh in the project root:
#!/bin/bash
# Run each hook the way Claude Code does: JSON on standard input, then read the exit code.
try() { # try <expected exit code> <script> <json>
message=$(echo "$3" | "$2" 2>&1 >/dev/null); code=$?
[ "$code" = "$1" ] && verdict="ok " || verdict="FAIL"
printf '%s exit %s %-22s %s\n' "$verdict" "$code" "$(basename "$2")" "${message:0:70}"
}
H=.claude/hooks
try 2 $H/protect-files.sh '{"tool_name":"Edit","tool_input":{"file_path":"/home/me/app/.env"}}'
try 0 $H/protect-files.sh '{"tool_name":"Edit","tool_input":{"file_path":"/home/me/app/src/index.ts"}}'
try 2 $H/protect-files.sh '{"tool_name":"Write","tool_input":{"file_path":"C:\\project\\src\\gen\\client.ts"}}'
try 2 $H/block-commands.sh '{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}}'
try 2 $H/block-commands.sh '{"tool_name":"Bash","tool_input":{"command":"psql -c \"DROP TABLE users\""}}'
try 0 $H/block-commands.sh '{"tool_name":"Bash","tool_input":{"command":"npm test"}}'
PROJECT_CHECK=false try 2 $H/check-before-stop.sh '{"hook_event_name":"Stop","stop_hook_active":false}'
PROJECT_CHECK=true try 0 $H/check-before-stop.sh '{"hook_event_name":"Stop","stop_hook_active":false}'
PROJECT_CHECK=false try 0 $H/check-before-stop.sh '{"hook_event_name":"Stop","stop_hook_active":true}'
Each line states the exit code it expects. This is the output from the run for this article:
$ ./test-hooks.sh
ok exit 2 protect-files.sh Blocked: /home/me/app/.env matches protected pattern '.env'. Ask the u
ok exit 0 protect-files.sh
ok exit 2 protect-files.sh Blocked: C:/project/src/gen/client.ts matches protected pattern '/src/
ok exit 2 block-commands.sh Blocked: this command contains 'git push --force'. Explain what you wa
ok exit 2 block-commands.sh Blocked: this command contains 'drop table'. Explain what you wanted t
ok exit 0 block-commands.sh
ok exit 2 check-before-stop.sh The check 'false' failed. Fix it before finishing:
ok exit 0 check-before-stop.sh
ok exit 0 check-before-stop.sh
The two remaining hooks change files, so they were checked by their effect:
| Hook | Test | Result |
|---|---|---|
format-on-edit.sh | A JSON file written on two cramped lines | Exit 0; the file was rewritten with standard indentation |
format-on-edit.sh | A JSON file cut off halfway | Exit 2, with a message naming the file as invalid |
log-commands.sh | Two commands, npm test and git status | Two lines in the log, each with a UTC timestamp |
Run the test script whenever you change a hook, and add a line for each new rule. If a hook ever lets something through that it should have stopped, the first step is to add that case here and watch it fail.
| You want | Use |
|---|---|
| A guideline with exceptions | A line in CLAUDE.md; let Claude judge |
| Something to happen every time, with no exceptions | A hook |
| Access that must be impossible, not just discouraged | A permission deny rule or the sandbox |
| A check that holds even if someone skips the tool | CI and branch protection |
Anthropic's guide offers a test for both directions. If you keep adding emphasis to a line in CLAUDE.md and it is still missed, it belongs in a hook. If you have hooks for things that are only preferences, delete them.
| Symptom | Check |
|---|---|
| Nothing happens | Run /hooks. If it is empty, the settings file is in the wrong place or is not valid JSON. |
| "Permission denied" | The script is not executable; run chmod +x again. |
| The hook runs but does not block | It exits with 1, not 2. Only 2 blocks. |
| Path checks never match on Windows | The backslash line from step 2 is missing. |
| Claude keeps working and then warns about the Stop hook | The stop_hook_active test from step 5 is missing. |
jq: command not found | Install jq, and open a new terminal. |
For how hooks sit beside the other project files, see Claude Code project setup. For plugins, which can bring hooks of their own, see plugins and MCP servers from the terminal.
This article reflects public information available when it was written. Versions, defaults and prices can change; check the linked official documentation.
All five scripts and the test script were run for this article on Linux with bash and jq 1.7, and the results table shows the actual exit codes and messages. They were tested the way the documentation describes, by sending sample input to each script, not inside a live Claude Code session. The Windows notes follow Anthropic's documentation as read on November 12, 2026 and were not run on Windows. Written for this site with AI assistance, from the sources above. For errors or additional information, please request a correction. Editorial policy
Found this useful? Share it, or follow for new guides.