Code Recipes
14 copy-paste-ready snippets for AI engineering
MCP Tool Definition
Define a tool that an AI agent can call via Model Context Protocol.
const tool = {
name: "search_documents",
description: "Search the knowledge base for relevant documents",
input_schema: {
type: "object",
properties: {
query: {
type: "string",
description: "Natural language search query"
},
limit: {
type: "number",
description: "Max results to return (default: 10)"
}
},
required: ["query"]
}
}Claude API Call
Make a basic Claude API request with system prompt and message history.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="You are a helpful coding assistant.",
messages=[
{"role": "user", "content": "Explain async/await in Python"}
]
)
print(message.content[0].text)Agent Loop Pattern
The core agentic loop: send message, check stop reason, handle tool calls, repeat.
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "What's the weather in NYC?"}]
while True:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=tools,
messages=messages,
)
class="code-comment"># Check if the model wants to use a tool
if response.stop_reason == "tool_use":
tool_block = next(
b for b in response.content if b.type == "tool_use"
)
result = execute_tool(tool_block.name, tool_block.input)
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_block.id,
"content": str(result),
}],
})
else:
class="code-comment"># Model is done — extract final text
print(response.content[0].text)
breakCLAUDE.md Template
Starter template for a CLAUDE.md file that configures Claude Code project behavior.
# CLAUDE.md
## Project Overview
Brief description of what this project does and its tech stack.
## Architecture
- Backend: FastAPI / Express / etc.
- Frontend: Next.js / React / etc.
- Database: PostgreSQL / SQLite / etc.
- Deployment: Vercel / Docker / etc.
## Conventions
- **Git**: Feature branches, PR-based workflow. Never commit to main.
- **Testing**: pytest for backend, vitest for frontend. 90% coverage floor.
- **Style**: Prettier + ESLint for JS/TS. Black + ruff for Python.
## Key Commands
\`\`\`bash
npm run dev # Start dev server
npm run build # Production build
npm run test # Run tests
\`\`\`
## File Structure (Tiered)
### Tier 1 — Always Reference
| File | Purpose |
|------|---------|
| src/app/page.tsx | Main entry point |
| src/lib/api.ts | API client |
### Tier 2 — Load on Demand
Components, hooks, utils — load when relevant to the task.
## Do NOT
- Modify .env files without confirmation
- Push directly to main
- Skip tests before committingPrompt Chain Pattern
Chain multiple AI calls where each step feeds into the next for complex tasks.
import anthropic
client = anthropic.Anthropic()
def chain_step(system: str, user_input: str) -> str:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
system=system,
messages=[{"role": "user", "content": user_input}],
)
return response.content[0].text
class="code-comment"># Step 1: Research
research = chain_step(
"You are a research analyst. Extract key facts.",
f"Analyze this topic: {topic}"
)
class="code-comment"># Step 2: Outline
outline = chain_step(
"You are a content strategist. Create a structured outline.",
f"Based on this research, create an article outline:\n{research}"
)
class="code-comment"># Step 3: Write
article = chain_step(
"You are an expert technical writer.",
f"Write the full article from this outline:\n{outline}"
)Error Handling with Retry
Exponential backoff retry pattern for API calls that may fail transiently.
import time
import random
import anthropic
def call_with_retry(
func,
max_retries: int = 3,
base_delay: float = 1.0,
):
"""Call func with exponential backoff + jitter."""
for attempt in range(max_retries + 1):
try:
return func()
except anthropic.RateLimitError:
if attempt == max_retries:
raise
delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
print(f"Rate limited. Retrying in {delay:.1f}s...")
time.sleep(delay)
except anthropic.APIError as e:
if attempt == max_retries or e.status_code < 500:
raise
delay = base_delay * (2 ** attempt)
print(f"API error {e.status_code}. Retrying in {delay:.1f}s...")
time.sleep(delay)
class="code-comment"># Usage
client = anthropic.Anthropic()
result = call_with_retry(
lambda: client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
)Streaming Response Pattern
Stream Claude responses token-by-token for real-time output in UIs and CLIs.
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print() class="code-comment"># Final newline
class="code-comment"># Access the complete message after streaming
message = stream.get_final_message()
print(f"\nTokens used: {message.usage.input_tokens} in, {message.usage.output_tokens} out")MCP Server Skeleton
Minimal MCP server with tool registration and request handling.
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server(
{ name: "my-mcp-server", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
class="code-comment">// Register available tools
server.setRequestHandler("tools/list", async () => ({
tools: [{
name: "get_data",
description: "Fetch data from the system",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "What to look up" }
},
required: ["query"],
},
}],
}));
class="code-comment">// Handle tool calls
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "get_data") {
const result = await fetchData(args.query);
return { content: [{ type: "text", text: JSON.stringify(result) }] };
}
throw new Error(`Unknown tool: ${name}`);
});
const transport = new StdioServerTransport();
await server.connect(transport);Supabase RLS Policy
Row-Level Security policy for multi-tenant data isolation in Supabase.
"code-comment">-- Enable RLS on the table
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
"code-comment">-- Users can only read their own documents
CREATE POLICY "Users read own documents"
ON documents FOR SELECT
USING (auth.uid() = user_id);
"code-comment">-- Users can only insert their own documents
CREATE POLICY "Users insert own documents"
ON documents FOR INSERT
WITH CHECK (auth.uid() = user_id);
"code-comment">-- Users can only update their own documents
CREATE POLICY "Users update own documents"
ON documents FOR UPDATE
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
"code-comment">-- Users can only delete their own documents
CREATE POLICY "Users delete own documents"
ON documents FOR DELETE
USING (auth.uid() = user_id);
"code-comment">-- Service role bypasses RLS (for server-side operations)
"code-comment">-- Use supabase.auth.admin or service_role keyNext.js API Route with Auth
Protected Next.js API route that verifies Supabase auth before processing.
import { createClient } from "@supabase/supabase-js";
import { NextRequest, NextResponse } from "next/server";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!
);
export async function POST(request: NextRequest) {
class="code-comment">// Extract and verify auth token
const authHeader = request.headers.get("authorization");
if (!authHeader?.startsWith("Bearer ")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const token = authHeader.replace("Bearer ", "");
const { data: { user }, error } = await supabase.auth.getUser(token);
if (error || !user) {
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
}
class="code-comment">// Process the authenticated request
const body = await request.json();
const result = await processRequest(user.id, body);
return NextResponse.json(result);
}Webhook Handler Pattern
Secure webhook endpoint with signature verification and idempotent processing.
import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
function verifySignature(
payload: string,
signature: string,
secret: string
): boolean {
const expected = crypto
.createHmac("sha256", secret)
.update(payload)
.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
export async function POST(request: NextRequest) {
const body = await request.text();
const signature = request.headers.get("x-webhook-signature") ?? "";
class="code-comment">// Verify webhook signature
if (!verifySignature(body, signature, process.env.WEBHOOK_SECRET!)) {
return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
}
const event = JSON.parse(body);
class="code-comment">// Idempotency check
const eventId = event.id;
if (await isAlreadyProcessed(eventId)) {
return NextResponse.json({ status: "already_processed" });
}
class="code-comment">// Process event by type
switch (event.type) {
case "payment.completed":
await handlePaymentCompleted(event.data);
break;
case "subscription.cancelled":
await handleSubscriptionCancelled(event.data);
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
await markAsProcessed(eventId);
return NextResponse.json({ status: "ok" });
}System Prompt Template
Structured system prompt with role, constraints, output format, and examples.
You are a senior software architect specializing in distributed systems.
## Role
- Analyze code and architecture decisions with production-grade rigor
- Identify performance bottlenecks, security gaps, and scalability limits
- Suggest concrete improvements with tradeoff analysis
## Constraints
- Never suggest unproven or experimental patterns for production code
- Always consider backwards compatibility when proposing changes
- Flag any changes that require database migrations
- Estimate effort level: trivial / small / medium / large
## Output Format
For each finding, provide:
1. **Issue**: What the problem is
2. **Impact**: Why it matters (performance, security, reliability)
3. **Fix**: Concrete code change or architecture adjustment
4. **Effort**: Estimated implementation effort
## Examples
**Good**: "The N+1 query in getUserPosts() will degrade at 1000+ users.
Fix: Add .includes(:posts) to the ActiveRecord query. Effort: trivial."
**Bad**: "Consider using microservices." (too vague, no concrete fix)Structured Output with Claude
Force Claude to return JSON matching a specific schema using tool_choice.
import anthropic
import json
client = anthropic.Anthropic()
class="code-comment"># Define the output schema as a tool
extract_tool = {
"name": "extract_entities",
"description": "Extract structured entities from text",
"input_schema": {
"type": "object",
"properties": {
"people": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"role": {"type": "string"},
"sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
},
"required": ["name", "role", "sentiment"],
},
},
"topics": {
"type": "array",
"items": {"type": "string"},
},
"summary": {"type": "string"},
},
"required": ["people", "topics", "summary"],
},
}
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[extract_tool],
tool_choice={"type": "tool", "name": "extract_entities"},
messages=[{"role": "user", "content": f"Extract entities from: {text}"}],
)
class="code-comment"># The response will always be a tool_use block with valid JSON
structured = response.content[0].input
print(json.dumps(structured, indent=2))CLAUDE.md Hooks Configuration
Configure pre-commit and custom hooks in .claude/settings.json for automated checks.
{
"hooks": {
"PreToolCall": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo 'Bash command intercepted'"
}
]
}
],
"PostToolCall": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "npx eslint --fix $CLAUDE_FILE_PATH 2>/dev/null || true"
}
]
}
],
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification "$CLAUDE_NOTIFICATION" with title "Claude Code"'"
}
]
}
]
}
}