सामग्री पर जाएँ

लेसन 18 · Tools, Terminal and MCP

Hooks: Automate and Guard the Agent

Use Cursor hooks to run your own scripts before and after agent actions: hooks.json, events, JSON input and output, exit codes and fail-closed settings.

A rule asks the model to behave. A hook is your own program that runs at a set moment in the agent's work, so it can observe, format or block an action. Use hooks for things that should happen at that moment whatever the model decides.

hooks.json

Project hooks live in .cursor/hooks.json, and personal ones in ~/.cursor/hooks.json. Administrators can also set enterprise and team hooks, which have higher priority. A file has a version (use 1) and a hooks object that maps event names to lists:

JSON
{
  "version": 1,
  "hooks": {
    "afterFileEdit": [
      { "command": ".cursor/hooks/format.sh" }
    ],
    "beforeShellExecution": [
      {
        "command": "python3 .cursor/hooks/guard.py",
        "timeout": 10,
        "failClosed": true
      }
    ]
  }
}

Project hook commands run from the project root. Other documented options include matcher (a regular expression that filters when the hook runs), type (command by default, or prompt for a check judged by a model) and loop_limit, which caps automatic follow-ups.

Common events

Event Moment
sessionStart, sessionEnd A session begins or ends
beforeShellExecution, afterShellExecution Around terminal commands
beforeMCPExecution, afterMCPExecution Around MCP tool calls
beforeReadFile Before the agent reads a file
afterFileEdit After the agent edits a file
beforeSubmitPrompt Before your prompt is sent
preToolUse, postToolUse Around tool calls in general
stop The agent finishes

There are also events for subagents, context compaction, Tab file access and opening a workspace. Check the documentation for the current list.

Input, output and exit codes

A command hook receives JSON on standard input. It includes fields such as hook_event_name and workspace_roots, plus data for the event. For beforeShellExecution, that includes command and cwd.

A permission hook replies with JSON on standard output. It contains permission, which is allow, deny or ask, with optional user_message and agent_message.

Exit code Meaning
0 Success; the JSON output is used
2 Block the action
Any other The hook failed; the action continues unless failClosed is true

That last row is important. By default, a crashing hook fails open. For security checks, set failClosed: true. The documentation also says that for permission hooks, invalid JSON output with exit code 0 blocks the action. When several hooks match, all run, and deny beats ask, which beats allow.

Not every event supports every answer. For example, the documentation says ask is not enforced for preToolUse. Read the notes for your event and test the behavior.

A guard script

Here is the decision logic of a guard for shell commands, as real Python. On this site it reads sample events from a list. A real hook reads one JSON object from standard input.

Python The decision logic of a shell guard hook

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the file you save as guard.py, replace the sample loop with these lines:

Python
import sys

print(json.dumps(decide(json.load(sys.stdin))))

An allow answer from a hook means this hook does not object. Test how it combines with your run mode, and consider returning allow only for events you have really checked.

Pattern guards are limited

A blocklist can be bypassed. The same effect has many spellings. Test your guard against them:

Python Test your guard against tricks

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Treat such a hook as a seat belt, not a wall. Combine it with sandboxing, narrow allowlists, limited credentials and backups.

Good uses

  • Format files after edits.
  • Log which commands ran, without storing secrets.
  • Block reading of specific sensitive paths.
  • Send one follow-up when a run stops, such as a reminder to run tests, with a loop limit.

Hooks run your programs with real access, and their input can include data such as file contents or your email address. Review project hooks before you trust a repository. Git hooks are a different mechanism that runs at Git events.

Develop a hook step by step

Hooks are small programs, so build them like programs:

  1. Write the decision as a plain function, as in the example above.
  2. Test it with many sample events, including odd and empty input.
  3. Wrap it with a few lines that read and write JSON.
  4. Run the script in a terminal by piping a sample event into it.
  5. Add it to hooks.json in a practice project.
  6. Trigger it on purpose, once for each kind of answer.

Check the behavior when things go wrong: a missing interpreter, a syntax error and a timeout. With failClosed, a broken hook blocks work, which is the point for a security check, but your team needs to know how to repair it. Keep hooks fast, because a hook on a common event runs again and again.

The command that starts a hook can differ between systems. For example, the name of the Python command is not the same on every machine, so test shared hooks on each operating system your team uses.

Common mistakes

  • Forgetting failClosed on a security check.
  • Printing debug text to standard output, which breaks the JSON reply. Write debug messages to standard error.
  • Assuming a hook works without triggering it once on purpose.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does exit code 2 do in a command hook?

    Exit code 2 is documented as blocking the action.
  2. 2. A security hook crashes and failClosed is not set. What happens?

    Hooks fail open by default, so set failClosed for security checks.
  3. 3. Why is a pattern blocklist not enough?

    Use it as one layer next to sandboxing and limited permissions.

Summary

  • Hooks run your code at defined points of the agent's work.
  • Configure them in hooks.json; input and output are JSON.
  • Exit code 2 blocks; other failures are fail-open unless failClosed is set.
  • Test guards and keep other protections.

Next: Reviewing AI-Written Changes

आपकी प्रगति इसी ब्राउज़र में सेव होती है। खाते की ज़रूरत नहीं है।