Claude Agent SDK
A complete Claude Agent SDK tutorial in TypeScript: install the package, run a bounded code-review agent, stream its messages, and record estimated cost safely.
Stop configuring. Start building.
SaaS builder templates with AI orchestration.
The Claude Agent SDK lets a TypeScript program run the same tool-using loop that powers Claude Code. Your program can ask Claude to inspect a repository, run approved commands, and return a result without keeping a terminal chat open.
This tutorial builds a bounded code-review agent. It can read and search a repository, run its existing checks, and report findings. It cannot edit files or quietly approve an unknown tool.
What the Agent SDK does
The Agent SDK is Claude Code packaged as a library. Anthropic's current SDK overview says it includes the built-in file, shell, and editing tools plus the agent loop and context management. You decide which tools the agent sees and how your program handles its messages.
That makes the SDK different from a normal model API call. A normal call returns text. An agent call may read a file, search for a symbol, run a test command, inspect the result, and then decide what to do next.
| Use case | Better starting point |
|---|---|
| One shell command | claude -p |
| A CI step with JSON output | claude -p |
| Typed messages in TypeScript | Agent SDK |
| Runtime permission decisions | Agent SDK |
| A reusable product feature | Agent SDK |
| A full build pipeline with specialist roles | Code Kit or another harness |
The existing Claude Code headless mode guide covers the CLI path. Stay with claude -p until a shell script becomes awkward. Moving to a library too early gives you more code to own without changing the result.
Final file tree
The finished project has one agent, one configuration file, and no framework dependency. It runs against whichever repository you launch it from.
claude-review-agent/
├── src/
│ └── agent.ts
├── .env.example
├── package.json
└── tsconfig.jsonCreate the project
Anthropic's Agent SDK quickstart currently requires Node.js 18 or newer and installs @anthropic-ai/claude-agent-sdk. The project uses ES modules because the SDK returns an async stream and top-level module behavior keeps the runner simple.
Run these commands in an empty directory. They create the package, install the SDK, and add tsx so Node can execute TypeScript without a separate build step during development.
mkdir claude-review-agent
cd claude-review-agent
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev typescript tsx @types/node
mkdir srcThe package needs two explicit commands. npm run review executes the agent, while npm run typecheck catches SDK option or message-shape mistakes before the first paid request.
Let npm preserve the dependency versions it just installed, then add only the scripts. This avoids copying a stale SDK version from an article into a new project.
npm pkg set scripts.review="tsx src/agent.ts"
npm pkg set scripts.typecheck="tsc --noEmit"The TypeScript configuration is deliberately strict. It uses Node's modern module resolution and emits nothing because tsx handles execution.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}Set up authentication
The safest local setup is to authenticate through the installed Claude Code client and confirm the account before running the script. For a hosted process, use the credential method documented for that environment rather than committing a secret.
The example file names the variable a deployment may need but contains no real key. Copy it to .env only if your chosen authentication path requires it, and keep .env out of Git.
ANTHROPIC_API_KEY=replace_with_your_own_keyDo not paste credentials into the TypeScript file. An agent can read its working directory, so secret scope matters as much as Git hygiene.
Build the review agent
The agent below accepts a review goal as command-line text. It exposes only Read, Glob, Grep, and Bash, blocks all file-editing tools, limits the run to eight agent turns, and prints the final result plus Anthropic's estimated SDK cost.
The cost value is useful for comparing runs, but it is not an invoice. Anthropic's cost tracking documentation says the SDK calculates it locally from a bundled price table, so the authoritative number still lives in the Claude Console or provider billing system.
import { query } from "@anthropic-ai/claude-agent-sdk";
const requestedReview = process.argv.slice(2).join(" ").trim();
if (!requestedReview) {
console.error(
'Usage: npm run review -- "Review the authentication code for security bugs"',
);
process.exit(1);
}
const prompt = `
You are reviewing the repository in the current working directory.
Goal:
${requestedReview}
Rules:
- Read the smallest relevant set of files.
- Run existing read-only checks when they help.
- Do not modify any file.
- Report only findings supported by a file path and line number.
- For each finding, explain the failure mode and the smallest safe fix.
- If you find no material issue, say so and list what you checked.
`.trim();
let finalResult = "";
let estimatedCostUsd: number | undefined;
let failed = false;
for await (const message of query({
prompt,
options: {
cwd: process.cwd(),
model: "sonnet",
allowedTools: ["Read", "Glob", "Grep", "Bash"],
disallowedTools: ["Write", "Edit", "NotebookEdit"],
permissionMode: "dontAsk",
maxTurns: 8,
},
})) {
if (message.type === "result") {
finalResult = message.result;
estimatedCostUsd = message.total_cost_usd;
failed = message.subtype !== "success";
}
}
if (finalResult) {
process.stdout.write(`${finalResult}\n`);
}
if (typeof estimatedCostUsd === "number") {
process.stderr.write(
`Estimated SDK cost: $${estimatedCostUsd.toFixed(4)}\n`,
);
}
if (failed) {
process.exitCode = 1;
}dontAsk matters here. According to Anthropic's SDK permission guide, that mode denies tools that would otherwise require a prompt. An unattended job should fail closed instead of waiting forever or granting itself broader access.
There is one subtle limit in this example. Bash is available because the reviewer may need to run a repository's test or type-check command. The prompt says read-only, but a malicious package script could still write files. Run unknown repositories inside a disposable environment and tighten command permissions before using this in a service.
Run it against a repository
First run the type checker from the agent project. This catches local code problems without spending model tokens.
npm run typecheckThen launch the agent from the repository you want it to inspect. The simplest approach is to keep the runner inside that repository or set cwd to an explicit, validated path in your own wrapper.
npm run review -- \
"Review the authentication flow for missing ownership checks and unsafe redirects"A good result cites the evidence instead of dumping general advice. If the answer says "validate inputs" without naming the affected file and condition, strengthen the prompt before adding more tools.
Add a hard budget
Turn limits bound the number of agent steps, not the exact price. Model choice, context size, tool output, and cache behavior all affect cost. The Claude Code cost guide explains when subscription access and API billing fit different workloads.
For a first production test, wrap the agent in an external job budget as well. Stop scheduling new runs once your provider's authoritative usage reaches the limit, and keep maxTurns low until you have real measurements from your repository.
const reviewPolicy = {
model: "sonnet",
maxTurns: 8,
allowedTools: ["Read", "Glob", "Grep", "Bash"],
disallowedTools: ["Write", "Edit", "NotebookEdit"],
} as const;
export default reviewPolicy;This policy object is not magic enforcement by itself. It becomes useful when every entry point imports the same object instead of inventing permissions for each job.
Move from review to edits
Do not change disallowedTools and hope for the best. An editing agent needs a different permission policy, a disposable branch or worktree, a test command, and a human review step before merge.
A safe progression looks like this:
- Read-only review with cited findings.
- Plan mode that proposes exact changes.
- Edits in an isolated branch.
- Type check, lint, tests, and production build.
- Human diff review.
Anthropic documents hooks and runtime approval callbacks for finer control. Add them when the agent must cross a real boundary, such as editing a migration, calling a payment API, or deploying. Never use broad bypass permissions because a job is inconvenient to configure.
Agent SDK versus a build harness
The SDK gives you primitives. You still own prompts, role boundaries, retries, test orchestration, state, logs, and the definition of "done." That is a reasonable trade if the agent itself is your product.
A build harness sits one level up. The Code Kit orchestration docs show the other shape: planning hands work to focused builders, evaluators check it, browser and API tests run, and quality gates require zero type errors, zero lint errors, and a clean build.
The difference is easiest to see in the failure path. The SDK reports that a test failed. A harness decides which specialist should diagnose it, applies the fix in the right context, reruns the test, and refuses to finish while the gate is red.
Frequently asked questions
What is the Claude Agent SDK?
The Claude Agent SDK is Anthropic's TypeScript and Python library for embedding Claude Code's agent loop in a program. It includes built-in tools, context management, streamed messages, permissions, hooks, and usage information.
Should I use claude -p or the Agent SDK?
Use claude -p when a shell command is enough. Choose the Agent SDK when your application needs typed message handling, sessions, runtime approvals, custom tools, or detailed programmatic control.
How do I stop an SDK agent from changing files?
Do not expose editing tools. Use a restrictive permission mode, list the tools the job actually needs, explicitly disallow Write, Edit, and NotebookEdit, and run untrusted code in an isolated environment.
The $29 Code Kit is a one-time harness on top of Claude Code, not another model subscription. It supplies the plan, build, evaluate, test, and quality-gate pipeline when you would rather ship the product than maintain that orchestration yourself. Claude Code still requires a paid Anthropic plan, and your plan or API usage is separate.
Posted by @speedy_devv
Stop configuring. Start building.
SaaS builder templates with AI orchestration.