All Agent Engineering

Build a Cursor Hooks review policy for tool calls

Pick the right hook event, fix its input contract, decide allow, deny or ask, merge across sources, then verify logs and cloud exceptions. Docs only.

AINavWritten / Updated
On this page

At a glance

Hooks are processes Cursor spawns at defined stages of the agent loop, exchanging JSON over stdio in both directions, so they can observe, block or modify behavior. They are configured in .cursor/hooks.json at the project root or ~/.cursor/hooks.json in your home directory, and every matching hook from every source runs before the responses merge. This guide does not claim that adding an interceptor makes you safe. It walks the event contract instead: pick the event, fix the input fields, decide output and failure posture, handle multi-source merging, write the log, and record the cloud and HTTP MCP exceptions. Statements such as preToolUse accepting ask in the schema without enforcing it come from that page.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • Cursor Build a Cursor Hooks review policy for tool calls

Execution locations and responsibilities

  • Cursor Agent execution environment and host Use the workflow below to distinguish responsibilities of the caller, runtime, and external actions.
Engineering workflow order
Engineering workflow order1. 1. Pick the event and write the condition → 2. 2. Choose the config source and path form → 3. 3. Fix the input fields → 4. 4. Decide output and failure posture → 5. 5. Write the log and handle sensitive content → 6. 6. Handle merging across sources → 7. 7. Verify and record the exceptions. Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.1. 1. Pick the event and write the condition2. 2. Choose the config source and path form3. 3. Fix the input fields4. 4. Decide output and failure posture5. 5. Write the log and handle sensitive content6. 6. Handle merging across sources7. 7. Verify and record the exceptions

Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.

When to use

  • Different events carry different input. beforeShellExecution gives command, cwd and sandbox; beforeMCPExecution gives tool_name, tool_input and mcp_server_name plus a url for HTTP or SSE servers or a command for stdio servers; beforeReadFile gives the file path and contents; preToolUse is the generic entry point for all tool types and filters with matcher. Session fields apply to Agent-session events; workspaceOpen lacks conversation_id, generation_id, model, session_id and transcript_path. Read each event schema instead of assuming identical common fields.

When not to use

  • Failures default to allowing: exit codes other than 0 and 2 are logged and the action proceeds, so blocking requires failClosed to be turned on explicitly.
  • Permission hooks block when JSON is invalid or does not match the schema, the opposite direction from ordinary failures; a branch written the wrong way reverses the behavior entirely.
  • ask is not universal: preToolUse accepts it in the schema but does not enforce it, while subagentStart treats ask as deny, so the two cannot share one assumption.
  • Cloud agents run command-based hooks only, do not load user-level hooks.json, and do not apply sessionStart, sessionEnd or the MCP before and after hooks.
  • For backend HTTP MCP tools specifically under documented Cloud agent support, preToolUse can deny but ignores updated_input and postToolUse receives redacted output it cannot replace. Do not apply this restriction to every local HTTP MCP tool.
  • The page provides no official validator and no restriction on script language; the example here is an original illustration and your implementation defines the script's behavior.

Prerequisites and input

  • You have decided which class of action to review: shell commands, MCP tools, file reads, or generic tool calls that cover every tool type.
  • You know which directory the hook script will run in: project hooks run from the project root and user hooks from ~/.cursor, so the relative path differs between them.
  • You accept one premise up front: crashes, timeouts and non-zero exit codes other than 2 fail open, unless failClosed is enabled on the hook definition.

Engineering checks

The trigger decides what you can see — Different events carry different input. beforeShellExecution gives command, cwd and sandbox; beforeMCPExecution gives tool_name, tool_input and mcp_server_name plus a url for HTTP or SSE servers or a command for stdio servers; beforeReadFile gives the file path and contents; preToolUse is the generic entry point for all tool types and filters with matcher. Session fields apply to Agent-session events; workspaceOpen lacks conversation_id, generation_id, model, session_id and transcript_path. Read each event schema instead of assuming identical common fields.

The output decides allow or block — Permission hooks return permission as allow, deny or ask, but not every event enforces ask. Exit code 2 is equivalent to deny. For permission hooks, invalid JSON or a response that does not match the schema blocks the action, which runs opposite to how ordinary failures are handled. Allowing returns allow with exit code 0 so the JSON output is used.

Sources and failure posture decide the final result — Enterprise, team, project and user hooks all run, and responses merge with deny beating ask and ask beating allow, while user_message and agent_message are concatenated; fields with priority order follow the source order. Crashes, timeouts and non-zero codes other than 2 fail open unless failClosed is set. Plugin hooks come after all sources and are command hooks only.

1. 1. Pick the event and write the condition

Where: the hook event table. Input: the action you want to review. Action: choose one or two events from preToolUse, beforeShellExecution, beforeMCPExecution and beforeReadFile, and write the condition, for example "the command starts with kubectl apply, carries -f, and targets a production namespace". Completion check: one concrete call can prove the condition true or false. Stop condition: if the condition needs a field that event does not provide, switch events or move the check to after execution rather than guessing at field names.

2. 2. Choose the config source and path form

Where: <project>/.cursor/hooks.json or ~/.cursor/hooks.json. Input: whether the team shares this policy. Action: for a shared policy use the project file and write .cursor/hooks/... paths; to affect only yourself use the user file and write ./hooks/... Priority runs enterprise, team, project, user, with plugin hooks last. Completion check: every command path matches the working directory of that source. Stop condition: if a cloud agent must also run this, move to the project file, because user-level ~/.cursor/hooks.json is not available in cloud agents.

3. 3. Fix the input fields

Where: hook input parsing. Input: the actual event type. beforeShellExecution reads top-level command/cwd; beforeMCPExecution reads mcp_server_name, tool_name and string-valued tool_input; preToolUse reads tool_name and object-valued tool_input, with shell command inside tool_input. Generic MCP preToolUse must not require mcp_server_name. File events follow their file_path contract. Read common fields only where applicable; workspaceOpen lacks session common fields. Completion: verify fields, types and missing-value branches per event. Stop with the documented deny recommendation for a dedicated beforeMCPExecution missing its required server name, without transferring an unsupported-field check to generic preToolUse.

4. 4. Decide output and failure posture

Where: the output JSON and the hook definition. Input: the condition from step 1. Action: return allow to proceed, deny or exit code 2 to block, and use ask when a person should confirm after checking that the event actually enforces ask. Turn on failClosed for security-critical hooks so crashes and timeouts block rather than pass. Completion check: every branch has a return value, and the policy records whether that event supports ask. Stop condition: if you depend on ask and the event does not enforce it, stop and convert that branch into deny plus a user-facing message.

5. 5. Write the log and handle sensitive content

Where: a local log file outside the workspace. Input: the event input and your decision. Action: record the time, event name, decision and the fields used to decide. tool_input and command text can carry credentials, so do not write them verbatim. Completion check: the log can reconstruct one decision and contains no plaintext credentials. Stop condition: if the log would land in a version-controlled directory, stop and move it outside the workspace.

6. 6. Handle merging across sources

Where: the hooks.json files at enterprise, team, project and user level. Input: the configurations that already exist. Action: expect deny to beat ask and ask to beat allow when several hooks run, and do not assume your allow overrides a deny elsewhere; read the conditions of any team or enterprise hook already deployed. Completion check: the policy states which sources can act at the same time in this project. Stop condition: when a team or enterprise hook conflicts with local intent, stop working around it locally and raise the change with the administrator.

7. 7. Verify and record the exceptions

Where: the Hooks tab in Customize and the Hooks output channel. Input: the condition from step 1 and one real call. Action: make one real call and check whether it is allowed or blocked as intended. Cursor reloads hooks.json on save, so if nothing happens check relative paths first. Record cloud behavior separately: cloud agents run command hooks only, and sessionStart, sessionEnd, beforeMCPExecution, afterMCPExecution and the Tab hooks do not apply. For tools on HTTP MCP servers, preToolUse can deny but Cursor ignores updated_input, and postToolUse receives a redacted tool_output. Completion check: both the allow and the block path were verified once, and the cloud and HTTP MCP exceptions are written down. Stop condition: do not finish after verifying only the allow path; the block path needs a run as well. The ignored input edits and redacted output limits here apply specifically to backend HTTP MCP under documented Cloud agent support, not every local HTTP MCP tool.

Task example

This complete example targets a local practice repository, not production namespace policy. Confirm Python 3 is available and save the code below as .cursor/hooks/shell_guard.py. The interpreter runs it, so a script executable bit is unnecessary. In project .cursor/hooks.json use {"version":1,"hooks":{"beforeShellExecution":[{"command":"python3 .cursor/hooks/shell_guard.py","timeout":10,"failClosed":true}]}}. beforeShellExecution supports ask: this example allows only the whole command pwd, asks for human review otherwise, and denies malformed input or JSON. The definition explicitly chooses timeout and failClosed, rather than relying on default allow after a missing script, crash or timeout. This tiny allowlist is not a production command parser.

Example: local hook JSON guard
python
import json
import sys

try:
    payload = json.load(sys.stdin)
    command = payload.get("command")
    if not isinstance(command, str):
        decision = "deny"
    elif command == "pwd":
        decision = "allow"
    else:
        decision = "ask"
except (ValueError, TypeError, AttributeError):
    decision = "deny"

print(json.dumps({
    "permission": decision,
    "user_message": "Demo shell policy: review any command except pwd.",
    "agent_message": "Demo shell policy: review any command except pwd."
}))

Offline cases check command=pwd for allow, another command for ask, and bad JSON for deny. Still verify actual execution, approval and denial in the Cursor Hooks output channel. No real client or external command was executed.

Completion checks

  • The chosen event covers the action you want to control, and the condition was checked against one concrete call.
  • Config paths match the working directory of their source, with project hooks written as .cursor/hooks/....
  • Every output branch has an explicit return value, and whether the event enforces ask is checked and recorded.
  • failClosed on security-critical hooks is a deliberate choice rather than the default left in place.
  • Both the allow and the block path were verified, and the log reconstructs the decision without plaintext credentials.
  • Cloud support and backend HTTP MCP exceptions are recorded separately without applying them to the general local preToolUse/postToolUse contract.

Verification scope

Official documentation was read and the example Python JSON branches were checked offline. Cursor was not installed or signed in, no hook ran in its real client, no external command was issued, and no real tool output was observed. Cloud and local scopes stay separate. The sample covers a whole-command pwd allowlist and human requests for other commands; it establishes no production parser or access isolation.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. Cursor · Cursor documentation: cursor-hooks

Found an error? Tell us →