Get started with Claude Managed Agents
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.
This guide shows you how to protect an application with Arcjet by blocking automated clients that inflate costs and enforcing per-user token budgets.
1. Install Arcjet
Section titled “1. Install Arcjet”In your project root, run the following:
pip install "arcjet[claude-managed-agents]"Or with uv:
uv add "arcjet[claude-managed-agents]"npm i @arcjet/guard @anthropic-ai/sdkpnpm add @arcjet/guard @anthropic-ai/sdkyarn add @arcjet/guard @anthropic-ai/sdkRequirements
Section titled “Requirements”- Node.js 22 or later.
- CommonJS is not supported. Arcjet is ESM only.
@anthropic-ai/sdk(>=0.86.0 <1) is an optional peer of@arcjet/guard. The peer is@anthropic-ai/sdk, not@anthropic-ai/claude-agent-sdk.
- CPython 3.10 or later.
arcjet[claude-managed-agents]depends onanthropic>=0.92.0,<2. The peer isanthropic, notclaude-agent-sdk.
2. Set your key
Section titled “2. Set your key”Create a free Arcjet account then 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=developmentANTHROPIC_API_KEY=sk-yourkeySet your environment variables:
# Export your Arcjet API key from https://console.arcjet.comARCJET_KEY=ajkey_yourkeyARCJET_ENV=developmentANTHROPIC_API_KEY=sk-yourkey3. Configure
Section titled “3. Configure”This configures Arcjet to protect your AI application: block automated clients that inflate costs, and enforce per-user token budgets.
Create a client, screen inbound user.message before send, and wrap a
custom tool with a token budget:
import jsonimport os
from anthropic import AsyncAnthropicfrom arcjet.guard import DetectPromptInjection, TokenBucket, launch_arcjetfrom arcjet.guard.claude_managed_agents import ( guard_custom_tool, guard_events,)
# guard_events runs an inbound check before each user.message reaches the# session, so use the async client: the sync one can't be awaited here.client = AsyncAnthropic()arcjet = launch_arcjet(key=os.environ["ARCJET_KEY"])inbound = DetectPromptInjection()lookup_limit = TokenBucket( refill_rate=5, interval_seconds=10, max_tokens=10, bucket="lookups",)
async def lookup_order(event) -> dict: return { "order_id": event.input["order_id"], "status": "shipped", }
# session_id is the Anthropic session id from sessions.create.# conversation_id is your own id, which is what Arcjet correlates on.async def run_agent(session_id: str, conversation_id: str, user_text: str): # Pass run= for the hosted path. On DENY the handler sends the denial # as the tool result and lookup_order never runs. guarded_lookup = guard_custom_tool( guard=arcjet, run=lookup_order, action="order.looked-up", session_id=conversation_id, rules=lambda arguments: [ lookup_limit(key=arguments["order_id"], requested=1) ], )
# guard_events wraps send, so a denied prompt is never sent. send = guard_events( guard=arcjet, send=client.beta.sessions.events.send, action="message.received", session_id=conversation_id, rules=lambda arguments: [inbound(arguments["prompt"])], )
stream = await client.beta.sessions.events.stream(session_id) await send( session_id, events=[ { "type": "user.message", "content": [{"type": "text", "text": user_text}], } ], )
async for event in stream: # This agent has one tool. Once you add a second, dispatch on # event.name and return an error for names you do not recognize, so # an unexpected name cannot reach a tool that was not meant for it. if event.type == "agent.custom_tool_use": result = await guarded_lookup( event, send=client.beta.sessions.events.send, session_id=session_id, ) # The wrapper already sent the denial and returned None. if result is None: continue await client.beta.sessions.events.send( session_id, events=[ { "type": "user.custom_tool_result", "custom_tool_use_id": event.id, "content": [ {"type": "text", "text": json.dumps(result)} ], } ], )Create a client, screen inbound user.message before send, and wrap a
custom tool with a token budget:
import Anthropic from "@anthropic-ai/sdk";import { launchArcjet, detectPromptInjection, tokenBucket,} from "@arcjet/guard";import { claudeManagedAgentsContext, guardCustomTool, guardEvents,} from "@arcjet/guard/claude-managed-agents/v0";
const arcjet = launchArcjet({ key: process.env.ARCJET_KEY! });const client = new Anthropic();
const lookupLimit = tokenBucket({ bucket: "lookups", refillRate: 5, intervalSeconds: 10, maxTokens: 10,});
async function lookupOrder(input: { [key: string]: unknown }) { return { orderId: String(input.orderId), status: "shipped" };}
export async function runAgent( conversationId: string, sessionId: string, userText: string,) { // Correlation is your own conversation id, never the Anthropic session id. const context = claudeManagedAgentsContext({ correlationId: conversationId, });
const stream = await client.beta.sessions.events.stream(sessionId);
// Anthropic runs the tool loop, so there is no PreToolUse hook. This // screens the prompt and sends it only if the guard allows. const inbound = await guardEvents( arcjet, { events: [ { type: "user.message", content: [{ type: "text", text: userText }] }, ], inbound: { action: "message.received", rules: ({ text }) => [detectPromptInjection()(text)], }, context, }, (body) => client.beta.sessions.events.send(sessionId, body), ); if (!inbound.allowed) { throw new Error(inbound.message); }
for await (const event of stream) { // This agent has one tool. Once you add a second, dispatch on // `event.name` and return an error for names you do not recognize, // so an unexpected name cannot reach a tool that was not meant for it. if (event.type === "agent.custom_tool_use") { // On deny, guardCustomTool sends the error result itself and // lookupOrder never runs. const gated = await guardCustomTool( arcjet, { event, execute: lookupOrder, send: (result) => client.beta.sessions.events.send(sessionId, { events: [result] }), }, { action: "order.looked-up", rules: (input) => [ lookupLimit({ key: String(input.orderId), requested: 1 }), ], context, }, );
if (gated.allowed) { await client.beta.sessions.events.send(sessionId, { events: [ { type: "user.custom_tool_result", custom_tool_use_id: event.id, content: [{ type: "text", text: JSON.stringify(gated.output) }], }, ], }); } } }}4. Start app
npx tsx --env-file .env.local agent.tsrunAgent takes two ids. sessionId is the Anthropic session id from
sessions.create, and conversationId is your own id for the
conversation, which is what Arcjet correlates on. Don’t mint either one in
the handler. Denied prompts and custom tool calls appear in your
Arcjet dashboard in real time.
python -c "import asyncio; from agent import run_agent; asyncio.run(run_agent(SESSION_ID, 'Look up order 1001'))"Replace SESSION_ID with the Anthropic session id from
sessions.create. Don’t mint an ID. Denied prompts and custom tool
calls appear in your
Arcjet dashboard in real time.
For helper options, denial payloads, and correlation, see the Claude Managed Agents agent guard.
The requests also appear in the Arcjet dashboard.
Do I need to run any infrastructure, such as Redis?
No, Arcjet handles all the infrastructure for you so you don't need to worry about deploying global Redis clusters, designing data structures to track rate limits, or keeping security detection rules up to date.
What is the performance overhead?
Arcjet SDK tries to do as much as possible asynchronously and locally to minimize latency for each request. Where decisions can be made locally or previous decisions are cached in-memory, latency is usually <1ms.
When a call to the Cloud API is required, such as when tracking a rate limit in a serverless environment, there is some additional latency before a decision is made. The Cloud API has been designed for high performance and low latency, and is deployed to multiple regions around the world. The SDK will automatically use the closest region which means the total overhead is typically no more than 20-30ms, often significantly less.
What happens if Arcjet is unavailable?
Where a decision has been cached locally, such as blocking a client, Arcjet will continue to function even if the service is unavailable.
If a call to the Cloud API is needed and there is a network problem or Arcjet is unavailable, the default behavior is to fail open and allow the request. You have control over how to handle errors, including choosing to fail close if you prefer. See the reference docs for details.
How does Arcjet protect me against DDoS attacks?
Network layer attacks tend to be generic and high volume, so these are best handled by your hosting platform. Most cloud providers include network DDoS protection by default.
Arcjet sits closer to your application so it can understand the context. This is important because some types of traffic may not look like a DDoS attack, but can still have the same effect. For example, a customer making too many API requests and affecting other customers, or large numbers of signups from disposable email addresses.
Network-level DDoS protection tools find it difficult to protect against this type of traffic because they don't understand the structure of your application. Arcjet can help you to identify and block this traffic by integrating with your codebase and understanding the context of the request, such as the customer ID or the sensitivity of the API route.
Volumetric network attacks are best handled by your hosting provider. Application level attacks need to be handled by the application. That's where Arcjet helps.
What next?
Section titled “What next?”Get help
Section titled “Get help”Need help with anything? Email us or join our Discord to get support from our engineering team.