Asking your code with can_use_tool
can_use_tool is a function the SDK calls when a tool call reaches the end of the permission checks undecided. It returns an allow or a deny, and the run waits for it.
Last updated: 20 Oct, 2026 · Claude Agent SDK
Rules are decided before the run starts. The shop's rule is not: a refund runs once a person has approved that particular order, which is a question only your own code can answer.
The callback
from claude_agent_sdk import PermissionResultAllow, PermissionResultDeny
APPROVED = {"A17"} # the refunds a person has signed off
async def check(tool_name, input_data, context):
# printed so a run shows whether the callback was reached at all
print("asked about", tool_name, input_data, context.tool_use_id)
if tool_name.endswith("refund_order") and input_data["order_id"] not in APPROVED:
return PermissionResultDeny(message="Refunds need a person's approval first.")
return PermissionResultAllow(updated_input=input_data)The SDK calls it with three arguments: the tool's full name, the arguments Claude wants to use, and a context object. The context carries tool_use_id, suggestions, blocked_path, agent_id and the prompt text fields title and display_name, typed in the Python reference as ToolPermissionContext. Return PermissionResultAllow or PermissionResultDeny; a deny carries a message Claude reads.
The desk asks, and waits
shop_desk.py changes twice: permit is replaced with one that falls through to the callback, and ask_permission is added below it.
async def permit(self, name, args, call):
o = self.options
if any(matches(rule, name, args) for rule in o.disallowed_tools):
return False, f"Permission to use {name} was denied by a rule."
if o.permission_mode == "bypassPermissions":
return True, args
if any(matches(rule, name, args) for rule in o.allowed_tools):
return True, args
# nothing approved the call, so the last step is to ask your code
if o.can_use_tool is None or o.permission_mode == "dontAsk":
return False, f"Permission to use {name} was not granted."
return await self.ask_permission(name, args, call) async def ask_permission(self, name, args, call):
# the SDK runs your callback and writes its answer back on this channel
decision = (await self.ask({"subtype": "can_use_tool", "tool_name": name,
"input": args, "tool_use_id": call,
"permission_suggestions": None,
"blocked_path": None}))["response"]
# an allow may hand back different arguments to run with
if decision["behavior"] == "allow":
return True, decision["updatedInput"]
return False, decision["message"]A call nothing has approved becomes a can_use_tool control request. The SDK runs your function and writes the answer back: behavior, and either the arguments to run with or the message to send instead.
View the code here
import asyncio
import itertools
import json
import os
import re
from fnmatch import fnmatch
from claude_agent_sdk import (AssistantMessage, ClaudeAgentOptions, ResultMessage,
SystemMessage, TextBlock, ToolResultBlock, ToolUseBlock,
Transport, UserMessage, query)
ORDER = re.compile(r"\b[A-Z]\d+\b")
SESSIONS = itertools.count(1)
WANTS = {"refund": "refund_order", "stock": "stock_level"}
def read_file(args):
"""What the desk serves for a Read call: the file's lines, numbered."""
lines = open(args["file_path"]).read().splitlines()
return "\n".join(f"{number:>5} {line}" for number, line in enumerate(lines, 1))
BUILT_IN = {"Read": read_file}
def matches(rule, name, args):
"""Does one allow or deny rule match this call?"""
head, _, scope = rule.partition("(")
if not fnmatch(name, head):
return False
# a bare rule covers the whole tool; a scoped one only matching calls
target = args.get("file_path") or args.get("command") or ""
return not scope or fnmatch(target, scope.rstrip(")"))
class ShopModel:
"""Stands in for Claude: reads the conversation, picks the next step."""
def __init__(self, script=None):
self.script = list(script or [])
self.searched = False
def reply(self, said, results, tools):
if self.script:
return self.script.pop(0)
# a search result is not an answer, so a searching turn does not stop here
if results and not self.searched:
return {"text": " ".join(results)}
orders = ORDER.findall(said[-1]) or ORDER.findall(" ".join(said))[-1:]
wanted = next((name for word, name in WANTS.items() if word in said[-1].lower()),
"lookup_order")
tool = next((name for name in tools if name.endswith(wanted)), None)
# the tool this message needs has no definition in context: search for it first
if orders and tool is None and not self.searched and "ToolSearch" in tools:
self.searched = True
return {"calls": [("ToolSearch", {"query": wanted.replace("_", " ")})]}
# the definition is in context now, so the call itself can be made
if orders and tool:
self.searched = False
return {"calls": [(tool, {"order_id": order}) for order in orders]}
return {"text": f"I cannot help with order {orders[0]} yet." if orders
else "Which order is this about?"}
class ShopDesk(Transport):
"""Stands in for the Claude Code binary: it runs the loop over JSON lines."""
def __init__(self, options=None, model=None):
self.options = options or ClaudeAgentOptions()
self.model = model or ShopModel()
self.session_id = f"session-{next(SESSIONS)}"
self.inbox, self.outbox = asyncio.Queue(), asyncio.Queue()
self.prompts, self.said = asyncio.Queue(), []
self.ids, self.setup = itertools.count(1), {}
self.ready, self.tools = False, {}
self.waiting = {}
self.external, self.servers = {}, []
# Claude Code defers by default; the desk waits to be asked, so a run stays short
self.deferring = self.options.env.get("ENABLE_TOOL_SEARCH", "false").startswith(
("true", "auto"))
self.loaded = set()
async def connect(self):
self.ready = True
def is_ready(self):
return self.ready
async def write(self, data):
# one JSON line at a time, which is what the SDK writes to a real process
await self.inbox.put(json.loads(data))
async def end_input(self):
# for a real process this would close its standard input
await self.inbox.put(None)
async def close(self):
self.ready = False
async def send(self, message):
await self.outbox.put(message)
async def read_messages(self):
# the listener and the worker run alongside the SDK's own read loop
asyncio.create_task(self.listen())
self.worker = asyncio.create_task(self.work())
while (message := await self.outbox.get()) is not None:
if isinstance(message, Exception):
raise message
yield message
async def listen(self):
while (message := await self.inbox.get()) is not None:
# a control request is the SDK asking a question; initialize is first
if message["type"] == "control_request":
if message["request"]["subtype"] == "initialize":
self.setup = message["request"]
await self.respond(message["request_id"])
# a control response answers a question the desk itself asked
elif message["type"] == "control_response":
answer = message["response"]
self.waiting.pop(answer["request_id"]).set_result(answer)
elif message["type"] == "user":
await self.prompts.put(message["message"]["content"])
# the input has ended: finish the work in hand, then close the stream
await self.prompts.put(None)
await self.worker
await self.send(None)
async def respond(self, request_id):
# the stand-in says yes to every request the SDK makes of it
await self.send({"type": "control_response", "response": {
"subtype": "success", "request_id": request_id, "response": {}}})
async def ask(self, request):
# a future per request, so the answer can be awaited where it was asked
request_id = f"desk_{next(self.ids)}"
self.waiting[request_id] = asyncio.get_running_loop().create_future()
await self.send({"type": "control_request", "request_id": request_id,
"request": request})
return await self.waiting[request_id]
async def work(self):
while (prompt := await self.prompts.get()) is not None:
await self.turn(prompt)
async def start(self, prompt):
self.said.append(prompt)
if not self.tools:
self.tools = await self.find_tools()
# the init message reports what each configured server is doing
await self.send({"type": "system", "subtype": "init", "model": "shop-desk",
"session_id": self.session_id, "tools": list(self.tools),
"mcp_servers": self.servers})
async def turn(self, prompt):
await self.start(prompt)
results, turns = [], 0
# the model is given the definitions in context, not every tool the desk has
while "calls" in (step := self.model.reply(self.said, results, self.in_context())):
turns += 1
results = [await self.use(name, args) for name, args in step["calls"]]
await self.say(step["text"])
await self.finish("success", turns + 1, step["text"])
def offered(self):
# the tools option is the availability layer: None means every built-in the
# desk has, a list names the ones to keep, and [] leaves Claude none
asked = self.options.tools
if asked is None or isinstance(asked, dict):
return list(BUILT_IN)
return [name for name in asked if name in BUILT_IN]
async def mcp(self, server, method, params):
message = {"jsonrpc": "2.0", "id": next(self.ids), "method": method,
"params": params}
answer = await self.ask({"subtype": "mcp_message", "server_name": server,
"message": message})
return answer["response"]["mcp_response"]["result"]
async def connect_stdio(self, name, config):
# Claude Code starts the command and talks MCP over its standard input
process = await asyncio.create_subprocess_exec(
config["command"], *config.get("args", []),
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
env={**os.environ, **config.get("env", {})})
self.external[name] = process
hello = await self.stdio(name, "initialize", {"protocolVersion": "2025-06-18"})
if hello is None:
return {"name": name, "status": "failed",
"error": "the server gave no answer to initialize"}
return {"name": name, "status": "connected", "serverInfo": hello["serverInfo"]}
async def stdio(self, name, method, params):
process = self.external[name]
request = {"jsonrpc": "2.0", "id": next(self.ids), "method": method,
"params": params}
process.stdin.write((json.dumps(request) + "\n").encode())
await process.stdin.drain()
# a server that died writes nothing and its pipe reaches end of file
line = await process.stdout.readline()
return json.loads(line)["result"] if line else None
async def list_from(self, name, config):
# an in-process server is handed over by the SDK; a stdio one is a command to run
if not isinstance(config, dict) or config.get("type") == "sdk":
await self.mcp(name, "initialize", {"protocolVersion": "2025-06-18",
"capabilities": {}, "clientInfo": {"name": "desk", "version": "1"}})
listed = await self.mcp(name, "tools/list", {})
return {"name": name, "status": "connected", "tools": listed["tools"]}
status = await self.connect_stdio(name, config)
if status["status"] == "connected":
status["tools"] = (await self.stdio(name, "tools/list", {}))["tools"]
return status
async def find_tools(self):
tools = {name: ("built-in", name) for name in self.offered()}
self.servers = []
for name, config in self.options.mcp_servers.items():
status = await self.list_from(name, config)
self.servers.append(status)
for tool in status.pop("tools", []):
tools[f"mcp__{name}__{tool['name']}"] = (name, tool["name"])
# a deny rule with no scope removes the tool before any call is made
bare = [rule for rule in self.options.disallowed_tools if "(" not in rule]
return {name: where for name, where in tools.items()
if not any(fnmatch(name, rule) for rule in bare)}
def in_context(self):
# what the model has definitions for: everything, or the searcher plus what it found
if not self.deferring:
return dict(self.tools)
found = {name: self.tools[name] for name in self.loaded}
return {"ToolSearch": ("built-in", "ToolSearch"), **found}
def search(self, query):
words = set(query.lower().split())
# the search matches the query against tool names, as the docs describe
hits = [name for name in self.tools
if words & set(name.lower().replace("mcp__", "").split("_"))]
# five at most, and each one's definition stays in context from now on
self.loaded.update(hits[:5])
return "Loaded: " + ", ".join(hits[:5]) if hits else "No tool matched."
async def use(self, name, args, parent=None):
call = f"toolu_{next(self.ids)}"
block = {"type": "tool_use", "id": call, "name": name, "input": args}
await self.send(self.message("assistant", [block], parent))
# a refused call reuses args as the text to send back, so Claude is told why
allowed, args = await self.permit(name, args, call)
text, failed = (await self.run(name, args, call)) if allowed else (args, True)
result = {"type": "tool_result", "tool_use_id": call, "content": text,
"is_error": failed}
await self.send(self.message("user", [result], parent))
return text
async def run(self, name, args, call):
# the searcher is a tool like any other, and it answers from the desk's catalogue
if name == "ToolSearch":
return self.search(args["query"]), False
where, tool = self.tools[name]
if where == "built-in":
try:
return BUILT_IN[tool](args), False
except Exception as error:
return f"{type(error).__name__}: {error}", True
call_args = {"name": tool, "arguments": args}
result = (await self.stdio(where, "tools/call", call_args) if where in self.external
else await self.mcp(where, "tools/call", call_args))
return result["content"][0]["text"], result.get("isError", False)
async def say(self, text):
# with include_partial_messages on, the text goes out a word at a time
if self.options.include_partial_messages:
for word in text.split(" "):
delta = {"type": "text_delta", "text": word + " "}
await self.send({"type": "stream_event", "uuid": f"ev_{next(self.ids)}",
"session_id": self.session_id, "event": {
"type": "content_block_delta", "index": 0,
"delta": delta}})
# the whole message still follows, so code written earlier keeps working
await self.send(self.message("assistant", [{"type": "text", "text": text}]))
async def finish(self, subtype, turns, text):
ok = subtype == "success"
result = {"type": "result", "subtype": subtype, "is_error": not ok,
"duration_ms": 0, "duration_api_ms": 0, "num_turns": turns,
"session_id": self.session_id, "total_cost_usd": 0.0,
"usage": {"input_tokens": len(" ".join(self.said).split()),
"output_tokens": len(text.split())}}
# cost is zero and usage counts words, because no model was called
result.update({"result": text} if ok else {"errors": [text]})
await self.send(result)
def message(self, kind, content, parent=None):
body = {"role": kind, "content": content}
if kind == "assistant":
body.update(model="shop-desk", id=f"msg_{next(self.ids)}")
return {"type": kind, "message": body, "parent_tool_use_id": parent,
"session_id": self.session_id}
async def permit(self, name, args, call):
o = self.options
if any(matches(rule, name, args) for rule in o.disallowed_tools):
return False, f"Permission to use {name} was denied by a rule."
if o.permission_mode == "bypassPermissions":
return True, args
if any(matches(rule, name, args) for rule in o.allowed_tools):
return True, args
# nothing approved the call, so the last step is to ask your code
if o.can_use_tool is None or o.permission_mode == "dontAsk":
return False, f"Permission to use {name} was not granted."
return await self.ask_permission(name, args, call)
async def ask_permission(self, name, args, call):
# the SDK runs your callback and writes its answer back on this channel
decision = (await self.ask({"subtype": "can_use_tool", "tool_name": name,
"input": args, "tool_use_id": call,
"permission_suggestions": None,
"blocked_path": None}))["response"]
# an allow may hand back different arguments to run with
if decision["behavior"] == "allow":
return True, decision["updatedInput"]
return False, decision["message"]
def describe(message):
# the two messages with no content blocks are read from their own fields
if isinstance(message, SystemMessage):
return f"system {message.subtype}"
if isinstance(message, ResultMessage):
return f"result {message.subtype}: {message.result or message.errors}"
# a type this course does not use prints its name rather than failing
if not isinstance(message, (AssistantMessage, UserMessage)):
return type(message).__name__
return describe_block(message.content[0])
def describe_block(block):
if isinstance(block, TextBlock):
return f"assistant {block.text}"
if isinstance(block, ToolUseBlock):
return f"assistant calls {block.name} {block.input}"
# a tool result sits on the user's side, and its error flag is worth seeing
if isinstance(block, ToolResultBlock):
flag = " (error)" if block.is_error else ""
return f"user result{flag}: {block.content}"
return type(block).__name__
async def watch(prompt, options, model=None):
"""Run one question through a fresh desk and print every message that comes back."""
async for message in query(prompt=prompt, options=options,
transport=ShopDesk(options, model)):
print(describe(message))
from claude_agent_sdk import create_sdk_mcp_server, tool
ORDERS = {"A17": "Order A17 shipped on 3 March."}
REFUNDED = []
# the description is what Claude reads to decide this is the right tool
@tool("lookup_order", "Look up an order's shipping status by its id, such as A17.",
{"order_id": str})
async def lookup_order(args):
order = args["order_id"]
# an unknown id is answered in words, not raised, so Claude can pass it on
status = ORDERS.get(order, f"No order {order} was found.")
return {"content": [{"type": "text", "text": status}]}
# the money moves, so this is the call that must not run unasked
@tool("refund_order", "Refund an order by its id. The money goes back to the customer.",
{"order_id": str})
async def refund_order(args):
# recorded so a lesson can show whether the refund happened at all
REFUNDED.append(args["order_id"])
text = f"Order {args['order_id']} has been refunded."
return {"content": [{"type": "text", "text": text}]}
shop = create_sdk_mcp_server("shop", tools=[lookup_order, refund_order])
Two refunds, one approved
from claude_agent_sdk import ClaudeAgentOptions
from shop_desk import watch
from shop_tools import REFUNDED, shop
options = ClaudeAgentOptions(mcp_servers={"shop": shop}, can_use_tool=check)
await watch("Please refund my order A17", options)
await watch("Please refund my order C40", options)
print("refunded:", REFUNDED)system init
assistant calls mcp__shop__refund_order {'order_id': 'A17'}
asked about mcp__shop__refund_order {'order_id': 'A17'} toolu_5
user result: Order A17 has been refunded.
assistant Order A17 has been refunded.
result success: Order A17 has been refunded.
system init
assistant calls mcp__shop__refund_order {'order_id': 'C40'}
asked about mcp__shop__refund_order {'order_id': 'C40'} toolu_5
user result (error): Refunds need a person's approval first.
assistant Refunds need a person's approval first.
result success: Refunds need a person's approval first.
refunded: ['A17']What the callback decided
- Both calls reached it, printed as "asked about", with the same tool name and the arguments Claude chose.
- A17 was on the approved list, so the callback allowed it and the refund ran.
- C40 was not, so the deny went back to Claude as the message, and the desk's model repeated it. A real model would put it to the customer in its own words.
- The id ties the two together.
context.tool_use_idis the same id the tool request carried, which is what you log an approval against.
One difference from the user input page is worth knowing. Its examples register a dummy PreToolUse hook, marked as a required workaround to keep the stream open for can_use_tool. On the pinned 0.2.157 the callback is reached without it, as the run above shows: no hooks are registered anywhere in this lesson. The hooks part of this course writes real ones.
A callback that is never asked
An allow rule resolves a call before the callback's step, so a rule and a callback about the same tool do not combine. The SDK warns when it sees that configuration:
import warnings
# a bare name in allowed_tools approves the whole tool, callback or no callback
shadowed = ClaudeAgentOptions(mcp_servers={"shop": shop}, can_use_tool=check,
allowed_tools=["mcp__shop__refund_order"])
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
await watch("Please refund my order C40", shadowed)
print(caught[0].category.__name__)
print(caught[0].message)system init
assistant calls mcp__shop__refund_order {'order_id': 'C40'}
user result: Order C40 has been refunded.
assistant Order C40 has been refunded.
result success: Order C40 has been refunded.
CanUseToolShadowedWarning
can_use_tool will not be invoked for: mcp__shop__refund_order. An allowed_tools entry that allows a whole tool auto-approves it before the callback is consulted. To gate every tool call, use a PreToolUse hook; or narrow the entry so calls fall through to can_use_tool. Allow rules from settings files can also shadow the callback but are not visible here.C40 was refunded and check never printed. The warning is CanUseToolShadowedWarning, and the SDK raises it once per query for two configurations: bypassPermissions, and any allowed_tools entry that allows a whole tool. An entry with a real specifier such as Bash(ls *) does not trigger it, and neither does acceptEdits. Allow rules in settings files can shadow the callback too, and the check cannot see those.
The mode that never asks
# dontAsk turns every prompt into a denial without calling your code
quiet = ClaudeAgentOptions(mcp_servers={"shop": shop}, can_use_tool=check,
permission_mode="dontAsk")
await watch("Please refund my order A17", quiet)system init
assistant calls mcp__shop__refund_order {'order_id': 'A17'}
user result (error): Permission to use mcp__shop__refund_order was not granted.
assistant Permission to use mcp__shop__refund_order was not granted.
result success: Permission to use mcp__shop__refund_order was not granted.A17 is on the approved list, and it was still refused: in dontAsk the callback step is skipped. That mode paired with allowed_tools is the shape of a headless agent with a fixed tool surface and a hard denial behind it.
A rule against a callback
| An allow rule | can_use_tool | |
|---|---|---|
| Decided | Before the run starts | While the run waits |
| Sees the arguments | Only through a specifier pattern | All of them, as a dict |
| Can change the call | No | Yes, with updated_input |
| Can explain itself | No | Yes, the deny message reaches Claude |
| Runs for every call | Not applicable | No. Anything approved earlier skips it; a hook is the step nothing skips |
What the SDK does when you set a callback
Setting can_use_tool changes the options the SDK starts Claude Code with: it sets permission_prompt_tool_name to "stdio", so permission requests come over the control protocol rather than through a tool. That is also why the two options cannot be combined:
from claude_agent_sdk import ClaudeAgentOptions, query
from shop_desk import ShopDesk
# the SDK routes prompts over stdio for a callback, so a prompt tool would clash
clash = ClaudeAgentOptions(can_use_tool=check,
permission_prompt_tool_name="mcp__gate__ask")
try:
async for message in query(prompt="Hello", options=clash,
transport=ShopDesk(clash)):
pass
except ValueError as error:
print(error)can_use_tool callback cannot be used with permission_prompt_tool_name. Please use one or the other.
PreToolUse hook that returns a defer decision instead, so the process can exit and the session resume later.Related
- Previous: Allow and deny rules
- Next: Handling approvals and questions
- Reference: the user input page and ToolPermissionContext
- Return
PermissionResultAllow(updated_input={"order_id": "A17"})for every refund and ask about C40. Which order is refunded? - Add C40 to
APPROVEDbetween two runs. - Print
context.suggestionsinsidecheckand compare it with the next lesson's version.
This is what real progress feels like.