Claude (Anthropic) Agent SDK: permissions, hooks, audit
Run agents? ACP lets you see, control, and price every tool call they make — allow/ask/deny policy, per-session cost, and a full audit log for Claude Code, Cursor, Codex, and OpenClaw, in one command:
curl -sf https://agenticcontrolplane.com/install.sh | bash
irm https://agenticcontrolplane.com/install.ps1 | iex
Getting started → · see your first governed call → · free up to 5 agents
The Claude Agent SDK, which many people search as the Anthropic Agent SDK, gives you two control points of its own. One is a canUseTool permission callback. The other is lifecycle hooks: PreToolUse before a call, and PostToolUse, PostToolUseFailure and PostToolBatch after it (Anthropic hooks guide; our hooks reference). It also has a per-query cost cap, maxBudgetUsd, which stops the query on a client-side cost estimate. Session transcripts are saved to local disk by default (persistSession defaults to true) (TypeScript reference).
What it doesn’t give you is the user’s identity on each call, policy shared across machines, or one central audit log. The raw Anthropic SDK (@anthropic-ai/sdk) has no hooks at all.
Updated 2026-11-07. Earlier versions of this page said the SDK had no post-call hook. That was wrong.
PostToolUse,PostToolUseFailureandPostToolBatchare in Anthropic’s hooks guide.
Say you’re running a tool-use loop on Anthropic, with the Messages API, the Agent SDK or your own runner. It works. Then your CISO asks what is logging this, and on whose authority.
This is the TypeScript reference for answering that with @agenticcontrolplane/governance-anthropic: per-user identity, a policy check on each call, and an audit record.
The functions you use
| Symbol | What it does | When to use |
|---|---|---|
configure({ baseUrl }) |
Points the package at your ACP gateway. Once per process. | At startup |
governHandlers({ ... }) |
Wraps a map of tool handlers. Returns a map of the same shape. | The default, one-line install |
governed(name, handler) |
Wraps a single handler. | When you want per-handler control |
withContext({ userToken, ... }, fn) |
Binds the end user’s identity to every governance call inside fn, using Node’s AsyncLocalStorage. |
Around your request handler |
governed, withContext and configure come from @agenticcontrolplane/governance, the framework-agnostic core, and are re-exported. governHandlers is the one this package adds. You need one import.
A governed loop
import Anthropic from "@anthropic-ai/sdk";
import {
configure,
governHandlers,
withContext,
} from "@agenticcontrolplane/governance-anthropic";
configure({ baseUrl: "https://api.agenticcontrolplane.com" });
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const handlers = governHandlers({
lookup_record: async ({ id }: { id: string }) => {
return await db.records.findOne({ id });
},
send_email: async ({ to, subject, body }: { to: string; subject: string; body: string }) => {
return await mailer.send({ to, subject, body });
},
});
const tools: Anthropic.Tool[] = [
{ name: "lookup_record", description: "Look up a record by ID.",
input_schema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } },
{ name: "send_email", description: "Send an email.",
input_schema: { type: "object",
properties: { to: { type: "string" }, subject: { type: "string" }, body: { type: "string" } },
required: ["to", "subject", "body"] } },
];
app.post("/run", async (req, res) => {
const userToken = req.header("authorization")!.replace(/^Bearer /, "").trim();
await withContext(
{ userToken, agentName: "research-agent", agentTier: "interactive" },
async () => {
const messages: Anthropic.MessageParam[] = [{ role: "user", content: req.body.prompt }];
for (let i = 0; i < 10; i++) {
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-6", max_tokens: 4096, tools, messages,
});
messages.push({ role: "assistant", content: msg.content });
if (msg.stop_reason !== "tool_use") {
return res.json({ result: msg.content });
}
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of msg.content) {
if (block.type !== "tool_use") continue;
const out = await handlers[block.name](block.input);
results.push({
type: "tool_result",
tool_use_id: block.id,
content: typeof out === "string" ? out : JSON.stringify(out),
});
}
messages.push({ role: "user", content: results });
}
},
);
});
Three additions to the loop you already had: configure, governHandlers and withContext.
What governHandlers does
It takes a map of { toolName: AsyncHandler } and returns a map of the same shape. Each handler now does this:
- Posts the tool name, the input and the user token from
withContextto ACP’s/govern/tool-use. - If ACP answers deny or ask, returns the string
"tool_error: <reason>". Claude reads that as the tool result and adjusts. An ask is not held for a person here. The model gets the error and the loop moves on. - If ACP allows, runs your handler.
- Posts the output to
/govern/tool-outputfor audit and scanning. - If ACP returns a redacted output, hands that back instead (see
onRedactbelow). - If ACP blocks the output, for example because it contained a leaked secret, returns
"tool_error: <reason>".
Your dispatch line, handlers[block.name](block.input), doesn’t change.
governed: one handler at a time
Use it when some tools shouldn’t be governed, or when one needs a different onRedact:
import { governed } from "@agenticcontrolplane/governance-anthropic";
const handlers = {
// governed
send_email: governed("send_email", async ({ to, subject, body }) => sendMail(to, subject, body)),
// not governed (a fully internal calculation)
add: async ({ a, b }: { a: number; b: number }) => a + b,
// governed, with redaction overridden
search_logs: governed(
"search_logs",
async ({ query }) => searchLogs(query),
{ onRedact: "keep" }, // the model sees the raw output even if ACP redacts
),
};
onRedact defaults to "replace". When ACP returns a redacted version, the model sees that one. Set "keep" only for a tool whose raw output the model really needs. Leave "replace" on anything that can return personal data or secrets.
withContext: who is acting
withContext runs your function with a context object bound to the async scope. Every governed handler inside it uses that context.
{
userToken: string; // required: JWT, Firebase ID token, or gsk_ key
sessionId?: string; // auto-generated UUID if omitted
agentTier?: "interactive" | "subagent" | "background" | "api";
agentName?: string; // shown in the dashboard
}
userToken is the end user’s identity. ACP checks the token against your identity provider (or the workspace key issuer) on each governed call. If the token doesn’t validate, the gateway answers without a decision, and the package treats that like an outage (see below).
agentTier tells ACP what kind of run this is, and your rules can differ by tier:
interactive: a person is watching.subagent: another agent started it.background: nobody is in the loop.api: a programmatic call from your own backend.
So the same tool can be allowed for interactive, ask for subagent and deny for background, if you write the rules that way. Set the tier to what is actually true.
When ACP can’t be reached
The package fails open. If the gateway times out (5 seconds by default), is unreachable, or answers without a decision, the tool call runs. This is deliberate: a policy service shouldn’t be the one thing that stops your agent.
It is not silent. The first lapse of each kind prints an [ACP] UNGOVERNED warning to the console, and every ungoverned call adds a line to ~/.acp/lapse.log. The same file holds lapses from the Claude Code hook, so you can see all ungoverned calls on a machine in one place. A 4xx that carries an allow-or-deny verdict, such as a rate-limit deny, is treated as a real answer and enforced.
There is no fail-closed switch in the package. If you need one, check the reason string on the result yourself. Calls that ran without a decision carry fail-open (<cause>).
Where the audit lands
Governed calls show up on the Activity page with:
- Actor. The verified user from
userToken. - Tool name. The key from your
governHandlersmap. - Decision. Allow, deny, redact or block, and the reason.
- Session. All calls from one
withContextscope. - Findings. Personal-data or secret patterns found in the input or output.
- Tier. The
agentTieryou set.
These rows sit next to the ones from Claude Code, Cursor, Codex CLI and the other harnesses, so one user has one audit log across agents.
Sub-agents
Anthropic’s loop dispatches by tool name through your handler map. The Claude Agent SDK also has sub-agents, started by its built-in Agent tool (Anthropic’s tool list). A sub-agent can have its own tools and its own dispatch.
Only handlers that go through governHandlers or governed are governed. If a sub-agent’s tools are wired straight to the SDK, those calls skip ACP. Wrap the sub-agent’s tools the same way you wrap the parent’s.
governHandlers or canUseTool
canUseTool is the Agent SDK’s permission callback. governHandlers wraps your handlers instead. They differ like this:
governHandlers (ACP) |
canUseTool (Anthropic SDK) |
|
|---|---|---|
| Where it lives | Wraps your handler map | Inside the SDK’s tool dispatch |
| Coverage | Any tool-use loop: Messages API, Agent SDK, your own | Claude Agent SDK only |
| Policy | Workspace rules on the ACP gateway | You write the callback |
| Audit | Identity-attributed, sent to the ACP dashboard | Local session transcripts by default, no central log |
| Output redaction | postToolOutput handles it |
You write it in a PostToolUse hook (updatedToolOutput) |
| User identity | withContext binds the user token |
You pass it through closures yourself |
You can use both. canUseTool gates a call after the model asks for it and before it runs. governHandlers adds the policy check and the audit record at dispatch. If you use both, decide which one owns which rule. A cheap deny-pattern check fits canUseTool. The identity-based policy and the audit fit governHandlers.
Pick governHandlers when you run more than one framework, want one audit trail across them, or want policy kept on a server instead of in a callback. Pick canUseTool alone when you only use the Claude Agent SDK and are happy to build the audit and redaction yourself.
Common mistakes
Forgetting withContext. Without it the package has no user token. Each call runs ungoverned, prints a one-time [ACP] UNGOVERNED warning with cause not-configured, and writes to the lapse log. The tool still runs. Wrap your request handler.
Calling a handler outside the wrapped map. If any code path calls lookup_record(input) directly, that call skips ACP. Send every call through handlers[name](input).
Binding a workspace key as the user. A gsk_ workspace key works for testing, but it isn’t a person. For real attribution, bind the end user’s token (an Auth0 sub, an Okta user ID, a Firebase ID token). The audit row is only as good as the token you bind.
Setting the wrong tier. If a background agent runs as interactive, ACP applies the rules for a watched session, and a call you meant to block can get through. Match the tier to reality.
Assuming canUseTool and governHandlers overlap. They don’t. Both can fire on the same call.
Frequently asked questions
How do I add auditable logging to an Anthropic Agent SDK loop in TypeScript?
Wrap your tool handlers with governHandlers(handlers), once, when you build the loop. Every handler call is then checked against workspace policy and logged on the ACP gateway: the verified user, the tool name, the allow or deny decision and the reason. The record is written by a separate service, not by the process that ran the tool.
Does the Anthropic Agent SDK have lifecycle hooks?
Yes. The Claude Agent SDK takes callback hooks in options.hooks. PreToolUse runs before a call (allow, deny, ask or rewrite the input). After a call you get PostToolUse (add context or replace the tool’s output), PostToolUseFailure and, in TypeScript, PostToolBatch. There is also a canUseTool permission callback (Anthropic hooks guide; field by field in our Claude Agent SDK hooks reference). Updated 2026-11-07: an earlier version of this answer said the SDK had no post-call hook, which was wrong. The raw Anthropic SDK (@anthropic-ai/sdk) has no hooks because you own the loop. governHandlers wraps each handler to get the pre-call decision and the post-call record.
How do Claude Code's PreToolUse and PostToolUse hooks map to the Agent SDK?
One to one. The Agent SDK fires the same PreToolUse and PostToolUse events, and its callbacks return the same JSON format as Claude Code shell hooks. It also runs shell hooks from settings files when the matching settingSources entry is on (Anthropic). In a raw Anthropic SDK loop there is no hook event, so the wrapped handler does both jobs.
What do the governance functions look like?
Three you call in your own code: governHandlers(handlers) wraps a whole handler map, governed(name, handler) wraps one, and withContext({ userToken, … }, fn) binds the end user’s identity for everything inside fn. A fourth, configure({ baseUrl }), points the package at the gateway. All TypeScript, and your tool definitions don’t change.
What counts as evidence for an agent's actions?
Records written when the action happens, by something the agent can’t edit: who the user and agent were, the tool, the policy decision and why. That differs from a log the agent’s own process writes about itself, which the agent could change.
What are the Anthropic Agent SDK lifecycle hooks?
The Claude Agent SDK (the package people search as the Anthropic Agent SDK) fires PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest and Notification in both Python and TypeScript. TypeScript adds more, including SessionStart, SessionEnd, PostCompact and PermissionDenied. The full table, with what each can return, is in Anthropic’s hooks guide.
Does docs.anthropic.com publish Anthropic Agent SDK benchmarks?
Not that we could find. Anthropic’s Agent SDK docs (now at code.claude.com/docs/en/agent-sdk) cover hooks, permissions, sessions and the TypeScript and Python references, but no benchmark page for the SDK itself. Published benchmark numbers are for the models, in Anthropic’s announcements and system cards. Any SDK-versus-framework latency figures come from third parties.
Where this fits
governHandlers is the integration we ship for this SDK. The starter at acp-governance-sdks/examples/starters/claude-agent-sdk is a runnable example. Clone it and swap in your own tool.
Governing the Anthropic Agent SDK in 3 minutes → · Anthropic Agent SDK governance scorecard → · Integration install guide → · Get started →