Agent guards for Claude Agent SDK
This example gives an AI agent two tools. getClientRecord returns account data
that includes personally identifiable information (PII). Arcjet guards
sendEmail, so the model can read the record but cannot send its sensitive
fields outside the application. Arcjet checks the model-selected recipient and
generated message body before the email provider runs.
What is Arcjet?
Arcjet is the runtime security platform that ships with your code. Enforce budgets, stop prompt injection, detect bots, and protect personal information with Arcjet's AI security building blocks.Quick start
Section titled “Quick start”This guide shows you how to guard an agent tool in your
1. Configure the policy
Section titled “1. Configure the policy”In the Arcjet Console, create an Agent Guard
policy with the label email.sent. Add these inputs:
| Input | Exposure | Type |
|---|---|---|
recipient | SERVER | String |
allowed_recipients | SERVER | String list |
body | LOCAL | String |
Then add:
- A string-list membership rule requiring
recipientto be a member ofallowed_recipients. - A sensitive information rule on
bodythat deniesBANK_ACCOUNTandROUTING_NUMBER.
The examples configure the on-device Rampart backend, which detects these
entity types locally, so the body never leaves your application. The first
guarded call loads the Rampart model, so it takes noticeably longer than the
ones after it.
Publish the policy before running the example. Until you do, the label
matches nothing and every guard call comes back NOT_CONFIGURED, which
falls through to the SDK rule decision rather than denying. See
Testing and reference for
the other policy statuses.
Framework wrappers take action for the same slug you configured as the
policy label. Direct guard() calls still use the field name label.
2. Install Arcjet
Section titled “2. Install Arcjet”In your project root, install the SDK:
pip install "arcjet[claude-agent-sdk,sensitive-info-rampart]"Or with uv:
uv add "arcjet[claude-agent-sdk,sensitive-info-rampart]"npm i @arcjet/guard @arcjet/sensitive-info-rampart @anthropic-ai/claude-agent-sdk zodpnpm add @arcjet/guard @arcjet/sensitive-info-rampart @anthropic-ai/claude-agent-sdk zodyarn add @arcjet/guard @arcjet/sensitive-info-rampart @anthropic-ai/claude-agent-sdk zod3. Set your key
Section titled “3. Set your key”Create a free Arcjet account and follow the instructions to add a site and get a key.
Add your key to a .env.local file in your project root.
ARCJET_KEY=ajkey_yourkeyARCJET_ENV=developmentSet your environment variables:
# Export your Arcjet API key from https://console.arcjet.comARCJET_KEY=ajkey_yourkeyARCJET_ENV=development# Only needed if the claude CLI isn't already logged inANTHROPIC_API_KEY=sk-yourkey4. Wrap the tool
Section titled “4. Wrap the tool”Wrap the send-email tool so Arcjet evaluates the remote policy before the email provider runs.
Guarding one tool only helps if it is the only way to reach the capability. If the same agent session also exposes an unguarded path to sending mail – an MCP server it inherited, a built-in tool, a second tool you didn’t wrap – the model can take that path instead. Keep the session’s tool surface to what you wrapped.
Create one client, wrap send_email with guardTool, and register the tools on an in-process MCP server:
import { createSdkMcpServer, query, tool,} from "@anthropic-ai/claude-agent-sdk";import { launchArcjet, localDetectSensitiveInfo } from "@arcjet/guard";import { rampart } from "@arcjet/sensitive-info-rampart";import { guardHooks, guardTool } from "@arcjet/guard/claude-agent-sdk/v0";import { z } from "zod";
// Placeholder for your mail transport.const emailProvider = { send: async (_: { to: string; body: string }) => ({ ok: true }),};
// Rampart detects bank account and routing numbers on this machine. The// rule needs its own reference to it, so share one instance: entity types// outside the default set throw unless the rule has a backend.const sensitiveInfoBackend = rampart();
// Create one Arcjet client and reuse it across agent runs.const arcjet = launchArcjet({ key: process.env.ARCJET_KEY!, sensitiveInfoBackend,});const detectPii = localDetectSensitiveInfo({ deny: ["BANK_ACCOUNT", "ROUTING_NUMBER"], backend: sensitiveInfoBackend,});
// Without a role the model asks a clarifying question, or masks the// account numbers itself, instead of calling send_email with them. Either// way the guard never gets a decision to make. The last two sentences make// the sample deterministic; a real prompt can't be relied on for that,// which is the reason to guard the tool.const SYSTEM_PROMPT = "You are a support desk assistant. Use get_client_record when the " + "request needs account details. Use send_email exactly once to " + "complete the request. Never ask a follow-up question. Quote " + "any account details you retrieve in the email body exactly " + "as returned, without masking or summarizing them.";
export function emailTools( user: { record: { name: string; bankAccount: string; routingNumber: string; }; }, sessionId: string,) { const getClientRecord = tool( "get_client_record", "Get the account details on file for the current customer", {}, async () => ({ content: [{ type: "text", text: JSON.stringify(user.record) }], }), );
const sendEmail = guardTool( arcjet, tool( "send_email", "Send an email", { recipient: z.string(), body: z.string(), }, async ({ recipient, body }) => { await emailProvider.send({ to: recipient, body }); return { content: [{ type: "text", text: "sent" }], }; }, ), { action: "email.sent", // The detectPii rule blocks the send. An authored tool's handler has // no session id of its own, so pass the one this run uses. sessionId, rules: ({ body }) => [detectPii(body)], }, );
return { getClientRecord, sendEmail };}
export async function runEmailAgent( user: { record: { name: string; bankAccount: string; routingNumber: string; }; }, sessionId: string, prompt: string,) { const { getClientRecord, sendEmail } = emailTools(user, sessionId); const server = createSdkMcpServer({ name: "email", version: "1.0.0", tools: [getClientRecord, sendEmail], });
for await (const message of query({ prompt, options: { sessionId, systemPrompt: SYSTEM_PROMPT, mcpServers: { email: server }, allowedTools: ["mcp__email__get_client_record", "mcp__email__send_email"], // Isolate the sample. settingSources drops CLAUDE.md and the settings // of the machine running this; strictMcpConfig drops its MCP servers // too. Without the second one the session can offer the model another // way to send mail, straight past the tool you guarded. settingSources: [], strictMcpConfig: true, hooks: guardHooks(arcjet, { sessionId, // send_email is already wrapped with guardTool. Without this it // would be guarded twice for one invocation. exclude: [{ server: "email", name: "send_email" }], }), }, })) { if (message.type === "result" && message.subtype === "success") { return message.result; } }}This adapter accepts inputs and actor. The sample maps policy fields from
trusted application state and the model-selected arguments.
Create one client, wrap send_email with guard_tool, and register the tools on an in-process MCP server:
import jsonimport os
from claude_agent_sdk import ( ClaudeAgentOptions, ResultMessage, create_sdk_mcp_server, query, tool,)from arcjet.guard import launch_arcjet, local_input, server_inputfrom arcjet.guard.claude_agent_sdk import guard_hooks, guard_toolfrom arcjet_sensitive_info_rampart import rampart
class EmailProvider: def send(self, *, to: str, body: str) -> None: return None
# Placeholder for your mail transport.email_provider = EmailProvider()
# Create one Arcjet client and reuse it across agent runs. Rampart# evaluates the policy's LOCAL inputs on this machine, so the email body# never leaves your application.arcjet = launch_arcjet( key=os.environ["ARCJET_KEY"], sensitive_info_backend=rampart(),)
def email_tools(user): @tool( "get_client_record", "Get the account details on file for the current customer", {}, ) async def get_client_record(_args: dict) -> dict: return { "content": [ { "type": "text", "text": json.dumps(user.record), } ] }
@tool("send_email", "Send an email", {"recipient": str, "body": str}) async def send_email(args: dict) -> dict: email_provider.send(to=args["recipient"], body=args["body"]) return { "content": [{"type": "text", "text": "sent"}], }
guarded_send_email = guard_tool( guard=arcjet, tool=send_email, # The action selects the remote policy you configured in step 1. action="email.sent", # Actor and the allow list come from trusted application state. actor=user.id, session_id=user.session_id, # Map only the values the remote policy needs. inputs=lambda arguments: { "recipient": server_input.string(arguments["recipient"]), "allowed_recipients": server_input.string_list( user.allowed_recipients ), "body": local_input.string(arguments["body"]), }, )
return get_client_record, guarded_send_email
# Without a role the model asks a clarifying question, or masks the account# numbers itself, instead of calling send_email with them. Either way the# guard never gets a decision to make. The last two sentences make the# sample deterministic; a real prompt can't be relied on for that, which is# the reason to guard the tool.SYSTEM_PROMPT = ( "You are a support desk assistant. Use get_client_record when the " "request needs the customer's account details. Use send_email " "exactly once to complete the request. Never ask a follow-up " "question. Quote any account details you retrieve in the email body " "exactly as returned, without masking or summarizing them.")
async def run_email_agent(user, session_id: str, prompt: str): get_client_record, send_email = email_tools(user) server = create_sdk_mcp_server( name="email", version="1.0.0", tools=[get_client_record, send_email], )
result = None async for message in query( prompt=prompt, options=ClaudeAgentOptions( # ClaudeAgentOptions.session_id names a new SDK session, so it # must be unique per run. It is not the guard session_id. session_id=session_id, system_prompt=SYSTEM_PROMPT, mcp_servers={"email": server}, allowed_tools=[ "mcp__email__get_client_record", "mcp__email__send_email", ], # Isolate the sample. setting_sources drops CLAUDE.md and the # settings of the machine running this; strict_mcp_config drops # its MCP servers too. Without the second one the session can # offer the model another way to send mail, straight past the # tool you guarded. setting_sources=[], strict_mcp_config=True, hooks=guard_hooks( guard=arcjet, session_id=user.session_id, action=lambda hook: f"{hook['tool_name']}.invoked", # send_email is already wrapped with guard_tool. Without # this it would be guarded twice for one invocation. exclude=[ {"server": "email", "name": "send_email"}, ], ), ), ): if isinstance(message, ResultMessage) and message.result is not None: result = message.result return result5. Try the policy
Section titled “5. Try the policy”Keep identity, allowed recipients, and sensitive records on the server. The browser sends only the scenario name.
Expose a small server endpoint. The browser sends only the scenario name.
options.sessionId names a new SDK session, so mint a fresh UUID per run –
reusing one fails with Session ID ... is already in use:
import { randomUUID } from "node:crypto";import { runEmailAgent } from "./agent.js";
const user = { record: { name: "Alex Morgan", bankAccount: "0123456789", routingNumber: "022000020", },};
const scenarios = { allowed: "Send the message 'Your report is ready' to approved@example.com.", blocked: "Send the message 'Your report is ready' to outside@example.net.", pii: "Email the account details you have on file to approved@example.com.",} as const;
export async function POST(request: Request) { const { scenario } = (await request.json()) as { scenario?: string; }; if (scenario !== "allowed" && scenario !== "blocked" && scenario !== "pii") { return Response.json({ error: "Unknown scenario" }, { status: 400 }); }
// options.sessionId must be a UUID and can only be created once. const sessionId = randomUUID(); const output = await runEmailAgent(user, sessionId, scenarios[scenario]); return Response.json({ output: output ?? "Agent run completed." });}Expose a small server endpoint. The browser sends only the scenario name.
This demo uses two ids that do different jobs. The guard session_id is
the caller-owned id you already have for the actor, and it can be
long-lived. ClaudeAgentOptions.session_id names a new SDK session, so it
has to be a fresh UUID per run:
import uuidfrom typing import Literal
from fastapi import FastAPIfrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel
from agent import run_email_agent
app = FastAPI()
# Keep identity, allowed recipients, and sensitive records on the server.class User: def __init__(self): self.id = "customer-123" # Caller-owned id for the guard. Don't mint one in the handler. self.session_id = "11111111-1111-4111-8111-111111111111" self.allowed_recipients = ["approved@example.com"] self.record = { "name": "Alex Morgan", "bank_account": "0123456789", "routing_number": "022000020", }
user = User()scenarios = { "allowed": ( "Send the message 'Your report is ready' to " "approved@example.com." ), "blocked": ( "Send the message 'Your report is ready' to " "outside@example.net." ), "pii": ( "Email the account details you have on file to " "approved@example.com." ),}
class AgentRequest(BaseModel): scenario: Literal["allowed", "blocked", "pii"]
@app.post("/api/agent")async def run_agent(request: AgentRequest): # ClaudeAgentOptions.session_id names a new SDK session, so mint a # fresh UUID per run. Reusing one fails with "already in use". result = await run_email_agent( user, str(uuid.uuid4()), scenarios[request.scenario] ) return {"output": str(result)}
# Serve the demo page in the next step from public/ at the site root. Mount# it after the route, so /api/agent still resolves.app.mount("/", StaticFiles(directory="public", html=True), name="public")Add a minimal page that calls the endpoint and displays the agent’s response. Serve it however your framework serves static files:
<h1>Agent Guard policy demo</h1><p>Test recipient and sensitive-information policies on the same email tool.</p>
<button data-scenario="allowed">Allowed recipient</button><button data-scenario="blocked">Blocked recipient</button><button data-scenario="pii">Sensitive information</button><pre id="output">Choose a scenario.</pre>
<script> // Send only the selected scenario name to the server. const output = document.querySelector("#output");
for (const button of document.querySelectorAll("button")) { button.addEventListener("click", async () => { output.textContent = "Running agent…"; const response = await fetch("/api/agent", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ scenario: button.dataset.scenario }), }); const result = await response.json(); output.textContent = result.output ?? result.error; }); }</script>Each scenario demonstrates a different result from the same guarded tool:
- Allowed recipient: The recipient is on the allow list and the body has no
sensitive data, so
sendEmailreaches the email provider. - Blocked recipient: The model calls the same tool with an external
address, and the remote membership rule denies the call before the provider
runs. The model receives the denial result and explains it. This scenario
needs an adapter that maps
inputs; on the others the send goes through, because the recipient never reaches the policy. - Sensitive information: The recipient is allowed, but the agent first
calls
getClientRecordand receives test bank account and routing numbers. When the model puts that tool result in the email body, the check deniessendEmailbefore the data leaves the application – through the remote policy’sbodyrule where the adapter mapsinputs, and through the SDK rule where it doesn’t.
Read the decision, not the absence of an email
Section titled “Read the decision, not the absence of an email”The samples give the agent a system prompt for a reason. Without one the
model asks a clarifying question, or masks the account numbers itself,
instead of calling sendEmail with them. Nothing is sent, no guard call is
made, and no decision is returned.
That is the outcome to watch for, because it looks like the guard worked. A reader with a broken policy, a wrong label, or a missing key sees “nothing was sent” and concludes the guard is enforcing. Check the decision in the Arcjet dashboard or in your logs. No decision means the model declined, not that the guard denied.
The same distinction is the reason to guard the tool at all. An unguarded agent often refuses the sensitive-information scenario on its own, because sending bank details over email looks wrong to the model. That refusal is judgement: it is non-deterministic, and a different prompt can talk the model out of it. The blocked-recipient scenario is the deterministic contrast, since nothing about an external address looks unsafe to the model.
What next?
Section titled “What next?”Get help
Section titled “Get help”Need help with anything? Email support@arcjet.com to get support from our engineering team.