Open History to see the last commit
1---
2title: Harness Structured Output
3id: structured-outputs-harnesses
4order: 6
5description: "Let a coding agent inspect a repo in a sandbox, then read a typed object from chat({ outputSchema }). Works with Claude Code, Codex, OpenCode, Grok Build, and acpCompatible."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - harness
10 - claude code
11 - codex
12 - opencode
13 - grok build
14 - outputSchema
15 - sandbox
16---
17
18Pass `outputSchema` to a coding-agent `chat()` call. The agent still streams tool calls, and the run ends with a typed object.
19
20The agent runs its native tools in the sandbox. Read the validated object from `await chat()` or from `useChat().final`.
21
22This page is for the sandbox harness adapters:
23
24- [Claude Code](../adapters/claude-code)
25- [Codex](../adapters/codex)
26- [OpenCode](../adapters/opencode)
27- [Grok Build](../adapters/grok-build)
28- [ACP-Compatible](../adapters/acp-compatible) (`acpCompatible`)
29
30To extract JSON from a prompt with no sandbox, use [One-Shot Extraction](./one-shot) with an HTTP adapter.
31
32## Quick setup
33
34This setup assumes you have a sandbox provider ready. See [Sandbox Quick Start](../sandbox/quick-start).
35
36### 1. Define the schema
37
38```typescript
39// schemas/report.ts
40import { z } from "zod";
41
42export const ReportSchema = z.object({
43 name: z.string(),
44 oneLiner: z.string(),
45 audience: z.string(),
46 mainPackages: z.array(z.object({ name: z.string(), role: z.string() })),
47 howToRun: z.string(),
48});
49```
50
51### 2. Add the server endpoint
52
53Add `withSandbox(...)` to the middleware. Pass `stream: true` so the client gets a stream:
54
55```typescript
56// api/repo-report.ts
57import {
58 chat,
59 chatParamsFromRequest,
60 toServerSentEventsResponse,
61} from "@tanstack/ai";
62import { claudeCodeText } from "@tanstack/ai-claude-code";
63import {
64 defineSandbox,
65 defineWorkspace,
66 githubRepo,
67 withSandbox,
68} from "@tanstack/ai-sandbox";
69import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
70import { ReportSchema } from "../schemas/report";
71
72const sandbox = defineSandbox({
73 id: "repo-report",
74 provider: dockerSandbox({ image: "node:22" }),
75 workspace: defineWorkspace({
76 source: githubRepo({ repo: "TanStack/ai" }),
77 }),
78});
79
80export async function POST(request: Request) {
81 const { messages, threadId, runId } = await chatParamsFromRequest(request);
82
83 const stream = chat({
84 adapter: claudeCodeText("claude-opus-4-8"),
85 messages,
86 threadId,
87 runId,
88 outputSchema: ReportSchema,
89 stream: true,
90 middleware: [withSandbox(sandbox)],
91 });
92
93 return toServerSentEventsResponse(stream);
94}
95```
96
97### 3. Read the report on the client
98
99```tsx
100import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
101import { z } from "zod";
102
103// The same schema as schemas/report.ts. In your app, import it from that file.
104const ReportSchema = z.object({
105 name: z.string(),
106 oneLiner: z.string(),
107 audience: z.string(),
108 mainPackages: z.array(z.object({ name: z.string(), role: z.string() })),
109 howToRun: z.string(),
110});
111
112export function RepoReport() {
113 const { messages, sendMessage, isLoading, final } = useChat({
114 connection: fetchServerSentEvents("/api/repo-report"),
115 threadId: "support-chat",
116 outputSchema: ReportSchema,
117 });
118
119 return (
120 <>
121 <button
122 disabled={isLoading}
123 onClick={() => void sendMessage("What is this repository about?")}
124 >
125 Run report
126 </button>
127 {messages.map((message) => (
128 <div key={message.id}>
129 {message.parts.map((part, index) => {
130 if (part.type === "thinking") {
131 return <p key={index}>{part.content}</p>;
132 }
133 if (part.type === "tool-call") {
134 return (
135 <p key={part.id}>
136 {part.name} ({part.state})
137 </p>
138 );
139 }
140 if (part.type === "text") {
141 return <p key={index}>{part.content}</p>;
142 }
143 return null;
144 })}
145 </div>
146 ))}
147 {final && (
148 <section>
149 <h2>{final.name}</h2>
150 <p>{final.oneLiner}</p>
151 </section>
152 )}
153 </>
154 );
155}
156```
157
158Click Run report. Tool calls such as `Read` and `Bash` appear first. When the agent finishes, the report shows the name and the one-line summary of the repo.
159
160## How it works
161
1621. `withSandbox` starts the sandbox and clones the repo.
1632. The agent runs its native tools inside the sandbox. Each call streams to the client as a `tool-call` part.
1643. The adapter applies your schema on the same turn. See [How each harness applies the schema](#how-each-harness-applies-the-schema).
1654. The object arrives as a `structured-output.complete` event. `useChat` sets `final`.
166
167`partial` stays empty on harness adapters, because the object does not stream field by field. Show the tool calls while you wait.
168
169To change the agent, swap the adapter:
170
171- `codexText("gpt-5.3-codex")`
172- `opencodeText("anthropic/claude-opus-4-5")`
173- `grokBuildText("composer-2.5")`
174- `acpCompatibleText(...)` for any ACP CLI. See [ACP-Compatible](../adapters/acp-compatible).
175
176## Script without a UI
177
178If you do not stream to a browser, leave out `stream: true`. Then the promise resolves with the typed object:
179
180```typescript
181import { chat } from "@tanstack/ai";
182import { claudeCodeText } from "@tanstack/ai-claude-code";
183import {
184 defineSandbox,
185 defineWorkspace,
186 githubRepo,
187 withSandbox,
188} from "@tanstack/ai-sandbox";
189import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
190import { ReportSchema } from "./schemas/report";
191
192const sandbox = defineSandbox({
193 id: "repo-report",
194 provider: dockerSandbox({ image: "node:22" }),
195 workspace: defineWorkspace({
196 source: githubRepo({ repo: "TanStack/ai" }),
197 }),
198});
199
200const report = await chat({
201 adapter: claudeCodeText("claude-opus-4-8"),
202 messages: [{ role: "user", content: "What is this repository about?" }],
203 threadId: "thread-1",
204 outputSchema: ReportSchema,
205 middleware: [withSandbox(sandbox)],
206});
207
208console.log(report.name, report.oneLiner);
209```
210
211## Try it in the example app
212
213The React chat example has a repo-report page.
214
2151. Open [`examples/ts-react-chat`](https://github.com/TanStack/ai/tree/main/examples/ts-react-chat).
2162. Open `/repo-report`.
2173. Pick Claude Code, Grok Build, ACP compatible, or Codex.
2184. Pick Auth. The default is **API key**. If the machine already ran `claude login`, `grok login`, or `codex login`, use **Host login**.
2195. Run the report.
220
221The page clones `TanStack/ai` into a sandbox, asks the agent to inspect it, and shows the validated report. It renders tool calls and reasoning from `messages[].parts`, and reads the object from the `structured-output` part and from `final`.
222
223## Advanced
224
225### Parts on the message
226
227The assistant message holds the live run:
228
229- `thinking`: reasoning from the harness, when the agent emits it.
230- `tool-call`: native harness tools, such as `Read` or `Bash`.
231- `text`: prose that the agent writes before the JSON.
232- `structured-output`: the schema object. `part.data` is the validated value, and `part.raw` is the source string. `part.partial` is a progressive parse, when the adapter streams JSON text.
233
234`final` has the type of your schema. It stays `null` until `structured-output.complete` arrives, and it always matches the latest assistant turn. Older turns keep their own `structured-output` parts. For the `partial` and `final` shape, see [Streaming UIs](./streaming).
235
236### How each harness applies the schema
237
238| Adapter | How the schema is applied |
239| --- | --- |
240| Claude Code | Native `--json-schema` flag on the same turn. The value is inline JSON, not a file path. |
241| Codex | Native `--output-schema` flag on the same turn. Assistant text streams while Codex writes it. The last message is also the schema object. |
242| OpenCode | The schema goes into the prompt. The adapter parses the last assistant text. |
243| Grok Build | The schema goes into the prompt. The adapter parses the last assistant text. |
244| ACP compatible | The schema goes into the prompt. The adapter parses the last assistant text. |
245
246OpenCode, Grok Build, and `acpCompatible` parse JSON from the last assistant message. If that message is not JSON, the parse fails. If the job is only extraction and you do not need a sandbox, use `@tanstack/ai-openai` or `@tanstack/ai-grok`.
247
248### Approval gates and client tools
249
250Harness adapters run tools inside the sandbox. They do not pause for a round trip to the browser:
251
252- A tool with no server `execute()` is still listed to the agent. When the agent calls it, the bridge returns an `Unknown tool` error to the agent, and the run goes on.
253- A tool with `needsApproval` stops the run before the agent starts. The bridge cannot pause for approval, so it throws an error and does not run the tool.
254
255For approval gates or client tools, use [With Tools](./with-tools) with an HTTP adapter.
256
257### Persist the typed object
258
259Add `withPersistence` next to `withSandbox`. The engine stores the complete structured-output part on the transcript. A reload rebuilds that transcript through `reconstructChat`. See [Chat Persistence](../persistence/chat-persistence).
260
261The message id decides how the parts are stored:
262
263- A new message id keeps the harness prose and the structured object as two assistant messages.
264- The id of the last text message keeps both on one message.
265
266```typescript
267// api/repo-report.ts
268import {
269 chat,
270 chatParamsFromRequest,
271 toServerSentEventsResponse,
272} from "@tanstack/ai";
273import { claudeCodeText } from "@tanstack/ai-claude-code";
274import { withPersistence } from "@tanstack/ai-persistence";
275import {
276 defineSandbox,
277 defineWorkspace,
278 githubRepo,
279 withSandbox,
280} from "@tanstack/ai-sandbox";
281import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
282import { persistence } from "../persistence";
283import { ReportSchema } from "../schemas/report";
284
285const sandbox = defineSandbox({
286 id: "repo-report",
287 provider: dockerSandbox({ image: "node:22" }),
288 workspace: defineWorkspace({
289 source: githubRepo({ repo: "TanStack/ai" }),
290 }),
291});
292
293export async function POST(request: Request) {
294 const { messages, threadId, runId } = await chatParamsFromRequest(request);
295
296 const stream = chat({
297 adapter: claudeCodeText("claude-opus-4-8"),
298 messages,
299 threadId,
300 runId,
301 outputSchema: ReportSchema,
302 stream: true,
303 middleware: [withSandbox(sandbox), withPersistence(persistence)],
304 });
305
306 return toServerSentEventsResponse(stream);
307}
308```
309
310### Claude Code and the trust dialog
311
312Claude Code does not ask you to accept a trust dialog for the cloned repo. The adapter loads only user settings, so the `.claude/settings.json` of the clone does not block headless `-p`. Host login uses your host `claude login`. The sandbox type does not decide this. See [Harness Auth](../sandbox/auth).