hook-reference.mdx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. ---
  2. title: "Hook Reference"
  3. sidebarTitle: "Hook Reference"
  4. description: "Complete API reference for all Cline hook types, JSON schemas, and field documentation"
  5. ---
  6. This reference provides complete technical documentation for all hook types, their JSON schemas, input/output formats, and communication protocols.
  7. ## Hook Types
  8. Cline provides multiple hook types that let you tap into different stages of the AI workflow. They're organized into categories based on their trigger points and use cases.
  9. <Note>
  10. The hook names below are the exact file names you need to create. For example, to use the TaskStart hook, create a file named `TaskStart` (no file extension) in your hooks directory.
  11. </Note>
  12. Each hook receives base fields in addition to its specific data: `clineVersion`, `hookName`, `timestamp`, `taskId`, `workspaceRoots`, `userId`.
  13. ### Tool Execution Hooks
  14. These hooks intercept and validate tool operations before and after they execute. Use them to enforce policies, track changes, and learn from operations.
  15. #### `PreToolUse`
  16. Triggered immediately before Cline uses any tool (see the [Cline Tools Reference Guide](/cline-tools) for all available tools). Use it to block invalid operations, validate parameters, and enforce project policies before changes happen.
  17. **Input Fields:**
  18. ```json
  19. {
  20. "clineVersion": "string",
  21. "hookName": "PreToolUse",
  22. "timestamp": "string",
  23. "taskId": "string",
  24. "workspaceRoots": ["string"],
  25. "userId": "string",
  26. "preToolUse": {
  27. "toolName": "string",
  28. "parameters": {}
  29. }
  30. }
  31. ```
  32. **Example Usage:**
  33. ```bash
  34. #!/usr/bin/env bash
  35. input=$(cat)
  36. # Block creating .js files in TypeScript projects
  37. tool_name=$(echo "$input" | jq -r '.preToolUse.toolName')
  38. if [[ "$tool_name" == "write_to_file" ]]; then
  39. file_path=$(echo "$input" | jq -r '.preToolUse.parameters.path')
  40. if [[ "$file_path" == *.js ]] && [[ -f "tsconfig.json" ]]; then
  41. echo '{"cancel": true, "errorMessage": "JavaScript files not allowed in TypeScript project"}'
  42. exit 0
  43. fi
  44. fi
  45. echo '{"cancel": false}'
  46. ```
  47. #### `PostToolUse`
  48. Triggered immediately after Cline uses any tool (see the [Cline Tools Reference Guide](/cline-tools) for all available tools). Use it to learn from results, track performance metrics, and build project knowledge based on operations performed.
  49. **Input Fields:**
  50. ```json
  51. {
  52. "clineVersion": "string",
  53. "hookName": "PostToolUse",
  54. "timestamp": "string",
  55. "taskId": "string",
  56. "workspaceRoots": ["string"],
  57. "userId": "string",
  58. "postToolUse": {
  59. "toolName": "string",
  60. "parameters": {},
  61. "result": "string",
  62. "success": boolean,
  63. "executionTimeMs": number
  64. }
  65. }
  66. ```
  67. **Example Usage:**
  68. ```bash
  69. #!/usr/bin/env bash
  70. input=$(cat)
  71. # Log slow operations for performance monitoring
  72. execution_time=$(echo "$input" | jq -r '.postToolUse.executionTimeMs')
  73. tool_name=$(echo "$input" | jq -r '.postToolUse.toolName')
  74. if (( execution_time > 5000 )); then
  75. context="PERFORMANCE: Slow operation detected - $tool_name took ${execution_time}ms"
  76. echo "{\"cancel\": false, \"contextModification\": \"$context\"}"
  77. else
  78. echo '{"cancel": false}'
  79. fi
  80. ```
  81. ### User Interaction Hooks
  82. These hooks monitor and enhance user communication with Cline. Use them to validate input, inject context, and track interaction patterns.
  83. #### `UserPromptSubmit`
  84. Triggered when the user enters text into the prompt box and presses enter to start a new task, continue a completed task, or resume a cancelled task. Use it to validate input, inject context based on the prompt, and track interaction patterns.
  85. **Input Fields:**
  86. ```json
  87. {
  88. "clineVersion": "string",
  89. "hookName": "UserPromptSubmit",
  90. "timestamp": "string",
  91. "taskId": "string",
  92. "workspaceRoots": ["string"],
  93. "userId": "string",
  94. "userPromptSubmit": {
  95. "prompt": "string",
  96. "attachments": ["string"]
  97. }
  98. }
  99. ```
  100. **Example Usage:**
  101. ```bash
  102. #!/usr/bin/env bash
  103. input=$(cat)
  104. # Inject coding standards context for certain keywords
  105. prompt=$(echo "$input" | jq -r '.userPromptSubmit.prompt')
  106. context=""
  107. if echo "$prompt" | grep -qi "component\|react"; then
  108. context="CODING_STANDARDS: Follow React functional component patterns with proper TypeScript types"
  109. elif echo "$prompt" | grep -qi "api\|endpoint"; then
  110. context="CODING_STANDARDS: Use consistent REST API patterns with proper error handling"
  111. fi
  112. if [[ -n "$context" ]]; then
  113. jq -n --arg ctx "$context" '{"cancel": false, "contextModification": $ctx}'
  114. else
  115. echo '{"cancel": false}'
  116. fi
  117. ```
  118. ### Task Lifecycle Hooks
  119. These hooks monitor and respond to task state changes from start to finish. Use them to track progress, restore state, and trigger workflows.
  120. #### `TaskStart`
  121. Triggered once at the beginning of a new task. Use it to detect project type, initialize tracking, and inject initial context that shapes how Cline approaches the work.
  122. **Input Fields:**
  123. ```json
  124. {
  125. "clineVersion": "string",
  126. "hookName": "TaskStart",
  127. "timestamp": "string",
  128. "taskId": "string",
  129. "workspaceRoots": ["string"],
  130. "userId": "string",
  131. "taskStart": {
  132. "taskMetadata": {
  133. "taskId": "string",
  134. "ulid": "string",
  135. "initialTask": "string"
  136. }
  137. }
  138. }
  139. ```
  140. **Example Usage:**
  141. ```bash
  142. #!/usr/bin/env bash
  143. input=$(cat)
  144. # Detect project type and inject relevant context
  145. context=""
  146. if [[ -f "package.json" ]]; then
  147. if grep -q "react" package.json; then
  148. context="PROJECT_TYPE: React application detected. Follow component-based architecture."
  149. elif grep -q "express" package.json; then
  150. context="PROJECT_TYPE: Express.js API detected. Follow RESTful patterns."
  151. else
  152. context="PROJECT_TYPE: Node.js project detected."
  153. fi
  154. elif [[ -f "requirements.txt" ]] || [[ -f "pyproject.toml" ]]; then
  155. context="PROJECT_TYPE: Python project detected. Follow PEP 8 standards."
  156. elif [[ -f "Cargo.toml" ]]; then
  157. context="PROJECT_TYPE: Rust project detected. Follow Rust conventions."
  158. fi
  159. if [[ -n "$context" ]]; then
  160. jq -n --arg ctx "$context" '{"cancel": false, "contextModification": $ctx}'
  161. else
  162. echo '{"cancel": false}'
  163. fi
  164. ```
  165. #### `TaskResume`
  166. Triggered when the user resumes a task that has been cancelled or aborted. Use it to restore state, refresh context, and log resumption for analytics or external system notifications.
  167. **Input Fields:**
  168. ```json
  169. {
  170. "clineVersion": "string",
  171. "hookName": "TaskResume",
  172. "timestamp": "string",
  173. "taskId": "string",
  174. "workspaceRoots": ["string"],
  175. "userId": "string",
  176. "taskResume": {
  177. "taskMetadata": {
  178. "taskId": "string",
  179. "ulid": "string"
  180. },
  181. "previousState": {
  182. "lastMessageTs": "string",
  183. "messageCount": "string",
  184. "conversationHistoryDeleted": "string"
  185. }
  186. }
  187. }
  188. ```
  189. #### `TaskCancel`
  190. Triggered when the user cancels a task or aborts a hook execution. Use it to cleanup resources, log cancellation details, and notify external systems about interrupted work.
  191. **Input Fields:**
  192. ```json
  193. {
  194. "clineVersion": "string",
  195. "hookName": "TaskCancel",
  196. "timestamp": "string",
  197. "taskId": "string",
  198. "workspaceRoots": ["string"],
  199. "userId": "string",
  200. "taskCancel": {
  201. "taskMetadata": {
  202. "taskId": "string",
  203. "ulid": "string"
  204. }
  205. }
  206. }
  207. ```
  208. #### `TaskComplete`
  209. Triggered when Cline finishes its work and successfully executes the `attempt_completion` tool to finalize the task output. Use it to track completion metrics, generate reports, log task outcomes, and trigger completion workflows.
  210. **Input Fields:**
  211. ```json
  212. {
  213. "clineVersion": "string",
  214. "hookName": "TaskComplete",
  215. "timestamp": "string",
  216. "taskId": "string",
  217. "workspaceRoots": ["string"],
  218. "userId": "string",
  219. "taskComplete": {
  220. "taskMetadata": {
  221. "taskId": "string",
  222. "ulid": "string"
  223. }
  224. }
  225. }
  226. ```
  227. **Example Usage:**
  228. ```bash
  229. #!/usr/bin/env bash
  230. input=$(cat)
  231. # Extract task metadata
  232. task_id=$(echo "$input" | jq -r '.taskComplete.taskMetadata.taskId // "unknown"')
  233. ulid=$(echo "$input" | jq -r '.taskComplete.taskMetadata.ulid // "unknown"')
  234. # Log completion
  235. completion_log="$HOME/.cline_completions/$(date +%Y-%m-%d).log"
  236. mkdir -p "$(dirname "$completion_log")"
  237. echo "$(date -Iseconds): Task $task_id completed (ULID: $ulid)" >> "$completion_log"
  238. # Provide context about completion
  239. context="TASK_COMPLETED: Task $task_id finished successfully. Completion logged."
  240. jq -n --arg ctx "$context" '{"cancel": false, "contextModification": $ctx}'
  241. ```
  242. ### System Events Hooks
  243. These hooks monitor internal Cline operations and system-level events. Use them to track context usage, log system behavior, and analyze performance patterns.
  244. ## JSON Communication Protocol
  245. Hooks receive JSON via stdin and return JSON via stdout.
  246. ### Input Format
  247. All hooks receive a JSON object through stdin with this base structure:
  248. ```json
  249. {
  250. "clineVersion": "string",
  251. "hookName": "string",
  252. "timestamp": "string",
  253. "taskId": "string",
  254. "workspaceRoots": ["string"],
  255. "userId": "string",
  256. "[hookSpecificField]": {
  257. // Hook-specific data structure
  258. }
  259. }
  260. ```
  261. ### Output Format
  262. Your hook script must output a JSON response as the final stdout content:
  263. ```json
  264. {
  265. "cancel": false,
  266. "contextModification": "WORKSPACE_RULES: Use TypeScript",
  267. "errorMessage": "Error details if blocking"
  268. }
  269. ```
  270. **Field Descriptions:**
  271. - **`cancel`** (required): Boolean controlling whether execution continues
  272. - `true`: Block the current action
  273. - `false`: Allow the action to proceed
  274. - **`contextModification`** (optional): String that gets injected into the conversation
  275. - Affects future AI decisions, not the current one
  276. - Use clear prefixes like `WORKSPACE_RULES:`, `PERFORMANCE:`, `SECURITY:` for categorization
  277. - Maximum length: 50KB
  278. - **`errorMessage`** (optional): String shown to user when `cancel` is `true`
  279. - Only displayed when blocking an action
  280. - Should explain why the action was blocked
  281. ### Logging During Execution
  282. Your hook script can output logging or diagnostic information to stdout during execution, as long as the JSON response is the last thing written:
  283. ```bash
  284. #!/usr/bin/env bash
  285. echo "Processing hook..." # This is fine
  286. echo "Tool: $tool_name" # This is also fine
  287. # The JSON must be last:
  288. echo '{"cancel": false}'
  289. ```
  290. Cline will parse only the final JSON object from stdout.
  291. ### Error Handling
  292. Hook execution errors don't prevent task execution - only returning `"cancel": true` can halt a task. All other errors are treated as hook failures, not reasons to abort the task.
  293. **Hook Status Display:**
  294. - **Completed** (grey): Hook executed successfully, regardless of whether it returned `"cancel": false` or no JSON output
  295. - **Failed** (red): Hook exited with non-zero status, output invalid JSON, or timed out. The UI displays the error details (e.g., exit code number)
  296. - **Aborted** (red): Hook returned `"cancel": true`, halting the task. User must manually resume the task to continue
  297. **Important:** Even when a hook fails (non-zero exit, invalid JSON, timeout), Cline continues with the task. Only `"cancel": true` stops execution.
  298. ### Context Modification Timing
  299. Context injection affects future decisions, not current ones. When a hook runs:
  300. 1. The AI has already decided what to do
  301. 2. The hook can block or allow it
  302. 3. Any context gets added to the conversation
  303. 4. The next AI request sees that context
  304. This means:
  305. - **PreToolUse hooks**: Use for blocking bad actions + injecting context for next decision
  306. - **PostToolUse hooks**: Use for learning from completed actions
  307. ### Helpful Tip: String Escaping in JSON
  308. When your hook needs to include strings containing unescaped quote characters (`"`) in JSON output, use jq's `--arg` flag for proper escaping:
  309. ```bash
  310. #!/usr/bin/env bash
  311. # When $output contains unescaped quote characters (")...
  312. output='{"foo":"bar"}'
  313. # Use the --arg flag for automatic string escaping
  314. jq -n --arg ctx "$output" '{cancel: false, contextModification: $ctx}'
  315. # This will result in:
  316. # {
  317. # "cancel": false,
  318. # "contextModification": "{\"foo\":\"bar\"}"
  319. # }
  320. ```
  321. The `--arg` flag automatically escapes special characters, preventing JSON parsing errors when your context modification includes complex strings or nested JSON structures.
  322. ## Hook Execution Environment
  323. ### Execution Context
  324. Hooks are executable scripts that run with the same permissions as VS Code. They have unrestricted access to:
  325. - The entire filesystem (any file the user can access)
  326. - All environment variables
  327. - System commands and tools
  328. - Network resources
  329. Hooks can perform any operation the user could perform in a terminal, including reading and writing files outside the workspace, making network requests, and executing system commands.
  330. ### Security Considerations
  331. <Warning>
  332. Hooks run with the same permissions as VS Code. They can access all workspace files and environment variables. Review hooks from untrusted sources before enabling them.
  333. </Warning>
  334. ### Performance Guidelines
  335. Hooks have a 30 second timeout. As long as your hook completes within this time, it can perform any operations needed, including network calls or heavy computations.
  336. ### Hook Discovery
  337. Cline searches for hooks in this order:
  338. 1. Project-specific: `.clinerules/hooks/` in workspace root
  339. 2. User-global: `~/Documents/Cline/Hooks/`
  340. Project-specific hooks override global hooks with the same name.