The Claude Agent SDK is the Claude Code harness as a library — the agent loop, built-in Read/Edit/Bash/Glob/Grep tools, permissions and context management, called from your own script. It is a different package from the Anthropic API SDK.
1. Install
Node.js 18 or later.
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
What it does: "type": "module" lets your script use top-level await, and tsx runs
TypeScript directly with no build step. The SDK ships a native Claude Code binary through
npm optional dependencies — an install that skips them (npm ci --omit=optional) gets no
binary, so reinstall without the flag or point pathToClaudeCodeExecutable at a native
install. In an existing CommonJS project, name the script agent.mts instead.
2. Set the key
export ANTHROPIC_API_KEY=your-api-key
$env:ANTHROPIC_API_KEY = "your-api-key"
What it does: authenticates the agent. The SDK reads the variable from the process
environment and does not load .env files on its own.
3. Write the agent
agent.ts:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Review utils.ts for bugs that would cause crashes. Fix any issues you find.",
options: {
allowedTools: ["Read", "Edit", "Glob"],
permissionMode: "acceptEdits",
},
})) {
if (message.type === "assistant" && message.message?.content) {
for (const block of message.message.content) {
if ("text" in block) console.log(block.text);
else if ("name" in block) console.log(`Tool: ${block.name}`);
}
} else if (message.type === "result") {
console.log(`Done: ${message.subtype}`);
}
}
What it does: query() returns an async generator of messages, so for await streams
Claude’s reasoning, each tool call, and finally the outcome. allowedTools pre-approves
those three tools; anything else falls through to permissionMode.
4. Run it
npx tsx agent.ts
What it does: executes the loop against the current directory and its subdirectories. Check the file on disk afterwards — a changed file is the only proof that matters.
5. Read the result
The result message is the one to log or persist. On subtype: "success" it carries
result (the final text), plus num_turns, duration_ms, is_error, session_id and
total_cost_usd. Treat total_cost_usd as a client-side estimate computed from a bundled
price table, not a billing statement.
Other options worth knowing: systemPrompt, maxTurns, cwd, model, and mcpServers
to hand the agent external tools.
Next: the same agent in Python or run Claude Code headless in CI.