Cursor hooks: hooks.json, every event, examples, and fixes
Short answer: Cursor hooks are your own scripts that Cursor runs at set points in the agent loop: before a shell command, after a file edit, when the agent stops, and 18 other events. You list them in a hooks.json file, either .cursor/hooks.json in a project or ~/.cursor/hooks.json for every project. Each script gets JSON on stdin and can answer with JSON on stdout, so it can log what happened, block an action (exit code 2 or "permission": "deny"), or send the agent a follow-up message. Cursor reloads the file when you save it.
What Cursor hooks are
Hooks are separate processes that talk to Cursor over stdio, JSON both ways. Cursor's own list of uses: run formatters after edits, add analytics, scan for PII or secrets, gate risky operations such as SQL writes, control subagents, and add context at session start.
Agent hooks fire during an Agent chat, Tab hooks for inline Tab completions (so Tab can get its own policy), and workspaceOpen when Cursor opens a workspace. You don't have to write one from scratch: Cursor has a built-in /create-hook skill that creates hooks and updates hooks.json for you.
Where hooks.json goes: project, user, team, enterprise
| Source | File | Scripts run from | Good to know |
|---|---|---|---|
| Project | <project>/.cursor/hooks.json | The project root | Checked into Git. Runs only in a trusted workspace. Cloud agents run these too. |
| User | ~/.cursor/hooks.json | ~/.cursor/ | Every project on your machine. Not available in cloud agents. |
| Team | Set in the web dashboard | The managed hooks folder | Enterprise only. Syncs to everyone every thirty minutes. |
| Enterprise | /Library/Application Support/Cursor/hooks.json (macOS), /etc/cursor/hooks.json (Linux/WSL), C:\ProgramData\Cursor\hooks.json (Windows) | The enterprise config folder | Pushed by your IT team (MDM). |
| Plugin | Inside an installed plugin | The plugin's folder (CURSOR_PLUGIN_ROOT) | Command hooks only. Run after all the sources above. |
The common path mistake: project hooks run from the project root, so write .cursor/hooks/format.sh, not ./hooks/format.sh. In ~/.cursor/hooks.json, ./hooks/format.sh is right.
When several sources have hooks for the same event, all of them run and Cursor merges the answers: any deny beats ask, and ask beats allow, whatever the source. user_message and agent_message are joined together. Cursor can also run your Claude Code hooks (see below).
The hooks.json format
This is Cursor's quickstart for a project hook that runs after every file edit:
{
"version": 1,
"hooks": {
"afterFileEdit": [{ "command": ".cursor/hooks/format.sh" }]
}
}
Free rules starter pack for Cursor, Claude Code, Codex and Antigravity
One shared AGENTS.md that works across Cursor, Claude Code, Codex, Copilot and Antigravity, plus database and test rules in each tool's format. Unzip it into your project and fill in two sections. I'll email you the link.
Free. No spam. Unsubscribe anytime. See our privacy note.
#!/bin/bash
# Read input, do something, exit 0
cat > /dev/null
exit 0
chmod +x .cursor/hooks/format.sh
The top level needs "version": 1 and a hooks object. Each event name holds a list, and each entry can take these options:
| Option | What it does | Default |
|---|---|---|
command | The script or shell command to run | Required |
type | "command" runs a script; "prompt" asks a fast model to judge | "command" |
timeout | Time limit in seconds | Platform default |
matcher | A regex that limits when the hook runs ("" or "*" means always) | None |
failClosed | If the hook crashes, times out, exits non-zero or prints nothing, block the action instead of letting it through | false |
loop_limit | How many automatic follow-ups a stop or subagentStop hook may send (null = no limit) | 5 |
Exit codes: 0 means "use my JSON output". 2 blocks the action, the same as "permission": "deny". Any other code counts as the hook failing, and the action goes ahead (fail-open) unless you set failClosed. One catch: for permission hooks (beforeShellExecution, beforeMCPExecution, beforeReadFile, beforeTabFileRead, subagentStart, preToolUse), output that isn't valid JSON, or doesn't match the schema, blocks the action. A stray echo can block every command.
On Windows, the desktop app runs hook commands through PowerShell. A PowerShell script reads the JSON from $input; other programs read stdin.
Every Cursor hook event
| Event | When it fires | What it can do |
|---|---|---|
sessionStart | A new chat is created | Set env vars for later hooks, add context. Can't block. |
sessionEnd | A chat ends | Logging only |
beforeSubmitPrompt | You hit send, before it goes out | Stop the prompt ("continue": false) |
preToolUse | Before any tool (Shell, Read, Write, MCP, Task…) | Allow, deny, or change the input (updated_input) |
postToolUse | After a tool succeeds | Add context; replace MCP output |
postToolUseFailure | A tool fails, times out or is denied | Add context for the retry |
beforeShellExecution | Before a terminal command | Allow, deny or ask |
afterShellExecution | After a terminal command | See the command and its full output |
beforeMCPExecution | Before an MCP tool call | Allow, deny or ask |
afterMCPExecution | After an MCP tool call | See the input and JSON result |
beforeReadFile | Before Agent reads a file | Allow or deny (keep a file away from the model) |
afterFileEdit | After Agent edits a file | Run a formatter, log the edit |
subagentStart | Before a subagent (Task tool) starts | Allow or deny (ask counts as deny) |
subagentStop | A subagent finishes | Send a follow-up message |
preCompact | Before the context window is summarized | Show a message. Can't block. |
stop | The agent loop ends | Send a follow-up so it keeps going |
afterAgentResponse | After each assistant message | Observe the text |
afterAgentThought | After a thinking block | Observe the thinking |
beforeTabFileRead | Before Tab reads a file | Allow or deny |
afterTabFileEdit | After Tab edits a file | Observe (with line ranges) |
workspaceOpen | A workspace opens or its folders change | Return extra plugin paths to load |
Matchers: for preToolUse, postToolUse and postToolUseFailure the regex is tested against the tool type (Shell, Read, Write, Grep, Delete, Task, or MCP:<tool_name>). For the shell hooks it's tested against the full command. For subagent hooks it's the subagent type, like explore or generalPurpose.
What every hook receives: conversation_id, generation_id, model, hook_event_name, cursor_version, workspace_roots, user_email and transcript_path (workspaceOpen gets fewer), plus the event's own fields (for example command and cwd for beforeShellExecution, file_path for afterFileEdit). Scripts also get env vars such as CURSOR_PROJECT_DIR, CURSOR_VERSION and CLAUDE_PROJECT_DIR (an alias, for Claude Code scripts).
Cursor hooks examples
The first three are Cursor's. The last is ours, built only from fields in Cursor's reference; try it on a scratch project first.
1. Ask a model before running a command (prompt hook). No script needed. The model answers with ok and an optional reason, and you can pick the model with a model field.
{
"version": 1,
"hooks": {
"beforeShellExecution": [
{
"type": "prompt",
"prompt": "Does this command look safe to execute? Only allow read-only operations.",
"timeout": 10
}
]
}
}
2. Only check network commands (matcher). The script runs only when the command matches curl|wget|nc.
{
"version": 1,
"hooks": {
"beforeShellExecution": [
{
"command": "./scripts/approve-network.sh",
"timeout": 30,
"matcher": "curl|wget|nc"
}
]
}
}
3. Log everything the agent does. Point any event at this script and it appends each JSON input to /tmp/agent-audit.log. Cursor's Hooks page has longer ones too: block-git.sh, a kubectl apply guard in Python, and a TypeScript stop hook.
#!/bin/bash
# audit.sh - Hook script that writes all JSON input to /tmp/agent-audit.log
# This script is designed to be called by Cursor's hooks system for auditing purposes
# Read JSON input from stdin
json_input=$(cat)
# Create timestamp for the log entry
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# Create the log directory if it doesn't exist
mkdir -p "$(dirname /tmp/agent-audit.log)"
# Write the timestamped JSON entry to the audit log
echo "[$timestamp] $json_input" >> /tmp/agent-audit.log
# Exit successfully
exit 0
4. Our example (VibeKits): keep .env out of the chat, format edits, and run tests when the agent stops. One project hooks.json with three hooks. failClosed makes the .env guard refuse the read if the script breaks. loop_limit caps the test loop at three tries.
{
"version": 1,
"hooks": {
"beforeReadFile": [
{ "command": "python3 .cursor/hooks/no-env-read.py", "failClosed": true }
],
"beforeTabFileRead": [
{ "command": "python3 .cursor/hooks/no-env-read.py", "failClosed": true }
],
"afterFileEdit": [
{ "command": ".cursor/hooks/prettier-after-edit.sh" }
],
"stop": [
{ "command": ".cursor/hooks/tests-on-stop.sh", "loop_limit": 3, "timeout": 300 }
]
}
}
#!/usr/bin/env python3
# OUR example (VibeKits), not from Cursor's docs. A beforeReadFile and
# beforeTabFileRead hook that keeps .env files out of the chat and Tab.
# Field names come from Cursor's hooks reference.
import json, os, sys
data = json.load(sys.stdin)
name = os.path.basename(data.get("file_path") or "")
secret = (name == ".env" or name.startswith(".env.")) and name != ".env.example"
out = {"permission": "deny" if secret else "allow"}
# Tab's output has only "permission", so add a message for Agent reads only
if secret and data.get("hook_event_name") == "beforeReadFile":
out["user_message"] = "Blocked by the no-env-read hook: " + name + " stays out of the chat."
print(json.dumps(out))
#!/bin/bash
# OUR example (VibeKits), not from Cursor's docs. An afterFileEdit hook that
# formats each file the agent edits. Needs jq, and Prettier in node_modules.
file=$(jq -r '.file_path // empty')
[ -x node_modules/.bin/prettier ] || exit 0 # project hooks run from the project root
case "$file" in
*.js|*.jsx|*.ts|*.tsx|*.css|*.json|*.md)
node_modules/.bin/prettier --write "$file" >/dev/null 2>&1 ;;
esac
exit 0
#!/bin/bash
# OUR example (VibeKits), not from Cursor's docs. A stop hook: when the agent
# says it's done, run the tests. If they fail, send it back to fix them.
status=$(jq -r '.status // empty')
if [ "$status" != "completed" ]; then echo '{}'; exit 0; fi
if npm test --silent >/dev/null 2>&1; then
echo '{}'
else
echo '{"followup_message": "npm test is failing. Run it, fix the failures, and stop when it passes."}'
fi
exit 0
chmod +x .cursor/hooks/prettier-after-edit.sh .cursor/hooks/tests-on-stop.sh
# Test a hook by hand before you trust it: pipe in sample JSON
echo '{"hook_event_name":"beforeReadFile","file_path":"/proj/.env"}' | python3 .cursor/hooks/no-env-read.py
# -> {"permission": "deny", "user_message": "Blocked by the no-env-read hook: .env stays out of the chat."}
The .env guard covers Agent's file reads and Tab. It doesn't see a shell command like cat .env; that goes through beforeShellExecution. Treat it as a guard rail, not a lock, and keep real secrets out of the repo.
Cursor hooks vs rules vs skills
The short version: rules and skills are words the agent reads; hooks are code that runs whether the agent agrees or not.
| Hook | Rule | Skill | |
|---|---|---|---|
| What it is | A script (or prompt) run at an event | Instructions added at the start of the model's context | A SKILL.md folder of instructions, scripts and templates |
| Where it lives | .cursor/hooks.json or ~/.cursor/hooks.json | .cursor/rules/*.mdc, user rules, team rules, AGENTS.md | .cursor/skills/ or ~/.cursor/skills/ |
| When it acts | Every time its event fires | Always, by file pattern, when relevant, or when you @ it | When the agent decides it's relevant, or you type /name |
| Can it block an action? | Yes | No, it asks | No, it asks |
| You write | Bash, Python, TypeScript… plus JSON | Markdown with frontmatter | Markdown |
Use a rule for "how we write code here" (see Cursor rules examples), a skill for a step-by-step job you repeat (see Cursor rules vs skills), and a hook for anything that must happen every time, like formatting or refusing a command. Hooks, rules and skills can all ship inside a Cursor plugin.
Cursor hooks vs Claude Code hooks
They work alike: JSON in, JSON out, and exit code 2 blocks in both. Cursor's docs say exit code 2 "matches Claude Code behavior for compatibility." And Cursor can run your Claude Code hooks as they are. With Include Third-Party Plugins, Skills, and Other Configs turned on (Cursor Settings → Agents → Third-Party Imports; on by default), Cursor loads hooks from .claude/settings.local.json, .claude/settings.json and ~/.claude/settings.json. They rank below Cursor's own files.
- Names are mapped for you:
PreToolUse→preToolUse,PostToolUse→postToolUse,UserPromptSubmit→beforeSubmitPrompt, plusStop,SubagentStop,SessionStart,SessionEndandPreCompact.NotificationandPermissionRequestaren't supported. - Tool names too: Claude's
Bashis Cursor'sShell, andEditandWriteboth becomeWrite.Globisn't mapped. - Both answer styles work: Claude Code's nested
hookSpecificOutputand Cursor's flatpermission/updated_input. A ClaudeStophook's"decision": "block"with areasonbecomes a Cursor follow-up message. - Cursor-only:
subagentStart,loop_limitand dashboard distribution need Cursor's ownhooks.jsonformat.
For Claude Code's side, with seven hooks to copy, see Claude Code hooks examples. Claude Code plugins can also carry JavaScript hooks that draw on screen: Claude Code mods.
Hooks in cloud agents and the CLI
Cloud agents run the command hooks in your repo's .cursor/hooks.json (and team and enterprise hooks on Enterprise). They skip user hooks, prompt hooks, sessionStart/sessionEnd, the MCP and Tab hooks and workspaceOpen, and nothing runs during a cloud agent's early read-only turns. Self-hosted workers run the same project hooks, and there sessionStart and sessionEnd fire when a session claims and releases the worker. In the Cursor CLI (agent), workspaceOpen runs too, and the CLI changelog shows plugin hooks running since v2026.08.11 and post-tool hooks firing for subagents since v2026.10.17.
Cursor hooks not working? Check these
- Look first: open Customize and the Hooks tab, and the Hooks output channel. They show configured hooks, runs and errors.
- Not loading: Cursor reloads
hooks.jsonon save; if it still doesn't pick it up, restart Cursor. Check the JSON is valid and has"version": 1. - "No such file": the path is relative to the wrong folder. Project hooks:
.cursor/hooks/x.sh. User hooks:./hooks/x.sh. Make scripts executable withchmod +x. - Project hooks do nothing: they only run in a trusted workspace.
- Hook runs but doesn't block: exit with
2, or print"permission": "deny"and exit0. Other exit codes fail open. ForpreToolUse,"ask"isn't enforced today; usebeforeShellExecutionif you want a prompt. - Everything gets blocked: a permission hook printed something that isn't valid JSON. Send debug text to a log file or stderr, not stdout.
sessionStartcan't stop a chat: it's fire-and-forget. UsebeforeSubmitPromptto stop a prompt.- Stop hook keeps going, or won't: a
followup_messagecontinues the chat, up toloop_limittimes (5 by default). Return{}to let it end. - Only the first folder of a multi-root workspace worked: fixed in Cursor 3.0 (Apr 2, 2026). Update Cursor.
- Turning a hook off ("cursor disable hooks"): remove its entry from
hooks.json(it reloads on save), or manage hooks for each scope from Customize.
Where Cursor's own pages disagree
- Which source wins a merge. The Hooks page says fields like
followup_messageuse the last response, so "a lower-priority source overrides a higher-priority one." The Third Party Hooks page says "higher-priority sources take precedence during merge." Both agreedenybeatsaskbeatsallow. Don't let two sources send different follow-ups. - Is
commandrequired? The options table markscommandas required, and the page says each entry "currently supports acommandproperty." But prompt hooks use"type": "prompt"and apromptfield with nocommand. Follow the prompt-hook example for prompt hooks. $COMMANDin the Third Party Hooks sample. Its exit-code example checks$COMMAND, but the Hooks page says input arrives as JSON on stdin and lists noCOMMANDvariable. Read the command from stdin (for examplejq -r '.command'), as Cursor'sblock-git.shdoes.
Related setups
Hooks enforce; rules and skills explain. Start with Cursor rules examples for the instructions, then add a hook for the one or two things that must never be skipped. Using Claude Code as well? Claude Code hooks examples has the matching set, and Cursor will load them.
Next step for Cursor: Agent Skills
Skills are folders your AI coding agent loads only when the job comes up, and Claude Code, Cursor and OpenAI Codex all read the same SKILL.md format. The Vibe Coder Skills Pack ($9) is 6 ready-to-copy SKILL.md skills (fix-one-bug, stop-the-loop, leak-check, ship-check, explain-project, builder-handoff) for Claude Code, Cursor and OpenAI Codex. Also included in the 6-kit bundle.
Get the Skills Pack for $9 on Gumroad → See what's inside
One .zip of skill folders plus one markdown file. 7-day refund, no questions asked.
Best value
All 6 kits for $29 — or $20.30 with code WELCOME30 (through Nov 30)
Hooks keep Cursor in line. The kits tell it what to build, step by step: a small game, a Discord bot, an email-triage agent, an MVP, or a cleanup of messy code.
Get all 6 kits for $29 → See what's in each kit
$29 instead of $48 for the six kits bought separately; WELCOME30 takes 30% off that at checkout ($20.30). Instant download from Gumroad. 7-day refund, no questions asked.
Related
- Claude Code hooks examples (7 copy-paste hooks, plus Cursor)
- Cursor rules examples (10 copy-paste .mdc rules)
- Cursor rules vs skills (when to use a SKILL.md instead)
- Cursor rules vs AGENTS.md
- Claude Code mods (what a mod is, sample mods, your first mod)
- Kiro hooks (.kiro/hooks JSON, every trigger, exit codes, examples)
- Antigravity hooks (hooks.json, six events, PreToolUse decisions, fixes)
- Custom slash commands (Claude Code, Cursor, Codex, Copilot)
- Cursor vs Claude Code vs Codex for beginners (real prices)
- Vibe coding security checklist (12 checks before you launch)
- Free rules file generator
Sources
- Cursor docs: Hooks
- Cursor docs: Third Party Hooks (Claude Code compatibility)
- Cursor docs: Plugins
- Cursor docs: Customize Cursor
- Cursor docs: Rules
- Cursor docs: Agent Skills (built-in /create-hook)
- Cursor docs: Self-hosted pools (hooks on workers)
- Cursor CLI changelog
- Cursor changelog: New Cursor Interface (3.0, Apr 2, 2026)
- Cursor changelog: Side Chats (new hooks, Jul 10, 2026)
Every file path, event name, field and limit here was checked Nov 9, 2026 on Cursor's own docs and changelogs. Cursor adds hooks and fields often, so the Hooks page in Cursor's docs wins over this page. If something here no longer matches, tell us at [email protected].