Cursor hooks provide a powerful way to run custom scripts in response to AI agent actions, giving you the ability to intercept workflows, inject context, or trigger automations. This lesson introduces the fundamental mechanics of hooks through the beforeReadFile event, which executes a command just before the AI agent accesses a file.
You'll configure the .cursor/hooks.json file, write a simple shell script to capture the JSON payload sent by the hook, and examine the rich contextual data it contains—details like file path, content, and conversation ID. This data opens up endless possibilities for automation and workflow enhancement.
A critical and often-missed step is making your script executable with chmod. Without this, your hooks will fail silently, and you'll wonder why nothing is working. By the end of this lesson, you'll have a working hook and understand the foundation for building more sophisticated automations.
The Configuration: hooks.json
First, create a .cursor directory in your project root and add a hooks.json file. This file defines which scripts to run for specific events. For this example, we'll run a debug.sh script every time the beforeReadFile event is triggered.
The Script: debug.sh
Next, create the debug.sh script inside the .cursor directory. The hook will pass a JSON payload to this script via standard input. We can capture this payload by redirecting stdin to a file.
The Critical Step: Making it Executable
For the hook to successfully run the script, the script file must have execute permissions. This is a common point of failure. Open your terminal and run the following command:
Triggering the Hook
Now, you can ask the agent to perform an action that reads a file.
After the agent attempts to read the file, the hook will execute, and you will find a new stdin.json file in your .cursor directory.
The Result: The Captured Payload
The generated stdin.json file contains a wealth of information about the event, including the conversation context and details about the file being accessed. This data can be parsed and used in more complex scripts to build powerful automations.
