Open History to see the last commit
1---
2title: Claude Code
3id: claude-code-adapter
4order: 11
5description: "Use Claude Code as a chat backend in TanStack AI — agent harness with local tool execution, stateful coding sessions, and tool bridging via @tanstack/ai-claude-code."
6keywords:
7 - tanstack ai
8 - claude code
9 - claude agent sdk
10 - anthropic
11 - harness
12 - agent
13 - coding agent
14 - adapter
15---
16
17The Claude Code adapter runs [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (via the `@anthropic-ai/claude-agent-sdk`) as a chat backend. Unlike HTTP provider adapters, this is a **harness adapter**: Claude Code runs its own agent loop and executes its own tools — bash, file reads and edits, glob/grep search, web search — locally on your server. Each `chat()` call runs one full harness turn; the harness's tool activity streams back as already-resolved tool-call events your UI can render.
18
19> **Server-only.** The harness spawns the Claude Code runtime as a subprocess, so this adapter only works in a Node.js server environment — never in the browser. Treat it like giving Claude a shell on the machine it runs on, and configure permissions accordingly.
20
21## Installation
22
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24
25react: @tanstack/ai-claude-code
26vue: @tanstack/ai-claude-code
27solid: @tanstack/ai-claude-code
28svelte: @tanstack/ai-claude-code
29preact: @tanstack/ai-claude-code
30angular: @tanstack/ai-claude-code
31vanilla: @tanstack/ai-claude-code
32octane: @tanstack/ai-claude-code
33
34<!-- ::end:tabs -->
35
36A runnable demo lives at [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare) — pick Claude Code, Codex, or Grok Build in the UI, with session resume, the harness tool timeline, and tool bridging, wired into a TanStack Start app on Workers. For the same wiring on plain Node with durable, refresh-surviving runs (this adapter on Docker), see [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web).
37
38## Authentication
39
40Your laptop can already have `claude login`. A CI runner only has
41`ANTHROPIC_API_KEY`. The default `authMode` is `'api-key'`. Set `'host'`
42when you want `claude login`. See [Harness Auth](../sandbox/auth).
43
44```ts
45import { claudeCodeText } from "@tanstack/ai-claude-code"
46
47claudeCodeText("claude-opus-4-8")
48claudeCodeText("claude-opus-4-8", { authMode: "host" })
49```
50
51- `'api-key'` (default): inject `ANTHROPIC_API_KEY` (or pass `apiKey`).
52- `'host'`: use `claude login`. Do not inject `ANTHROPIC_API_KEY`.
53
54## Basic Usage
55
56```typescript
57import { chat } from "@tanstack/ai";
58import { claudeCodeText } from "@tanstack/ai-claude-code";
59
60const stream = chat({
61 adapter: claudeCodeText("claude-opus-4-8", {
62 cwd: "/path/to/project",
63 permissionMode: "acceptEdits",
64 }),
65 messages: [{ role: "user", content: "Fix the failing test in utils.test.ts" }],
66});
67```
68
69## Configuration
70
71| Option | Description |
72| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
73| `cwd` | Working directory for the harness session. Defaults to `process.cwd()`. |
74| `permissionMode` | Claude Code permission mode (`'default'`, `'acceptEdits'`, `'bypassPermissions'`, `'plan'`, `'dontAsk'`, `'auto'`). See the permissions note below. |
75| `allowedTools` | Built-in tools the harness may use without prompting (e.g. `['Read', 'Grep', 'Bash(npm test:*)']`). |
76| `disallowedTools` | Built-in tools removed from the harness entirely. |
77| `maxTurns` | Maximum harness-internal turns per run. |
78| `systemPromptMode` | `'append'` (default) keeps Claude Code's preset system prompt and appends your `systemPrompts`; `'replace'` sends yours as the entire prompt. |
79| `mcpServers` | Extra MCP servers passed through to the harness untouched. |
80| `authMode` | `'api-key'` (default) injects `ANTHROPIC_API_KEY`. `'host'` uses `claude login`. Also valid on `modelOptions`. See [Harness Auth](../sandbox/auth). |
81| `apiKey` | Anthropic API key for the harness subprocess. |
82| `env` | Extra environment variables for the harness subprocess. |
83| `pathToClaudeCodeExecutable` | Use a specific Claude Code executable instead of the SDK's bundled one. |
84| `streamPartials` | Emit true token-level deltas for text and tool-call arguments (default `true`). When `false`, both emit whole from the complete message. |
85| `canUseTool` | Custom permission handler; replaces the adapter's default handler. |
86| `settingSources` | Claude Code settings tiers to load. Default `['project']`: the workspace's `CLAUDE.md`, `.claude/skills`, and `.mcp.json` apply, and the host's `~/.claude` (plugins, hooks, skills) is not loaded. Pass `['user', 'project', 'local']` for CLI-equivalent behavior, or `[]` to load no settings. |
87
88**Permissions on headless servers.** Without an explicit `permissionMode` or `canUseTool`, the adapter installs a safe default handler: bridged TanStack tools always run, and any built-in tool call that would normally prompt a human is denied with guidance instead of hanging the request. To let the harness edit files or run commands, set `permissionMode: 'acceptEdits'` / `'bypassPermissions'`, or enumerate `allowedTools`.
89
90## Stateful Sessions
91
92Claude Code sessions are stateful — the harness keeps the full working context (files read, commands run, conclusions reached) between turns. The adapter surfaces the session id of every run as a custom stream event named `claude-code.session-id`; thread it back via `modelOptions.sessionId` to resume the session. When resuming, only the latest user message is sent — the harness already holds the prior context.
93
94The `claude-code.session-id` event payload also includes `skills`, an array of skills loaded during SDK initialization (or an empty array when none are reported).
95
96Server endpoint:
97
98```typescript
99import {
100 chat,
101 chatParamsFromRequest,
102 toServerSentEventsResponse,
103} from "@tanstack/ai";
104import { claudeCodeText } from "@tanstack/ai-claude-code";
105
106export async function POST(request: Request) {
107 const params = await chatParamsFromRequest(request);
108
109 // Extra fields the client puts in the connection `body` arrive here.
110 const sessionId =
111 typeof params.forwardedProps.sessionId === "string"
112 ? params.forwardedProps.sessionId
113 : undefined;
114
115 const stream = chat({
116 adapter: claudeCodeText("claude-opus-4-8", {
117 cwd: "/path/to/project",
118 permissionMode: "acceptEdits",
119 }),
120 messages: params.messages,
121 modelOptions: { sessionId },
122 });
123
124 return toServerSentEventsResponse(stream);
125}
126```
127
128Client (React) — capture the session id from the custom event and send it back on subsequent requests:
129
130```typescript
131import { useState } from "react";
132import { useChat } from "@tanstack/ai-react";
133import { fetchServerSentEvents } from "@tanstack/ai-client";
134
135function CodingAssistant() {
136 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
137
138 const { messages, sendMessage } = useChat({
139 connection: fetchServerSentEvents("/api/chat", () => ({
140 body: { sessionId },
141 })),
142 onCustomEvent: (name, value) => {
143 if (
144 name === "claude-code.session-id" &&
145 typeof value === "object" &&
146 value !== null &&
147 "sessionId" in value &&
148 typeof value.sessionId === "string"
149 ) {
150 setSessionId(value.sessionId);
151 }
152 },
153 });
154
155 // ... render messages; harness tool activity (Bash, Edit, Read, ...)
156 // arrives as regular tool-call parts with their results attached.
157}
158```
159
160Sessions are stored on the machine that ran them (`~/.claude/projects/`), so resuming only works on the same server instance. Pass `modelOptions: { forkSession: true }` alongside `sessionId` to branch a session instead of continuing it.
161
162## Tools
163
164Two kinds of tools flow through this adapter:
165
1661. **Built-in harness tools** (`Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebSearch`, ...) are executed by Claude Code itself. Their activity streams back as tool-call events with results already attached, so `useChat` UIs render them with no extra wiring — but your code never executes them.
167
1682. **Your TanStack tools** are bridged *into* the harness as an in-process MCP server. Define them as usual with `toolDefinition().server()`; the model sees them as `mcp__tanstack__<name>` and the adapter strips the prefix on the way back out, so events match the names you registered.
169
170```typescript
171import { z } from "zod";
172import { chat, toolDefinition } from "@tanstack/ai";
173import { claudeCodeText } from "@tanstack/ai-claude-code";
174
175const lookupTicket = toolDefinition({
176 name: "lookup_ticket",
177 description: "Look up an issue ticket by id",
178 inputSchema: z.object({ ticketId: z.string() }),
179}).server(async ({ ticketId }) => {
180 return { ticketId, status: "open", title: "Crash on startup" };
181});
182
183const stream = chat({
184 adapter: claudeCodeText("claude-opus-4-8"),
185 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
186 tools: [lookupTicket],
187});
188```
189
190**Client-side and approval-gated tools are not supported.** The harness executes tools inside a live subprocess, which cannot pause across HTTP requests to wait for a browser round-trip or a human approval. Passing a tool without a server `execute()` implementation — or one marked `needsApproval` — fails fast with a descriptive error. Run those tools outside the harness with a regular provider adapter.
191
192## Structured Output
193
194Pass `outputSchema` on `chat()`. Claude Code runs one harness turn, uses its native tools, and returns a typed object. The schema JSON is passed to `--json-schema` as inline JSON (the CLI rejects a file path). Tool activity and prose stream as usual. The object arrives as `structured-output.complete`, including when Claude delivers it through its built-in `StructuredOutput` tool.
195
196By default, the adapter loads only project settings (`--setting-sources project`). Workspace projections (instructions, skills, MCP config) are project-scoped, so they apply. The host's `~/.claude` is not loaded, so a local-process run does not pick up your personal skills and hooks. A cloned repo's `.claude/settings.json` and hooks apply to the run. Set `settingSources` to change this. The adapter does not pass `--bare`, because that flag ignores a host `claude login`.
197
198On local-process, Claude uses your host `claude login`. On Docker, pass `ANTHROPIC_API_KEY` in the process env. A container has no host login.
199
200```ts
201import { chat } from "@tanstack/ai"
202import { claudeCodeText } from "@tanstack/ai-claude-code"
203import { defineSandbox, withSandbox } from "@tanstack/ai-sandbox"
204import { dockerSandbox } from "@tanstack/ai-sandbox-docker"
205import { z } from "zod"
206
207const Report = z.object({
208 summary: z.string(),
209 filesChanged: z.array(z.string()),
210})
211
212const sandbox = defineSandbox({
213 id: "repo-report",
214 provider: dockerSandbox({ image: "node:22" }),
215})
216
217const report = await chat({
218 adapter: claudeCodeText("claude-opus-4-8"),
219 messages: [{ role: "user", content: "Review this repo." }],
220 outputSchema: Report,
221 middleware: [withSandbox(sandbox)],
222})
223
224report.summary
225```
226
227On the client, pass the same schema to `useChat` and read `final`. `partial` stays empty until the end.
228
229```tsx
230import { fetchServerSentEvents, useChat } from "@tanstack/ai-react"
231import { z } from "zod"
232
233const Report = z.object({
234 summary: z.string(),
235 filesChanged: z.array(z.string()),
236})
237
238function ReportView() {
239 const { final, isLoading } = useChat({
240 connection: fetchServerSentEvents("/api/repo-report"),
241 outputSchema: Report,
242 })
243
244 if (isLoading) return <p>The agent is inspecting the repo.</p>
245 if (!final) return null
246 return <p>{final.summary}</p>
247}
248```
249
250If you only need to extract JSON from a prompt and do not need a sandbox, use `@tanstack/ai-anthropic`. That path is faster.
251
252Full walkthrough, including the client: [Harness Agents](../structured-outputs/harnesses).
253
254## Limitations
255
256- **Server-only (Node).** The harness spawns a subprocess; Windows support is untested.
257- **The harness owns the agent loop.** TanStack's agent-loop strategies and per-iteration middleware don't apply inside a harness turn; `maxTurns` is the equivalent control.
258- **No sampling controls.** `temperature`-style options don't exist here.
259- **Sessions are machine-local.** Resume requires hitting the same server instance.
260- **Cold starts.** Each call spawns a harness turn; expect higher first-token latency than HTTP adapters.