Claude Agent SDK
Answer the Claude Agent SDK's canUseTool callback with a person's decision, in TypeScript and Python: refunds, shell commands and file writes wait for a yes.
The Claude Agent SDK is Claude Code as a library, and it already stops before a tool runs to ask its host: the canUseTool callback, or can_use_tool in Python. Answer that callback with a request in your VariantGate inbox, and a refund, a shell command or a file write waits for a person’s yes on their phone, by email or in Slack, while a rule can settle the routine ones. The code below ran against @anthropic-ai/claude-agent-sdk 0.3.328 and claude-agent-sdk 0.2.185 for Python, with a scripted model standing in for Claude: approved, denied, a lowered amount, reworded, a refund that failed, and the approvals API out of reach.
1. Install
npm install @anthropic-ai/claude-agent-sdk zod
npm install https://variantgate.com/sdk/variantgate-agent-latest.tgzMake an agent key under Agents in your workspace and put it in VARIANTGATE_KEY. The SDK finds Claude through its usual ANTHROPIC_API_KEY.
2. Answer canUseTool with a person’s decision
One file holds the callback and a hook that records how each approved call went. describe is where you write what a person reads.
import {
type CanUseTool,
type HookCallback,
type PermissionResult,
} from "@anthropic-ai/claude-agent-sdk";
import { ApprovalClient } from "@variantgate/agent";
import {
ChangedApprovalError,
NotApprovedError,
} from "@variantgate/agent/errors";
import type { ApprovalRequest, Decision } from "@variantgate/agent/types";
export const REFUND = "mcp__shop__refund_order";
const LOOK_ONLY = new Set(["Read", "Glob", "Grep"]);
const FIFTEEN_MINUTES = 15 * 60_000;
const SECRET_FILE = /(^|\/)\.env|secret|credential|\.pem$|\.key$/i;
const approvals = new ApprovalClient({
agent: "support-agent",
apiUrl: "https://api.variantgate.com",
key: process.env.VARIANTGATE_KEY ?? "",
});
// Which approval let each tool call run, so the outcome lands on its record.
const approvedCalls = new Map<string, string>();
/** What a person reads for one tool call. */
function describe(
toolName: string,
input: Record<string, unknown>
): ApprovalRequest {
if (toolName === REFUND) {
return {
action: "payment.refund",
summary: `Refund €${input.amount_eur} for order ${input.order_id}`,
amount: String(input.amount_eur),
currency: "EUR",
details: { order: input.order_id },
};
}
if (toolName === "Bash") {
return {
action: "shell.run",
summary: `Run: ${String(input.command).slice(0, 500)}`,
details: { command: input.command },
};
}
const target = input.file_path ?? input.url;
// What it would write, fetch or send, cut short for the inbox; for a file
// that may hold secrets, only its path.
const preview = SECRET_FILE.test(String(input.file_path ?? ""))
? {}
: { input: JSON.stringify(input).slice(0, 2000) };
return {
action: `tool.${toolName}`,
summary: target ? `${toolName} ${String(target)}` : `Use ${toolName}`,
details: { tool: toolName, ...preview },
};
}
/** The input to run once approved, or null when the change cannot be done. */
function approvedInput(
toolName: string,
input: Record<string, unknown>,
decision: Decision
): Record<string, unknown> | null {
if (!decision.changed) {
return input;
}
// A refund a person lowered runs for the lower amount; any other change
// (new wording) is not something this code knows how to do.
const onlyAmount =
toolName === REFUND &&
decision.approved_summary === decision.summary &&
decision.approved_amount !== null;
return onlyAmount ? { ...input, amount_eur: decision.approved_amount } : null;
}
export const askAPerson: CanUseTool = async (
toolName,
input,
{ toolUseID }
): Promise<PermissionResult> => {
if (LOOK_ONLY.has(toolName)) {
return { behavior: "allow", updatedInput: input };
}
const request = await approvals.ask(describe(toolName, input), 30);
// Unanswered after 15 minutes: the request is withdrawn and the call denied.
const decision = await approvals.waitForDecision(request, {
timeoutMs: FIFTEEN_MINUTES,
});
if (!decision.allowed) {
return { behavior: "deny", message: new NotApprovedError(decision).message };
}
const runWith = approvedInput(toolName, input, decision);
if (!runWith) {
await approvals
.reportOutcome(decision.id, "failed", "not done: approved with changes")
.catch(() => undefined);
return {
behavior: "deny",
message: new ChangedApprovalError(decision).message,
};
}
approvedCalls.set(toolUseID, decision.id);
return { behavior: "allow", updatedInput: runWith };
};
/** Records how each approved call went. Never fails the run over the record. */
export const recordOutcome: HookCallback = async (event) => {
if (
event.hook_event_name !== "PostToolUse" &&
event.hook_event_name !== "PostToolUseFailure"
) {
return {};
}
const id = approvedCalls.get(event.tool_use_id);
approvedCalls.delete(event.tool_use_id);
if (id) {
const failed = event.hook_event_name === "PostToolUseFailure";
const note = failed ? event.error.slice(0, 500) : undefined;
await approvals
.reportOutcome(id, failed ? "failed" : "succeeded", note)
.catch(() => undefined);
}
return {};
};- Reading files goes ahead without asking. Every other call becomes a request:
payment.refundwith its amount for the refund tool,shell.runwith the command for Bash, and the tool name and file for anything else, with the start of what it would write or fetch in the details, so a person sees what they approve and rules can match on each action. That preview is kept with the request, where everyone in the workspace can read it, so for a file that may hold secrets, such as.envor a.pemkey, only the path is sent. Add your own patterns toSECRET_FILE. - A denied, expired or withdrawn request, or any request while the workspace or this agent is paused, reaches Claude as a denial with the reason, such as “Not approved: the request is denied”, so it can tell the customer instead of trying again.
- If a person lowers a refund, the tool runs with the lower amount through
updatedInput, so the model cannot refund more than was approved. A reworded approval is not something this code can carry out: the call is denied, the model is told what was approved, and the record says nothing was done. - If nobody answers in 15 minutes, the request is withdrawn and the call denied, so nobody can approve it after the agent stopped waiting. If your app stops a run early, withdraw its open requests yourself: in our runs, aborting the query did not reach the callback.
- If the approvals API cannot be reached, the callback throws. The SDK then refuses the call (“Tool permission request failed”) and nothing is refunded.
- After the tool ran, the
PostToolUseandPostToolUseFailurehooks put “succeeded” or the error on the request’s record; a refund that throws arrives asPostToolUseFailure. A failure to record never fails the run, so nothing tempts the agent into a second refund.
3. Give the agent its tool and the callback
import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
import { askAPerson, recordOutcome } from "./approvals";
import { shop } from "./shop"; // your own refund code
const EUROS = /^\d+(\.\d{1,2})?$/;
const shopTools = createSdkMcpServer({
name: "shop",
tools: [
tool(
"refund_order",
"Refund an order to the customer's original payment method.",
{ order_id: z.string(), amount_eur: z.string().regex(EUROS) },
async ({ order_id, amount_eur }) => {
const refund = await shop.refund(order_id, amount_eur);
return {
content: [
{ type: "text", text: `Refunded €${amount_eur} for order ${order_id} (${refund}).` },
],
};
},
{ alwaysLoad: true } // keep it in front of the model, not behind tool search
),
],
});
for await (const message of query({
prompt: "Order 1182 arrived broken. Please refund the €49.",
options: {
model: "claude-sonnet-5-5",
mcpServers: {
// always_ask: no allow rule or allowedTools entry can skip the person.
shop: { ...shopTools, tools: [{ name: "refund_order", permission_policy: "always_ask" as const }] },
},
permissionMode: "default", // ask through canUseTool, not a classifier
canUseTool: askAPerson,
hooks: {
PostToolUse: [{ hooks: [recordOutcome] }],
PostToolUseFailure: [{ hooks: [recordOutcome] }],
},
},
})) {
if (message.type === "result") {
console.log(message.subtype === "success" ? message.result : message.subtype);
}
}permissionMode: "default"matters. Without it the SDK may start in auto mode, where a classifier approves calls itself and askscanUseToolonly when it cannot decide.permission_policy: "always_ask"makes the refund ask every time, even if anallowedToolsentry or an allow rule in a settings file would otherwise let it through without callingcanUseTool. We checked that case: the SDK warns that the callback is shadowed, and the policy still sends the call to it.- The SDK keeps MCP tools behind its tool search until the model looks for them.
alwaysLoadkeeps a support agent’s one real tool in view.
In Python
pip install claude-agent-sdk
pip install https://variantgate.com/sdk/variantgate-latest.tar.gzThe same callback and hooks, with the Python client. Its calls block, so they run in a thread and other sessions keep going while a person decides.
import asyncio
import contextlib
import json
import re
from typing import Any
from claude_agent_sdk import (
ClaudeAgentOptions,
HookMatcher,
PermissionResultAllow,
PermissionResultDeny,
ResultMessage,
ToolPermissionContext,
create_sdk_mcp_server,
query,
tool,
)
from variantgate import (
ApprovalClient,
ChangedApprovalError,
NotApprovedError,
VariantGateError,
is_allowed,
is_changed,
)
from shop import shop # your own refund code
REFUND = "mcp__shop__refund_order"
LOOK_ONLY = {"Read", "Glob", "Grep"}
SECRET_FILE = re.compile(r"(^|/)\.env|secret|credential|\.pem$|\.key$", re.IGNORECASE)
approvals = ApprovalClient("support-agent") # reads VARIANTGATE_KEY
approved_calls: dict[str, str] = {} # tool call id -> approval request id
@tool("refund_order", "Refund an order to the customer's original payment method.",
{"order_id": str, "amount_eur": str})
async def refund_order(args: dict[str, Any]) -> dict[str, Any]:
refund = await asyncio.to_thread(shop.refund, args["order_id"], args["amount_eur"])
text = f"Refunded €{args['amount_eur']} for order {args['order_id']} ({refund})."
return {"content": [{"type": "text", "text": text}]}
def describe(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
"""What a person reads for one tool call."""
if tool_name == REFUND:
return {
"action": "payment.refund",
"summary": f"Refund €{args['amount_eur']} for order {args['order_id']}",
"amount": args["amount_eur"],
"currency": "EUR",
"details": {"order": args["order_id"]},
}
if tool_name == "Bash":
return {"action": "shell.run", "summary": f"Run: {args['command'][:500]}",
"details": {"command": args["command"]}}
target = args.get("file_path") or args.get("url")
summary = f"{tool_name} {target}" if target else f"Use {tool_name}"
details = {"tool": tool_name}
if not SECRET_FILE.search(str(args.get("file_path", ""))): # for those, only the path
details["input"] = json.dumps(args, ensure_ascii=False)[:2000] # cut short for the inbox
return {"action": f"tool.{tool_name}", "summary": summary, "details": details}
def approved_input(tool_name: str, args: dict[str, Any], decision: dict) -> dict | None:
"""The input to run once approved, or None when the change cannot be done."""
if not is_changed(decision):
return args
only_amount = (
tool_name == REFUND
and decision["approved_summary"] == decision["summary"]
and decision["approved_amount"] is not None
)
return {**args, "amount_eur": decision["approved_amount"]} if only_amount else None
def ask_and_wait(tool_name: str, args: dict[str, Any]) -> dict:
request = approvals.ask(**describe(tool_name, args), wait_seconds=30)
return approvals.wait(request, timeout=15 * 60) # withdrawn if unanswered
async def ask_a_person(tool_name: str, args: dict[str, Any], context: ToolPermissionContext):
if tool_name in LOOK_ONLY:
return PermissionResultAllow(updated_input=args)
decision = await asyncio.to_thread(ask_and_wait, tool_name, args)
if not is_allowed(decision):
return PermissionResultDeny(message=str(NotApprovedError(decision)))
run_with = approved_input(tool_name, args, decision)
if run_with is None:
with contextlib.suppress(VariantGateError):
await asyncio.to_thread(approvals.report_outcome, decision["id"], "failed",
"not done: approved with changes")
return PermissionResultDeny(message=str(ChangedApprovalError(decision)))
approved_calls[context.tool_use_id] = decision["id"]
return PermissionResultAllow(updated_input=run_with)
async def record_outcome(event: Any, tool_use_id: str | None, context: Any) -> dict:
"""Records how each approved call went. Never fails the run over the record."""
request_id = approved_calls.pop(event["tool_use_id"], None)
if request_id:
failed = event["hook_event_name"] == "PostToolUseFailure"
with contextlib.suppress(VariantGateError):
await asyncio.to_thread(approvals.report_outcome, request_id,
"failed" if failed else "succeeded",
event["error"] if failed else None)
return {}
async def main() -> None:
options = ClaudeAgentOptions(
model="claude-sonnet-5-5",
mcp_servers={"shop": create_sdk_mcp_server("shop", tools=[refund_order])},
permission_mode="default", # ask through can_use_tool, not a classifier
can_use_tool=ask_a_person, # and keep the refund out of allowed_tools
hooks={
"PostToolUse": [HookMatcher(hooks=[record_outcome])],
"PostToolUseFailure": [HookMatcher(hooks=[record_outcome])],
},
)
async for message in query(
prompt="Order 1182 arrived broken. Please refund the €49.", options=options
):
if isinstance(message, ResultMessage):
print(message.result)
asyncio.run(main())The Python SDK has no per-tool always_ask policy yet, so keep the refund tool out of allowed_tools and out of allow rules in your settings files. The SDK prints a warning when an entry would let a tool skip can_use_tool.
Coding agents: Bash, Write and Edit
The same callback guards Claude Code’s own tools. A shell command arrives as shell.run with the command in the details, a file write as tool.Write with the path. Give them their own action names if you want finer rules, such as deploy.production for a command that starts with your deploy script. For Claude Code itself, the terminal app rather than the library, the Claude Code page shows the same check as a PreToolUse hook.
When the answer may take hours
The SDK sets no deadline on a permission prompt, so the run waits as long as your process does. To wait longer than 15 minutes, raise the timeout and pass ttlSeconds in describe, since a request expires after 15 minutes unless told otherwise. Run the agent in a worker that can stay up that long, such as a queue job, rather than in a web request.
When the SDK’s own prompt is enough
If the person using your app is the one who should decide, answer canUseTool in your own interface and leave VariantGate out. It earns its place when the agent runs with nobody watching, when someone else must decide, when rules should settle routine calls, or when you need a record of who approved what. The framework comparison goes through that choice, and the playground lets you try both sides first. If Anthropic hosts your agent instead, the Claude Managed Agents page answers its tool confirmations the same way.