HITLGuides

Claude Agent SDK

Gate Claude Agent SDK tool calls with a PreToolUse hook, and verify your own MCP tools right before they run.

Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.

Install from the registry (to run the repo's own examples, clone it as in the README):

pip install "viewport-hitl[claude-agent-sdk]"    # claude-agent-sdk >= 0.2.189
npm install @viewportai/hitl @anthropic-ai/claude-agent-sdk    # @anthropic-ai/claude-agent-sdk >= 0.3.300

Verified against claude-agent-sdk 0.2.189 (Python) and @anthropic-ai/claude-agent-sdk 0.3.332 (TypeScript). The example calls the hook callbacks and the tool handler exactly as the SDK would, so it needs no model, no key and no Claude Code CLI.

Wire it in

Two pieces:

  • hooks(gate, only=...) returns PreToolUse (plus PostToolUse and PostToolUseFailure) hooks. PreToolUse is the only layer that sees every tool call, so it is where the gate decides. only (a glob or a list) gates just those tools and leaves built-ins such as Read and Bash to Claude's own permissions; without it every tool is gated and the policy must cover the built-ins.
  • tools(gate, [...], server=...) wraps your SDK MCP tool handlers, so right before a handler runs, its arguments must be the ones the hook approved, and the approval is consumed once.
examples/python/claude-agent-sdk/main.py (excerpt)
gate = hitl.Gate(
    {
        "approvers": {"finance": {"channel": "desk", "members": ["desk:dana"]}},
        "rules": {
            "refunds": {"allow": "mcp__payments__issue_refund"},
            "large-refunds": {
                "ask": "mcp__payments__issue_refund",
                "when": {"args": {"amount": {"gt": 50}}},
                "approver": "finance",
                "reason": "Refunds over $50 need finance",
            },
        },
    },
    channels=[desk],
    clock=FakeClock("2026-11-25T10:00:00Z"),
)


@tool("issue_refund", "Refund an order", {"order_id": str, "amount": float})
async def issue_refund(args: dict[str, Any]) -> dict[str, Any]:
    refunded.append(args)
    return {"content": [{"type": "text", "text": f"Refunded ${args['amount']:g} on {args['order_id']}"}]}


gated_tools = hitl.claude_agent_sdk.tools(gate, [issue_refund], server="payments")  # verify, consume, then run
payments = create_sdk_mcp_server(name="payments", tools=gated_tools)

options = ClaudeAgentOptions(
    mcp_servers={"payments": payments},
    hooks=hitl.claude_agent_sdk.hooks(gate, only="mcp__payments__*"),  # built-ins stay under Claude's permissions
)
# pass `options` to query(prompt=..., options=options) or ClaudeSDKClient(options) as usual
examples/ts/claude-agent-sdk/main.ts (excerpt)
const gate = new Gate(
  {
    approvers: { finance: { channel: "desk", members: ["desk:dana"] } },
    rules: {
      refunds: { allow: "mcp__payments__issue_refund" },
      "large-refunds": {
        ask: "mcp__payments__issue_refund",
        when: { args: { amount: { gt: 50 } } },
        approver: "finance",
        reason: "Refunds over $50 need finance",
      },
    },
  },
  { channels: [desk], clock: new FakeClock("2026-11-25T10:00:00Z") },
);

const issueRefund = tool(
  "issue_refund",
  "Refund an order",
  { order_id: z.string(), amount: z.number() },
  async ({ order_id, amount }) => {
    refunded.push({ order_id, amount });
    return { content: [{ type: "text", text: `Refunded $${amount} on ${order_id}` }] };
  },
);
const gatedTools = tools(gate, [issueRefund], { server: "payments" }); // verify and consume right before running
const payments = createSdkMcpServer({ name: "payments", tools: gatedTools });

const options: Options = {
  mcpServers: { payments },
  hooks: hooks(gate, { only: "mcp__payments__*" }), // Read, Bash and friends stay under Claude's own permissions
};
// pass `options` to query({ prompt, options }) as usual

Policies name SDK MCP tools as Claude sees them: mcp__<server>__<tool>.

What the hook answers

  • allow: permissionDecision: "allow" with updatedInput set to the frozen (or edited) arguments.
  • deny: permissionDecision: "deny" with the reason, which Claude sees.
  • ask: in wait mode (the default) the hook waits for the decision, then answers allow or deny.
examples/python/claude-agent-sdk/main.py (excerpt)
data = call("toolu_01", {"order_id": "A-1002", "amount": 900})
decision = asyncio.create_task(pre_tool_use(data, "toolu_01", {"signal": None}))  # the hook waits

await until(lambda: len(desk.requests) == 1)  # finance got the request
request = desk.requests[0]
await gate.respond(request.approval_id, hitl.approve(by="desk:dana", digest=request.digest))

out = (await decision)["hookSpecificOutput"]
print(f"hook decision: {out['permissionDecision']}, input {json.dumps(out['updatedInput'])}")
# hook decision: allow, input {"amount": 900, "order_id": "A-1002"}
examples/ts/claude-agent-sdk/main.ts (excerpt)
const input = call("toolu_01", { order_id: "A-1002", amount: 900 });
const decision = preToolUse(input, input.tool_use_id, { signal: AbortSignal.timeout(60_000) }); // the hook waits

await until(() => requests.length === 1); // finance got the request
await gate.respond(requests[0]?.approval_id as string, approve({ by: "desk:dana", digest: requests[0]?.digest }));

const out = ((await decision) as PreToolUseOutput).hookSpecificOutput;
console.log(`hook decision: ${out?.permissionDecision}, input ${JSON.stringify(out?.updatedInput)}`);
// hook decision: allow, input {"amount":900,"order_id":"A-1002"}

The execution-time check

The SDK then calls your MCP handler with updatedInput. The wrapper accepts exactly the approved call and refuses anything else, so arguments changed between the hook and the handler never run:

examples/python/claude-agent-sdk/main.py (excerpt)
# The SDK runs the MCP tool with updatedInput; the wrapper checks it is the approved call and consumes the approval.
result = await handler(out["updatedInput"])
print(f"tool ran: {result['content'][0]['text']}")  # tool ran: Refunded $900 on A-1002

# Args changed between the hook and the handler are refused, and the refund never runs.
swapped = await handler({"order_id": "A-1002", "amount": 9000})
print(f"swapped args: {swapped['content'][0]['text']}")
# swapped args: Not approved: the call differs from what was approved
examples/ts/claude-agent-sdk/main.ts (excerpt)
// The SDK runs the MCP tool with updatedInput; the wrapper checks it is the approved call and consumes the approval.
const result = await handler(out?.updatedInput as { order_id: string; amount: number }, {});
console.log(`tool ran: ${(result.content[0] as { text: string }).text}`); // tool ran: Refunded $900 on A-1002

// Args changed between the hook and the handler are refused, and the refund never runs.
const swapped = await handler({ order_id: "A-1002", amount: 9000 }, {});
console.log(`swapped args: ${(swapped.content[0] as { text: string }).text}`);
// swapped args: Not approved: the call differs from what was approved

Hook order. Register the gate's hooks last among your PreToolUse hooks. A hook that runs after the gate and returns its own updatedInput changes what a built-in tool runs (wrapped MCP tools still refuse it: their ticket is bound to the approved arguments). The gate cannot stop that, but it detects it: PostToolUse sees the arguments that ran, and when their digest differs from the approved one the gate reports hitl.args_mismatch to onError / on_error and records the execution as ok: false with error_type: "hitl.args_mismatch".

Details that matter

  • The hooks set on_failure="block" / onFailure: "block": by default the SDK lets a tool run when its hook throws. The gate's hook fails closed.
  • The hook timeout (timeout= in seconds) defaults to the longest approval timeout your policy can produce plus 30 seconds, so a waiting hook outlives every approval it waits for. The SDK's own default is 600 seconds. We have not verified an upper cap or what the SDK does when a hook callback times out, so keep approval timeouts within what your runtime allows, and use mode: "suspend" for approvals that take long. The default is recomputed per call from the tenant's current policy, and a waiting hook answers deny (hitl.hook_timeout) 10 seconds before its registered timeout, so the decision is always the gate's, never the SDK's timeout.
  • mode="suspend" returns defer: the run ends with stop_reason: "tool_deferred" and resumer(...) resumes the session once the approval is decided. Claude honors defer only in non-interactive runs with one tool call in the turn; with several calls in flight the hook waits instead, so it never fails open.
  • Built-in tools have no handler to wrap: for them the hook consumes the approval and PostToolUse settles limits and the executed receipt.
  • can_use_tool(gate, session=...) / canUseTool(gate, { session }) is the alternative for apps that use Claude's own permission prompt flow. It waits in process. Calls approved by allow rules or the permission mode never reach it, which is why the hook is the default. It never hands Claude a permission rule: session grants ("always allow for this session") live only in the gate. The SDK gives it no session id, so pass the session your host started; without session, a "remember for this session" answer is not stored and the next call is asked again. hooks() sees the session id and needs nothing extra.

On this page