Anthropic + Claude Code 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 200K-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), (2) reuse a long prefix and read it from prompt cache at 90 % off, (3) use tool_use when the model needs to call functions instead of stuffing fresh data into context. Extended thinking 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 ~5× between 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 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 Sonnet 4.6, prompt caching saves about $66/mo (44%) 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 + Claude Code 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
| Resource | URL |
|---|---|
| Claude API Docs | https://docs.anthropic.com |
| Claude Code Docs | https://code.claude.com/docs |
| Model Context Protocol | https://modelcontextprotocol.io |
| API Reference | https://docs.anthropic.com/en/api |
| MCP SDK (TypeScript) | https://github.com/modelcontextprotocol/typescript-sdk |
| MCP SDK (Python) | https://github.com/modelcontextprotocol/python-sdk |
MCP Server Setup
Claude Code as an MCP Server
Claude Code itself can act as an MCP server, exposing its tools to other clients.
# Start Claude Code as an MCP server (stdio transport)
claude mcp serveBuilding a Custom MCP Server with @anthropic-ai/mcpb
@anthropic-ai/mcpb is Anthropic's official MCP bundle tool for creating distributable local MCP servers.
npm install -g @anthropic-ai/mcpbCreate a new MCP bundle project:
mcpb init my-server
cd my-server
mcpb build
mcpb install # installs the bundle into Claude CodeConnecting to the Official Claude Code MCP Server
# Add Claude Code as an MCP server inside another MCP client
claude mcp add claude-code -- claude mcp serve.mcp.json Configuration
Create .mcp.json in your project root to auto-connect MCP servers when Claude Code opens:
{
"mcpServers": {
"anthropic-code": {
"command": "claude",
"args": ["mcp", "serve"],
"env": {}
}
}
}Claude Code CLI Integration
Installation
npm install -g @anthropic-ai/claude-codeKey Commands
# Start interactive session
claude
# Run a one-shot prompt (non-interactive)
claude -p "Explain the auth flow in src/auth.ts"
# Run with a specific model
claude --model claude-opus-4-7
# Continue the most recent session
claude --continue
# Run a bash command within a Claude session
claude -p "Fix the TypeScript errors" --allowedTools Bash,Edit,Write
# Start as MCP server
claude mcp serve
# Manage MCP servers
claude mcp add <name> -- <command> [args]
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/mcpAnthropic 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";
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Review this code for security issues." }],
});
console.log(message.content[0].text);Python
pip install anthropicimport anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Generate unit tests for this function."}],
)
print(message.content[0].text)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 roughly 0.1× input cost on cache hits, with lower latency. 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.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
// Cache the tool set — tools render at position 0, so this prefix is reused first.
tools: [
{
name: "search_orders",
description: "Look up M-Pesa orders by phone number.",
input_schema: {
type: "object",
properties: { phone: { type: "string" } },
required: ["phone"],
},
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 is ~1024–4096 tokens depending on model — 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 instead. - Economics: writes cost ~1.25× (5m TTL) or ~2× (1h TTL). Break-even is two calls for the 5-minute default, ~three for the 1-hour TTL.
Via the AI Gateway: when calling Claude through the Vercel AI SDK with
anthropic/...model strings (codeAmani's default — see the insight), passcache_controlthroughproviderOptions.anthropicso the marker reaches the underlying API. Caching is an Anthropic-side feature; the gateway forwards it but does not invent it.
Canonical reference: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
Environment Variables
# Required
ANTHROPIC_API_KEY=sk-ant-...
# Optional overrides
ANTHROPIC_BASE_URL=https://api.anthropic.com # default
ANTHROPIC_MODEL=claude-sonnet-4-6 # default model for claude CLI
ANTHROPIC_MAX_TOKENS=8096 # default max tokens
# Claude Code specific
CLAUDE_CODE_MAX_OUTPUT_TOKENS=32000Set in your shell profile or use a .env file with dotenv.
Automation Workflows
Claude Code Hooks
Hooks run shell commands automatically at lifecycle events. Configure in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo 'Tool: Bash about to run' >> .claude/audit.log"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $CLAUDE_FILE_PATH 2>/dev/null || true"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node scripts/notify-complete.js"
}
]
}
]
}
}Slash Commands
Create custom slash commands as markdown files in .claude/commands/:
mkdir -p .claude/commands.claude/commands/review.md:
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: /project:review src/api/auth.ts
Headless Automation with the SDK
Use the Claude API to automate code review in CI:
// 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 review = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 2048,
system: "You are a senior code reviewer. Be concise and actionable.",
messages: [{ role: "user", content: `Review this diff:\n\n${diff}` }],
});
console.log(review.content[0].text);Common Use Cases
| Use Case | Approach |
|---|---|
| Automated PR review | Fetch diff via gh, pipe to Claude API |
| Code generation | claude -p "Generate CRUD endpoints for User model" |
| Test generation | Hook on PostToolUse[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 | Export it in shell: export ANTHROPIC_API_KEY=sk-ant-... |
| Rate limit errors | Add retry logic with exponential backoff |
| MCP server not connecting | Run claude mcp list to verify registration |
| Hooks not firing | Check .claude/settings.json syntax with cat .claude/settings.json | jq . |
| Model not available | Check available models at docs.anthropic.com/en/docs/about-claude/models |