Code Examples
Practical examples showing how to build and use Claude Code agents.
First Agent (Python)
SDK
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Read package.json and tell me the main entry point",
options=ClaudeAgentOptions(allowed_tools=["Read"])
):
print(f"Message: {message}")
asyncio.run(main())Rate Limiting Agent
Production
from datetime import datetime, timedelta
from collections import defaultdict
user_calls = defaultdict(list)
max_calls_per_hour = 10
def check_rate_limit(user_id: str) -> bool:
now = datetime.now()
hour_ago = now - timedelta(hours=1)
user_calls[user_id] = [
t for t in user_calls[user_id]
if t > hour_ago
]
if len(user_calls[user_id]) >= max_calls_per_hour:
return False
user_calls[user_id].append(now)
return TrueSubagent Definition
CLI
---
type: agent
description: Security specialist reviewing code for vulnerabilities
model: sonnet
tools:
- Read
- Grep
- WebSearch
---
You are a code security reviewer. Check for:
- SQL injection, XSS vulnerabilities
- Insecure cryptography
- Exposed secrets
- Authentication bypass risks
Format: Issue: [name] | Severity: [level] | Fix: [suggestion]Custom Tool (TypeScript)
Tools
import { tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const getTemperature = tool(
"get_temperature",
"Get current temperature at a location",
{
latitude: z.number(),
longitude: z.number(),
unit: z.enum(["celsius", "fahrenheit"])
},
async (args) => {
const response = await fetch(
`https://api.weather.example.com/temp?lat=${args.latitude}&lon=${args.longitude}`
);
const { temperature } = await response.json();
return {
content: [{
type: "text" as const,
text: `Temperature: ${temperature}°${args.unit[0].toUpperCase()}`
}]
};
}
);💡 More Examples in Modules
Each module contains practical code examples embedded throughout the content. Check out the modules for in-depth examples within their specific topics.