Build This Now
Build This Now
Qu'est-ce que le code Claude ?Installer Claude CodeL'installateur natif de Claude CodeTon premier projet Claude Code
Subscription BillingMulti-Tenant SaaSAI Chat FeatureRate LimitingStripe WebhooksSemantic SearchRealtime UpdatesDrip Email Sequencesv2.1.122 Release NotesClaude Code Dynamic Workflows : comment orchestrer 1 000 sous-agents sur une vraie codebaseBonnes pratiques Claude CodeMeilleures pratiques pour Claude Opus 4.7Claude Code sur un VPSIntégration GitRevue de code avec Claude CodeLes Worktrees avec Claude CodeClaude Code à distanceClaude Code ChannelsChannels, Routines, Teleport, DispatchTâches planifiées avec Claude CodePermissions Claude CodeLe mode auto de Claude CodeAjouter les paiements Stripe avec Claude CodeFeedback LoopsWorkflows TodoGestion des tâches dans Claude CodeTemplates de projetTarification et utilisation des tokens Claude CodeTarifs de Claude Code : ce que tu vas vraiment payerClaude Code Ultra ReviewConstruire une app Next.js avec Claude CodeSupabase DatabaseVercel DeepsecTest-Driven DevelopmentConstruire un MVP SaaS avec Claude CodeAjouter l'authentification avec Claude Code (Supabase Auth)Ajouter les emails transactionnels avec Claude Code (Resend + React Email)Construire une API type-safe avec Claude Code (oRPC + Zod)File UploadsBackground Jobs (Inngest)Admin DashboardFull-Text SearchClaude Agent SDKKiro Migration GuideClaude Research AgentLeave Grok BuildRoute Subagent ModelsClaude Monorepo SetupCI Repair AgentVisual Regression TestsAgent Cost DashboardCursor Migration GuideCommerce agentique : comment construire une app que les agents IA peuvent payer1M ContextUser API KeysAudit LogsCSV Import PipelineDatabase MigrationsProduction Error TrackingFeature FlagsGitHub ActionsHeadless ModeMax Plan vs APICaching and RevalidationIn-App NotificationsOutbound WebhooksPrompt CachingRoles & PermissionsMarketplace PaymentsUsage-Based BillingCombien coûte la création d'un SaaS avec Claude Code en 2026Parallel AI AgentsCoding Agent Injection
speedy_devvkoen_salo
Blog/Handbook/Workflow/Claude Agent SDK

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.

Arrête de tout configurer. Place à la construction.

Des templates SaaS avec orchestration IA.

Découvrez ce que nous construisons pour les entreprises →
speedy_devvWritten by speedy_devvPublished Jul 26, 202611 min readHandbook hubWorkflow index

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 caseBetter starting point
One shell commandclaude -p
A CI step with JSON outputclaude -p
Typed messages in TypeScriptAgent SDK
Runtime permission decisionsAgent SDK
A reusable product featureAgent SDK
A full build pipeline with specialist rolesCode 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.json

Create 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 src

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

Do 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 typecheck

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

  1. Read-only review with cited findings.
  2. Plan mode that proposes exact changes.
  3. Edits in an isolated branch.
  4. Type check, lint, tests, and production build.
  5. 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

Continue in Workflow

  • Commerce agentique : comment construire une app que les agents IA peuvent payer
    Un guide en français simple du commerce agentique en 2026 : ce que font x402, ACP et le Machine Payments Protocol, plus un pas-à-pas d'un week-end pour livrer une API payante que les agents IA peuvent acheter.
  • Bonnes pratiques Claude Code
    Cinq habitudes séparent les ingénieurs qui livrent avec Claude Code : les PRDs, les règles CLAUDE.md modulaires, les slash commands personnalisés, les resets /clear, et un état d'esprit d'évolution du système.
  • Le mode auto de Claude Code
    Un second modèle Sonnet examine chaque appel d'outil Claude Code avant qu'il s'exécute. Ce que le mode auto bloque, ce qu'il autorise, et les règles d'autorisation qu'il place dans tes paramètres.
  • Channels, Routines, Teleport, Dispatch
    Les quatre fonctionnalités Claude Code livrées par Anthropic en mars et avril 2026 qui transforment le CLI en une couche de coordination orientée événements, entre téléphone, web et desktop.
  • Claude Code 1M Context in Practice: When Bigger Isn't Better
    The 1M-token context window is GA at flat pricing, but bigger isn't always better. A decision framework, token-cost math, and when to use /compact, subagents, and dynamic workflows instead.
  • How to Build an Admin Dashboard With Claude Code
    Ship an internal admin panel with Claude Code: role-gated routes, a searchable users and orders table with pagination, impersonation-safe RLS, and metrics tiles pulled through a type-safe API.

More from Handbook

  • Principes de base de l'agent
    Cinq façons de construire des agents spécialisés dans le code Claude : Sous-agents de tâches, .claude/agents YAML, commandes slash personnalisées, personas CLAUDE.md, et invites de perspective.
  • L'ingénierie du harness agent
    Le harness, c'est toutes les couches autour de ton agent IA sauf le modèle lui-même. Découvre les cinq leviers de contrôle, le paradoxe des contraintes, et pourquoi le design du harness détermine les performances de l'agent bien plus que le modèle.
  • Patterns d'agents
    Orchestrateur, fan-out, chaîne de validation, routage par spécialiste, raffinement progressif, et watchdog. Six formes d'orchestration pour câbler des sub-agents Claude Code.
  • Meilleures pratiques des équipes d'agents
    Patterns éprouvés pour les équipes d'agents Claude Code. Prompts de création riches en contexte, tâches bien calibrées, propriété des fichiers, mode délégué, et correctifs v2.1.33-v2.1.45.

Arrête de tout configurer. Place à la construction.

Des templates SaaS avec orchestration IA.

Découvrez ce que nous construisons pour les entreprises →

Full-Text Search

Build fast in-app search without a new service. Postgres tsvector columns, GIN indexes, ranking, a debounced React UI, and RLS-safe results through oRPC.

Kiro Migration Guide

Migrate Kiro to Claude Code without losing steering files, feature specs, hooks, or MCP servers. This guide maps each Kiro artifact to a working Claude Code equivalent.

On this page

What the Agent SDK does
Final file tree
Create the project
Set up authentication
Build the review agent
Run it against a repository
Add a hard budget
Move from review to edits
Agent SDK versus a build harness
Frequently asked questions
What is the Claude Agent SDK?
Should I use claude -p or the Agent SDK?
How do I stop an SDK agent from changing files?

Arrête de tout configurer. Place à la construction.

Des templates SaaS avec orchestration IA.

Découvrez ce que nous construisons pour les entreprises →