Skip to content
AgenticAIWiki
  1. Learn
  2. Part 12
  3. 65. Agent security
  4. 65.8

Lesson 65.8 · 8 of 10 · 5 min read · Reviewed 24 Nov 2026

Worked example: agent SDK permission callbacks

By the end, you can

  • Use the Agent SDK's permission controls.
  • Write a canUseTool callback.

The Agent SDKClaude Agent SDK: Anthropic’s library for building agents on the same loop that powers Claude Code, with tools, hooks, subagents and MCP. gives you several layers of control over tool useTool use: Letting a model call functions you define, by returning a structured request your code executes.. In order, it checks:

  1. HooksHook: Code that runs automatically at a lifecycle event, such as before or after a tool call, to check, block or log it. (PreToolUsePreToolUse hook: A hook that runs before a tool call and can allow, deny or ask for approval.) can allow, deny or modify.
  2. Permission rulesPermission rule: An allow, ask or deny rule that controls which tools, commands or paths a coding agent may use. (allow, ask, deny lists).
  3. Permission mode, such as default, acceptEdits, plan or bypassPermissions.
  4. canUseTool, your callback, for anything not yet decided.

canUseTool

const options = {
  canUseTool: async (toolName, input) => {
    if (toolName === 'Write' || toolName === 'Edit') {
      const path = String(input.file_path ?? '');
      if (!path.startsWith(workspaceDir)) {
        return { behavior: 'deny', message: `Writes are only allowed in ${workspaceDir}.` };
      }
    }
    return { behavior: 'allow', updatedInput: input };
  },
};
  • Return allow (optionally with changed input) or deny with a message the model sees.
  • You can also show the call to a person and wait for their answer: a human approval gate in code.

Choosing the mechanism

Need Use
Static list of allowed tools allowedTools / permission rules
Rule on inputs, same for everyone PreToolUse hook
Rule depending on user, tenant or live data canUseTool
Human approval canUseTool that waits, or an ask rule

Key points

  • The Agent SDK checks permissions in order: hooks, permission rules, the permission mode, then canUseTool.
  • canUseTool is your code deciding allow or deny for each call, with full context, and optionally changed input.
  • Use it for rules that depend on runtime facts, such as the user's role or the amount.
Hands-on labRuns in the Playground

Write a canUseTool callback and test it

Decide each tool call with runtime facts, after hooks and permission rules have had their say.

You will have: A can_use_tool() callback inside a small simulation of the SDK's decision order, run over six tool calls.

Steps

  1. Run the starter and see which layer decides each call.
  2. Deny Write and Edit calls outside the ticket's workspace, with a message the model sees.
  3. Deny refunds above the user's limit, which is a runtime fact a static rule cannot know.
  4. Check that Read and rm -rf are decided by the rules before your callback runs.

Done when

  • The /etc/passwd write and the 250 refund are denied by can_use_tool.
  • rm -rf is denied by rule_decision, and the output shows 'denied: 3 of 6'.

Open in the Playground No API key needed.

Starter code (Python)
# Simulate the order the Agent SDK uses to decide a tool call: hooks, rules, mode, then your callback.
# In the real Python SDK the callback is passed as can_use_tool and returns PermissionResultAllow or PermissionResultDeny.
WORKSPACE = "/work/ticket-42/"
DENY_RULES = {"Bash(rm -rf*)"}
ALLOW_RULES = {"Read"}
MODE = "default"
USER = {"role": "agent", "refund_limit": 100}

def pre_tool_hook(tool, inp):
    return None   # no opinion

def rule_decision(tool, inp):
    if tool == "Bash" and inp.get("command", "").startswith("rm -rf"):
        return "deny"
    if tool in ALLOW_RULES:
        return "allow"
    return None

def can_use_tool(tool, inp):
    # TODO: deny Write or Edit outside WORKSPACE with a message the model will see
    # TODO: deny refunds above USER["refund_limit"]; allow everything else, returning the input
    return {"behavior": "allow", "updated_input": inp}

def decide(tool, inp):
    for step in (pre_tool_hook, rule_decision):
        d = step(tool, inp)
        if d: return {"behavior": d, "by": step.__name__}
    r = can_use_tool(tool, inp)
    return {**r, "by": "can_use_tool"}

CALLS = [("Read", {"file_path": "/work/ticket-42/a.txt"}), ("Bash", {"command": "rm -rf /"}),
         ("Write", {"file_path": "/etc/passwd"}), ("Write", {"file_path": "/work/ticket-42/notes.md"}),
         ("refund", {"amount": 250}), ("refund", {"amount": 40})]
for tool, inp in CALLS:
    d = decide(tool, inp)
    print(f"{tool:6} {d['behavior']:5} by {d['by']} {d.get('message', '')}")
Show a solution
# Simulate the order the Agent SDK uses to decide a tool call: hooks, rules, mode, then your callback.
# In the real Python SDK the callback is passed as can_use_tool and returns PermissionResultAllow or PermissionResultDeny.
WORKSPACE = "/work/ticket-42/"
DENY_RULES = {"Bash(rm -rf*)"}
ALLOW_RULES = {"Read"}
MODE = "default"
USER = {"role": "agent", "refund_limit": 100}

def pre_tool_hook(tool, inp):
    return None   # no opinion

def rule_decision(tool, inp):
    if tool == "Bash" and inp.get("command", "").startswith("rm -rf"):
        return "deny"
    if tool in ALLOW_RULES:
        return "allow"
    return None

def can_use_tool(tool, inp):
    if tool in ("Write", "Edit"):
        path = str(inp.get("file_path", ""))
        if not path.startswith(WORKSPACE):
            return {"behavior": "deny", "message": f"Writes are only allowed in {WORKSPACE}"}
    if tool == "refund" and inp.get("amount", 0) > USER["refund_limit"]:
        return {"behavior": "deny", "message": "Refunds over the limit need a person to approve."}
    return {"behavior": "allow", "updated_input": inp}

def decide(tool, inp):
    for step in (pre_tool_hook, rule_decision):
        d = step(tool, inp)
        if d: return {"behavior": d, "by": step.__name__}
    r = can_use_tool(tool, inp)
    return {**r, "by": "can_use_tool"}

CALLS = [("Read", {"file_path": "/work/ticket-42/a.txt"}), ("Bash", {"command": "rm -rf /"}),
         ("Write", {"file_path": "/etc/passwd"}), ("Write", {"file_path": "/work/ticket-42/notes.md"}),
         ("refund", {"amount": 250}), ("refund", {"amount": 40})]
for tool, inp in CALLS:
    d = decide(tool, inp)
    print(f"{tool:6} {d['behavior']:5} by {d['by']} {d.get('message', '')}")
denied = sum(decide(t, i)["behavior"] == "deny" for t, i in CALLS)
print("denied:", denied, "of", len(CALLS))
Quick checkYou need to allow file writes only inside the current user's workspace folder. What's the best SDK mechanism?
How sure are you?
Pick an answer and how sure you are