Anthropic Integration Guide
What is an LLM API?
Bounded-context, token-priced, prefix-cacheable streaming.
The Messages API is a stateless HTTPS endpoint: every call sends the full conversation, and Claude returns a completion (optionally streamed via SSE). Tokens are billed both directions; output is the expensive side. The 1M-token context is the working set — system prompt + tool definitions + history + the next reply have to coexist inside it. Three levers move cost dramatically: (1) pick the smallest sufficient model (Haiku → Sonnet → Opus → Fable), (2) reuse a long prefix and read it from prompt cache at 90–95 % off, (3) use tool_use when the model needs to call functions instead of stuffing fresh data into context. Adaptive thinking, steered by the effort setting (low → max), trades latency and output tokens for harder reasoning.
The Claude family
Three sizes, one API. Pick the smallest model that holds the quality bar for the task — pricing scales ~40× between the top and bottom tiers. Tap a card for the long version.
Why prompt caching changes the math
Every API call resends the full context — system prompt, tool definitions, chat history. Prompt caching lets Anthropic hash a stable prefix and bill cache reads at 5–10% of the normal input price (writes cost 25% more, paid once per cached prefix per ~5 minutes). For agent loops and long system prompts the savings are dramatic — drag the sliders to see your bill at a realistic hit rate.
At a 60% hit rate on Opus 5.5, prompt caching saves about $94/mo (47%) on input. Output tokens are unaffected — caching only rebates the prefix you send in, not what Claude writes out. The win compounds with long system prompts, big tool definitions, and chat histories that don't churn.
Real-world hit rates: ~30–50% for chat with rotating context, 70–90% for agents that reuse a big system prompt and tool list every turn. The cache TTL is 5 min by default (1 hour available at a higher write multiplier) — refresh before it expires by re-sending the same prefix.
█████╗ ███╗ ██╗████████╗██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██████╗
██╔══██╗████╗ ██║╚══██╔══╝██║ ██║██╔══██╗██╔═══██╗██╔══██╗██║██╔════╝
███████║██╔██╗ ██║ ██║ ███████║██████╔╝██║ ██║██████╔╝██║██║
██╔══██║██║╚██╗██║ ██║ ██╔══██║██╔══██╗██║ ██║██╔═══╝ ██║██║
██║ ██║██║ ╚████║ ██║ ██║ ██║██║ ██║╚██████╔╝██║ ██║╚██████╗
╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝Anthropic Integration Guide
Focus: Using Anthropic's APIs, SDKs, and MCP tooling directly within Claude Code workflows and automation pipelines.
Overview
Anthropic is the company behind Claude and Claude Code itself. Integrating Anthropic's APIs into Claude Code lets you build AI-assisted workflows, automate code generation, chain Claude API calls inside hooks, and extend Claude Code with custom MCP servers — all using first-party tooling.
Here is the big picture of how these first-party pieces fit together — once you see the shape, everything below slots right in.
Official Documentation
Docs domain moved. Anthropic's developer docs now live at
platform.claude.com/docs(the olddocs.anthropic.com/...URLs 301-redirect there); the console is atplatform.claude.com, status atstatus.claude.com, and pricing atclaude.com/pricing. Claude Code docs stay atcode.claude.com/docs.
MCP Server Setup
Claude Code as an MCP Server
Claude Code itself can act as a stdio MCP server, exposing its tools to other clients (for example Claude Desktop).
# Start Claude Code as an MCP server (stdio transport).
# It prints nothing on start: a silent terminal means it is waiting for a client.
claude mcp serveTo use it from another MCP client, register the command claude with args ["mcp", "serve"] in that client's config (see the .mcp.json shape below).
Packaging a Local MCP Server with @anthropic-ai/mcpb
@anthropic-ai/mcpb is the CLI for MCP Bundles (.mcpb, formerly .dxt): a zip of a local MCP server plus a manifest.json, installable with one click in Claude for macOS and Windows. It packages a server you already wrote; it does not register anything with Claude Code.
npm install -g @anthropic-ai/mcpbcd my-server # a folder containing your local MCP server
mcpb init # interactive: writes manifest.json
mcpb pack # produces my-server.mcpb
# Open the .mcpb file with Claude Desktop to get the install dialog.For Claude Code, register the server directly with claude mcp add (below) or in .mcp.json.
.mcp.json Configuration
Create .mcp.json in your project root to share project-scoped MCP servers with your team. Claude Code asks each user to approve servers from this file before connecting:
{
"mcpServers": {
"anthropic-code": {
"command": "claude",
"args": ["mcp", "serve"],
"env": {}
}
}
}Claude Code CLI Integration
Installation
The native installer is the recommended path and auto-updates in the background:
# macOS / Linux / WSL
curl -fsSL https://claude.ai/install.sh | bash
# Windows (WinGet; does not auto-update, run `winget upgrade Anthropic.ClaudeCode`)
winget install Anthropic.ClaudeCode
# Homebrew (does not auto-update, run `brew upgrade claude-code`)
brew install --cask claude-codeThe npm package still works and installs the same native binary (needs Node.js 22+; never sudo). Upgrade with npm install -g @anthropic-ai/claude-code@latest, not npm update -g:
npm install -g @anthropic-ai/claude-codeKey Commands
# Start interactive session
claude
# Run a one-shot prompt (non-interactive / headless)
claude -p "Explain the auth flow in src/auth.ts"
# Machine-readable output for scripts and CI
claude -p "Summarize this project" --output-format json | jq -r '.result'
# Run with a specific model (alias or full ID) and effort level
claude --model opus --effort high
claude --model claude-opus-5-5
# Continue the most recent session
claude --continue
# Pre-approve tools for a headless run
claude -p "Fix the TypeScript errors" --allowedTools "Bash,Edit,Read"
# Start as MCP server
claude mcp serve
# Manage MCP servers ("--" separates Claude's flags from the server command)
claude mcp add <name> -- <command> [args]
claude mcp add my-server -e API_KEY=placeholder -- npx my-mcp-server
claude mcp list
claude mcp remove <name>
# Add remote MCP server (HTTP transport)
claude mcp add --transport http my-server https://my-server.example.com/mcp
# Share a server with the team via .mcp.json
claude mcp add --scope project --transport http my-server https://my-server.example.com/mcp
--allowedToolspre-approves tools; to restrict which tools exist at all, use--tools "Bash,Edit,Read". Real secrets for-ecome from Hazina or your shell, never from a committed file.
Anthropic SDK Integration
A single messages.create call is the heartbeat of every SDK example below — here is exactly what happens on each request.
Node.js / TypeScript
npm install @anthropic-ai/sdkimport Anthropic from "@anthropic-ai/sdk";
// Zero-arg constructor resolves ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN,
// or an `ant auth login` profile — see Authentication below.
const client = new Anthropic();
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
messages: [{ role: "user", content: "Review this code for security issues." }],
});
// `content` is a discriminated union — narrow by `.type` before reading `.text`.
// On Opus 5.5 a response can begin with (empty) thinking blocks.
for (const block of message.content) {
if (block.type === "text") console.log(block.text);
}The TypeScript SDK is at
@anthropic-ai/sdk0.135.0. Themessages.createshape above is stable across the 0.x line; newer features (fallbacks,between_tools, the Tool Runner) need a recent 0.13x release for the types.
Python
pip install anthropicimport anthropic
# Resolves ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or an `ant auth login` profile.
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Generate unit tests for this function."}],
)
# Narrow by block type — thinking and tool_use blocks have no .text attribute.
for block in message.content:
if block.type == "text":
print(block.text)The Python SDK is at
anthropic1.15.0 and requires Python 3.10+. The 0.x → 1.x break was the move to httpx 2 (see the SDK'sMIGRATION.md);client.messages.create(...)usage is unchanged. Pinanthropic>=1,<2.
Models and Defaults
| Model | API ID | $/MTok in / out | Use at codeAmani |
|---|---|---|---|
| Claude Fable 5.1 | claude-fable-5-1 | $10 / $50 | Frontier, long-horizon agents where correctness beats cost |
| Claude Opus 5.5 | claude-opus-5-5 | $4 / $20 | Default: agentic coding, deep review, anything correctness-sensitive |
| Claude Sonnet 5.5 | claude-sonnet-5-5 | $2 / $10 | Everyday volume once an eval shows quality holds |
| Claude Haiku 5.5 | claude-haiku-5-5 | $0.10 / $0.50 (prompts ≤100K), $0.50 / $2.50 above | Classification, routing, extraction, sub-agents |
All four have a 1M-token context and 128K max output. IDs are dateless pinned snapshots: never append a date suffix. Bedrock prefixes anthropic. (anthropic.claude-opus-5-5); Vertex, Foundry, and Claude Platform on AWS use the bare ID.
Older models still served: Fable 5, Opus 5 ($5/$25), Opus 4.8/4.7/4.6/4.5, Sonnet 5 ($2/$10), Sonnet 4.6, Haiku 4.5 (
claude-haiku-4-5, 200K context, $1/$5). Move new work to the 5.5 / 5.1 line; Opus 5.5 is cheaper than Opus 5 per token and per solved task.
Thinking, Effort, and the Request Shape
Claude 5.x models reject several 4.x-era patterns with a 400. Per model:
| Model | Thinking | Default effort | Notes |
|---|---|---|---|
claude-opus-5-5 | Always on. Omit thinking or send { type: "adaptive" }. disabled and budget_tokens → 400 at every effort | medium | Forced tool_choice any/tool → 400; temperature/top_p/top_k → 400 |
claude-sonnet-5-5 | Adaptive by default. disabled → 400; to turn thinking off send { type: "between_tools" } (no other fields, effort high or below) | high (levels recalibrated) | Forced tool_choice → 400; non-default sampling → 400 |
claude-haiku-5-5 | Adaptive by default; disabled accepted at effort high or below | medium | budget_tokens, sampling params, prefill → 400 |
claude-fable-5-1 | Always on; omit thinking | high | Forced tool_choice → 400; 30-day retention required (no ZDR unless authorized) |
Assistant-message prefill is a 400 on every current model; shape output with output_config.format or a system instruction instead.
Effort is the dial that replaced budget_tokens, and it lives inside output_config, not at the top level:
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
thinking: { type: "adaptive", display: "summarized" },
output_config: { effort: "high" }, // low | medium (default on Opus 5.5) | high | xhigh | max
messages: [{ role: "user", content: "Refactor this module and explain why." }],
});- Set effort explicitly on Opus 5.5. Its default is
medium, one level below Opus 5'shigh, and the levels don't map 1:1: Opus 5.5 atmediumbeats Opus 5 athighon Anthropic's coding evals. Start atmedium, sweeplowandhigh, and reservexhigh/maxfor measured gains. To get less thinking, lower effort before adding "think less" prompts. - Sonnet 5.5 thinking-off route (latency-critical paths that previously sent
disabled):
const message = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 16000,
thinking: { type: "between_tools" }, // no other fields; effort high or below
output_config: { effort: "low" },
messages: [{ role: "user", content: "Classify this ticket: billing, bug, or feature." }],
});displaydefaults to"omitted"— thinking blocks arrive with empty text. Setdisplay: "summarized"if a UI renders reasoning. On Opus 5.5 and Sonnet 5.5, text written between tool calls also arrives as thinking blocks;display: "updates"(betathinking-display-updates-2026-08-18) returns short progress notes so an agent UI doesn't go silent.- Thinking is billed identically under every
displaysetting and counts towardmax_tokens; the raw chain of thought is never returned. Pass thinking blocks back unchanged in tool loops. - Preserved thinking: on Opus 5.5 / Sonnet 5.5 / Fable 5.1, editing earlier turns (deleting a reminder, changing the system prompt or tool list mid-session) invalidates replayed thinking blocks, and accounts created on or after 2026-08-31 get a 400. Keep histories append-only; use a mid-conversation
{ role: "system" }message instead of editingsystem.
max_tokensis a truncation cliff, not a cost control. Default to16000for non-streaming calls and64000when streaming. Thinking counts toward it. Current models support up to 128K output tokens, but the SDKs require streaming at that size to avoid HTTP timeouts.
Refusals and Fallbacks
Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable 5.1 run safety classifiers. A decline is HTTP 200 with stop_reason: "refusal" and a stop_details.category (cyber, bio, reasoning_extraction, frontier_llm, general_harms, or null). Always check stop_reason before reading content.
Opt into server-side fallback from day one so a false positive is not an outage. fallbacks: "default" lets Anthropic route the retry by refusal category, so you never maintain a model list:
const response = await client.beta.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default", // Anthropic picks the fallback model by refusal category
messages: [{ role: "user", content: "Summarize this incident report." }],
});
if (response.stop_reason === "refusal") {
// The whole chain declined. stop_details is informational (category may be null).
console.warn("declined:", response.stop_details?.category);
} else {
for (const block of response.content) {
if (block.type === "fallback") console.info(`${block.from.model} -> ${block.to.model}`);
if (block.type === "text") console.log(block.text);
}
}fallbacks: "default"pairs only withserver-side-fallback-2026-07-01; the older array form (fallbacks: [{ model: "claude-opus-4-8" }]) pairs only withserver-side-fallback-2026-06-01. Mixing them is a 400.- Claude API and Claude Platform on AWS only, and not on the Batches API. On Bedrock / Vertex / Foundry use the SDK's client-side refusal-fallback middleware.
- Sonnet 5.5:
"default"form only, and server-side fallback retriescyber/frontier_llmonly. Haiku 5.5 has no server-side fallback: don't sendfallbacks(a list is a 400); handle the refusal in code. reasoning_extractiondeclines are never retried. They come from prompts that ask the model to write its reasoning into the answer; remove that instruction and readdisplay: "summarized"blocks instead.- A fallback model runs without Opus 5.5's thinking blocks, so expect a cold-reasoning turn after a switch.
Structured Outputs
When you need JSON that actually validates, constrain the response instead of parsing hopefully. Use output_config.format — the older top-level output_format parameter is deprecated:
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
output_config: {
effort: "low",
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
severity: { type: "string", enum: ["low", "medium", "high"] },
summary: { type: "string" },
},
required: ["severity", "summary"],
additionalProperties: false,
},
},
},
messages: [{ role: "user", content: "Triage this Sentry error: " + stackTrace }],
});For tool arguments, set strict: true as a top-level field on the tool definition (not on tool_choice); the schema needs additionalProperties: false plus required. This is also the replacement for forced tool use, which is a 400 on Opus 5.5 / Sonnet 5.5 / Fable 5.1: use tool_choice: { type: "auto" }, name the tool in the prompt, and check that a tool_use block came back. Structured outputs are incompatible with document citations — sending both returns a 400.
Tool Use with the Tool Runner
Tool use is a loop (stop_reason: "tool_use" → run tools → send tool_result → repeat). The SDK's Tool Runner (beta, client.beta.messages.toolRunner) drives that loop for tools you define; prefer it over a hand-written loop. Full runnable versions of both live in examples/tool-use.ts.
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
const getOrderStatus = betaZodTool({
name: "get_order_status",
description: "Look up a Stripe order by payment intent ID.",
inputSchema: z.object({ payment_intent_id: z.string() }),
run: async ({ payment_intent_id }) =>
JSON.stringify({ id: payment_intent_id, status: "succeeded" }), // your executor
});
const finalMessage = await client.beta.messages.toolRunner({
model: "claude-opus-5-5",
max_tokens: 16000,
tools: [getOrderStatus, { type: "web_search_20260209", name: "web_search", max_uses: 3 }],
messages: [{ role: "user", content: "What's the status of payment pi_abc123?" }],
});- Server tools: use
web_search_20260209/web_fetch_20260209(dynamic filtering) on Opus 5.5, Sonnet 5.5, and the 4.6+ Opus/Sonnet line. Don't also declarecode_execution; the new web tools run it internally. Vertex AI offers only basicweb_search_20250305. Web search costs $10 per 1,000 searches plus tokens. pause_turn: the runner does not auto-resume a paused server-tool turn. If you mix server tools in, checkstop_reasonon each iteration (pattern in the skill / SDK docs) or use the manual loop.- Parallel calls: in a manual loop, run every
tool_useblock and return alltool_resultblocks in a single user message; mark failures withis_error: trueinstead of dropping them. - The Tool Runner is not the Claude Agent SDK: it has no built-in tools or sandbox. See the box under Managed Agents.
Managed Agents
The docs home leads with two developer surfaces: the Messages API (you own the loop) and Managed Agents (Anthropic runs the loop and hosts the sandbox where tools execute). Reach for Managed Agents when the alternative is writing your own scheduler, session store, and container runtime.
The flow is agent once → session per run. model, system, and tools live on the agent, never on the session; a session needs an existing agent and an environment:
// 1. Setup script, run once. Store agent.id / agent.version / environment.id.
const environment = await client.beta.environments.create({
name: "reconcile-env",
config: { type: "cloud", networking: { type: "limited", allow_package_managers: true } },
});
const agent = await client.beta.agents.create({
name: "Payout Reconciler",
model: "claude-opus-5-5",
system: "You reconcile Stripe payout reports against our order ledger.",
tools: [
{
type: "agent_toolset_20260401",
default_config: { enabled: true, permission_policy: { type: "auto" } },
configs: [
{ name: "web_fetch", enabled: false },
{ name: "web_search", enabled: false },
],
},
],
});
// 2. Every run: start a session that references the stored IDs.
const session = await client.beta.sessions.create({
agent: { type: "agent", id: agent.id, version: agent.version },
environment_id: environment.id,
});- The beta header
managed-agents-2026-04-01is set automatically by the SDK forclient.beta.{agents,environments,sessions,vaults,deployments,deployment_runs}.*. Memory stores useagent-memory-2026-07-22instead; sending both on a memory-store call is a 400. - Never call
agents.create()in the request path. To change behavior, update the agent (each update is a new version; sessions pin a version). The recommended control plane is version-controlled agent files synced withant apply. - Scheduled deployments fire sessions on a cron cadence — use those rather than a client-side scheduler for nightly or weekly agent jobs. Session budgets give a hard dollar cap per session.
- Vault credentials (
environment_variable) are held by Anthropic and substituted at egress, so secrets never enter the sandbox. Prefer them to passing keys into tool code; keep the source of truth in Hazina. - Not available on Bedrock, Vertex AI, or Foundry — use Messages + tool use on those platforms.
Three different things that sound alike. Agent Skills generate
.pptx/.xlsxviacontainer.skillson a normalmessages.create. The Claude Agent SDK (@anthropic-ai/claude-agent-sdk) is Claude Code packaged as a library that you host. Only Managed Agents supplies both a managed harness and managed deployment.
Prompt Caching
When you reuse the same large block across calls — a frozen system prompt, a long tool set, retrieved RAG context — mark it with cache_control: { type: "ephemeral" }. Anthropic caches that prefix and serves it back at a fraction of input cost on cache hits, with lower latency: 0.05× on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.1, 0.1× on everything else (Haiku 5.5 included). For codeAmani's AI features (review bots, support agents, Swahili/English assistants) this is the single biggest cost lever when the per-request question is small but the shared context is huge.
The one rule: caching is a prefix match. Render order is tools → system → messages, and any byte change before a breakpoint invalidates everything after it. Keep stable content first; put volatile content (the user's question, a timestamp, a per-request ID) after the last breakpoint.
Two ways to cache. Automatic caching — set one
cache_control: { type: "ephemeral" }at the top level of the request and Anthropic manages the breakpoint, moving it forward to the last cacheable block as a conversation grows (ideal for multi-turn chat/agents). Explicit breakpoints — the block-level markers shown below, for fine-grained control over exactly what caches. Automatic caching consumes one of your 4 breakpoint slots. The explicit form is used in this example because codeAmani's hot paths reuse a fixed tool set + system prompt.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
// Cache the tool set — tools render at position 0, so this prefix is reused first.
tools: [
{
name: "search_orders",
description: "Look up orders by customer email.",
input_schema: {
type: "object",
properties: { email: { type: "string" } },
required: ["email"],
},
cache_control: { type: "ephemeral" },
},
],
// Cache the large, frozen system prompt — breakpoint on the LAST block caches tools + system together.
system: [
{
type: "text",
text: LARGE_SHARED_PROMPT, // e.g. product catalog, brand rules, RAG context
cache_control: { type: "ephemeral" }, // add `ttl: "1h"` for bursty traffic with idle gaps
},
],
// Volatile content goes last, after the cached prefix — no marker here.
messages: [{ role: "user", content: "Where is my last order?" }],
});
// Confirm it worked — cache_read_input_tokens should be > 0 on the 2nd+ identical-prefix call.
console.log(message.usage.cache_read_input_tokens, message.usage.cache_creation_input_tokens);Notes that bite in practice:
- Max 4 breakpoints per request. Minimum cacheable prefix depends on model — 512 tokens (Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.1, Opus 5, Fable 5), 1024 (Sonnet 5, Opus 4.8, Sonnet 4.6), 2048 (Opus 4.7), 4096 (Haiku 4.5, Opus 4.6/4.5). Shorter prefixes silently won't cache (
cache_creation_input_tokens: 0, no error). - Verify with
usage. Ifcache_read_input_tokensstays 0 across repeated calls, a silent invalidator is in the prefix —new Date()/Date.now()in the system prompt, unsortedJSON.stringify, a per-user ID interpolated early, or a tool set that changes per request. - Don't interpolate dynamic values into the system prompt (current date, user name, mode). Those sit at the front and break every downstream cache — pass them in a later
messagesentry, or as a mid-conversation{ role: "system" }message, instead. - Changing top-level
effortbetween requests invalidates the cache. Pick an effort per route and keep it stable. - Economics: writes cost 1.25× base input (5m TTL) or 2× (1h TTL). At a 0.1× read rate, caching pays off after one read on the 5-minute TTL and two reads on the 1-hour TTL; the deeper 0.05×/0.025× read rates on the 5.5/5.1 models make misses relatively more expensive, so keep the cache warm.
Via the AI Gateway: when calling Claude through the Vercel AI SDK with
anthropic/...model strings (codeAmani's default — see the insight), set the marker asproviderOptions: { anthropic: { cacheControl: { type: "ephemeral" } } }on the message or content part (camelCase in the AI SDK) so it reaches the underlying API ascache_control. Caching is an Anthropic-side feature; the gateway forwards it but does not invent it.
Canonical reference: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Authentication and Environment Variables
An unset ANTHROPIC_API_KEY does not mean you have no credentials. The SDKs and the ant CLI resolve in this order, first match wins:
ANTHROPIC_API_KEYANTHROPIC_AUTH_TOKEN- The
ANTHROPIC_PROFILE-selected (or active) OAuth profile fromant auth login - Workload Identity Federation environment variables
- The default profile on disk
A bare new Anthropic() therefore works after ant auth login with no env var set. Check which source is actually live before concluding a key is missing:
ant auth status # shows the active credential source and profile
ant auth login # stores a profile under ~/.config/anthropic/ that the SDKs read# Server-side only — never ship this into a client bundle
ANTHROPIC_API_KEY=sk-ant-...That is the only secret. The rest are optional, non-secret settings. Set them in your shell profile or project config when you need them, not in the vault:
| Variable | Example | What it does |
|---|---|---|
ANTHROPIC_BASE_URL | https://api.anthropic.com (default) | Point the SDKs / CLI at a proxy or gateway |
ANTHROPIC_MODEL | claude-opus-5-5 (or an alias like opus) | Model for the claude CLI |
ANTHROPIC_PROFILE | work | Select a named ant auth login profile |
CLAUDE_CODE_MAX_OUTPUT_TOKENS | 32000 | Claude Code output cap (capped per model) |
CLAUDE_CODE_EFFORT_LEVEL | high | Claude Code effort: low · medium · high · xhigh · max · auto |
Put the key in .env.local for local dev and the Vercel dashboard for production. For codeAmani, the Hazina vault is the source of truth for real keys; the value above is a placeholder.
Raw
curlunder OAuth: anantprofile is not an API key. Mint a short-lived token withant auth print-credentials --access-token, then send it asAuthorization: Bearer <token>plus the headeranthropic-beta: oauth-2025-04-20. OAuth tokens do not go inx-api-key— converting a working curl from an API key is a header change, not just a value swap.
Automation Workflows
Claude Code Hooks
Hooks run shell commands automatically at lifecycle events. Configure in .claude/settings.json. Command hooks receive the event as JSON on stdin (for tool events, tool_name and tool_input), so extract fields with jq rather than relying on environment variables:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.command' >> .claude/audit.log"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node \"$CLAUDE_PROJECT_DIR\"/scripts/notify-complete.js"
}
]
}
]
}
}$CLAUDE_PROJECT_DIR points at the project root, so hook scripts resolve no matter which directory Claude is in.
Skills (formerly custom slash commands)
Custom commands have been merged into skills. A skill is a directory with a SKILL.md; its folder name (or frontmatter name) becomes the slash command. Files in .claude/commands/ keep working, but prefer skills for new work since they support supporting files and let Claude load them automatically when relevant.
mkdir -p .claude/skills/codeamani-review.claude/skills/codeamani-review/SKILL.md:
---
description: Review code for security, performance, and codeAmani conventions.
---
Review the following code for: security issues, performance problems, and code quality.
Focus on: $ARGUMENTS
Provide actionable fixes with code examples.Usage inside Claude Code: /codeamani-review src/api/auth.ts. (Avoid names like /review or /security-review: those are built-in commands.)
Headless Automation with the SDK
Use the Claude API to automate code review in CI. Stream it, since reviews of large diffs can run long:
// scripts/ai-review.ts
import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "fs";
const client = new Anthropic();
const diff = readFileSync("latest.diff", "utf-8");
const stream = client.messages.stream({
model: "claude-opus-5-5",
max_tokens: 64000,
output_config: { effort: "high" },
system: "You are a senior code reviewer. Be concise and actionable.",
messages: [{ role: "user", content: `Review this diff:\n\n${diff}` }],
});
const review = await stream.finalMessage();
for (const block of review.content) {
if (block.type === "text") console.log(block.text);
}If you'd rather reuse Claude Code's own tools and settings in CI, run claude -p "..." --output-format json instead, or embed the same harness with the Claude Agent SDK.
Common Use Cases
| Use Case | Approach |
|---|---|
| Automated PR review | Fetch diff via gh, pipe to Claude API, or use anthropics/claude-code-action@v1 |
| Code generation | claude -p "Generate CRUD endpoints for User model" |
| Test generation | Hook on PostToolUse with matcher Edit|Write to auto-generate tests |
| Documentation | claude -p "Document all exported functions in src/" |
| Security scanning | Combine with Semgrep output piped to Claude API |
| Refactoring | Use --continue sessions for multi-step refactors |
CLAUDE.md Configuration
Create CLAUDE.md at your project root to give Claude Code persistent context:
# Project Context
## Tech Stack
- TypeScript, Node.js 22, PostgreSQL
- Test runner: Vitest
- Linter: ESLint + Prettier
## Conventions
- Use `async/await` — no raw Promises
- All functions must have JSDoc comments
- Tests go in `__tests__/` next to source files
## Forbidden
- Never use `any` type
- Never commit `.env` filesTroubleshooting
| Issue | Fix |
|---|---|
ANTHROPIC_API_KEY not found | Run ant auth status first; otherwise export the key in your shell or load it from Hazina |
| Rate limit errors | The SDK retries 429/5xx twice by default; add backoff on top. Opus 5.5 and Sonnet 5.5 have their own rate-limit pools |
| MCP server not connecting | Run claude mcp list to verify registration; .mcp.json servers need approval first |
| Hooks not firing | Check .claude/settings.json syntax with cat .claude/settings.json | jq . |
| Model not available | Check the live list at platform.claude.com/docs/en/models/overview; never add a date suffix to a 5.x ID |
400 thinking.type.disabled on Opus 5.5 | Thinking can't be disabled; omit thinking and lower output_config.effort to low |
400 thinking.type.disabled on Sonnet 5.5 | Send thinking: { type: "between_tools" } at effort high or below |
400 on budget_tokens | Removed on Claude 5.x — use thinking: { type: "adaptive" } + output_config.effort |
400 on tool_choice any/tool | Forced tool use is removed on Opus 5.5 / Sonnet 5.5 / Fable 5.1; use auto + strict: true + a prompt instruction |
400 on temperature or a prefilled assistant turn | Both removed on Claude 5.x — shape output with output_config.format |
| HTTP 200 but no usable text | Check stop_reason: refusal means a classifier declined (see stop_details.category); add fallbacks: "default" |
| Quality or latency changed after moving to Opus 5.5 | Default effort is now medium; set output_config.effort explicitly and re-sweep |
| Reasoning UI shows a long blank pause | display defaults to "omitted" — set thinking.display: "summarized" (or "updates" for agent progress) |