AI Engineer Guide

How to Extend Cursor Agent Behavior with Lifecycle Hooks

Cursor (latest version) has a hooks feature similar to Claude Code using it you can run your custom script before/after AI Agent execution lifecycle.

For example, you can run a script that validates if a shell command is safe to run, flag any potential security issue, run formatter after edits, etc

{{> video “https://cursor.com/docs-static/images/agent/hooks.mp4" }}

How does it work?

It runs the script in a new process and communicate over stdio using JSON

Available Hooks

Currently, hooks are available in both (tab/inline completion) and Agent.

As for inline completion, it only has the following two hooks

TriggerDescription
beforeTabFileReadControl file access for Tab completions
afterTabFileEditPost‑process Tab edits

And agents has the following hooks

TriggerDescription
sessionStart / sessionEndSession lifecycle management
beforeShellExecution / afterShellExecutionControl shell commands
beforeMCPExecution / afterMCPExecutionControl MCP tool usage
beforeReadFile / afterFileEditControl file access and edits
beforeSubmitPromptValidate prompts before submission
preCompactObserve context window compaction
stopHandle agent completion
afterAgentResponse / afterAgentThoughtTrack agent responses

How to create a hook?

You can place it at project level ($REPO/.cursor/hooks.json) or globally (~/.cursor/hooks.json)

And it’ll have a structure like this

{
  "version": 1,
  "hooks": {
    "afterFileEdit": [{ "command": "./hooks/custom-script.sh" }]
  }
}

Make sure to set that script as executable

chmod +x ~/.cursor/hooks/custom-script.sh

Now the above script will run after every file edit.

You can use Typescript for custom script as well and you can run it with bun

Something like this:

{
  "version": 1,
  "hooks": {
    "stop": [
      {
        "command": "bun run .cursor/hooks/track-stop.ts --stop"
      }
    ]
  }
}

Reference

#Cursor

Stay Updated

Get the latest AI engineering insights delivered to your inbox.

No spam. Unsubscribe at any time.