Anthropic Integration Guide

Technology: anthropic · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/anthropic

Insight:

Claude is codeAmani's primary model for reasoning and code generation. claude-opus-5-5 ($4/$20 per MTok) is the default, and it is cheaper than the Opus 5 it replaces, so do not downgrade for cost without a measured reason. Step down to claude-sonnet-5-5 ($2/$10) for everyday volume and claude-haiku-5-5 ($0.10/$0.50 up to 100K-token prompts) for latency-sensitive bulk work; step up to claude-fable-5-1 ($10/$50) for frontier long-running agents. Opus 5.5 thinks on every request and defaults to effort medium: set output_config.effort explicitly, handle stop_reason: "refusal", and opt into fallbacks: "default". Call Claude through the Vercel AI SDK / AI Gateway (anthropic/... model strings) so provider swaps stay config, not code, and lean on prompt caching whenever a large system prompt or RAG context repeats across calls.

 █████╗ ███╗   ██╗████████╗██╗  ██╗██████╗  ██████╗ ██████╗ ██╗ ██████╗
██╔══██╗████╗  ██║╚══██╔══╝██║  ██║██╔══██╗██╔═══██╗██╔══██╗██║██╔════╝
███████║██╔██╗ ██║   ██║   ███████║██████╔╝██║   ██║██████╔╝██║██║
██╔══██║██║╚██╗██║   ██║   ██╔══██║██╔══██╗██║   ██║██╔═══╝ ██║██║
██║  ██║██║ ╚████║   ██║   ██║  ██║██║  ██║╚██████╔╝██║     ██║╚██████╗
╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝   ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝     ╚═╝ ╚═════╝

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.

flowchart TD
  A["You · prompt or hook event"] --> B["Claude Code CLI"]
  B --> C["Anthropic SDK · messages.create"]
  C --> D["Claude API"]
  D --> E["Response · code, review, tests"]
  B --> F["MCP servers · custom tools"]
  F --> B
  B --> G["Automation · hooks and skills"]
  G --> C

Official Documentation

Resource URL
Claude API Docs https://platform.claude.com/docs/en/home
Claude Code Docs https://code.claude.com/docs
Models overview https://platform.claude.com/docs/en/models/overview
Migration guide https://platform.claude.com/docs/en/about-claude/models/migration-guide
Effort https://platform.claude.com/docs/en/build-with-claude/effort
Refusals and fallback https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
Tool Runner https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner
Managed Agents https://platform.claude.com/docs/en/managed-agents/quickstart
Claude Agent SDK https://code.claude.com/docs/en/agent-sdk/overview
CLI, SDKs & libraries https://platform.claude.com/docs/en/cli-sdks-libraries/overview
Release notes https://platform.claude.com/docs/en/release-notes/overview
Help Center (accounts, billing, plans) https://support.claude.com/en
Model Context Protocol https://modelcontextprotocol.io
API Reference https://platform.claude.com/docs/en/api/overview
MCP SDK (TypeScript) https://github.com/modelcontextprotocol/typescript-sdk
MCP SDK (Python) https://github.com/modelcontextprotocol/python-sdk
MCP Bundles (mcpb) https://github.com/modelcontextprotocol/mcpb

Docs domain moved. Anthropic's developer docs now live at platform.claude.com/docs (the old docs.anthropic.com/... URLs 301-redirect there); the console is at platform.claude.com, status at status.claude.com, and pricing at claude.com/pricing. Claude Code docs stay at code.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 serve

To 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/mcpb
cd 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-code

The 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-code

Key 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

--allowedTools pre-approves tools; to restrict which tools exist at all, use --tools "Bash,Edit,Read". Real secrets for -e come 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.

sequenceDiagram
  participant App as "Your app or script"
  participant SDK as "Anthropic SDK"
  participant API as "Claude API"
  App->>SDK: "messages.create · model, max_tokens, messages"
  SDK->>API: "authenticated request · ANTHROPIC_API_KEY"
  API-->>SDK: "message · stop_reason + content blocks"
  SDK-->>App: "check stop_reason, then read text blocks"

Node.js / TypeScript

npm install @anthropic-ai/sdk
import 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/sdk 0.135.0. The messages.create shape 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 anthropic
import 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 anthropic 1.15.0 and requires Python 3.10+. The 0.x → 1.x break was the move to httpx 2 (see the SDK's MIGRATION.md); client.messages.create(...) usage is unchanged. Pin anthropic>=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." }],
});
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." }],
});

max_tokens is a truncation cliff, not a cost control. Default to 16000 for non-streaming calls and 64000 when 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);
  }
}

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?" }],
});

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,
});

Three different things that sound alike. Agent Skills generate .pptx/.xlsx via container.skills on a normal messages.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:

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 as providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } } on the message or content part (camelCase in the AI SDK) so it reaches the underlying API as cache_control. Caching is an Anthropic-side feature; the gateway forwards it but does not invent it.

flowchart LR
  A["Request · tools then system then messages"] --> B{"Prefix byte-identical<br/>to a cached entry"}
  B -->|"yes · cache hit"| C["Served at 0.025×–0.1× input cost<br/>cache_read_input_tokens > 0"]
  B -->|"no · cache miss"| D["Full price · writes cache<br/>at 1.25× then reusable"]
  D --> E["Next call reuses the prefix"]
  E --> B

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:

  1. ANTHROPIC_API_KEY
  2. ANTHROPIC_AUTH_TOKEN
  3. The ANTHROPIC_PROFILE-selected (or active) OAuth profile from ant auth login
  4. Workload Identity Federation environment variables
  5. 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 curl under OAuth: an ant profile is not an API key. Mint a short-lived token with ant auth print-credentials --access-token, then send it as Authorization: Bearer <token> plus the header anthropic-beta: oauth-2025-04-20. OAuth tokens do not go in x-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` files

Troubleshooting

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)

Official docs: