Claude Managed Agents
Answer Claude Managed Agents tool confirmations with a person's decision: always_ask on the tools that change things, then allow or deny from an inbox, in TypeScript and Python.
Claude Managed Agents runs the agent loop and its tools on Anthropic’s side. Give a tool the always_ask permission policy and the session stops before each call and waits for your code to send a user.tool_confirmation. Answer that with a request in your VariantGate inbox, and a refund through your MCP server, 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/sdk 1.11.0 and anthropic 2.11.0 for Python, with a scripted stand-in for the Managed Agents session API and the real approvals API: approved, denied, a lowered refund, a refund that failed, two calls at once, a write to .env, the approvals API out of reach, and for the webhook version a webhook that arrived twice.
1. Install
npm install @anthropic-ai/sdk
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 Anthropic client reads its usual ANTHROPIC_API_KEY.
2. Make the agent ask before it changes anything
Create the agent once, in setup, and start every session from its id. Only reading runs on its own: read, glob and grep. The shell, writes, edits, any tool added to the toolset later and every tool on the shop’s MCP server wait for an answer.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// Once, in setup: keep the ids and start every session from them.
const environment = await client.beta.environments.create({
name: "support",
config: { type: "cloud", networking: { type: "limited", allow_mcp_servers: true } },
});
const agent = await client.beta.agents.create({
name: "Support agent",
model: "claude-opus-5-5",
system: "You help customers with their orders. Refund only what the order shows.",
mcp_servers: [{ type: "url", name: "shop", url: "https://mcp.shop.example/mcp" }],
tools: [
{
type: "agent_toolset_20260401",
// Everything asks, including tools added later; reading runs on its own.
default_config: { enabled: true, permission_policy: { type: "always_ask" } },
configs: [
{ name: "read", permission_policy: { type: "always_allow" } },
{ name: "glob", permission_policy: { type: "always_allow" } },
{ name: "grep", permission_policy: { type: "always_allow" } },
{ name: "web_fetch", enabled: false },
{ name: "web_search", enabled: false },
],
},
{
type: "mcp_toolset",
mcp_server_name: "shop",
default_config: { permission_policy: { type: "always_ask" } },
},
],
});
console.log({ agent: agent.id, version: agent.version, environment: environment.id });always_askis the policy that means a person. Theautopolicy lets Anthropic’s server judge each call: it runs the calls it finds safe before anyone sees them, refuses the risky ones, and asks only when it cannot tell. That is fewer interruptions, not a review.- An MCP toolset asks by default, but the agent toolset runs everything by default. Here both ask by default and only the reading tools are let through, so a tool you did not think of asks rather than runs.
- Permission policies do not cover custom tools, since your own code runs those. Ask inside the handler instead, as in custom tools below.
3. Turn each paused call into a request
One file says what a person reads for each call and what the session is told afterwards. describe is where you write your own wording.
import type {
BetaManagedAgentsAgentMCPToolUseEvent,
BetaManagedAgentsAgentToolUseEvent,
BetaManagedAgentsSessionEvent,
BetaManagedAgentsStreamSessionEvents,
BetaManagedAgentsUserToolConfirmationEventParams,
} from "@anthropic-ai/sdk/resources/beta/sessions/events";
import type Anthropic from "@anthropic-ai/sdk";
import { ApprovalClient } from "@variantgate/agent";
import {
ChangedApprovalError,
NotApprovedError,
} from "@variantgate/agent/errors";
import type { ApprovalRequest, Decision } from "@variantgate/agent/types";
export type ToolUse =
| BetaManagedAgentsAgentToolUseEvent
| BetaManagedAgentsAgentMCPToolUseEvent;
export type Confirmation = BetaManagedAgentsUserToolConfirmationEventParams;
type SessionEvent =
| BetaManagedAgentsStreamSessionEvents // from events.stream()
| BetaManagedAgentsSessionEvent; // from events.list()
// Files whose contents must not land in a request everyone can read.
const SECRET_FILE =
/(^|\/)\.(env|npmrc|netrc|pgpass|git-credentials)|id_(rsa|ecdsa|ed25519|dsa)|kubeconfig|secret|credential|token|\.(pem|key|p12|pfx)$/i;
export const approvals = new ApprovalClient({
agent: "support-agent",
apiUrl: "https://api.variantgate.com",
key: process.env.VARIANTGATE_KEY ?? "",
});
/** A tool call the session paused on, waiting for a yes or no. */
export function isAsk(event: SessionEvent): event is ToolUse {
return (
(event.type === "agent.tool_use" || event.type === "agent.mcp_tool_use") &&
event.evaluated_permission === "ask"
);
}
/** What a person reads for one paused tool call. */
export function describe(use: ToolUse, sessionId: string): ApprovalRequest {
const input = use.input;
// Kept on the request so the record shows which session and call it was.
const where = { session: sessionId, event: use.id };
const shop = use.type === "agent.mcp_tool_use" && use.mcp_server_name === "shop";
if (shop && use.name === "refund_order") {
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, ...where },
};
}
if (use.type === "agent.tool_use" && use.name === "bash") {
const command = String(input.command);
if (command.split(/[\s'"<>|;&=:()`]+/).some((word) => SECRET_FILE.test(word))) {
// It may carry the secret itself: say so, show none of it.
return {
action: "shell.run",
summary: "Run a command that touches a secret file (not shown)",
details: { secret_file: true, ...where },
};
}
return {
action: "shell.run",
summary: `Run: ${command.slice(0, 500)}`,
details: { command: preview(command), ...where },
};
}
const tool =
use.type === "agent.mcp_tool_use"
? `${use.mcp_server_name}.${use.name}`
: use.name;
const path = String(input.file_path ?? input.path ?? input.filename ?? "");
// What it would write or send, cut short; for a file that may hold
// secrets, only its path.
const shown = SECRET_FILE.test(path) ? {} : { input: preview(JSON.stringify(input)) };
return {
action: `tool.${tool}`,
summary: path ? `${tool} ${path}` : `Use ${tool}`,
details: { tool, ...shown, ...where },
};
}
/** Text cut short for the inbox, saying so when it was. */
function preview(text: string): string {
return text.length > 2000
? `${text.slice(0, 2000)} [cut: ${text.length} characters in all]`
: text;
}
/** A no, with the reason the agent reads. */
export function refusal(use: ToolUse, reason: string): Confirmation {
return {
type: "user.tool_confirmation",
tool_use_id: use.id, // the event's sevt_ id, not a toolu_ id
result: "deny",
deny_message: reason,
};
}
/** The answer the session gets. It can say yes or no, never "do less". */
export function confirmation(use: ToolUse, decision: Decision): Confirmation {
const no = (reason: string) => refusal(use, reason);
if (!decision.allowed) {
return no(new NotApprovedError(decision).message);
}
if (decision.changed !== false) {
// A lowered refund or new wording cannot be passed to a server-run tool:
// say no, and tell the agent what was approved so it can ask again.
return no(new ChangedApprovalError(decision).message);
}
return { type: "user.tool_confirmation", tool_use_id: use.id, result: "allow" };
}
/** The tool call a result event answers, if it is one. */
export function resultOf(event: SessionEvent) {
if (event.type === "agent.tool_result") {
return { useId: event.tool_use_id, failed: event.is_error === true, event };
}
if (event.type === "agent.mcp_tool_result") {
return { useId: event.mcp_tool_use_id, failed: event.is_error === true, event };
}
return null;
}
/** The first text of a failed result, for the record. */
export function errorText(content: Array<{ type: string }> | undefined) {
const text = content?.find((block) => block.type === "text");
return text && "text" in text ? String(text.text).slice(0, 500) : "the tool failed";
}
/** Whether the session already has an answer for this call. */
export async function delivered(client: Anthropic, sessionId: string, useId: string) {
for await (const event of client.beta.sessions.events.list(sessionId)) {
if (event.type === "user.tool_confirmation" && event.tool_use_id === useId) {
return true;
}
}
return false;
}- A refund on the shop’s MCP server becomes
payment.refundwith its amount, a shell commandshell.runwith the command, and anything else the tool’s name with the start of its input, marked when it was cut, so rules can match on each action. The preview is kept with the request, where everyone in the workspace can read it, so for a file that may hold secrets, such as.env, an SSH key,.npmrcor a.pemfile, only the path is sent, and a shell command that names one is not shown at all, since it may carry the secret itself. Add your own patterns toSECRET_FILE. - The confirmation names the paused event by its
sevt_id, not atoolu_id. The session and event ids also go into the request’s details, so its record shows which call it was. - A confirmation can only say yes or no: it cannot change what a server-run tool does. So when a person lowers a refund or rewords it, the call is denied and the agent is told what was approved, such as “for at most 20.00 EUR”, and it can ask again for that. The record says nothing was done.
4. Answer while the session streams
import Anthropic from "@anthropic-ai/sdk";
import type { BetaManagedAgentsStreamSessionEvents } from "@anthropic-ai/sdk/resources/beta/sessions/events";
import { messageOf } from "@variantgate/agent";
import type { Decision } from "@variantgate/agent/types";
import {
approvals,
type Confirmation,
confirmation,
delivered,
describe,
errorText,
isAsk,
refusal,
resultOf,
type ToolUse,
} from "./approvals";
const client = new Anthropic();
const FIFTEEN_MINUTES = 15 * 60_000;
// Which approval let each tool call run, so its outcome lands on the record.
const approvedCalls = new Map<string, { requestId: string; sessionId: string }>();
// Requests still waiting, per session, and the sessions we stopped answering.
const waiting = new Map<string, Set<string>>();
const ended = new Set<string>();
/** Asks a person about one paused call and answers the session. */
async function answer(sessionId: string, use: ToolUse) {
let request: Decision | undefined;
let reply: Confirmation;
try {
request = await approvals.ask(describe(use, sessionId)); // returns at once
if (ended.has(sessionId)) throw new Error("no longer answering this session");
const open = waiting.get(sessionId) ?? new Set<string>();
waiting.set(sessionId, open.add(request.id));
// Unanswered after 15 minutes: the request is withdrawn, the call denied.
const decision = await approvals
.waitForDecision(request, { timeoutMs: FIFTEEN_MINUTES })
.finally(() => open.delete(request?.id ?? ""));
reply = confirmation(use, decision);
if (reply.result === "allow") {
approvedCalls.set(use.id, { requestId: decision.id, sessionId });
} else if (decision.allowed) {
await approvals
.reportOutcome(decision.id, "failed", "not done: approved with changes")
.catch(() => undefined);
}
} catch (error) {
// No answer we can trust: take the request back so nobody approves it
// later, and the call does not run.
if (request) await approvals.withdraw(request.id).catch(() => undefined);
reply = refusal(use, `Not approved, no answer from approvals: ${messageOf(error)}`);
}
if (ended.has(sessionId)) {
await notDone(use.id, "not done: no longer answering this session");
return;
}
try {
await client.beta.sessions.events.send(sessionId, { events: [reply] });
} catch (error) {
// A send that timed out may still have arrived: look before saying so.
if (await delivered(client, sessionId, use.id).catch(() => false)) return;
await notDone(use.id, "not done: the answer did not reach the session");
throw error;
}
}
/** An approved call that will never run: say so on its record. */
async function notDone(useId: string, note: string) {
const approved = approvedCalls.get(useId);
approvedCalls.delete(useId);
if (approved) {
await approvals
.reportOutcome(approved.requestId, "failed", note)
.catch(() => undefined);
}
}
/** Puts how an approved call went on its record. Never fails the run. */
async function record(event: BetaManagedAgentsStreamSessionEvents) {
const result = resultOf(event);
const requestId = result && approvedCalls.get(result.useId)?.requestId;
if (result && requestId) {
approvedCalls.delete(result.useId);
const note = result.failed ? errorText(result.event.content) : undefined;
await approvals
.reportOutcome(requestId, result.failed ? "failed" : "succeeded", note)
.catch(() => undefined);
}
}
/** Sends one message and answers every paused call until the agent is done. */
export async function run(sessionId: string, text: string) {
const stream = await client.beta.sessions.events.stream(sessionId); // open first
await client.beta.sessions.events.send(sessionId, {
events: [{ type: "user.message", content: [{ type: "text", text }] }],
});
const answering: Promise<void>[] = [];
let failure: unknown;
try {
for await (const event of stream) {
if (isAsk(event)) {
// Several calls can wait at once; each gets its own request.
const answered = answer(sessionId, event).catch((error) => {
failure ??= error; // a call left unanswered would wait forever
stream.controller.abort();
});
answering.push(answered);
continue;
}
await record(event);
if (event.type === "agent.message") {
for (const block of event.content) {
if (block.type === "text") console.log(block.text);
}
}
if (event.type === "session.status_terminated") {
await stopAnswering(sessionId, true); // those calls can never run
break;
}
if (
event.type === "session.status_idle" &&
event.stop_reason.type !== "requires_action"
) break; // end_turn, retries_exhausted or budget_reached
}
} catch (error) {
if (failure === undefined) throw error; // else: we stopped the stream
}
if (failure !== undefined) await stopAnswering(sessionId, false); // end other waits
await Promise.all(answering);
waiting.delete(sessionId);
if (failure !== undefined) throw failure;
}
/** Takes back what a session still waits on; if it ended, approved calls never ran. */
async function stopAnswering(sessionId: string, sessionEnded: boolean) {
ended.add(sessionId);
const open = [...(waiting.get(sessionId) ?? [])];
await Promise.all(open.map((id) => approvals.withdraw(id).catch(() => undefined)));
for (const [useId, approved] of approvedCalls) {
if (sessionEnded && approved.sessionId === sessionId) {
await notDone(useId, "not done: the session ended first");
}
}
}- The stream is opened before the message is sent, so no event is missed, and the loop stops only on an idle that is not
requires_action: a paused session is idle too. - Each paused call gets its own request and its own answer, so a refund and a shell command from one turn can be decided separately.
- A denied, expired or withdrawn request, or any request while the workspace or this agent is paused, reaches the agent as a denial with the reason, such as “Not approved: the request is denied”. If the approvals API cannot be reached or refuses the request, the call is denied with that reason, and a request already in the inbox is withdrawn so nobody approves it later.
- If the answer cannot be sent to the session, the run stops with the error instead of waiting forever, and the record says the call was not done.
- If the session ends while a call still waits, its request is withdrawn: that call can never run.
- If nobody answers in 15 minutes, the request is withdrawn and the call denied, so nobody approves it after the agent stopped waiting.
- When the tool has run, its result event puts “succeeded” or the error on the request’s record. A failure to record never fails the run.
When the answer may take hours
Holding a stream open for hours is fragile. Instead, let two webhooks do the work: Managed Agents says a session went idle, your code asks about each call it paused on, and VariantGate’s signed webhook says a request was decided, so your code sends the answer. Nothing waits in between.
import Anthropic from "@anthropic-ai/sdk";
import {
verifyWebhook,
WebhookVerificationError,
} from "@variantgate/agent/webhook";
import {
approvals,
confirmation,
delivered,
describe,
errorText,
isAsk,
resultOf,
type ToolUse,
} from "./approvals";
const client = new Anthropic(); // reads ANTHROPIC_WEBHOOK_SIGNING_KEY too
const ONE_DAY = 24 * 60 * 60;
const DECIDED = new Set([
"request.approved",
"request.denied",
"request.expired",
"request.withdrawn",
]);
/** One paused call and its request. A table in production, keyed by useId. */
interface Asked {
sessionId: string;
use: ToolUse;
requestId?: string;
answered?: boolean;
allowed?: boolean;
recorded?: boolean;
}
const asked = new Map<string, Asked>(); // sevt_ id -> what we asked
const ended = new Set<string>(); // sessions that have ended
const byRequest = new Map<string, string>(); // request id -> sevt_ id
/** Answers the session once the request is decided. Safe to call twice. */
export async function settle(requestId: string) {
const entry = asked.get(byRequest.get(requestId) ?? "");
if (!entry || entry.answered) return;
entry.answered = true; // claimed before any await: settle runs only once
let decision;
try {
decision = await approvals.check(requestId); // the request, not the webhook body
} catch (error) {
entry.answered = false;
throw error;
}
if (decision.status === "pending") {
entry.answered = false;
return;
}
const reply = confirmation(entry.use, decision);
entry.allowed = reply.result === "allow"; // set first: its result may come fast
if (decision.allowed && !entry.allowed) {
await approvals
.reportOutcome(requestId, "failed", "not done: approved with changes")
.catch(() => undefined);
}
try {
await client.beta.sessions.events.send(entry.sessionId, { events: [reply] });
} catch (error) {
// A send that timed out may still have arrived: look before deciding.
const arrived = await delivered(client, entry.sessionId, entry.use.id).catch(
() => undefined
);
if (arrived) return;
if (arrived === undefined || !(error instanceof Anthropic.BadRequestError)) {
entry.answered = false; // not sure yet: try again on the next webhook or sweep
throw error;
}
if (entry.allowed) {
entry.allowed = false; // the session refused it, so the call never runs
await approvals
.reportOutcome(requestId, "failed", "not done: the session no longer waited")
.catch(() => undefined);
}
}
}
/** A session that ended: take back its open requests and forget its calls. */
async function forget(sessionId: string) {
ended.add(sessionId); // a late idled webhook must not ask again
for (const [useId, entry] of asked) {
if (entry.sessionId !== sessionId) continue;
if (entry.requestId) {
// Refused when already decided, which is fine.
await approvals.withdraw(entry.requestId).catch(() => undefined);
}
if (entry.requestId && entry.allowed && !entry.recorded) {
await approvals
.reportOutcome(entry.requestId, "failed", "not done: the session ended first")
.catch(() => undefined);
}
if (entry.requestId) byRequest.delete(entry.requestId);
asked.delete(useId);
}
}
/** Records outcomes, then asks about paused calls that have no request yet. */
export async function catchUp(sessionId: string, ending = false) {
if (ended.has(sessionId)) return;
const paused: ToolUse[] = [];
const confirmed = new Set<string>();
for await (const event of client.beta.sessions.events.list(sessionId)) {
if (isAsk(event)) paused.push(event);
if (event.type === "user.tool_confirmation") confirmed.add(event.tool_use_id);
const result = resultOf(event);
const entry = result && asked.get(result.useId);
if (result && entry?.requestId && entry.allowed && !entry.recorded) {
entry.recorded = true;
const note = result.failed ? errorText(result.event.content) : undefined;
await approvals
.reportOutcome(entry.requestId, result.failed ? "failed" : "succeeded", note)
.catch(() => undefined);
}
}
if (ending) {
await forget(sessionId); // nothing it paused on can run any more
return;
}
for (const use of paused) {
if (confirmed.has(use.id) || asked.has(use.id)) continue;
asked.set(use.id, { sessionId, use }); // claim first: webhooks arrive twice
let request;
try {
request = await approvals.ask({ ...describe(use, sessionId), ttlSeconds: ONE_DAY });
} catch (error) {
asked.delete(use.id); // let the retried webhook ask again
throw error;
}
const entry = asked.get(use.id);
if (!entry) {
// The session ended while we asked: nothing can run there.
await approvals.withdraw(request.id).catch(() => undefined);
continue;
}
entry.requestId = request.id;
byRequest.set(request.id, use.id);
if (request.status !== "pending") await settle(request.id); // a rule answered
}
}
/** POST /anthropic: Managed Agents tells you a session went idle. */
export async function anthropicWebhook(request: Request) {
let event;
try {
event = client.beta.webhooks.unwrap(await request.text(), {
headers: Object.fromEntries(request.headers),
});
} catch {
return new Response(null, { status: 400 });
}
const type = event.data.type;
if (type === "session.status_idled" || type === "session.status_terminated") {
await catchUp(event.data.id, type === "session.status_terminated");
}
return new Response(null, { status: 204 });
}
/** POST /variantgate: a request was decided. Only a wake-up. */
export async function variantgateWebhook(request: Request) {
const secret = process.env.VARIANTGATE_WEBHOOK_SECRET;
if (!secret) throw new Error("Set VARIANTGATE_WEBHOOK_SECRET"); // not a bad signature
let event;
try {
event = await verifyWebhook(secret, request.headers, await request.text());
} catch (error) {
if (error instanceof WebhookVerificationError) {
return new Response(null, { status: 400 });
}
throw error;
}
if (DECIDED.has(event.type) && "request_id" in event.data) {
await settle(event.data.request_id);
}
return new Response(null, { status: 204 });
}
/** Every few minutes: settles what a lost VariantGate webhook left waiting. */
export async function sweep() {
for (const [requestId, useId] of byRequest) {
if (asked.get(useId)?.answered) continue;
// One session failing must not hold up the rest.
await settle(requestId).catch((error) => console.error("settle", requestId, error));
}
}- Register
/anthropicin the Claude Console under Manage, Webhooks, forsession.status_idledandsession.status_terminated, and put itswhsec_secret inANTHROPIC_WEBHOOK_SIGNING_KEY. Add/variantgateunder Settings, Webhooks in your workspace (Pro and up) and put its secret inVARIANTGATE_WEBHOOK_SECRET. - Both webhooks may arrive twice. A call is claimed before its request is made, so a repeated webhook does not ask twice, and
settleanswers each call once. If the session refuses an answer as a bad request, it is not sent again, and the record says nothing was done. - When a session ends, its open requests are withdrawn and nothing new is asked: a call in a finished session can never run.
- The VariantGate webhook only wakes your code:
settlereads the request from the API before it answers, and never acts on the webhook’s body. - A webhook that fails every retry is dropped. Run
sweepevery few minutes for lost VariantGate webhooks, andcatchUpfor your open sessions in case a Managed Agents one was lost. Keep the two maps in a database table with a unique key on the event id when more than one process serves them. - The request stays open for a day here; pick what suits the action. A request that expires is answered as a denial, so the session does not wait forever.
In Python
pip install anthropic
pip install https://variantgate.com/sdk/variantgate-latest.tar.gzThe same stream loop with the Python client. Its calls block, so each paused call is answered in a thread, and the stream is read in a thread of its own, so a call that cannot be answered ends the run with its error. The agent from step 2 is the same in Python: pass the same fields to client.beta.agents.create.
import contextlib
import json
import queue
import re
import threading
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, Literal
import anthropic
from anthropic.types.beta.sessions import BetaManagedAgentsUserToolConfirmationEventParams
from variantgate import (
ApprovalClient,
ChangedApprovalError,
NotApprovedError,
VariantGateError,
is_allowed,
is_changed,
)
client = anthropic.Anthropic()
approvals = ApprovalClient("support-agent") # reads VARIANTGATE_KEY
SECRET_FILE = re.compile( # files whose contents must not land in a request
r"(^|/)\.(env|npmrc|netrc|pgpass|git-credentials)|id_(rsa|ecdsa|ed25519|dsa)"
r"|kubeconfig|secret|credential|token|\.(pem|key|p12|pfx)$", re.IGNORECASE)
approved_calls: dict[str, tuple[str, str]] = {} # sevt_ id -> (request id, session id)
waiting: dict[str, set[str]] = {} # session -> requests still waiting
ended: set[str] = set() # sessions we stopped answering
lock = threading.Lock() # guards waiting and ended across threads
def preview(text: str) -> str:
"""Text cut short for the inbox, saying so when it was."""
return f"{text[:2000]} [cut: {len(text)} characters in all]" if len(text) > 2000 else text
def describe(use: Any, session_id: str) -> dict[str, Any]:
"""What a person reads for one paused tool call."""
args = use.input
where = {"session": session_id, "event": use.id}
shop = use.type == "agent.mcp_tool_use" and use.mcp_server_name == "shop"
if shop and use.name == "refund_order":
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"], **where}}
if use.type == "agent.tool_use" and use.name == "bash":
command = str(args["command"])
if any(SECRET_FILE.search(word) for word in re.split(r"[\s'\"<>|;&=:()`]+", command)):
# it may carry the secret itself: show none of it
return {"action": "shell.run",
"summary": "Run a command that touches a secret file (not shown)",
"details": {"secret_file": True, **where}}
return {"action": "shell.run", "summary": f"Run: {command[:500]}",
"details": {"command": preview(command), **where}}
tool = f"{use.mcp_server_name}.{use.name}" if use.type == "agent.mcp_tool_use" else use.name
path = str(args.get("file_path") or args.get("path") or args.get("filename") or "")
details: dict[str, Any] = {"tool": tool, **where}
if not SECRET_FILE.search(path): # for those, only the path
details["input"] = preview(json.dumps(args, ensure_ascii=False))
return {"action": f"tool.{tool}", "summary": f"{tool} {path}" if path else f"Use {tool}",
"details": details}
def reply(session_id: str, use: Any, result: Literal["allow", "deny"],
reason: str | None = None) -> None:
event: BetaManagedAgentsUserToolConfirmationEventParams = {
"type": "user.tool_confirmation", "tool_use_id": use.id, "result": result}
if reason:
event["deny_message"] = reason
if session_id in ended:
not_done(use.id, "not done: no longer answering this session")
return
try:
client.beta.sessions.events.send(session_id, events=[event])
except anthropic.APIError:
if delivered(session_id, use.id): # a send that timed out may still have arrived
return
not_done(use.id, "not done: the answer did not reach the session")
raise
def delivered(session_id: str, use_id: str) -> bool:
"""Whether the session already has an answer for this call."""
with contextlib.suppress(anthropic.APIError):
for event in client.beta.sessions.events.list(session_id):
if event.type == "user.tool_confirmation" and event.tool_use_id == use_id:
return True
return False
def not_done(use_id: str, note: str) -> None:
"""An approved call that will never run: say so on its record."""
approved = approved_calls.pop(use_id, None)
if approved:
with contextlib.suppress(VariantGateError):
approvals.report_outcome(approved[0], "failed", note)
def answer(session_id: str, use: Any) -> None:
"""Asks a person about one paused call and answers the session."""
request = None
try:
request = approvals.ask(**describe(use, session_id)) # returns at once
with lock:
if session_id in ended:
raise RuntimeError("no longer answering this session")
open_requests = waiting.setdefault(session_id, set())
open_requests.add(request["id"])
try:
decision = approvals.wait(request, timeout=15 * 60) # withdrawn if unanswered
finally:
open_requests.discard(request["id"])
except Exception as error: # no answer we can trust: take it back, say no
if request:
with contextlib.suppress(VariantGateError):
approvals.withdraw(request["id"])
reply(session_id, use, "deny", f"Not approved, no answer from approvals: {error}")
return
if not is_allowed(decision):
reply(session_id, use, "deny", str(NotApprovedError(decision)))
elif is_changed(decision): # a server-run tool can only be told yes or no
with contextlib.suppress(VariantGateError):
approvals.report_outcome(decision["id"], "failed", "not done: approved with changes")
reply(session_id, use, "deny", str(ChangedApprovalError(decision)))
else:
approved_calls[use.id] = (decision["id"], session_id)
reply(session_id, use, "allow")
def record(event: Any) -> None:
"""Puts how an approved call went on its record. Never fails the run."""
use_id = event.mcp_tool_use_id if event.type == "agent.mcp_tool_result" else event.tool_use_id
approved = approved_calls.pop(use_id, None)
if approved:
request_id = approved[0]
failed = bool(event.is_error)
text = next((b.text for b in event.content or [] if b.type == "text"), "the tool failed")
with contextlib.suppress(VariantGateError):
approvals.report_outcome(request_id, "failed" if failed else "succeeded",
text[:500] if failed else None)
def stop_answering(session_id: str, session_ended: bool) -> None:
"""Takes back what a session still waits on; if it ended, approved calls never ran."""
with lock:
ended.add(session_id)
open_requests = list(waiting.pop(session_id, ()))
for request_id in open_requests:
with contextlib.suppress(VariantGateError):
approvals.withdraw(request_id)
for use_id, (_, owner) in list(approved_calls.items()):
if session_ended and owner == session_id:
not_done(use_id, "not done: the session ended first")
def run(session_id: str, text: str) -> None:
"""Sends one message and answers every paused call until the agent is done."""
inbox: queue.Queue[Any] = queue.Queue() # events, an error, or None at the end
futures: list[Future[None]] = []
with client.beta.sessions.events.stream(session_id) as stream: # open first
def read() -> None: # reading blocks, so it gets a thread of its own
try:
for event in stream:
inbox.put(event)
except Exception as error:
inbox.put(error)
inbox.put(None) # the stream closed
def stop_on_failure(future: Future[None]) -> None:
if future.exception(): # a call left unanswered would wait forever
inbox.put(future.exception())
threading.Thread(target=read, daemon=True).start()
client.beta.sessions.events.send(session_id, events=[
{"type": "user.message", "content": [{"type": "text", "text": text}]}])
with ThreadPoolExecutor() as pool:
while (event := inbox.get()) is not None:
if isinstance(event, BaseException):
stop_answering(session_id, session_ended=False) # end the other waits
raise event
if event.type in ("agent.tool_use", "agent.mcp_tool_use") \
and event.evaluated_permission == "ask":
# several calls can wait at once
futures.append(pool.submit(answer, session_id, event))
futures[-1].add_done_callback(stop_on_failure)
elif event.type in ("agent.tool_result", "agent.mcp_tool_result"):
record(event)
elif event.type == "agent.message":
print("".join(b.text for b in event.content if b.type == "text"))
elif event.type == "session.status_terminated":
stop_answering(session_id, session_ended=True) # those can never run
break
elif event.type == "session.status_idle" \
and event.stop_reason.type != "requires_action":
break # end_turn, retries_exhausted or budget_reached
for future in futures:
future.result() # an answer that failed after the loop still says soCustom tools
A custom tool runs in your own code: the session sends agent.custom_tool_use and waits for your result. No permission policy applies, so ask inside the handler, the way the client guide shows with guard. There a person may lower a refund and the tool runs for the lower amount, since your code does the refunding. That makes a custom tool the better home for money that moves: the MCP route can only allow or deny.
When the console is enough
If the person running the session is the one who should decide, answer the confirmation in your own interface and leave VariantGate out. VariantGate earns its place when sessions run with nobody watching, when someone else must decide, when rules should settle the routine calls, or when you need a record of who approved what. The Claude Agent SDK page does the same for agents you host yourself, and the playground lets you try both sides first.