{"meta":{"title":"Pre-tool use hook","intro":"The onPreToolUse hook is called before a tool executes. Use it to:","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/enterprise-cloud@latest/copilot","title":"GitHub Copilot"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos","title":"How-tos"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks","title":"Use hooks"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks/pre-tool-use","title":"Pre Tool Use"}],"documentType":"article"},"body":"# Pre-tool use hook\n\nThe onPreToolUse hook is called before a tool executes. Use it to:\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n* Approve or deny tool execution\n* Modify tool arguments\n* Add context for the tool\n* Suppress tool output from the conversation\n\n## Hook signature\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\ntype PreToolUseHandler = (\n  input: PreToolUseHookInput,\n  invocation: HookInvocation\n) => Promise<PreToolUseHookOutput | null | undefined>;\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nPreToolUseHandler = Callable[\n    [PreToolUseHookInput, dict[str, str]],\n    Awaitable[PreToolUseHookOutput | None]\n]\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\ntype PreToolUseHandler func(\n    input PreToolUseHookInput,\n    invocation HookInvocation,\n) (*PreToolUseHookOutput, error)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\npublic delegate Task<PreToolUseHookOutput?> PreToolUseHandler(\n    PreToolUseHookInput input,\n    HookInvocation invocation);\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n```java\n@FunctionalInterface\npublic interface PreToolUseHandler {\n    CompletableFuture<PreToolUseHookOutput> handle(\n        PreToolUseHookInput input,\n        HookInvocation invocation);\n}\n```\n\n</div>\n\n</div>\n\n## Input\n\n| Field       | Type   | Description                                |\n| ----------- | ------ | ------------------------------------------ |\n| `timestamp` | number | Unix timestamp when the hook was triggered |\n| `cwd`       | string | Current working directory                  |\n| `toolName`  | string | Name of the tool being called              |\n| `toolArgs`  | object | Arguments passed to the tool               |\n\n## Output\n\nReturn `null` or `undefined` to allow the tool to execute with no changes. Otherwise, return an object with any of these fields:\n\n| Field                      | Type                             | Description                                       |\n| -------------------------- | -------------------------------- | ------------------------------------------------- |\n| `permissionDecision`       | `\"allow\"` \\| `\"deny\"` \\| `\"ask\"` | Whether to allow the tool call                    |\n| `permissionDecisionReason` | string                           | Explanation shown to user (for deny/ask)          |\n| `modifiedArgs`             | object                           | Modified arguments to pass to the tool            |\n| `additionalContext`        | string                           | Extra context injected into the conversation      |\n| `suppressOutput`           | boolean                          | If true, tool output won't appear in conversation |\n\n### Permission decisions\n\n| Decision  | Behavior                                       |\n| --------- | ---------------------------------------------- |\n| `\"allow\"` | Tool executes normally                         |\n| `\"deny\"`  | Tool is blocked, reason shown to user          |\n| `\"ask\"`   | User is prompted to approve (interactive mode) |\n\n### Skipping permission prompts for trusted custom tools\n\nIf you define a custom tool that is safe to run without prompting, set `skipPermission: true` on the tool definition. Use this for trusted, app-owned tools whose inputs are already constrained by your application; use `onPreToolUse` when you need per-call policy checks or argument validation.\n\n```typescript\nconst getWeather = defineTool(\"get_weather\", {\n  description: \"Get weather for a location.\",\n  parameters: {\n    type: \"object\",\n    properties: { location: { type: \"string\" } },\n    required: [\"location\"],\n  },\n  skipPermission: true,\n  handler: async ({ location }) => ({ forecast: `Sunny in ${location}` }),\n});\n```\n\n## Examples\n\n### Allow all tools (logging only)\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nconst session = await client.createSession({\n  hooks: {\n    onPreToolUse: async (input, invocation) => {\n      console.log(`[${invocation.sessionId}] Calling ${input.toolName}`);\n      console.log(`  Args: ${JSON.stringify(input.toolArgs)}`);\n      return { permissionDecision: \"allow\" };\n    },\n  },\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nfrom copilot.session import PermissionHandler\n\nasync def on_pre_tool_use(input_data, invocation):\n    print(f\"[{invocation['session_id']}] Calling {input_data['toolName']}\")\n    print(f\"  Args: {input_data['toolArgs']}\")\n    return {\"permissionDecision\": \"allow\"}\n\nsession = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={\"on_pre_tool_use\": on_pre_tool_use})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nsession, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{\n    Hooks: &copilot.SessionHooks{\n        OnPreToolUse: func(input copilot.PreToolUseHookInput, inv copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {\n            fmt.Printf(\"[%s] Calling %s\\n\", inv.SessionID, input.ToolName)\n            fmt.Printf(\"  Args: %v\\n\", input.ToolArgs)\n            return &copilot.PreToolUseHookOutput{\n                PermissionDecision: \"allow\",\n            }, nil\n        },\n    },\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nvar session = await client.CreateSessionAsync(new SessionConfig\n{\n    Hooks = new SessionHooks\n    {\n        OnPreToolUse = (input, invocation) =>\n        {\n            Console.WriteLine($\"[{invocation.SessionId}] Calling {input.ToolName}\");\n            Console.WriteLine($\"  Args: {input.ToolArgs}\");\n            return Task.FromResult<PreToolUseHookOutput?>(\n                new PreToolUseHookOutput { PermissionDecision = \"allow\" }\n            );\n        },\n    },\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nimport com.github.copilot.*;\nimport com.github.copilot.rpc.*;\nimport java.util.concurrent.CompletableFuture;\n\nvar hooks = new SessionHooks()\n    .setOnPreToolUse((input, invocation) -> {\n        System.out.println(\"[\" + invocation.getSessionId() + \"] Calling \" + input.getToolName());\n        System.out.println(\"  Args: \" + input.getToolArgs());\n        return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());\n    });\n\nvar session = client.createSession(\n    new SessionConfig()\n        .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n        .setHooks(hooks)\n).get();\n```\n\n</div>\n\n</div>\n\n### Block specific tools\n\n```typescript\nconst BLOCKED_TOOLS = [\"shell\", \"bash\", \"write_file\", \"delete_file\"];\n\nconst session = await client.createSession({\n  hooks: {\n    onPreToolUse: async (input) => {\n      if (BLOCKED_TOOLS.includes(input.toolName)) {\n        return {\n          permissionDecision: \"deny\",\n          permissionDecisionReason: `Tool '${input.toolName}' is not permitted in this environment`,\n        };\n      }\n      return { permissionDecision: \"allow\" };\n    },\n  },\n});\n```\n\n### Modify tool arguments\n\n```typescript\nconst session = await client.createSession({\n  hooks: {\n    onPreToolUse: async (input) => {\n      // Add a default timeout to all shell commands\n      if (input.toolName === \"shell\" && input.toolArgs) {\n        const args = input.toolArgs as { command: string; timeout?: number };\n        return {\n          permissionDecision: \"allow\",\n          modifiedArgs: {\n            ...args,\n            timeout: args.timeout ?? 30000, // Default 30s timeout\n          },\n        };\n      }\n      return { permissionDecision: \"allow\" };\n    },\n  },\n});\n```\n\n### Restrict file access to specific directories\n\n```typescript\nconst ALLOWED_DIRECTORIES = [\"/home/user/projects\", \"/tmp\"];\n\nconst session = await client.createSession({\n  hooks: {\n    onPreToolUse: async (input) => {\n      if (input.toolName === \"read_file\" || input.toolName === \"write_file\") {\n        const args = input.toolArgs as { path: string };\n        const isAllowed = ALLOWED_DIRECTORIES.some(dir => \n          args.path.startsWith(dir)\n        );\n        \n        if (!isAllowed) {\n          return {\n            permissionDecision: \"deny\",\n            permissionDecisionReason: `Access to '${args.path}' is not permitted. Allowed directories: ${ALLOWED_DIRECTORIES.join(\", \")}`,\n          };\n        }\n      }\n      return { permissionDecision: \"allow\" };\n    },\n  },\n});\n```\n\n### Suppress verbose tool output\n\n```typescript\nconst VERBOSE_TOOLS = [\"list_directory\", \"search_files\"];\n\nconst session = await client.createSession({\n  hooks: {\n    onPreToolUse: async (input) => {\n      return {\n        permissionDecision: \"allow\",\n        suppressOutput: VERBOSE_TOOLS.includes(input.toolName),\n      };\n    },\n  },\n});\n```\n\n### Add context based on tool\n\n```typescript\nconst session = await client.createSession({\n  hooks: {\n    onPreToolUse: async (input) => {\n      if (input.toolName === \"query_database\") {\n        return {\n          permissionDecision: \"allow\",\n          additionalContext: \"Remember: This database uses PostgreSQL syntax. Always use parameterized queries.\",\n        };\n      }\n      return { permissionDecision: \"allow\" };\n    },\n  },\n});\n```\n\n## Best practices\n\n1. **Always return a decision** - Returning `null` allows the tool, but being explicit with `{ permissionDecision: \"allow\" }` is clearer.\n\n2. **Provide helpful denial reasons** - When denying, explain why so users understand:\n\n   ```typescript\n   return {\n     permissionDecision: \"deny\",\n     permissionDecisionReason: \"Shell commands require approval. Please describe what you want to accomplish.\",\n   };\n   ```\n\n3. **Be careful with argument modification** - Ensure modified args maintain the expected schema for the tool.\n\n4. **Consider performance** - Pre-tool hooks run synchronously before each tool call. Keep them fast.\n\n5. **Use `suppressOutput` judiciously** - Suppressing output means the model won't see the result, which may affect conversation quality.\n\n## See also\n\n* [Use hooks](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks)\n* [Post-tool use hook](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks/post-tool-use)\n* [Debugging guide](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/debugging)"}