Liking cljdoc? Tell your friends :D

Session hooks

Hooks allow you to intercept and customize the behavior of Copilot sessions at key points in the conversation lifecycle. Use hooks to:

  • Control tool execution - approve, deny, or modify tool calls
  • Transform results - modify tool outputs before they're processed
  • Add context - inject additional information at session start
  • Handle errors - implement custom error handling
  • Audit and log - track all interactions for compliance

For filesystem hooks loaded from additional startup directories rather than registered SDK callbacks, see Repository hooks from additional directories.

Available hooks

HookTriggerUse Case
onPreToolUseBefore a tool executesPermission control, argument validation
onPreMcpToolCallBefore an MCP tool call is sentAttach or remove MCP request metadata
onPostToolUseAfter a tool executes (success only)Result transformation, logging
onPostToolUseFailureAfter a tool execution whose result was a failureInject retry guidance, log failures
onUserPromptSubmittedWhen user sends a messagePrompt modification, filtering
onUserPromptTransformedAfter runtime prompt transformationInspect or replace model-facing content
onSessionStartSession beginsAdd context, configure session
onSessionEndSession endsCleanup, analytics
onErrorOccurredError happensCustom error handling
onAgentStopTop-level agent naturally stopsValidate completion or request another turn
onSubagentStartBefore a sub-agent's first turnPrepend context to its prompt
onSubagentStopAfter a sub-agent completes a turnRequest another turn or replace its response

Hook metadata

The TypeScript, Python, Go, .NET, Rust, and Java SDKs expose the existing model tool-call ID for preToolUse, postToolUse, and postToolUseFailure. In TypeScript and Python this is optional toolCallId; .NET uses nullable ToolCallId, and Go uses ToolCallID (empty when absent). Java exposes nullable getToolCallId().

Correlate calls using (input.sessionId, input.toolCallId), not tool names or arguments. This ID also matches tool-execution events and preMcpToolCall.toolCallId, and argument changes do not change it. Use the input's session ID, not the hook invocation's session ID: the callback owner can differ from the child session reported in the input.

postToolUse observes successful results; postToolUseFailure observes failures. Other outcomes can invoke neither, so a pre-hook does not guarantee a matching post-hook.

TypeScript, Python, Go, Rust, and Java also expose optional W3C traceparent and tracestate (Traceparent and Tracestate in Go). .NET hook inputs do not expose these fields. They describe existing trace context, not tool-call identity. Older runtimes can omit these fields and the tool-call ID.

Java uses getTraceparent() and getTracestate() on class-based hook inputs, and traceparent() and tracestate() on record-based inputs. Existing record constructors remain available and leave tracing metadata null.

In Rust, access this metadata through HookActor::tool_call_id(), traceparent(), and tracestate() in SessionHooks::on_hook_with_actor. The existing input structs and callback signatures remain unchanged.

Quick start

Node.js / TypeScript
import { CopilotClient } from "copilot-sdk-supercharged";

const client = new CopilotClient({ mode: "coding-agent" });

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                console.log(`Tool called: ${input.toolName}`);
                // Allow all tools
                return { permissionDecision: "allow" };
            },
            onPostToolUse: async (input) => {
                console.log(`Tool result: ${JSON.stringify(input.toolResult)}`);
                return null; // No modifications
            },
            onSessionStart: async (input) => {
                return { additionalContext: "User prefers concise answers." };
            },
        },
    },
});
Python
from copilot import CopilotClient
from copilot.session import PermissionHandler


async def main():
    client = CopilotClient(mode="coding-agent")
    await client.start()

    async def on_pre_tool_use(input_data, invocation):
        print(f"Tool called: {input_data['toolName']}")
        return {"permissionDecision": "allow"}

    async def on_post_tool_use(input_data, invocation):
        print(f"Tool result: {input_data['toolResult']}")
        return None

    async def on_session_start(input_data, invocation):
        return {"additionalContext": "User prefers concise answers."}

    session = await client.create_session(
        permissions={"on_request": PermissionHandler.approve_all},
        hooks={
            "handlers": {
                "on_pre_tool_use": on_pre_tool_use,
                "on_post_tool_use": on_post_tool_use,
                "on_session_start": on_session_start,
            }
        },
    )
Go
package main

import (
	"context"
	"fmt"
	copilot "github.com/microsoft/copilot-sdk/go/v2"
)

func main() {
	client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})

	session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{
		Hooks: copilot.SessionHookOptions{
			Handlers: &copilot.SessionHooks{
				OnPreToolUse: func(input copilot.PreToolUseHookInput, inv copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
					fmt.Printf("Tool called: %s\n", input.ToolName)
					return &copilot.PreToolUseHookOutput{
						PermissionDecision: "allow",
					}, nil
				},
				OnPostToolUse: func(input copilot.PostToolUseHookInput, inv copilot.HookInvocation) (*copilot.PostToolUseHookOutput, error) {
					fmt.Printf("Tool result: %v\n", input.ToolResult)
					return nil, nil
				},
				OnSessionStart: func(input copilot.SessionStartHookInput, inv copilot.HookInvocation) (*copilot.SessionStartHookOutput, error) {
					return &copilot.SessionStartHookOutput{
						AdditionalContext: "User prefers concise answers.",
					}, nil
				},
			},
		},
	})
	_ = session
}
.NET
using Microsoft.Copilot;

var client = new CopilotClient(new CopilotClientOptions { Mode = CopilotClientMode.CodingAgent });
var session = await client.CreateSessionAsync(new CreateSessionOptions
{
    Hooks = new SessionHookOptions
    {
        Handlers = new SessionHooks
        {
            OnPreToolUse = (input, invocation) =>
            {
                Console.WriteLine($"Tool called: {input.ToolName}");
                return Task.FromResult<PreToolUseHookOutput?>(new PreToolUseHookOutput
                {
                    PermissionDecision = "allow"
                });
            },
            OnPostToolUse = (input, invocation) =>
            {
                Console.WriteLine($"Tool result: {input.ToolResult}");
                return Task.FromResult<PostToolUseHookOutput?>(null);
            },
            OnSessionStart = (input, invocation) =>
            {
                return Task.FromResult<SessionStartHookOutput?>(new SessionStartHookOutput
                {
                    AdditionalContext = "User prefers concise answers."
                });
            },
        }
    }
});
Java
import com.microsoft.copilot.*;
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

try (var client = new CopilotClient(new CopilotClientOptions().setMode(CopilotClientMode.CODING_AGENT))) {
    client
            .start()
            .get();

    var hooks = new SessionHooks()
            .setOnPreToolUse((input, invocation) -> {
                System.out
                        .println("Tool called: " + input
                                .getToolName());
                return CompletableFuture
                        .completedFuture(PreToolUseHookOutput
                                .allow());
            })
            .setOnPostToolUse((input, invocation) -> {
                System.out
                        .println("Tool result: " + input
                                .getToolResult());
                return CompletableFuture
                        .completedFuture(null);
            })
            .setOnSessionStart((input, invocation) -> {
                return CompletableFuture
                        .completedFuture(new SessionStartHookOutput("User prefers concise answers.", null));
            });

    var session = client
            .createSession(new CreateSessionOptions()
                    .setHooks(new SessionHookOptions()
                            .setHandlers(hooks))
                    .setPermissions(new SessionPermissionOptions()
                            .setOnRequest(PermissionHandler.APPROVE_ALL)))
            .get();
}

Hook invocation context

Every hook receives an invocation parameter with context about the current session:

FieldTypeDescription
sessionIdstringThe callback owner's session ID, which can differ from input.sessionId for a child session

This allows hooks to maintain state or perform session-specific logic.

Common patterns

Logging all tool calls

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                console.log(
                    `[${new Date().toISOString()}] Tool: ${input.toolName}, Args: ${JSON.stringify(input.toolArgs)}`,
                );
                return { permissionDecision: "allow" };
            },
            onPostToolUse: async (input) => {
                console.log(
                    `[${new Date().toISOString()}] Result: ${JSON.stringify(input.toolResult)}`,
                );
                return null;
            },
        },
    },
});

Blocking dangerous tools

const BLOCKED_TOOLS = ["shell", "bash", "exec"];

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                if (BLOCKED_TOOLS.includes(input.toolName)) {
                    return {
                        permissionDecision: "deny",
                        permissionDecisionReason: "Shell access is not permitted",
                    };
                }
                return { permissionDecision: "allow" };
            },
        },
    },
});

Adding user context

const session = await client.createSession({
    hooks: {
        handlers: {
            onSessionStart: async () => {
                const userPrefs = await loadUserPreferences();
                return {
                    additionalContext: `User preferences: ${JSON.stringify(userPrefs)}`,
                };
            },
        },
    },
});

Hook guides

See also

Can you improve this documentation? These fine people already did:
copilot-cli-release-app[bot], Steve Sanderson, Jeremiah Isaacson, Stephen Toub, Sunbrye Ly, Rince Yuan, Ed Burns, Belal Taher & copilot-sdk-mirror-writer[bot]
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close