Cursor Hooks: 3 Tested hooks.json Examples (Shell, .env, Prompt Secrets)
Cursor rules ask the agent to behave. A hook runs a script at a fixed point in the agent loop every time, whether the model remembers your rules or not. This page gives three hooks you can drop into a project today, plus the parts of the spec that trip people up.
Everything here was checked against Cursor's hooks documentation on 2026-11-15, and each script was tested by piping 31 sample payloads through it (the test file is in the download). We have not run them on Windows. Cursor changes quickly, so re-check the docs for anything you rely on.
Download free-cursor-hooks.zip (MIT, bash + jq, 3 hooks, hooks.json, test.sh)
Where hooks.json goes
| File | Scope | Commands run from |
|---|---|---|
.cursor/hooks.json in your repo |
That project, shared when you commit it (trusted workspaces only) | the project root |
~/.cursor/hooks.json |
All your projects on this machine | ~/.cursor/ |
The path rule is the most common reason a hook "does nothing": in a project file write .cursor/hooks/guard-shell.sh, not ./hooks/guard-shell.sh. Cursor watches the file and reloads it on save; the Hooks tab in Customize and the Hooks output channel show what loaded and any errors. Every file needs "version": 1 at the top.
Cloud agents run project command hooks from .cursor/hooks.json too, but not your user-level ~/.cursor/hooks.json, and not sessionStart or the MCP hooks.
How a hook answers
The hook gets JSON on stdin and prints JSON on stdout.
- Exit 0 and print a response. For permission hooks (
beforeShellExecution,beforeReadFile,beforeMCPExecution,preToolUseand others), invalid JSON or a response that doesn't match the schema blocks the action, so always print valid JSON. - Exit 2 blocks the action, the same as
"permission": "deny". - Any other exit code fails open: Cursor logs it and lets the action through, unless you set
"failClosed": trueon that hook.
When several hooks answer, deny beats ask and ask beats allow.
The hooks.json
{
"version": 1,
"hooks": {
"beforeShellExecution": [
{ "command": ".cursor/hooks/guard-shell.sh", "timeout": 10 }
],
"beforeReadFile": [
{ "command": ".cursor/hooks/guard-secret-files.sh", "timeout": 10 }
],
"beforeSubmitPrompt": [
{ "command": ".cursor/hooks/scan-prompt-secrets.sh", "timeout": 10 }
]
}
}
1. Block or pause risky shell commands
beforeShellExecution receives command, cwd and sandbox, and can answer allow, deny or ask. This script denies the commands you never want an agent to run, and asks you first for the ones that are sometimes right:
#!/usr/bin/env bash
command -v jq >/dev/null || { echo "jq is not installed; hook skipped" >&2; exit 1; }
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.command // empty')
reply() { jq -cn --arg p "$1" --arg m "$2" \
'{continue:true, permission:$p} + (if $m=="" then {} else {user_message:("guard-shell: "+$m), agent_message:("Blocked or paused by a hook (guard-shell): "+$m+". Choose a safer command or ask the user.")} end)'; exit 0; }
[ -z "$cmd" ] && reply allow ""
has() { printf '%s' "$cmd" | grep -Eiq "$1"; }
has '(curl|wget)[^|;&]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|z)?sh([[:space:]]|$)' && reply deny "piping a download into a shell"
has 'chmod[[:space:]]+(-R[[:space:]]+)?777' && reply deny "chmod 777"
has '(^|[;&|[:space:]])(cat|less|more|head|tail|bat)[[:space:]][^;&|]*\.env([[:space:]]|$)' && reply deny "printing a .env file into the chat"
has 'git[[:space:]]+push[^;&|]*[[:space:]](-f|--force)([[:space:]]|$)' && reply ask "force push"
has 'git[[:space:]]+reset[[:space:]]+--hard' && reply ask "git reset --hard discards uncommitted work"
has 'drop[[:space:]]+(table|database)' && reply ask "SQL DROP TABLE/DATABASE"
reply allow ""
The full script in the download also denies rm -rf aimed at /, ~, $HOME or .. (any flag order) and disk wipes (mkfs, dd of=/dev/...), and asks before git clean -f. A plain rm -rf ./build is allowed.
If you only care about a few commands, Cursor's matcher field (a regex tested against the full command string) skips the script for everything else, for example "matcher": "git|rm|curl".
2. Keep .env files and keys out of the model
beforeReadFile fires before the agent reads a file and gets file_path and content. Answer deny and the file never reaches the model:
#!/usr/bin/env bash
command -v jq >/dev/null || { echo "jq is not installed; hook skipped" >&2; exit 1; }
input=$(cat)
path=$(printf '%s' "$input" | jq -r '.file_path // empty')
base=$(basename -- "$path")
deny() { jq -cn --arg m "$1" '{permission:"deny", user_message:("guard-secret-files: kept "+$m+" out of the model context")}'; exit 0; }
case "$base" in
.env.example|.env.sample|.env.template|*.pub) ;;
.env|.env.*|*.pem|*.key|*.p12|*.pfx|id_rsa|id_ed25519|id_ecdsa|.npmrc|.netrc|.pgpass|credentials.json|service-account*.json) deny "$base" ;;
esac
case "$path" in
*/.aws/credentials|*/.ssh/*|*/.docker/config.json|*/.kube/config) [ "${base##*.}" = pub ] || deny "$base" ;;
esac
jq -cn '{permission:"allow"}'
This covers agent reads. Tab completions use a separate hook, beforeTabFileRead, with the same allow/deny answer; add the same script there if you want Tab kept away from secrets too.
3. Stop a prompt that contains an API key
beforeSubmitPrompt runs after you press send and before anything leaves your machine. Answer {"continue": false} to stop it:
#!/usr/bin/env bash
command -v jq >/dev/null || { echo "jq is not installed; hook skipped" >&2; exit 1; }
input=$(cat)
prompt=$(printf '%s' "$input" | jq -r '.prompt // empty')
pat='(sk-(ant-|proj-)?[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,}|xox[baprs]-[A-Za-z0-9-]{10,}|sk_live_[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_-]{35}|-----BEGIN [A-Z ]*PRIVATE KEY-----|(postgres|postgresql|mysql|mongodb(\+srv)?)://[^:/[:space:]]+:[^@[:space:]]+@)'
if printf '%s' "$prompt" | grep -Eq "$pat"; then
jq -cn '{continue:false, user_message:"scan-prompt-secrets: this prompt looks like it contains an API key, token, private key or a database URL with a password. Remove it (use an env var) and send again."}'
else
jq -cn '{continue:true}'
fi
It matches common key shapes (OpenAI, Anthropic, AWS, GitHub, Slack, Stripe live, Google) and never echoes the secret back.
Guarding MCP tools too
Shell and file hooks don't cover MCP servers. For an allow-list of MCP servers that fails closed (and the cloud-agent gap in beforeMCPExecution), see Cursor MCP allow-list hook and its free download.
Test a hook without opening Cursor
Hooks are just programs reading stdin, so you can test them in a terminal:
echo '{"command":"git push --force origin main"}' | .cursor/hooks/guard-shell.sh
# {"continue":true,"permission":"ask","user_message":"guard-shell: force push",...}
echo '{"file_path":"/repo/.env.local"}' | .cursor/hooks/guard-secret-files.sh
# {"permission":"deny","user_message":"guard-secret-files: kept .env.local out of the model context"}
The download's test.sh runs 31 cases like these and prints 31 passed, 0 failed.
Honest limits
- A hook is a safety net, not a sandbox. Pattern rules miss commands written in ways they don't expect (a script file that runs
rm, an alias, base64). Keep Cursor's own approval settings on for anything that matters. - These hooks fail open if
jqis missing: each script exits 1, which Cursor logs and treats as "allow". Installjq, or add"failClosed": trueonce you've confirmed they run. beforeReadFilegets the file's content; our script only looks at the path, so a secret pasted intoconfig.tsis not caught.
Using Claude Code too?
Cursor can also load hooks written for Claude Code (see its Third Party Hooks docs). If you use both tools, our free Claude Code guard hooks cover the same ground for Claude Code, and the Claude Code hooks examples post explains that format. For agent rules and context files across Cursor, Claude Code and Codex, see the AGENTS.md vs CLAUDE.md vs Cursor rules guide.
AI Coding Agent Config Kit
Instruction-file templates for 12 stacks and 12 prompts that write and audit them. 34-page PDF, $14.
Not ready to buy? Start with the free PDF.
Get 10 of our most-used prompts as a free PDF from Gumroad. You will be asked for your email so Gumroad can deliver it.