Skip to content

Claude Agent SDK in TypeScript: A Practical First Agent

Build a working AI agent with the Claude Agent SDK in TypeScript: install it, stream messages, add a custom Zod tool, and pick a safe permission mode.

· · 8 min read

Updated: November 25, 2026

Table of Claude Agent SDK permission modes in TypeScript and what each one does with a tool call

Quick Take

The Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) exposes Claude Code's actual agent loop as a TypeScript library: multi-turn reasoning, built-in tools, and session state, callable from `query()` instead of a CLI. Add your own tools with `tool()` and a Zod schema, limit what exists with `tools`, and pair an explicit `allowedTools` list with `permissionMode: 'dontAsk'` until you trust what you've built.

A note on evidence: both snippets below were type-checked on November 25, 2026 against @anthropic-ai/claude-agent-sdk 0.3.332 with TypeScript 7.0.2 under strict, and the permission rules are taken from Anthropic's SDK documentation as it read that day. No agent run is reported here, so there's no output to show.

Put Bash in allowedTools, point the agent at a repo with a half-finished migration script in it, and it can run npm run migrate without asking anyone, because pre-approving a tool means exactly that. Picture that on a branch you care about and you've understood the main thing about this SDK: the agent it gives you acts on the machine it runs on.

Claude Agent SDK vs the Claude API

The plain Claude API gives you one thing: a request goes in, a response comes back. Multi-step reasoning, tool calls, and file access are all things you build yourself on top of it. The Claude Agent SDK sits a layer above that: it's the same agent loop that powers Claude Code, packaged as an npm library you call from your own Node process.

Install it with npm install @anthropic-ai/claude-agent-sdk. That single package gives you query(), the built-in tool set (Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch), permission hooks, and session resume, all without shelling out to a CLI binary. If you've used Claude Code from the terminal, this is that same engine, embedded in your own TypeScript code instead of a chat interface.

Getting an Anthropic API key

You need a key before any of the code below will run. The quickstart is brief about it: create one in the Claude Console, then export it in the shell that runs your agent.

export ANTHROPIC_API_KEY=your-api-key

Two details from the same page save a confused first run. The SDK reads the key from the process environment and "doesn't load .env files automatically", so if you keep it in .env, load it yourself with something like dotenv. And Node.js 18.14 or newer is the stated minimum. Billing is per token, the same as any other API usage, which is why a spend limit on the workspace is worth setting before an agent loop starts retrying a failing tool call.

Can you skip the key and reuse a Claude subscription login? Not for something you ship: the docs say third-party developers may not offer claude.ai login for products built on the SDK. Bedrock, Google Cloud and Foundry credentials are the documented alternatives.

Install it and run a first agent

Set your API key, install the package, and call query(). It returns an async generator, so you stream messages with a plain for await loop:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "List the TypeScript files in this project and summarize what each one does.",
  options: {
    cwd: process.cwd(),
    tools: ["Read", "Glob"],
    allowedTools: ["Read", "Glob"],
    permissionMode: "dontAsk",
  },
})) {
  if (message.type === "assistant") {
    console.log(message.message);
  }
  if (message.type === "result") {
    console.log("done:", message);
  }
}

Four options matter more than the rest on your first run, and they work on two different layers.

tools is availability. With tools: ["Read", "Glob"], only those built-ins are in Claude's context; Bash, Write and Edit aren't there to call. This is the option the permissions docs and quickstart point to when you want to limit the built-in set.

allowedTools is permission. It pre-approves the tools it lists, so Read and Glob run without a prompt. On its own it isn't a fence: the docs put it bluntly, any tool not listed "is still available to Claude", and a call to it that needs approval falls through to the permission mode and then to a canUseTool callback, if you passed one.

permissionMode: "dontAsk" turns every would-be prompt into a denial. Is that a complete lock? No. Calls that need no approval in the first place still run, and the docs name read-only Bash commands, the Agent tool and file reads inside your working directories. That's why this example sets tools as well.

cwd sets the working directory. It isn't a sandbox. Reads inside it need no approval; a read outside it would prompt, which dontAsk denies.

A custom tool with tool() and Zod

Built-in tools cover file access and shell commands. For anything domain-specific, an internal API, a database query, a linter you wrote, you define your own with tool() and a Zod schema:

import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const lintCheck = tool(
  "lint_check",
  "Run the project's ESLint config against a file path and return violations",
  { filePath: z.string() },
  async ({ filePath }) => {
    const violations = await runEslint(filePath); // your own function
    return {
      content: [{ type: "text", text: JSON.stringify(violations) }],
    };
  },
);

const devTools = createSdkMcpServer({
  name: "dev-tools",
  tools: [lintCheck],
});

for await (const message of query({
  prompt: "Check src/index.ts for lint violations and explain the worst one.",
  options: {
    mcpServers: { "dev-tools": devTools },
    allowedTools: ["mcp__dev-tools__lint_check"],
  },
})) {
  console.log(message);
}

The Zod schema does double duty here. It validates the arguments Claude sends before your handler ever runs, and TypeScript infers the handler's argument types straight from it, so filePath is a string with zero manual typing. The description string is the only thing the model sees when deciding whether to call this tool, so write it like documentation, not a variable name. Note the naming convention on the allowlist too: in-process tools get addressed as mcp__<server>__<tool>, and getting that string wrong is an easy way to end up with a custom tool that silently never fires. The agent just won't have it available, and nothing in the output says why. A server name written with a hyphen in mcpServers and an underscore in allowedTools is enough to do it.

Permission modes for production

Six modes exist in SDK 0.3.332: default, dontAsk, acceptEdits, plan, auto and bypassPermissions. The table gives what the docs say each one does with a call that needs approval.

ModeWhat happens
defaultno automatic approvals; a call that matches no allow rule goes to your canUseTool callback, and is denied if nothing approves it
dontAskthe call is denied without calling canUseTool; pre-approved tools still run
acceptEditsfile edits and filesystem commands such as mkdir, mv and rm inside the working directories are approved; other Bash still needs permission
planClaude explores and plans; edits made with its file tools go to canUseTool even when an allow rule matches
autoa classifier model reviews actions such as shell commands and network requests
bypassPermissionstools run without prompts, apart from a short list of actions no mode auto-approves

Most of the safety decisions sit between dontAsk and bypassPermissions. The docs carry a warning in bold: allowedTools does not constrain bypassPermissions. Set allowedTools: ["Read"] with that mode and calls to Bash, Write and Edit are still approved. Only deny rules, ask rules and hooks are checked before the mode.

For a CI script or a scheduled job, don't reach for bypassPermissions just because there's no human around to click "approve." The docs' own recipe for a locked-down agent is allowedTools plus permissionMode: "dontAsk", and I'd add tools (or disallowedTools: ["Bash"]) so the tools you don't want aren't offered at all. What about leaving it on default? With Claude Code 2.1.302 or later behind the SDK, a call that needs approval and has no allow rule, hook or callback to approve it is denied, so nothing hangs, but you're relying on a default instead of stating the rule. Reserve bypassPermissions for a throwaway container, not a real repo.

canUseTool is the callback for calls nothing else resolved. It's an async function you pass in options that receives the tool name and its input and returns allow or deny. One trap is documented and easy to walk into: a tool approved earlier never reaches it. List bare Bash in allowedTools and your callback won't see a single Bash call; the TypeScript SDK even emits a process warning with the code CLAUDE_SDK_CAN_USE_TOOL_SHADOWED when it spots that combination. If you want to inspect commands, either leave Bash out of allowedTools, pre-approve only a scoped rule such as Bash(npm test *), or put the check in a PreToolUse hook, which runs for approved calls too.

Where the SDK fits next to MCP and agent frameworks

If you've already built MCP servers for Claude Code or Cursor, nothing here replaces them, mcpServers in the query() options accepts the same external MCP servers over stdio or HTTP, alongside your in-process tool() definitions. The mechanics of that protocol are covered at the end of this section. And if you're comparing this against a framework-first approach instead of Anthropic's own SDK, Mastra and the Vercel AI SDK covers that other path, provider-agnostic, more scaffolding, less tied to Claude specifically. Moving one of these tools out into a standalone server later? The typed-schema side of that, and which spec version your client actually speaks, is in MCP spec versions and typed tools.

The tradeoff: the Claude Agent SDK gets you Claude Code's actual agent loop with almost no glue code, at the cost of being Anthropic-specific. If your product is committed to Claude anyway, that's not a real cost. If you need to swap models later, budget the time to rebuild this layer on something provider-agnostic. For a sense of scale, the two code examples in this guide come to under 50 lines of TypeScript together.

Frequently Asked Questions

What is the Claude Agent SDK, and how is it different from the Claude API?
The Claude API's Messages endpoint gives you one request, one response. You handle the loop, the tool-calling, and the file access yourself. The Claude Agent SDK wraps that same model access in the actual agent loop Claude Code runs: multi-turn reasoning, built-in tools (Read, Write, Edit, Bash, Glob, Grep, WebSearch), permission handling, and session management, all exposed as a TypeScript library instead of a CLI-only tool. Install it with npm install @anthropic-ai/claude-agent-sdk and you're calling query() in your own Node process, not shelling out to a binary.
Do I need an Anthropic API key to use the Claude Agent SDK?
Yes, for your own scripts. The quickstart has you create a key in the Claude Console and export it as ANTHROPIC_API_KEY in the shell that runs the agent; the SDK does not load .env files on its own. It also supports Amazon Bedrock, Google Cloud and Microsoft Foundry credentials. The docs state that third-party developers may not offer claude.ai login for products built on the SDK, so plan on API key billing, and cap maxTurns so a long-running agent can't run up cost unnoticed.
How do I stop the agent from running arbitrary Bash commands?
allowedTools alone won't do it: it only pre-approves the tools it lists, and a tool that isn't listed is still available and falls through to the permission mode and your canUseTool callback. To take Bash away, leave it out of the tools option or put its bare name in disallowedTools; both remove the tool from Claude's context. permissionMode 'dontAsk' denies every call that would otherwise prompt, but per the docs read-only Bash commands need no approval and still run, so dontAsk by itself is not a Bash ban. If you need Bash for one task, pre-approve a scoped rule such as Bash(npm test *) and check the rest in a PreToolUse hook.
Can I give the Claude Agent SDK my own custom tools?
Yes, that's most of the value over the plain CLI. The tool() helper takes a name, a description, a Zod schema for the input, and an async handler that returns { content: [...] }. Wrap one or more with createSdkMcpServer() and pass it into the mcpServers option on query(). The agent sees your tool exactly like a built-in one, the model decides when to call it based on your description string, so a vague description produces vague tool-calling behavior, and a specific one produces reliable results.
Is the Claude Agent SDK the same thing as MCP?
No, they're complementary. MCP (Model Context Protocol) is the open standard for exposing tools and resources to any AI client, Claude Code, Cursor, Claude Desktop, all speak it. The Claude Agent SDK is Anthropic's own library for running Claude's agent loop from TypeScript code, and it happens to have first-class MCP client support built in, so an agent built with the SDK can call both your in-process tool() functions and any external MCP server over stdio or HTTP in the same conversation.