ACP for the Claude Agent SDK and Anthropic SDK: install guide
This is the install guide for per-user auth, per-call policy and audit on tool loops built with Anthropic’s SDKs. If you came for the Claude Agent SDK’s TypeScript hook interfaces, Anthropic documents them in its TypeScript SDK reference, and our walkthrough is the Claude Agent SDK hooks reference.
The Anthropic SDK and Claude Agent SDK let you build tool-use loops around Claude. Out of the box, a production deployment attributes every tool call to one backend API key. There is no per-user policy and no per-user audit.
@agenticcontrolplane/governance-anthropic closes that gap. One call wraps your handler map; before each tool handler runs, ACP decides allow / deny / redact. It uses the same /govern/tool-use endpoint and the same workspace policies as Claude Code.
Starter · 5-minute install.
npm install @agenticcontrolplane/governance-anthropic @anthropic-ai/sdk, wrap your handler map withgovernHandlers, bind the end user’s JWT per request viawithContext. See the governance model for the shared concepts across every framework, or the frameworks index for other options.
Disambiguation
Naming, because Anthropic’s lineup has shifted under this page: Claude Code is the terminal application with its own hook integration (see Claude Code integration). The Claude Agent SDK (@anthropic-ai/claude-agent-sdk, formerly the Claude Code SDK) is Claude Code’s engine as a library, with its own native PreToolUse hooks and canUseTool gate. This page covers the third thing: hand-rolled tool-use loops on the raw Anthropic SDK (@anthropic-ai/sdk), where you own the loop and governHandlers wraps your handlers. If you’re on the Claude Agent SDK, it runs shell command hooks from Claude Code settings files whenever the matching settingSources entry is enabled, which it is for default query() options (Anthropic: how hooks work), so the same ACP hook script as Claude Code applies there (untested under the SDK; if you set a custom env, pass {...process.env} so the hook keeps HOME and its credentials).
Install
npm install @agenticcontrolplane/governance-anthropic @anthropic-ai/sdk
Minimal governed tool-use loop
import Anthropic from "@anthropic-ai/sdk";
import express from "express";
import { governHandlers, withContext } from "@agenticcontrolplane/governance-anthropic";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const app = express();
app.use(express.json());
// Your tools: plain async handlers, your code, your credentials.
const handlers = governHandlers({
web_search: async ({ query }: { query: string }) => doSearch(query),
send_email: async ({ to, subject, body }: { to: string; subject: string; body: string }) =>
sendMail(to, subject, body),
});
const tools: Anthropic.Tool[] = [
{ name: "web_search", description: "Search the web",
input_schema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] } },
{ name: "send_email", description: "Send 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 token = req.header("authorization")!.slice("Bearer ".length);
await withContext({ userToken: token }, 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: 1024, tools, messages,
});
messages.push({ role: "assistant", content: msg.content });
if (msg.stop_reason !== "tool_use") {
const text = msg.content.filter((b): b is Anthropic.TextBlock => b.type === "text").map(b => b.text).join("\n");
return res.json({ result: text });
}
const toolResults: Anthropic.ToolResultBlockParam[] = [];
for (const block of msg.content) {
if (block.type !== "tool_use") continue;
const output = await handlers[block.name](block.input);
toolResults.push({
type: "tool_result",
tool_use_id: block.id,
content: typeof output === "string" ? output : JSON.stringify(output),
});
}
messages.push({ role: "user", content: toolResults });
}
res.status(500).json({ error: "max iterations" });
});
});
What governHandlers does
Takes Record<string, AsyncHandler>. Returns a handler map of the same shape where each function is wrapped to:
- POST to ACP
/govern/tool-usewith the tool name + input + user JWT. - If ACP denies, return
"tool_error: <reason>". Claude sees the denial and adapts. - If ACP allows, run your handler.
- POST the output to
/govern/tool-outputfor audit + PII scan. - If ACP redacts, return the redacted version; if ACP blocks, return
"tool_error".
The map shape is preserved, so the rest of your loop is unchanged.
Fail-open
This package always fails open, and it has no fail-closed switch. If the gateway is unreachable, times out (5 seconds by default, set with configure({ timeoutMs })), or answers without a decision, the tool runs and the reason reads fail-open (<cause>). “Answers without a decision” includes 5xx errors and 401/403 from a revoked key, so a revoked key stops governance without stopping your agent. A 4xx that carries a deny is still enforced.
Each lapse is warned once and appended to ~/.acp/lapse.log. The Claude Code hook differs: it can be set to fail closed with echo closed > ~/.acp/failmode.
Configure your ACP workspace
- An IdP configured. ACP verifies the end user’s JWT against your IdP. Dashboard → Settings → Identity Provider.
- Tools listed. Names in your handler map must match tools enabled in your workspace. Dashboard → Policies → Tools.
- Policy per tier. Set allow/deny, rate limits and PII mode. Dashboard → Policies.
What shows up in the dashboard
Every tool call appears in cloud.agenticcontrolplane.com/activity with:
- Actor: the end user’s sub
- Tool name: the key in your handler map
- Decision: allow / deny / redact, with reason
- Session: groups tool calls from one request
- Findings: PII detected in input or output
Anthropic SDK tool calls sit alongside Claude Code, Cursor, CrewAI, and LangChain calls from the same user. One audit log across every agent surface.
Adding a new tool
Three spots to edit:
- Push a schema entry to
tools. Claude uses it to decide when to call the tool. - Add the handler inside the
governHandlers({...})call. - Match the key between them.
Governance is automatic because the whole map is wrapped.
Alternative: wrap one handler at a time
If you don’t want to wrap the whole map, use governed from the core package:
import { governed } from "@agenticcontrolplane/governance";
const handlers = {
web_search: governed("web_search", async ({ query }) => doSearch(query)),
send_email: governed("send_email", async (input) => sendMail(input)),
};
Same result, handler-by-handler.
Price and meter the model calls
governed is the interception plane: what your agent does. The proxy
plane covers what it spends. Both run against the same gateway, and init()
wires them together:
import { init } from "@agenticcontrolplane/governance";
init(); // call before you construct any model client
Model calls now land on the same trail as tool calls, carrying real cost,
tokens, and cache economics. Constructing clients explicitly instead? Pass the
options rather than calling init():
import { modelClientOptions } from "@agenticcontrolplane/governance";
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(modelClientOptions("anthropic"));
Shapes are "anthropic", "openai" (chat completions), and
"openai-responses". The last two are not interchangeable. /v1 serves
chat completions, /openai/v1 serves responses.
init() is all-or-nothing per provider: it sets the base URL and the key, or
it leaves that provider completely alone and tells you which one it skipped. If
OPENAI_BASE_URL already points at your own gateway, ACP won’t silently
reroute you.
Your coverage: interception ✓ (decorated tools) · proxy ✓ (model calls).
Limitations
- Only handlers wrapped by
governHandlersorgovernedare covered. Dispatching atool_useblock to a handler outside this pattern bypasses governance. - The two planes are wired separately. The decorator covers tool calls; the proxy covers model calls. Both ship, but each is its own edit. See Price and meter the model calls above. Decorating tools without repointing the model client gives you control with no cost data.
- Works with any tool-use loop. The package doesn’t impose a loop structure. It just wraps handlers. Use it with the raw Messages API, the Agent SDK, or your own custom runner.
- Version note. This guide documents the
0.2.xhook-only API, whichnpm install @agenticcontrolplane/governance-anthropicgets it. Upgrading from0.1.x(the earlier loop-wrapper API)? The package README has the migration note.
Frequently asked questions
Where are the Anthropic Agent SDK TypeScript hook interfaces documented?
In Anthropic’s TypeScript SDK reference, which defines HookCallback, the per-event input types such as PreToolUseHookInput, and the hook output type. The hooks guide lists every event and how options.hooks takes matchers. Our field-by-field walkthrough is the Claude Agent SDK hooks reference for TypeScript.
Which lifecycle hooks does the Claude Agent SDK have?
Both the Python and TypeScript SDKs fire PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest and Notification. The TypeScript SDK adds more, including SessionStart, SessionEnd and PostCompact (Anthropic’s hook table).
Do I need this package if I use the Claude Agent SDK?
Not always. The Claude Agent SDK runs its built-in tools itself, so you put the policy check in a PreToolUse hook, or let the SDK load the ACP shell hook from your Claude Code settings files (untested under the SDK; if you set a custom env, pass {...process.env} so the hook keeps HOME and its credentials). This package is for loops you own on the raw Anthropic SDK, where you dispatch each tool_use block to your own handler. How the two layers fit is covered in Claude Agent SDK security architecture.
Related
- Claude Agent SDK permissions, hooks and audit reference: the deep reference for this integration
- Governed agent recipes: four runnable Python agents built on this pattern
@agenticcontrolplane/governance-anthropicon npm@agenticcontrolplane/governance(core SDK)- Claude Code integration: same protocol, terminal-side hook
- CrewAI integration
- LangChain / LangGraph integration
- Tool policies and scopes