GitHub Copilot hooks are commands, HTTP calls or (in Copilot CLI) prompts that Copilot runs at fixed points in an agent session, such as before a tool call (preToolUse) or when a session ends; you put them in .github/hooks/*.json, and they work in Copilot CLI, Copilot cloud agent, the GitHub Copilot app and, in preview, VS Code.

Applies to: Copilot CLI, Copilot cloud agent, the GitHub Copilot app and VS Code agent hooks (Preview); GitHub Docs and VS Code docs as of November 9, 2026. Last checked: November 9, 2026.

{
  "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
      }
    ]
  }
}

The example above is from GitHub’s hooks how-to for Copilot CLI: it appends a line to logs/session.log each time a session starts, with a Bash command for Linux and macOS and a PowerShell command for Windows. Save it as any NAME.json file in .github/hooks/ and merge it into the default branch.

On this page

Where do GitHub Copilot hooks work?

GitHub’s overview lists four surfaces and warns not to assume “that the same events, input, or output work unchanged across surfaces”:

Surface Where hooks come from Notes
Copilot CLI Policy, user, repository and plugin sources (table below) Supports every event in the hooks reference
Copilot cloud agent Only .github/hooks/*.json in the cloned repository Linux sandbox, a subset of events, file must be on the default branch
GitHub Copilot app Repository hooks and hooks supplied by plugins Listed in the overview
VS Code The shared Copilot harness when the Session Target is Copilot Hooks experience is in Preview (VS Code docs)

Do Copilot hooks work in VS Code?

Yes, as a preview. VS Code’s agent hooks page (updated November 4, 2026) says that when you select Copilot in the Session Target control, “VS Code, the GitHub Copilot app, and GitHub Copilot CLI share this harness and its hook format”, and that you do not need to install the CLI to configure hooks in the editor. So the same .github/hooks/*.json files and the same GitHub hooks reference apply.

  • Open the hooks UI from the Chat view (Open Customizations, then Hooks), from the Agents window (Customizations, then Hooks), or by typing /hooks in the chat input.
  • Select New Hook next to Workspace (repository hooks) or User (personal hooks in ~/.copilot/hooks/, or $COPILOT_HOME/hooks/).
  • The Claude and Codex session targets use their own hook implementations, and the older Local harness has a separate reference that VS Code says to use only when migrating.
  • Local settings such as chat.useHooks and chat.hookFilesLocations do not configure the Copilot harness.
  • Your organization can restrict which hooks run; the page notes that Claude and Codex harnesses are disabled when Copilot enterprise-managed settings apply.

VS Code’s first example is a workspace hook in .github/hooks/audit.json that records only the tool name and needs Node.js:

{
  "version": 1,
  "hooks": {
    "preToolUse": [
      {
        "type": "command",
        "command": "node .github/hooks/log-tool-use.cjs",
        "timeoutSec": 10
      }
    ]
  }
}

The supporting script goes in .github/hooks/log-tool-use.cjs; the editor creates the configuration, not the script:

const fs = require('node:fs');
const path = require('node:path');
const event = JSON.parse(fs.readFileSync(0, 'utf8'));
if (typeof event.toolName !== 'string') {
  throw new Error('Expected a Copilot preToolUse event with toolName.');
}
fs.appendFileSync(
  path.join(__dirname, 'tool-use.log'),
  `${JSON.stringify(event.toolName)}\n`
);
process.stdout.write('{}');

The docs add .github/hooks/tool-use.log to .gitignore and point out that returning {} makes no permission decision; it does not approve the tool.

Where do hook files go?

Location Surface Scope
.github/hooks/*.json in the repository CLI, cloud agent, Copilot app, VS Code Every agent session in that repository
~/.copilot/hooks/*.json (%USERPROFILE%\.copilot\hooks\ on Windows, $COPILOT_HOME/hooks/ if set) CLI and the shared harness Every session for that user
hooks field in .github/copilot/settings.json or .github/copilot/settings.local.json CLI That repository
hooks field in ~/.copilot/settings.json CLI That user (~/.copilot/config.json is no longer read for hooks)
.claude/settings.json and .claude/settings.local.json in the repository CLI Read as cross-tool settings
A plugin’s hooks.json or hooks/hooks.json CLI While the plugin is installed
hooks in a custom agent’s frontmatter CLI Only while that agent is selected
/etc/github-copilot/policy.d/*.json (Windows: C:\ProgramData\GitHub\Copilot\policy.d\*.json or the registry key HKLM\Software\Policies\GitHub\Copilot) CLI Machine-wide policy set by administrators

Per the reference, the CLI loads sources in the order policy, user, project, plugins, and runs every entry from every source when the same event appears more than once. Policy files on POSIX systems must be owned by root and not group- or world-writable; they cannot be turned off with disableAllHooks, and they always run on the host, even when the session sandbox is on.

With the CLI session sandbox enabled, repository, user and plugin command hooks run inside the sandbox with the same access as the agent’s shell commands. A hook’s cwd or env does not widen that access; the reference says to add paths to sandbox.userPolicy instead.

Cloud agent only reads .github/hooks/*.json, and the cloud agent how-to says the file “must be present on your repository’s default branch”. The CLI loads hook configuration when it starts, so restart it after a change.

Because the CLI reads .claude/settings.json, hooks written for Claude Code in a repository are picked up too; our Claude Code hooks guide covers that format.

Hooks for one custom agent

The CLI also accepts a hooks map in a custom agent’s frontmatter (agent-scoped hooks). These run only while that agent is selected, in addition to every other source:

---
name: formatter
description: Formats changed files
hooks:
  PostToolUse:
    - type: command
      command: ./scripts/format-changed-files.sh
      windows: ./scripts/format-changed-files.ps1
---
Format the files you change.

command is the fallback and windows, linux and osx override it per platform. Remote or organization-hosted agent definitions do not run scoped hooks. For the agent file format, see GitHub Copilot custom agents.

Which hook events exist?

Event Fires when Can change the outcome? Cloud agent
sessionStart A new or resumed session begins Can inject additionalContext Once per job
sessionEnd The session terminates (in the CLI, also on /clear) No Once per job
userPromptSubmitted The user submits a prompt No for config-file hooks Once, for the job’s prompt
userPromptTransformed The prompt has been turned into model-facing content Can rewrite that content Fires
preToolUse Before each tool runs Allow, deny or modify Fires; "ask" counts as "deny"
postToolUse After a tool succeeds Replace the result or add context Fires
postToolUseFailure After a tool fails Add recovery guidance Fires
permissionRequest Before the permission service runs Allow or deny No effect (tools are pre-approved)
agentStop The main agent finishes a turn block forces another turn Fires
subagentStart / subagentStop A subagent is spawned / completes Start adds context; Stop can block or rewrite the response Fires
preCompact Context compaction is about to start No Only trigger: "auto"
errorOccurred An error occurs No Fires
notification The CLI emits a system notification Can inject additionalContext Does not fire

Source: the hook events table. The built-in general-purpose agent does not emit subagentStart or subagentStop; other built-in agents such as explore, code-review and research, and your own custom agents, do.

Event names can be written in camelCase (preToolUse, with camelCase payload fields) or in PascalCase (PreToolUse, with snake_case fields “to match the VS Code Copilot extension format”). PascalCase PreToolUse and PermissionRequest hooks also use Claude-style matchers and tool names:

Copilot tool Claude tool name in PascalCase hooks
bash, powershell Bash
view Read
create Write
edit, str_replace_editor, apply_patch Edit
grep, rg / glob Grep / Glob
web_fetch / web_search WebFetch / WebSearch
task Agent (Task is also accepted)

How is a hook entry configured?

Every file needs "version": 1 and a hooks object whose keys are event names and whose values are arrays of entries. There are three entry types (hook configuration format):

Type What runs Where
command bash, powershell or the cross-platform command string; in the CLI also exec with args, which skips the shell All events
http A JSON POST of the payload to url CLI; cloud agent only to firewall-allowed hosts
prompt Text or a slash command submitted as if the user typed it sessionStart only, new interactive CLI sessions (not on resume or with -p)

type defaults to "command" when omitted. command is copied to bash and powershell when those are absent. Other fields are cwd (relative to the repository root or absolute), env, and timeoutSec, which defaults to 30 seconds (timeout is an alias). If a file in .github/hooks/ has one malformed hook item, only that item is dropped; invalid JSON, a bad version or a non-array event list rejects the whole file, and inline hooks in settings.json are rejected on any item error.

An optional matcher filters some events; it is a regex compiled as ^(?:PATTERN)$, so it must match the whole value:

{
    "type": "command",
    "matcher": "bash|edit",
    "bash": "./scripts/log-tool.sh"
}

matcher is compared with toolName for preToolUse, postToolUse and permissionRequest, with notification_type for notification, with trigger for preCompact and with agentName for subagentStart. An invalid regex skips the entry.

HTTP hooks must use https:// URLs, except http://localhost, http://127.* and http://[::1] when COPILOT_HOOK_ALLOW_LOCALHOST=1 is set. For preToolUse and permissionRequest the URL must be https:// “because the response can grant tool permissions”.

{
  "version": 1,
  "hooks": {
    "postToolUse": [
      {
        "type": "http",
        "url": "https://hooks.example.com/copilot",
        "headers": { "X-Source": "copilot-cli" },
        "allowedEnvVars": ["GITHUB_TOKEN"],
        "timeoutSec": 30
      }
    ]
  }
}

What does a preToolUse hook receive and return?

A camelCase preToolUse hook gets this payload on stdin (input payloads):

{
    sessionId: string;
    timestamp: number;
    cwd: string;
    toolName: string;
    toolArgs: unknown;
}

GitHub’s CLI hooks tutorial notes that toolArgs is a JSON string, so a script has to parse it before reading fields such as command. To decide, the hook writes one JSON object to stdout:

Field Values
permissionDecision "allow", "deny" or "ask"; empty output keeps the default behavior. In cloud agent and in CLI autopilot mode, "ask" is denied
permissionDecisionReason Shown to the agent; required for "deny"
modifiedArgs Replacement tool arguments

The tutorial’s deny response looks like this:

{"permissionDecision":"deny","permissionDecisionReason":"Privilege escalation requires manual approval."}

A permissionRequest hook (CLI only) answers with different fields: behavior ("allow" or "deny"), message for the reason and interrupt: true to stop the agent along with a deny. For a request to leave the sandbox, an allow from a hook does not skip the user prompt; only deny takes effect.

Command hooks can also print progress lines before the final object. Each must be a single-line JSON object (add "temporary": true for a line that replaces the previous one); the rest of stdout is parsed as one JSON document, so two separate decision objects become invalid JSON and are ignored:

echo '{"type": "progress", "message": "Checking policy..."}'
# ... perform work ...
echo '{"permissionDecision": "allow"}'

What do exit codes and timeouts mean?

Result Effect (exit codes)
Exit 0 Success; stdout is parsed as the hook output
Exit 2 A warning for most events. For preToolUse and permissionRequest it is a deny, even if stdout says allow. For postToolUseFailure, stdout is added to the failure the agent sees
Other non-zero exit Logged and skipped, except preToolUse, which fails closed: “Denied by preToolUse hook (hook errored)”
Timeout Always fails open, including preToolUse and admin policy hooks: the tool call goes through the normal permission flow

HTTP preToolUse hooks are fail-open: a network error, timeout or non-2xx response falls back to the default permission flow. The reference says to “choose the variant that matches your security requirements”. If several preToolUse hooks run, any "deny" blocks the tool.

agentStop and subagentStop hooks can return {"decision": "block", "reason": "..."} to force another turn with reason as the prompt; subagentStop can also return modifiedResponse to replace what the parent agent receives. After 8 consecutive blocks the CLI ends the turn anyway; the docs suggest reading the stop_hook_active input field to stop earlier.

How do hooks behave in Copilot cloud agent?

Cloud agent runs hooks inside its job sandbox (execution environment):

  • Linux only: bash (or command) entries run, powershell entries are ignored.
  • The working directory is /workspace when a repository is cloned, otherwise /root; HOME is /root.
  • The filesystem is ephemeral, so log files written by hooks disappear when the job ends; GitHub suggests an http entry to keep output.
  • Outbound network is limited by the cloud agent firewall. By default only GitHub and Copilot hostnames are reachable.
  • The sandbox sets GITHUB_COPILOT_API_TOKEN, GITHUB_COPILOT_GIT_TOKEN and COPILOT_AGENT_PROMPT; GITHUB_TOKEN is not set.
  • There are no user-level hook files, settings.json or installed plugins in the sandbox.
  • The job is non-interactive with all tool permissions pre-granted, so preToolUse is the place for permission decisions.

Example: a CLI notification hook from GitHub’s docs

For a user-level hook on macOS, the how-to creates ~/.copilot/hooks/notification-hooks.json with this content, which plays a sound and shows a dialog when the agent stops and when the session ends:

{
  "version": 1,
  "hooks": {
    "agentStop": [
      {
        "type": "command",
        "bash": "osascript -e 'do shell script \"afplay /System/Library/Sounds/Funk.aiff &> /dev/null &\"' -e 'display dialog \"Agent stopped.\" with title \"Hook-generated message\" buttons {\"OK\"} default button \"OK\"'",
        "timeoutSec": 5
      }
    ],
    "sessionEnd": [
      {
        "type": "command",
        "bash": "osascript -e 'do shell script \"afplay /System/Library/Sounds/Funk.aiff &> /dev/null &\"' -e 'display dialog \"Session ended.\" with title \"Hook-generated message\" buttons {\"OK\"} default button \"OK\"'",
        "timeoutSec": 5
      }
    ]
  }
}

The same page has a Windows version using PowerShell 7. For a team policy, GitHub’s rollout tutorial builds .github/hooks/copilot-cli-policy.json with a sessionStart banner, a userPromptSubmitted audit log and a preToolUse script that denies privilege escalation (sudo, su, runas), destructive operations (rm -rf /, mkfs, dd, format) and download-and-execute patterns (curl ... | bash, wget ... | sh), with Bash and PowerShell versions of each script. It recommends a logging-first rollout before adding deny rules. Running Copilot CLI itself is covered in our Copilot CLI guide.

Security and performance notes

Warning

GitHub’s overview says to “always validate and sanitize the input processed by hooks”, use proper shell escaping, never log sensitive data such as tokens or passwords, and be cautious with hooks that make external network calls. VS Code’s hooks page adds that hook configuration and scripts “are executable code”, including hooks bundled in plugins, and that hooks are not a substitute for enforced permissions or sandboxing.

  • Hooks run synchronously and block the agent. GitHub suggests keeping each one under 5 seconds when possible.
  • The tutorial’s script states that “GitHub does not currently provide built-in secret redaction for hooks”, so redact prompts and tool arguments before writing them to logs.
  • Set "disableAllHooks": true at the top of a hooks file to skip that file’s hooks without deleting them. At the top level of a repository settings.json it skips every non-policy hook for CLI sessions in that repository (disable all hooks).

How do I debug a Copilot hook?

From GitHub’s troubleshooting table: check that the file is in .github/hooks/, that it is valid JSON (jq . hooks.json), that version: 1 is set, and that the script is executable (chmod +x script.sh) with a shebang. For invalid output, keep it on one line (jq -c on Unix, ConvertTo-Json -Compress in PowerShell). Then pipe test input into the script:

# 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 .

In VS Code, the docs suggest confirming the Session Target and hook source, checking for the same command coming from another source, and using the agent debug logs. Other tools use different formats: see Cursor hooks and Codex hooks.