# Agent SDK

> Run the KazoCode coding agent from Node with @kazocode/sdk - in scripts, CI and your own apps - with file, search, shell and web tools, permission modes and custom tools.

`@kazocode/sdk` runs KazoCode's coding agent from Node, with the same file, search, shell and web tools, permission modes and `KAZO.md` instructions as the editor. Use it in scripts, CI jobs, bots or your own apps. The same package has the APIs for [extensions](https://kazocode.app/docs/sdk/extensions.md), [plugins and mods](https://kazocode.app/docs/sdk/plugins.md), and the [`kazocode-sdk` command](https://kazocode.app/docs/sdk/cli.md).

It needs Node 22 or later and has no runtime dependencies.

```sh
npm install @kazocode/sdk
```

## Run the agent

```ts
import { query, anthropic } from "@kazocode/sdk";

for await (const event of query({
  prompt: "Find why the date parser fails on leap years and fix it",
  provider: anthropic(), // reads ANTHROPIC_API_KEY
  model: "claude-opus-5-5",
  cwd: "./my-project",
  permissionMode: "acceptEdits",
})) {
  if (event.type === "text") process.stdout.write(event.text);
  if (event.type === "tool_use") console.log(`\n→ ${event.name}`, event.input);
  if (event.type === "result") console.log(`\nDone in ${event.turns} turns`);
}
```

`query` starts a fresh conversation. For several messages in one conversation, use `Agent`:

```ts
import { Agent, openai } from "@kazocode/sdk";

const agent = new Agent({ provider: openai(), model: "gpt-5", cwd: process.cwd() });
const { text } = await agent.run("What does src/server.ts do?");
await agent.run("Add a /health route to it");

const resumed = new Agent({ provider: openai(), model: "gpt-5" }, agent.messages);
```

Save `agent.messages` and pass them back later to continue a conversation. Pass an `AbortSignal` as `signal` to stop a run.

## Events

| Event | When |
| --- | --- |
| `text` | A piece of the answer as it streams |
| `assistant` | A whole model turn: its text and tool calls |
| `tool_use` | The agent calls a tool |
| `tool_result` | The tool's output (`isError` when it failed or was refused) |
| `usage` | Tokens used by one model turn |
| `result` | The final answer, total tokens, number of turns and why it stopped (`end`, `max_turns`, `aborted`, …) |
| `error` | The provider failed (bad key, network, rate limit) |

## Providers

| Function | Model API |
| --- | --- |
| `anthropic({ apiKey?, baseUrl? })` | Claude through the Messages API. Reads `ANTHROPIC_API_KEY` by default |
| `openai({ apiKey?, baseUrl?, headers? })` | Any OpenAI-compatible Chat Completions API. Reads `OPENAI_API_KEY` by default |
| `openrouter()`, `groq()` | Those services, reading `OPENROUTER_API_KEY` and `GROQ_API_KEY` |
| `ollama({ baseUrl? })` | A local Ollama server. Use a model with tool support |

A provider is any object with a `complete(request)` method, so you can wrap another API yourself.

## Permissions

| `permissionMode` | Reads | Edits | Commands and network |
| --- | --- | --- | --- |
| `default` | run | ask | ask |
| `acceptEdits` | run | run | ask |
| `plan` | run | refused | refused |
| `bypassPermissions` | run | run | run |

"Ask" calls your `canUseTool` callback. Without one, the call is refused and the agent is told why.

```ts
new Agent({
  provider: anthropic(),
  model: "claude-opus-5-5",
  canUseTool: async ({ name, input }) => {
    if (name === "bash" && String(input.command).startsWith("npm test")) return true;
    return { behavior: "deny", message: "Only npm test is allowed here." };
  },
});
```

Tools can't read or write outside `cwd` unless you set `allowOutsideCwd: true`. `onToolCall` runs before every call and can block it (`{ block: "reason" }`) or change its input (`{ input }`); `onToolResult` sees every result.

## Tools

The agent gets `read_file`, `write_file`, `edit_file`, `list_files`, `grep`, `bash` and `web_fetch`. Add your own with `defineTool`:

```ts
import { Agent, anthropic, defaultTools, defineTool } from "@kazocode/sdk";

const ticket = defineTool<{ id: string }>({
  name: "get_ticket",
  description: "Reads a ticket from our tracker",
  risk: "network",
  parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
  async run({ id }) {
    const response = await fetch(`https://tracker.example.com/api/tickets/${id}`);
    return await response.text();
  },
});

new Agent({ provider: anthropic(), model: "claude-opus-5-5", tools: [...defaultTools(), ticket] });
```

A tool returns a string, or `{ output, isError: true }` to tell the agent it failed. Thrown errors become failed results too.

## Instructions

Like the editor, the agent reads `~/.kazocode/KAZO.md`, then `KAZO.md`, `AGENTS.md` or `CLAUDE.md` in the project and its parent folders, and `KAZO.local.md`. Set `instructions: false` to skip them, `systemPrompt` to replace KazoCode's prompt, or `appendSystemPrompt` to add to it.
