Liking cljdoc? Tell your friends :D

Pre-tool use hook

The onPreToolUse hook is called before a tool executes. Use it to:

  • Approve or deny tool execution
  • Modify tool arguments
  • Add context for the tool
  • Suppress tool output from the conversation

Hook signature

Node.js / TypeScript
import type { PreToolUseHookInput, HookInvocation, PreToolUseHookOutput } from "copilot-sdk-supercharged";
type PreToolUseHandler = (
  input: PreToolUseHookInput,
  invocation: HookInvocation
) => Promise<PreToolUseHookOutput | null | undefined>;
type PreToolUseHandler = (
  input: PreToolUseHookInput,
  invocation: HookInvocation
) => Promise<PreToolUseHookOutput | null | undefined>;
Python
from copilot.session import PreToolUseHookInput, PreToolUseHookOutput
from copilot.session import PreToolUseHandler as SdkPreToolUseHandler
from typing import Callable, Awaitable

PreToolUseHandler = Callable[
    [PreToolUseHookInput, dict[str, str]],
    Awaitable[PreToolUseHookOutput | None]
]

def check(handler: PreToolUseHandler) -> SdkPreToolUseHandler:
    return handler
PreToolUseHandler = Callable[
    [PreToolUseHookInput, dict[str, str]],
    Awaitable[PreToolUseHookOutput | None]
]
Go
package main

import copilot "github.com/microsoft/copilot-sdk/go/v2"

// Aliases let the signature below use the package's own type names.
type (
    PreToolUseHookInput  = copilot.PreToolUseHookInput
    HookInvocation       = copilot.HookInvocation
    PreToolUseHookOutput = copilot.PreToolUseHookOutput
)

type PreToolUseHandler func(
    input PreToolUseHookInput,
    invocation HookInvocation,
) (*PreToolUseHookOutput, error)

var _ = copilot.PreToolUseHandler(PreToolUseHandler(nil))

func main() {}
type PreToolUseHandler func(
    input PreToolUseHookInput,
    invocation HookInvocation,
) (*PreToolUseHookOutput, error)
.NET
using Microsoft.Copilot;

public delegate Task<PreToolUseHookOutput?> PreToolUseHandler(
    PreToolUseHookInput input,
    HookInvocation invocation);

static class PreToolUseHandlerCheck
{
    static SessionHooks Check(PreToolUseHandler handler) =>
        new() { OnPreToolUse = handler.Invoke };
}
public delegate Task<PreToolUseHookOutput?> PreToolUseHandler(
    PreToolUseHookInput input,
    HookInvocation invocation);
Java
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

public class PreToolUseSignature {
    static class Documented {
        @FunctionalInterface
        public interface PreToolUseHandler {
            CompletableFuture<PreToolUseHookOutput> handle(
                PreToolUseHookInput input,
                HookInvocation invocation);
        }
    }

    // The documented interface and the SDK's accept each other's implementations.
    static PreToolUseHandler toSdk(Documented.PreToolUseHandler documented) {
        return documented::handle;
    }

    static Documented.PreToolUseHandler fromSdk(PreToolUseHandler sdk) {
        return sdk::handle;
    }

    public static void main(String[] args) {}
}
@FunctionalInterface
public interface PreToolUseHandler {
    CompletableFuture<PreToolUseHookOutput> handle(
        PreToolUseHookInput input,
        HookInvocation invocation);
}

40 languages supported. See the full SDK list with cookbooks for Objective-C, F#, Groovy, Julia, COBOL, OCaml, Zig, Nim, D, Erlang, Crystal, Tcl, Solidity, V, and 18 more.

Input

FieldTypeDescription
timestampSDK timestamp typeWhen the hook was triggered
workingDirectorystringCurrent working directory
sessionIdstringSession reported by the hook input, not necessarily the callback owner's session
toolCallIdstring (optional)Original tool-call ID, unchanged by argument modifications
traceparentstring (optional)Existing W3C trace context
tracestatestring (optional)Existing W3C vendor trace state
toolNamestringName of the tool being called
toolArgsobjectArguments passed to the tool

Tracing fields are exposed in TypeScript, Python, Go, Rust, and Java, not .NET. See Hook metadata for language-specific accessors and compatibility with older runtimes. Correlate with success or failure hooks and tool-execution events using (input.sessionId, input.toolCallId). A pre-hook does not guarantee a matching post-hook.

Output

Return null or undefined to allow the tool to execute with no changes. Otherwise, return an object with any of these fields:

FieldTypeDescription
permissionDecision"allow" | "deny" | "ask"Whether to allow the tool call
permissionDecisionReasonstringExplanation shown to user (for deny/ask)
modifiedArgsobjectModified arguments to pass to the tool
additionalContextstringExtra context injected into the conversation
suppressOutputbooleanIf true, tool output won't appear in conversation

Permission decisions

DecisionBehavior
"allow"Tool executes normally
"deny"Tool is blocked, reason shown to user
"ask"User is prompted to approve (interactive mode)

Skipping permission prompts for trusted custom tools

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

const getWeather = defineTool("get_weather", {
  description: "Get weather for a location.",
  parameters: {
    type: "object",
    properties: { location: { type: "string" } },
    required: ["location"],
  },
  skipPermission: true,
  handler: async ({ location }) => ({ forecast: `Sunny in ${location}` }),
});

Examples

Allow all tools (logging only)

Node.js / TypeScript
const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input, invocation) => {
                console.log(`[${invocation.sessionId}] Calling ${input.toolName}`);
                console.log(`  Args: ${JSON.stringify(input.toolArgs)}`);
                return { permissionDecision: "allow" };
            },
        },
    },
});
Python
from copilot import CopilotClient
from copilot.session import PermissionHandler

client = CopilotClient(mode="coding-agent")


async def on_pre_tool_use(input_data, invocation):
    print(f"[{invocation['session_id']}] Calling {input_data['toolName']}")
    print(f"  Args: {input_data['toolArgs']}")
    return {"permissionDecision": "allow"}


session = await client.create_session(
    permissions={"on_request": PermissionHandler.approve_all},
    hooks={"handlers": {"on_pre_tool_use": on_pre_tool_use}},
)
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("[%s] Calling %s\n", inv.SessionID, input.ToolName)
					fmt.Printf("  Args: %v\n", input.ToolArgs)
					return &copilot.PreToolUseHookOutput{
						PermissionDecision: "allow",
					}, nil
				},
			},
		},
	})
	_ = session
}
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("[%s] Calling %s\n", inv.SessionID, input.ToolName)
				fmt.Printf("  Args: %v\n", input.ToolArgs)
				return &copilot.PreToolUseHookOutput{
					PermissionDecision: "allow",
				}, nil
			},
		},
	},
})

.NET
var session = await client.CreateSessionAsync(new CreateSessionOptions
{
    Hooks = new SessionHookOptions
    {
        Handlers = new SessionHooks
        {
            OnPreToolUse = (input, invocation) =>
            {
                Console.WriteLine($"[{invocation.SessionId}] Calling {input.ToolName}");
                Console.WriteLine($"  Args: {input.ToolArgs}");
                return Task.FromResult<PreToolUseHookOutput?>(new PreToolUseHookOutput
                {
                    PermissionDecision = "allow"
                });
            },
        }
    }
});
Java
import com.microsoft.copilot.*;
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

public class LogAllToolCallsExample {
    public static void main(String[] args) throws Exception {
        try (var client = new CopilotClient(new CopilotClientOptions().setMode(CopilotClientMode.CODING_AGENT))) {
            var hooks = new SessionHooks()
                    .setOnPreToolUse((input, invocation) -> {
                        System.out
                                .println("[" + invocation
                                        .getSessionId() + "] Calling "
                                        + input
                                                .getToolName());
                        System.out
                                .println("  Args: " + input
                                        .getToolArgs());
                        return CompletableFuture
                                .completedFuture(PreToolUseHookOutput
                                        .allow());
                    });

            var session = client
                    .createSession(new CreateSessionOptions()
                            .setPermissions(new SessionPermissionOptions()
                                    .setOnRequest(PermissionHandler.APPROVE_ALL))
                            .setHooks(new SessionHookOptions()
                                    .setHandlers(hooks)))
                    .get();
        }
    }
}
import com.microsoft.copilot.*;
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

var hooks = new SessionHooks()
        .setOnPreToolUse((input, invocation) -> {
            System.out
                    .println("[" + invocation
                            .getSessionId() + "] Calling "
                            + input
                                    .getToolName());
            System.out
                    .println("  Args: " + input
                            .getToolArgs());
            return CompletableFuture
                    .completedFuture(PreToolUseHookOutput
                            .allow());
        });

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

Block specific tools

const BLOCKED_TOOLS = ["shell", "bash", "write_file", "delete_file"];

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                if (BLOCKED_TOOLS.includes(input.toolName)) {
                    return {
                        permissionDecision: "deny",
                        permissionDecisionReason: `Tool '${input.toolName}' is not permitted in this environment`,
                    };
                }
                return { permissionDecision: "allow" };
            },
        },
    },
});

Modify tool arguments

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                // Add a default timeout to all shell commands
                if (input.toolName === "shell" && input.toolArgs) {
                    const args = input.toolArgs as { command: string; timeout?: number };
                    return {
                        permissionDecision: "allow",
                        modifiedArgs: {
                            ...args,
                            timeout: args.timeout ?? 30000, // Default 30s timeout
                        },
                    };
                }
                return { permissionDecision: "allow" };
            },
        },
    },
});

Restrict file access to specific directories

const ALLOWED_DIRECTORIES = ["/home/user/projects", "/tmp"];

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                if (input.toolName === "read_file" || input.toolName === "write_file") {
                    const args = input.toolArgs as { path: string };
                    const isAllowed = ALLOWED_DIRECTORIES.some((dir) => args.path.startsWith(dir));

                    if (!isAllowed) {
                        return {
                            permissionDecision: "deny",
                            permissionDecisionReason: `Access to '${args.path}' is not permitted. Allowed directories: ${ALLOWED_DIRECTORIES.join(", ")}`,
                        };
                    }
                }
                return { permissionDecision: "allow" };
            },
        },
    },
});

Suppress verbose tool output

const VERBOSE_TOOLS = ["list_directory", "search_files"];

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                return {
                    permissionDecision: "allow",
                    suppressOutput: VERBOSE_TOOLS.includes(input.toolName),
                };
            },
        },
    },
});

Add context based on tool

const session = await client.createSession({
    hooks: {
        handlers: {
            onPreToolUse: async (input) => {
                if (input.toolName === "query_database") {
                    return {
                        permissionDecision: "allow",
                        additionalContext:
                            "Remember: This database uses PostgreSQL syntax. Always use parameterized queries.",
                    };
                }
                return { permissionDecision: "allow" };
            },
        },
    },
});

Best practices

  1. Always return a decision - Returning null allows the tool, but being explicit with { permissionDecision: "allow" } is clearer.

  2. Provide helpful denial reasons - When denying, explain why so users understand:

    return {
      permissionDecision: "deny",
      permissionDecisionReason: "Shell commands require approval. Please describe what you want to accomplish.",
    };
    
  3. Be careful with argument modification - Ensure modified args maintain the expected schema for the tool.

  4. Consider performance - Pre-tool hooks run synchronously before each tool call. Keep them fast.

  5. Use suppressOutput judiciously - Suppressing output means the model won't see the result, which may affect conversation quality.

See also

Can you improve this documentation? These fine people already did:
Patrick Nikoletich, Jeremiah Isaacson, copilot-cli-release-app[bot], Brett Cannon, Sunbrye Ly, Ed Burns, Bruno Borges, copilot-sdk-mirror-writer[bot], Steve Sanderson & Andy Feller
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