Home › Rules › Cursor hooks

Cursor hooks: hooks.json, every event, examples, and fixes

From Cursor's own docs (Hooks, Third Party Hooks, Plugins, Customize Cursor) and changelogs, checked Nov 9, 2026. Sources below.

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

SourceFileScripts run fromGood to know
Project<project>/.cursor/hooks.jsonThe project rootChecked 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.
TeamSet in the web dashboardThe managed hooks folderEnterprise 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 folderPushed by your IT team (MDM).
PluginInside an installed pluginThe 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:

1. .cursor/hooks.json
{
  "version": 1,
  "hooks": {
    "afterFileEdit": [{ "command": ".cursor/hooks/format.sh" }]
  }
}
2. .cursor/hooks/format.sh (Cursor's starter script)
#!/bin/bash
# Read input, do something, exit 0
cat > /dev/null
exit 0
3. Make it executable
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:

OptionWhat it doesDefault
commandThe script or shell command to runRequired
type"command" runs a script; "prompt" asks a fast model to judge"command"
timeoutTime limit in secondsPlatform default
matcherA regex that limits when the hook runs ("" or "*" means always)None
failClosedIf the hook crashes, times out, exits non-zero or prints nothing, block the action instead of letting it throughfalse
loop_limitHow 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

EventWhen it firesWhat it can do
sessionStartA new chat is createdSet env vars for later hooks, add context. Can't block.
sessionEndA chat endsLogging only
beforeSubmitPromptYou hit send, before it goes outStop the prompt ("continue": false)
preToolUseBefore any tool (Shell, Read, Write, MCP, Task…)Allow, deny, or change the input (updated_input)
postToolUseAfter a tool succeedsAdd context; replace MCP output
postToolUseFailureA tool fails, times out or is deniedAdd context for the retry
beforeShellExecutionBefore a terminal commandAllow, deny or ask
afterShellExecutionAfter a terminal commandSee the command and its full output
beforeMCPExecutionBefore an MCP tool callAllow, deny or ask
afterMCPExecutionAfter an MCP tool callSee the input and JSON result
beforeReadFileBefore Agent reads a fileAllow or deny (keep a file away from the model)
afterFileEditAfter Agent edits a fileRun a formatter, log the edit
subagentStartBefore a subagent (Task tool) startsAllow or deny (ask counts as deny)
subagentStopA subagent finishesSend a follow-up message
preCompactBefore the context window is summarizedShow a message. Can't block.
stopThe agent loop endsSend a follow-up so it keeps going
afterAgentResponseAfter each assistant messageObserve the text
afterAgentThoughtAfter a thinking blockObserve the thinking
beforeTabFileReadBefore Tab reads a fileAllow or deny
afterTabFileEditAfter Tab edits a fileObserve (with line ranges)
workspaceOpenA workspace opens or its folders changeReturn 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.

Cursor's example: prompt-based beforeShellExecution hook
{
  "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.

Cursor's example: a matcher on beforeShellExecution
{
  "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.

Cursor's example: audit.sh
#!/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.

Our example (VibeKits): .cursor/hooks.json
{
  "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 }
    ]
  }
}
Our example (VibeKits): .cursor/hooks/no-env-read.py
#!/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))
Our example (VibeKits): .cursor/hooks/prettier-after-edit.sh
#!/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
Our example (VibeKits): .cursor/hooks/tests-on-stop.sh
#!/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
Make them executable and test one by hand
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.

HookRuleSkill
What it isA script (or prompt) run at an eventInstructions added at the start of the model's contextA 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 actsEvery time its event firesAlways, by file pattern, when relevant, or when you @ itWhen the agent decides it's relevant, or you type /name
Can it block an action?YesNo, it asksNo, it asks
You writeBash, Python, TypeScript… plus JSONMarkdown with frontmatterMarkdown

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.

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

Where Cursor's own pages disagree

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

Sources

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].

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.

After that, an occasional email when I publish a new guide or rules file.

Free. No spam. Unsubscribe anytime. See our privacy note.