diff --git a/content/copilot/concepts/agents/about-copilot-cli.md b/content/copilot/concepts/agents/about-copilot-cli.md index 90292689613f..5a93c225a5cb 100644 --- a/content/copilot/concepts/agents/about-copilot-cli.md +++ b/content/copilot/concepts/agents/about-copilot-cli.md @@ -149,8 +149,10 @@ You can customize {% data variables.copilot.copilot_cli %} in a number of ways: * **Custom instructions**: Custom instructions allow you to give {% data variables.product.prodname_copilot_short %} additional context on your project and how to build, test and validate its changes. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-instructions). * **Model Context Protocol (MCP) servers**: MCP servers allow you to give {% data variables.product.prodname_copilot_short %} access to different data sources and tools. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/use-copilot-cli#add-an-mcp-server). * **{% data variables.copilot.custom_agents_caps_short %}**: {% data variables.copilot.custom_agents_caps_short %} allow you to create different specialized versions of {% data variables.product.prodname_copilot_short %} for different tasks. For example, you could customize {% data variables.product.prodname_copilot_short %} to be an expert frontend engineer following your team's guidelines. {% data variables.copilot.copilot_cli %} includes specialized {% data variables.copilot.custom_agents_short %} that it automatically delegates common tasks to. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents). +* **Hooks**: Hooks allow you to execute custom shell commands at key points during agent execution, enabling you to add validation, logging, security scanning, or workflow automation. See [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-hooks). * **Skills**: Skills allow you to enhance the ability of {% data variables.product.prodname_copilot_short %} to perform specialized tasks with instructions, scripts, and resources. For more information, see [AUTOTITLE](/copilot/concepts/agents/about-agent-skills). + ## Security considerations When you use {% data variables.copilot.copilot_cli_short %}, {% data variables.product.prodname_copilot_short %} can perform tasks on your behalf, such as executing or modifying files, or running shell commands. diff --git a/content/copilot/concepts/agents/coding-agent/about-coding-agent.md b/content/copilot/concepts/agents/coding-agent/about-coding-agent.md index 0206743ce633..c0aaeebd4f79 100644 --- a/content/copilot/concepts/agents/coding-agent/about-coding-agent.md +++ b/content/copilot/concepts/agents/coding-agent/about-coding-agent.md @@ -118,6 +118,7 @@ You can customize {% data variables.copilot.copilot_coding_agent %} in a number * **Custom instructions**: Custom instructions allow you to give {% data variables.product.prodname_copilot_short %} additional context on your project and how to build, test and validate its changes. For more information, see [AUTOTITLE](/copilot/how-tos/configure-custom-instructions/add-repository-instructions). * **Model Context Protocol (MCP) servers**: MCP servers allow you to give {% data variables.product.prodname_copilot_short %} access to different data sources and tools. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/coding-agent/extend-coding-agent-with-mcp). * **{% data variables.copilot.custom_agents_caps_short %}**: {% data variables.copilot.custom_agents_caps_short %} allow you to create different specialized versions of {% data variables.product.prodname_copilot_short %} for different tasks. For example, you could customize {% data variables.product.prodname_copilot_short %} to be an expert frontend engineer following your team's guidelines. For more information, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-custom-agents). +* **Hooks**: Hooks allow you to execute custom shell commands at key points during agent execution, enabling you to add validation, logging, security scanning, or workflow automation. For more information, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-hooks). * **Skills**: Skills allow you to enhance the ability of {% data variables.product.prodname_copilot_short %} to perform specialized tasks with instructions, scripts, and resources. For more information, see [AUTOTITLE](/copilot/concepts/agents/about-agent-skills). ## Built-in security protections diff --git a/content/copilot/concepts/agents/coding-agent/about-hooks.md b/content/copilot/concepts/agents/coding-agent/about-hooks.md new file mode 100644 index 000000000000..b0004f92764f --- /dev/null +++ b/content/copilot/concepts/agents/coding-agent/about-hooks.md @@ -0,0 +1,164 @@ +--- +title: About hooks +shortTitle: Hooks +intro: 'Extend and customize {% data variables.product.prodname_copilot %} agent behavior by executing custom shell commands at key points during agent execution.' +product: '{% data reusables.gated-features.copilot-coding-agent %}
Sign up for {% data variables.product.prodname_copilot_short %} {% octicon "link-external" height:16 %}' +versions: + feature: copilot +topics: + - Copilot +contentType: concepts +category: + - Configure Copilot +--- + +## About hooks + +Hooks enable you to execute custom shell commands at strategic points in an agent's workflow, such as when an agent session starts or ends, or before and after a prompt is entered or a tool is called. + +Hooks receive detailed information about agent actions via JSON input, enabling context-aware automation. For example, you can use hooks to: + +* Programmatically approve or deny tool executions. +* Utilize built-in security features like secret scanning to prevent credential leaks. +* Implement custom validation rules and audit logging for compliance. + +{% data variables.product.prodname_copilot_short %} agents support hooks stored in JSON files in your repository at `.github/hooks/*.json`. + +Hooks are available for use with: + +* {% data variables.copilot.copilot_coding_agent %} on {% data variables.product.github %} +* {% data variables.copilot.copilot_cli %} in the terminal + +## Types of hooks + +The following types of hooks are available: + +* **sessionStart**: Executed when a new agent session begins or when resuming an existing session. Can be used to initialize environments, log session starts for auditing, validate project state, and set up temporary resources. +* **sessionEnd**: Executed when the agent session completes or is terminated. Can be used to cleanup temporary resources, generate and archive session reports and logs, or send notifications about session completion. +* **userPromptSubmitted**: Executed when the user submits a prompt to the agent. Can be used to log user requests for auditing and usage analysis. +* **preToolUse**: Executed before the agent uses any tool (such as `bash`, `edit`, `view`). This is the most powerful hook as it can **approve or deny tool executions**. Use this hook to block dangerous commands, enforce security policies and coding standards, require approval for sensitive operations, or log tool usage for compliance. +* **postToolUse**: Executed after a tool completes execution (whether successful or failed). Can be used to log execution results, track usage statistics, generate audit trails, monitor performance metrics, and send failure alerts. +* **errorOccurred**: Executed when an error occurs during agent execution. Can be used to log errors for debugging, send notifications, track error patterns, and generate reports. + +To see a complete reference of hook types with example use cases, best practices, and advanced patterns, see [AUTOTITLE](/copilot/reference/hooks-configuration). + +## Hook configuration format + +You configure hooks using a special JSON format. The JSON must contain a `version` field with a value of `1` and a `hooks` object containing arrays of hook definitions. + +```json copy +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "bash": "string (optional)", + "powershell": "string (optional)", + "cwd": "string (optional)", + "env": { "KEY": "value" }, + "timeoutSec": 30 + } + ], + } +} +``` + +The hook object can contain the following keys: + +| Property | Required | Description | +| --- | --- | --- | +| `type` | Yes | Must be `"command"` | +| `bash` | Yes (on Unix systems) | Path to the bash script to execute | +| `powershell` | Yes (on Windows) | Path to the PowerShell script to execute | +| `cwd` | No | Working directory for the script (relative to repository root) | +| `env` | No | Additional environment variables that are merged with the existing environment | +| `timeoutSec` | No | Maximum execution time in seconds (default: 30) | + +## Example hook configuration file + +This is an example configuration file that lives in `~/.github/hooks/project-hooks.json` within a repository. + +```json copy +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "bash": "echo \"Session started: $(date)\" >> logs/session.log", + "powershell": "Add-Content -Path logs/session.log -Value \"Session started: $(Get-Date)\"", + "cwd": ".", + "timeoutSec": 10 + } + ], + "userPromptSubmitted": [ + { + "type": "command", + "bash": "./scripts/log-prompt.sh", + "powershell": "./scripts/log-prompt.ps1", + "cwd": "scripts", + "env": { + "LOG_LEVEL": "INFO" + } + } + ], + "preToolUse": [ + { + "type": "command", + "bash": "./scripts/security-check.sh", + "powershell": "./scripts/security-check.ps1", + "cwd": "scripts", + "timeoutSec": 15 + }, + { + "type": "command", + "bash": "./scripts/log-tool-use.sh", + "powershell": "./scripts/log-tool-use.ps1", + "cwd": "scripts" + } + ], + "postToolUse": [ + { + "type": "command", + "bash": "cat >> logs/tool-results.jsonl", + "powershell": "$input | Add-Content -Path logs/tool-results.jsonl" + } + ], + "sessionEnd": [ + { + "type": "command", + "bash": "./scripts/cleanup.sh", + "powershell": "./scripts/cleanup.ps1", + "cwd": "scripts", + "timeoutSec": 60 + } + ] + } +} +``` + +## Performance considerations + +Hooks run synchronously and block agent execution. To ensure a responsive experience, keep the following considerations in mind: + +* **Minimize execution time**: Keep hook execution time under 5 seconds when possible. +* **Optimize logging**: Use asynchronous logging, like appending to files, rather than synchronous I/O. +* **Use background processing**: For expensive operations, consider background processing. +* **Cache results**: Cache expensive computations when possible. + +## Security considerations + +To ensure security is maintained when using hooks, keep the following considerations in mind: + +* **Always validate and sanitize the input processed by hooks**. Untrusted input could lead to unexpected behavior. +* **Use proper shell escaping when constructing commands**. This prevents command injection vulnerabilities. +* **Never log sensitive data, such as tokens or passwords**. +* **Ensure hook scripts and logs have the appropriate permissions**. +* **Be cautious with hooks that make external network calls**. These can introduce latency, failures, or expose data to third parties. +* **Set appropriate timeouts to prevent resource exhaustion**. Long-running hooks can block agent execution and degrade performance. + +## Next steps + +To start creating hooks, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks). + diff --git a/content/copilot/concepts/agents/coding-agent/index.md b/content/copilot/concepts/agents/coding-agent/index.md index f295144cabd6..891b75fd423e 100644 --- a/content/copilot/concepts/agents/coding-agent/index.md +++ b/content/copilot/concepts/agents/coding-agent/index.md @@ -11,6 +11,7 @@ children: - /about-coding-agent - /agent-management - /about-custom-agents + - /about-hooks - /access-management - /mcp-and-coding-agent contentType: concepts diff --git a/content/copilot/how-tos/use-copilot-agents/coding-agent/index.md b/content/copilot/how-tos/use-copilot-agents/coding-agent/index.md index ed3b941f86c5..4113f067b4ff 100644 --- a/content/copilot/how-tos/use-copilot-agents/coding-agent/index.md +++ b/content/copilot/how-tos/use-copilot-agents/coding-agent/index.md @@ -20,6 +20,7 @@ children: - /changing-the-ai-model - /customize-the-agent-environment - /customize-the-agent-firewall + - /use-hooks - /troubleshoot-coding-agent redirect_from: - /copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks diff --git a/content/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks.md b/content/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks.md new file mode 100644 index 000000000000..a9e549792da4 --- /dev/null +++ b/content/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks.md @@ -0,0 +1,115 @@ +--- +title: Using hooks with GitHub Copilot agents +shortTitle: Use hooks +intro: 'Learn how to extend and customize {% data variables.product.prodname_copilot %} agent behavior by executing custom shell commands at key points during agent execution.' +versions: + feature: copilot +topics: + - Copilot +contentType: how-tos +category: + - Configure Copilot +--- + +Hooks allow you to extend and customize the behavior of {% data variables.product.prodname_copilot %} agents by executing custom shell commands at key points during agent execution. For a conceptual overview of hooks, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-hooks). + +## Creating a hook in a repository on {% data variables.product.github %} + +1. Create a new `hooks.json` file with the name of your choice in the `.github/hooks/` folder of your repository. The hooks configuration file **must be present** on your repository's default branch to be used by {% data variables.copilot.copilot_coding_agent %}. For {% data variables.copilot.copilot_cli %}, hooks are loaded from your current working directory. + +1. In your text editor, copy and paste the following hook template. Remove any hooks you don't plan on using from the `hooks` array. + + ```json copy + { + "version": 1, + "hooks": { + "sessionStart": [...], + "sessionEnd": [...], + "userPromptSubmitted": [...], + "preToolUse": [...], + "postToolUse": [...], + "errorOccurred": [...] + } + } + ``` + +1. Configure your hook syntax under the `bash` or `powershell` keys, or directly reference script files you have created. + + * This example runs a script that outputs the start date of the session to a log file using the `sessionStart` hook: + + ```json copy + "sessionStart": [ + { + "type": "command", + "bash": "echo \"Session started: $(date)\" >> logs/session.log", + "powershell": "Add-Content -Path logs/session.log -Value \"Session started: $(Get-Date)\"", + "cwd": ".", + "timeoutSec": 10 + } + ], + ``` + + * This example calls out to an external `log-prompt` script: + + ```json copy + "userPromptSubmitted": [ + { + "type": "command", + "bash": "./scripts/log-prompt.sh", + "powershell": "./scripts/log-prompt.ps1", + "cwd": "scripts", + "env": { + "LOG_LEVEL": "INFO" + } + } + ], + ``` + + For a full reference on the input JSON from agent sessions along with sample scripts, see [AUTOTITLE](/copilot/reference/hooks-configuration). + +1. Commit the file to the repository and merge it into the default branch. Your hooks will now run during agent sessions. + +## Troubleshooting + +If you run into problems using hooks, use the following table to troubleshoot. + +| Issue | Action | +| --- | --- | +| Hooks are not executing | | +| Hooks are timing out |