Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

claude-code.md

453 lines17.2 KB

1---
2title: Claude Code
3id: claude-code-adapter
4order: 11
5description: "Run Anthropic's Claude Code agent inside a sandbox from TanStack AI. It reads, edits, and runs code in a real repo and streams each step to your UI."
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 the `claude` CLI in a sandbox and streams each step to `chat()`. The agent reads files, edits them, and runs commands in a repo.
18​
19You need:
20​
21- A sandbox provider. The samples use Docker, so Docker must run on your machine.
22- An Anthropic API key, or a `claude login` on the machine.
23- The `claude` CLI inside the sandbox. A setup step in the sandbox installs it.
24​
25Do you only want a Claude chat, with no repo and no shell? Use the [Anthropic adapter](./anthropic).
26​
27## 1. Install
28​
29<!-- ::start:tabs variant="package-manager" mode="install" -->
30​
31react: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
32vue: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
33solid: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
34svelte: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
35preact: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
36angular: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
37vanilla: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
38octane: @tanstack/ai-claude-code @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
39​
40<!-- ::end:tabs -->
41​
42## 2. Set the API key
43​
44Put the key in the environment of your server:
45​
46```bash
47ANTHROPIC_API_KEY=sk-ant-...
48```
49​
50The sandbox in step 3 gives this key to the `claude` process as a workspace secret.
51​
52Did the machine already run `claude login`? Then you can use that login and no key. See [Harness Auth](../sandbox/auth).
53​
54## 3. Run the agent from the server
55​
56Define the sandbox once. It clones your repo into a Docker container and installs the `claude` CLI:
57​
58```ts
59// sandbox.ts
60import {
61 createSecrets,
62 defineSandbox,
63 defineWorkspace,
64 githubRepo,
65} from "@tanstack/ai-sandbox";
66import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
67​
68export const sandbox = defineSandbox({
69 id: "claude-code-agent",
70 provider: dockerSandbox({ image: "node:22" }),
71 workspace: defineWorkspace({
72 source: githubRepo({ repo: "owner/app" }),
73 setup: [
74 "npm install -g @anthropic-ai/claude-code --include=optional && claude --version",
75 ],
76 secrets: createSecrets({
77 ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY ?? "",
78 }),
79 }),
80});
81```
82​
83Then pass the adapter and the sandbox to `chat()` in your route:
84​
85```ts
86// api/agent.ts
87import {
88 chat,
89 chatParamsFromRequest,
90 toServerSentEventsResponse,
91} from "@tanstack/ai";
92import { claudeCodeText } from "@tanstack/ai-claude-code";
93import { withSandbox } from "@tanstack/ai-sandbox";
94import { sandbox } from "./sandbox";
95​
96export async function POST(request: Request) {
97 const { messages, threadId, runId } = await chatParamsFromRequest(request);
98​
99 const stream = chat({
100 adapter: claudeCodeText("claude-opus-4-8"),
101 messages,
102 threadId,
103 runId,
104 middleware: [withSandbox(sandbox)],
105 });
106​
107 return toServerSentEventsResponse(stream);
109```
110​
111Replace `owner/app` with your repo.
112​
113## 4. Render the agent's work
114​
115The client is the same as for any chat. Render the text, and show each tool that the agent ran:
116​
117```tsx
118import { useState } from "react";
119import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
120​
121export function CodingAgent() {
122 const [input, setInput] = useState("");
123 const { messages, sendMessage } = useChat({
124 connection: fetchServerSentEvents("/api/agent"),
125 threadId: "support-chat",
126 });
127​
128 return (
129 <form
130 onSubmit={(event) => {
131 event.preventDefault();
132 sendMessage(input);
133 setInput("");
134 }}
135 >
136 {messages.map((message) =>
137 message.parts.map((part, index) => {
138 if (part.type === "text") {
139 return <p key={`${message.id}-${index}`}>{part.content}</p>;
140 }
141 if (part.type === "tool-call") {
142 return <code key={part.id}>{part.name}</code>;
143 }
144 return null;
145 }),
146 )}
147 <input value={input} onChange={(event) => setInput(event.target.value)} />
148 </form>
149 );
151```
152​
153Ask it "Fix the failing test in utils.test.ts". You see the agent's text, plus a line for each tool it used: `Read`, `Edit`, `Bash`, and more. The agent edited the files inside the container.
154​
155## How it works
156​
157- `claudeCodeText` declares that it needs a sandbox. `withSandbox(sandbox)` gives it one. Without a sandbox, `chat()` fails at the call site.
158- Each `chat()` call runs one full agent turn. Claude Code runs its own loop and its own tools.
159- The tools of the agent stream back as `tool-call` parts with the results attached. Your code does not run them.
160- The agent runs with `permissionMode: 'bypassPermissions'` by default. The sandbox is the safety boundary. To limit what the agent can do, add a sandbox [Policy](../sandbox/policy).
161- When the run ends, the adapter sends a `file.changed` custom event with the `git diff` of the workspace.
162​
163To learn more about sandboxes, see [Sandboxes](../sandbox/overview).
164​
165## Resume a session
166​
167Claude Code keeps its working context between turns: the files it read, the commands it ran, and what it found. The adapter sends the session id of each run as a custom event named `claude-code.session-id`. Send it back in `modelOptions.sessionId` to continue the session.
168​
169On the server, read the id from the request:
170​
171```ts
172import {
173 chat,
174 chatParamsFromRequest,
175 toServerSentEventsResponse,
176} from "@tanstack/ai";
177import { claudeCodeText } from "@tanstack/ai-claude-code";
178import { withSandbox } from "@tanstack/ai-sandbox";
179import { sandbox } from "./sandbox";
180​
181export async function POST(request: Request) {
182 const params = await chatParamsFromRequest(request);
183​
184 // The client sends the id in `forwardedProps`.
185 const sessionId =
186 typeof params.forwardedProps.sessionId === "string"
187 ? params.forwardedProps.sessionId
188 : undefined;
189​
190 const stream = chat({
191 adapter: claudeCodeText("claude-opus-4-8"),
192 messages: params.messages,
193 threadId: params.threadId,
194 runId: params.runId,
195 middleware: [withSandbox(sandbox)],
196 modelOptions: { sessionId },
197 });
198​
199 return toServerSentEventsResponse(stream);
201```
202​
203On the client, keep the id from the custom event and pass it to `forwardedProps`. `useChat` sends the latest value with each request:
204​
205```tsx
206import { useState } from "react";
207import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
208​
209export function useCodingAgent() {
210 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
211​
212 return useChat({
213 connection: fetchServerSentEvents("/api/agent"),
214 forwardedProps: { sessionId },
215 threadId: "support-chat",
216 onCustomEvent: (name, value) => {
217 if (
218 name === "claude-code.session-id" &&
219 typeof value === "object" &&
220 value !== null &&
221 "sessionId" in value &&
222 typeof value.sessionId === "string"
223 ) {
224 setSessionId(value.sessionId);
225 }
226 },
227 });
229```
230​
231- On a resumed session, the adapter sends only the latest user message. The agent already has the rest.
232- The event value also has `skills`: the skills that Claude Code loaded when it started. It is an empty array when Claude Code reports none.
233- Claude Code saves the session inside the sandbox. Resume works only when the next call runs in the same sandbox. See [Lifecycle & Snapshots](../sandbox/lifecycle).
234​
235## Give the agent your own tools
236​
237The agent has its own tools for files and the shell. It cannot reach your database or your secrets. Pass your server tools to `chat()`, and the adapter bridges them into the sandbox:
238​
239```ts group=tools
240import { z } from "zod";
241import { chat, toolDefinition } from "@tanstack/ai";
242import { claudeCodeText } from "@tanstack/ai-claude-code";
243import { withSandbox } from "@tanstack/ai-sandbox";
244import { sandbox } from "./sandbox";
245​
246const lookupTicket = toolDefinition({
247 name: "lookup_ticket",
248 description: "Look up an issue ticket by id",
249 inputSchema: z.object({ ticketId: z.string() }),
250}).server(async ({ ticketId }) => {
251 return { ticketId, status: "open", title: "Crash on startup" };
252});
253​
254const stream = chat({
255 adapter: claudeCodeText("claude-opus-4-8"),
256 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
257 threadId: "thread-1",
258 tools: [lookupTicket],
259 middleware: [withSandbox(sandbox)],
260});
261```
262​
263- Each tool runs on your server, with its closures and secrets. The result goes back into the sandbox.
264- The agent sees the tool as `mcp__tanstack__lookup_ticket`. The adapter removes the prefix, so the events use the name you gave.
265- Only server tools work here. A client tool has no server `execute()`, so the agent cannot run it.
266​
267For how the bridge reaches your server from each provider, see [Sandbox Tools](../sandbox/tools).
268​
269## Tool choice
270​
271You want Claude Code to answer in text only, or to use only one of your tools. Pass `toolChoice` to `chat()`:
272​
273```ts group=tools
274const onlyLookup = chat({
275 adapter: claudeCodeText("claude-opus-4-8"),
276 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
277 threadId: "thread-1",
278 tools: [lookupTicket],
279 toolChoice: { type: "tool", name: "lookup_ticket" },
280 middleware: [withSandbox(sandbox)],
281});
282```
283​
284| Value | What the adapter does |
285| --- | --- |
286| `'auto'` | No change. Claude Code can call every tool. |
287| `'none'` | Turns off the built-in tools and bridges none of your tools. Claude Code answers in text. |
288| `{ type: 'tool', name }` | Turns off the built-in tools and bridges only the named tool. Claude Code can call only this tool, but it does not have to. |
289| `'required'` | No change. Claude Code cannot force a tool call, so the adapter logs a warning the first time. |
290​
291For the values on other adapters, see [Choose when the model calls a tool](../tools/tools#choose-when-the-model-calls-a-tool).
292​
293## Structured output
294​
295You want a typed report after the agent reads the repo. Pass `outputSchema` on the same `chat()` call:
296​
297```ts
298import { chat } from "@tanstack/ai";
299import { claudeCodeText } from "@tanstack/ai-claude-code";
300import { withSandbox } from "@tanstack/ai-sandbox";
301import { z } from "zod";
302import { sandbox } from "./sandbox";
303​
304const Report = z.object({
305 summary: z.string(),
306 filesChanged: z.array(z.string()),
307});
308​
309const report = await chat({
310 adapter: claudeCodeText("claude-opus-4-8"),
311 messages: [{ role: "user", content: "Review this repo." }],
312 threadId: "thread-1",
313 outputSchema: Report,
314 middleware: [withSandbox(sandbox)],
315});
316​
317console.log(report.summary);
318```
319​
320On the client, pass the same schema to `useChat` and read `final`. `partial` stays empty until the end.
321​
322```tsx
323import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
324import { z } from "zod";
325​
326const Report = z.object({
327 summary: z.string(),
328 filesChanged: z.array(z.string()),
329});
330​
331export function ReportView() {
332 const { final, isLoading } = useChat({
333 connection: fetchServerSentEvents("/api/repo-report"),
334 threadId: "support-chat",
335 outputSchema: Report,
336 });
337​
338 if (isLoading) return <p>The agent is inspecting the repo.</p>;
339 if (!final) return null;
340 return <p>{final.summary}</p>;
342```
343​
344- Claude Code runs one turn with its own tools. Tool activity and text stream as usual.
345- The adapter passes the schema to `--json-schema` as inline JSON. The CLI does not take a file path.
346- The object arrives as `structured-output.complete`. This also works when Claude sends it through its built-in `StructuredOutput` tool.
347​
348Do you only need JSON from a prompt, with no repo? Use `@tanstack/ai-anthropic`. That is faster. For the full walkthrough, see [Harness Agents](../structured-outputs/harnesses).
349​
350## Models and options
351​
352### Models
353​
354| Model | Reasoning levels | What `reasoning` sets |
355| --- | --- | --- |
356| `claude-opus-4-8`, `claude-opus-4-7`, `opus` | `low`, `medium`, `high`, `xhigh`, `max` | `--effort` |
357| `claude-opus-4-6`, `claude-sonnet-4-6`, `sonnet` | `low`, `medium`, `high`, `max` | `--effort` |
358| `claude-haiku-4-5`, `haiku` | `off`, `minimal`, `low`, `medium`, `high` | `MAX_THINKING_TOKENS` |
359​
360The package exports this list as `CLAUDE_CODE_MODELS`. The adapter also takes any other Claude model id as a string.
361​
362### Reasoning
363​
364Set `reasoning` on `chat()`:
365​
366```ts
367import { chat } from "@tanstack/ai";
368import { claudeCodeText } from "@tanstack/ai-claude-code";
369import { withSandbox } from "@tanstack/ai-sandbox";
370import { sandbox } from "./sandbox";
371​
372const stream = chat({
373 adapter: claudeCodeText("claude-opus-4-8"),
374 messages: [{ role: "user", content: "Refactor the auth module" }],
375 threadId: "thread-1",
376 reasoning: "xhigh",
377 middleware: [withSandbox(sandbox)],
378});
379```
380​
381For `claude-haiku-4-5`, the level picks a token budget. You can also set the budget with `budgetTokens`. `off` sends `0`. See [Reasoning](../chat/reasoning).
382​
383### Adapter options
384​
385Pass these as the second argument of `claudeCodeText`:
386​
387| Option | What it does |
388| --- | --- |
389| `cwd` | The working directory inside the sandbox. Default `/workspace`. |
390| `permissionMode` | `'default'`, `'acceptEdits'`, `'bypassPermissions'`, or `'plan'`. Default `'bypassPermissions'`. |
391| `allowedTools` | Built-in tools that the agent can use (`--allowedTools`), for example `['Read', 'Grep', 'Bash(npm test:*)']`. |
392| `disallowedTools` | Built-in tools that the agent cannot use (`--disallowedTools`). |
393| `addDirs` | More directories that the agent can access (`--add-dir`). |
394| `maxTurns` | The maximum number of agent turns in one run. |
395| `settingSources` | Which Claude Code settings to load. Default `['project']`. See [Settings sources](#settings-sources). |
396| `systemPromptMode` | `'append'` (default) adds your `systemPrompts` to the Claude Code prompt. `'replace'` sends only yours. |
397| `authMode` | `'api-key'` (default) gives `ANTHROPIC_API_KEY` to the process. `'host'` uses `claude login`. See [Harness Auth](../sandbox/auth). |
398| `claudeExecutable` | The path or name of the `claude` executable in the sandbox. Default `claude`. |
399| `streamPartials` | Stream text and tool arguments token by token. Default `true`. With `false`, each arrives whole. |
400| `env` | More environment variables for the `claude` process. |
401| `emitDiff` | Send the `file.changed` event with the `git diff` after the run. Default `true`. |
402​
403### Per-call options
404​
405Pass these in `modelOptions` on `chat()`. They override the adapter options for one call:
406​
407- `sessionId`: resume a session. See [Resume a session](#resume-a-session).
408- `cwd`, `maxTurns`, `permissionMode`, `allowedTools`, `disallowedTools`.
409- `authMode`: `'host'` or `'api-key'`.
410​
411## Advanced
412​
413### Permissions and policy
414​
415A headless run has no person to answer a permission prompt. So the default `permissionMode` is `'bypassPermissions'`, and the sandbox is the boundary.
416​
417- To allow fewer actions, set `permissionMode`, `allowedTools`, or `disallowedTools`.
418- To allow, ask, or deny each command and capability, add a sandbox [Policy](../sandbox/policy). The adapter maps the policy to Claude Code flags and answers the permission prompts of Claude Code from it.
419- If the policy says `ask`, the adapter sends an approval-requested event and denies the action. The client approves, then runs the turn again.
420​
421### Settings sources
422​
423By default, the adapter loads only the project settings (`--setting-sources project`):
424​
425- The workspace `CLAUDE.md`, `.claude/skills`, and `.mcp.json` apply to the run.
426- A cloned repo's `.claude/settings.json` and hooks also apply.
427- The host `~/.claude` (your personal plugins, hooks, and skills) does not load. This matters on the local-process provider.
428​
429For the same behavior as the CLI, pass `settingSources: ['user', 'project', 'local']`. To load no settings, pass `[]`.
430​
431The adapter does not pass `--bare`, because that flag ignores a host `claude login`.
432​
433### How tool choice changes the CLI flags
434​
435For `'none'` and a named tool, the adapter passes `--tools ""` and `--strict-mcp-config`. Then other MCP servers, for example from the workspace or a settings file, do not load.
436​
437### Token usage
438​
439`RUN_FINISHED.usage.promptTokens` counts the full input, cached tokens included. See [Token usage](../chat/stream-events#token-usage).
440​
441### Limitations
442​
443- **A sandbox is required.** Every call needs `withSandbox(...)`.
444- **The agent owns the loop.** TanStack agent-loop strategies and per-iteration middleware do not apply inside a turn. Use `maxTurns` to limit the turn.
445- **No sampling options.** Options such as `temperature` do not exist here.
446- **Sessions stay in the sandbox.** Resume needs the same sandbox.
447- **Cold starts.** Each call starts a CLI turn, so the first token arrives later than with an HTTP adapter.
448- **No `wrapFetch`.** This adapter ignores [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call), because the `claude` process sends the model requests.
449​
450### Example apps
451​
452- [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare): a TanStack Start app on Workers. You pick Claude Code, Codex, or Grok Build in the UI. It shows session resume, the tool timeline, and tool bridging.
453- [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web): this adapter on Docker, with durable runs that continue after a page refresh.