# Cursor Features and Practical Usage
🪝 Want to bake "auto-format on edit" or "block dangerous commands" into the agent's behavior? Cursor Hooks let you intervene at each stage of the agent loop.
🏷️ Title: Agent Loop Interception (JSON)
🔗 URL:
📘 Overview
Hooks are processes spawned to observe, control, and extend the agent loop. They communicate over stdio using JSON in both directions and run before or after defined stages of the loop. Use them for formatting, audit logging, secret scanning, and gating risky operations.
⚙️ How It Works
Configure hooks in `hooks.json`, with priority Enterprise → Team → project (`
/.cursor/hooks.json`) → user (`~/.cursor/hooks.json`). Key events include:
・`beforeShellExecution` / `afterShellExecution`: gate shell commands and post-process
・`beforeReadFile` / `afterFileEdit`: around file reads and edits
・`beforeMCPExecution`, `beforeSubmitPrompt`, `sessionStart`, `stop`, and more
Each hook receives JSON on stdin (`conversation_id`, `model`, `hook_event_name`, etc.) and returns JSON on stdout. Control hooks return `{"permission":"allow"|"deny"|"ask"}`, and on `deny` you can attach `user_message` / `agent_message`. Exit code 0 means success, 2 blocks the action (equivalent to deny), and other codes fail open (unless `failClosed: true`).
🛠️ Practical Usage
Auto-format after edits with `afterFileEdit`: read the JSON from stdin, pull `.file_path` with `jq`, run `prettier --write` on it, and exit 0.
Block dangerous SQL or destructive commands with `beforeShellExecution`: inspect the command string and, if it matches, return `echo '{"permission":"deny","user_message":"This SQL is not allowed"}'`. For PII or secret scanning, register a `beforeReadFile` hook with `"failClosed": true` so that if the scan fails, content is never passed to the model and you fail safe.
💡 Use Cases
Enforce formatting, linting, and commit conventions across the whole team. Gate production DB writes or `rm -rf`-style commands. Keep fire-and-forget audit logs via `sessionEnd` or `postToolUse`. Use a `matcher` to filter by tool type or command pattern so the hook runs only when needed.
⚠️ Caveats
Mind the working directory: project hooks run from the project root, user hooks from `~/.cursor/`, and wrong paths fail silently. The default is fail-open, so always add `failClosed: true` to security-critical hooks. Invalid output JSON causes the hook itself to fail. Cursor auto-reloads `hooks.json`, but restart if changes do not take effect. Cloud agents support command-type hooks only; `sessionStart`, `beforeMCPExecution`, Tab hooks, and prompt-type hooks are not available there.
#Cursor# #DevSecOps#