Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions content/copilot/concepts/agents/about-copilot-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
164 changes: 164 additions & 0 deletions content/copilot/concepts/agents/coding-agent/about-hooks.md
Original file line number Diff line number Diff line change
@@ -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 %}<br><a href="https://github.com/features/copilot/plans?ref_product=copilot&ref_type=purchase&ref_style=button" target="_blank" class="btn btn-primary mt-3 mr-3 no-underline"><span>Sign up for {% data variables.product.prodname_copilot_short %}</span> {% octicon "link-external" height:16 %}</a>'
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).

1 change: 1 addition & 0 deletions content/copilot/concepts/agents/coding-agent/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ children:
- /about-coding-agent
- /agent-management
- /about-custom-agents
- /about-hooks
- /access-management
- /mcp-and-coding-agent
contentType: concepts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
115 changes: 115 additions & 0 deletions content/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks.md
Original file line number Diff line number Diff line change
@@ -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 | <ul><li>Verify the JSON file is in the `.github/hooks/` directory.</li><li>Check for valid JSON syntax (for example, `jq . hooks.json`).</li><li>Ensure `version: 1` is specified in your `hooks.json` file.</li><li>Verify the script you are calling from your hook is executable (`chmod +x script.sh`)</li><li>Check that the script has a proper shebang (for example, `#!/bin/bash`)</li></ul> |
| Hooks are timing out | <ul><li>The default timeout is 30 seconds. Increase `timeoutSec` in the configuration if needed.</li><li>Optimize script performance by avoiding unnecessary operations.</li> |
| Invalid JSON output | <ul><li>Ensure the output is on a single line.</li><li>On Unix, use `jq -c` to compact and validate the JSON output.</li><li>On Windows, use the `ConvertTo-Json -Compress` command in PowerShell to do the same.</li></ul> |

## Debugging

You can debug hooks using the following methods:

* **Enable verbose logging** in the script to inspect the input data and trace script execution.

```shell copy
#!/bin/bash
set -x # Enable bash debug mode
INPUT=$(cat)
echo "DEBUG: Received input" >&2
echo "$INPUT" >&2
# ... rest of script
```

* **Test hooks locally** by piping test input into your hook to validate its behavior:

```shell copy
# Create test input
echo '{"timestamp":1704614400000,"cwd":"/tmp","toolName":"bash","toolArgs":"{\"command\":\"ls\"}"}' | ./my-hook.sh

# Check exit code
echo $?

# Validate output is valid JSON
./my-hook.sh | jq .
```

## Further reading

* For more information about configuring hooks, see [AUTOTITLE](/copilot/reference/hooks-configuration)
* For more information about {% data variables.copilot.copilot_coding_agent %}, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-coding-agent)
* For more information about {% data variables.copilot.copilot_cli %}, see [AUTOTITLE](/copilot/concepts/agents/about-copilot-cli)
* For information about customizing the agent environment, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/coding-agent/customize-the-agent-environment)
Loading
Loading