← Back to dashboard
anthropicaifresh

Anthropic + Claude Code Integration Guide

What is an LLM API?

The real model

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.

Prompt-caching cost playground
Input tokens / month50M
Cache hit rate60%
Without caching (input only)$150/mo
With caching (reads 0.1×, writes 1.25×)$84/mo

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.

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

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


MCP Server Setup

Claude Code as an MCP Server

Claude Code itself can act as an MCP server, exposing its tools to other clients.

Bash
# Start Claude Code as an MCP server (stdio transport)
claude mcp serve

Building a Custom MCP Server with @anthropic-ai/mcpb

@anthropic-ai/mcpb is Anthropic's official MCP bundle tool for creating distributable local MCP servers.

Bash
npm install -g @anthropic-ai/mcpb

Create a new MCP bundle project:

Bash
mcpb init my-server
cd my-server
mcpb build
mcpb install   # installs the bundle into Claude Code

Connecting to the Official Claude Code MCP Server

Bash
# 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:

JSON
{
  "mcpServers": {
    "anthropic-code": {
      "command": "claude",
      "args": ["mcp", "serve"],
      "env": {}
    }
  }
}

Claude Code CLI Integration

Installation

Bash
npm install -g @anthropic-ai/claude-code

Key Commands

Bash
# 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/mcp

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

Bash
npm install @anthropic-ai/sdk
TypeScript
import 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

Bash
pip install anthropic
Python
import 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 toolssystemmessages, 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.

TypeScript
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. If cache_read_input_tokens stays 0 across repeated calls, a silent invalidator is in the prefix — new Date()/Date.now() in the system prompt, unsorted JSON.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 messages entry 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), pass cache_control through providerOptions.anthropic so 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

Bash
# 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=32000

Set 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:

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/:

Bash
mkdir -p .claude/commands

.claude/commands/review.md:

Markdown
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:

TypeScript
// 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 CaseApproach
Automated PR reviewFetch diff via gh, pipe to Claude API
Code generationclaude -p "Generate CRUD endpoints for User model"
Test generationHook on PostToolUse[Write] to auto-generate tests
Documentationclaude -p "Document all exported functions in src/"
Security scanningCombine with Semgrep output piped to Claude API
RefactoringUse --continue sessions for multi-step refactors

CLAUDE.md Configuration

Create CLAUDE.md at your project root to give Claude Code persistent context:

Markdown
# 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

IssueFix
ANTHROPIC_API_KEY not foundExport it in shell: export ANTHROPIC_API_KEY=sk-ant-...
Rate limit errorsAdd retry logic with exponential backoff
MCP server not connectingRun claude mcp list to verify registration
Hooks not firingCheck .claude/settings.json syntax with cat .claude/settings.json | jq .
Model not availableCheck available models at docs.anthropic.com/en/docs/about-claude/models