OmniscioGuidesStructured output from the Claude Agent SDK
Structured output from the Claude Agent SDK
An agent that returns free-form text is useful to a reader and useless to a program. Structured outputs close that gap: you declare the shape you want, and the SDK guarantees the reply parses as it — or tells you that it could not.
This page covers the quick start in both languages, schema generation with Zod and Pydantic, the tool call the SDK adds behind the scenes, and the two result subtypes you have to handle.
Sources read on November 22, 2026. By the Omniscio team. Updated .
Why structured outputs exist
Agents return free-form text by default, which works for chat but not when the output feeds application logic, a database or a UI. Structured outputs let you define the exact shape of the data you want: the agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end.
Anthropic's example is a recipe app where an agent searches the web and brings back recipes. Without structured outputs you get prose you have to parse yourself; with them, you define the shape and get typed data you can use directly.
Quick start: one option, one field
Define a JSON Schema, pass it to query() through outputFormat in TypeScript or output_format in Python, and read the structured_output field on the result message when the agent finishes.
import { query } from "@anthropic-ai/claude-agent-sdk";
const schema = {
type: "object",
properties: {
company_name: { type: "string" },
founded_year: { type: "number" },
headquarters: { type: "string" }
},
required: ["company_name"]
};
for await (const message of query({
prompt: "Research Anthropic and provide key company information",
options: {
outputFormat: { type: "json_schema", schema }
}
})) {
if (message.type === "result" && message.subtype === "success" &&
!message.is_error && message.structured_output) {
console.log(message.structured_output);
}
}The Python form takes the same schema under output_format in ClaudeAgentOptions, and reads structured_output from a ResultMessage:
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async for message in query(
prompt="Research Anthropic and provide key company information",
options=ClaudeAgentOptions(
output_format={"type": "json_schema", "schema": schema}
),
):
if isinstance(message, ResultMessage) and not message.is_error and message.structured_output:
print(message.structured_output)Before either example runs, install the SDK as the quickstart describes.
Type-safe schemas with Zod and Pydantic
Rather than writing JSON Schema by hand, you can define the shape with Zod in TypeScript or Pydantic in Python, and have the library generate the JSON Schema and parse the response into a typed object.
One detail decides whether this works: the SDK validates schemas with JSON Schema draft-07 and rejects a schema that declares a newer version, while Zod targets draft 2020-12 by default. Pass target: "draft-7" when you convert a Zod schema.
import { z } from "zod";
const FeaturePlan = z.object({
feature_name: z.string(),
summary: z.string(),
steps: z.array(z.object({
step_number: z.number(),
description: z.string(),
estimated_complexity: z.enum(["low", "medium", "high"])
})),
risks: z.array(z.string())
});
const schema = z.toJSONSchema(FeaturePlan, { target: "draft-7" });Then pass that schema as the schema field of an outputFormat object whose type is json_schema, and use FeaturePlan.safeParse() on the returned structured_output to get a fully typed object back.
What the option accepts
The option is an object with two fields: type, set to "json_schema", and schema, a JSON Schema object you can write by hand or generate from Zod with z.toJSONSchema(schema, { target: "draft-7" }) or from Pydantic with .model_json_schema().
The SDK supports the standard JSON Schema features: every basic type, enum, const, required, nested objects and $ref definitions. The format keyword, such as "format": "email", is accepted as an annotation but is not enforced by the validator.
A schema that is not valid JSON Schema fails the run at startup with an error naming the problem. Before v2.1.205 an invalid schema was silently ignored and the agent returned unstructured text, which is why an old SDK can look like it is working when it is not.
Tool use and structure are not alternatives. In a separate example, Anthropic has the agent find TODO comments with Grep, look up git blame with Bash, and combine the results into one structured response, with optional fields for the blame information it could not always find.
The StructuredOutput tool call you never wrote
When you set the option, Claude Code adds a tool named StructuredOutput to the session, and the agent calls it to return its answer. The system init message lists it in the tools array, and each call arrives as two blocks: a tool_use block carrying the object the agent produced, and a tool_result reading Structured output provided successfully.
When the object does not match the schema, that tool_result carries is_error: true and the agent calls StructuredOutput again, so one query's stream can hold several calls. Read the validated data from structured_output on the result message, not from a tool_use block.
If your application shows or logs tool calls, skip the ones named StructuredOutput so the mechanism does not look like a step the agent chose. A tool_result block carries no tool name, only the tool_use_id of the call it answers, so match that against the id of each call you skipped.
When it fails, and what you get
Generation can fail because the schema is too complex for the task, the task is ambiguous, or the agent used up its retries fixing validation errors. It can also fail without any validation failure: a model fallback can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. The errors list on the error result tells the two causes apart.
| Result subtype | What it means |
|---|---|
success | The run ended without an error subtype |
error_max_structured_output_retries | No valid output remained after multiple attempts |
success alone does not mean you have an answer. Treat the result as a failure when is_error is true — for example a final API error or a refusal — or when structured_output is absent. A single-shot query() also throws after yielding an error result.
A single-shot query() throws when the run ends with an error result, so a caller that skips the subtype check has nothing to fall back on. The headless guide covers running Claude Code programmatically, and the parallel agents guide covers running more than one.
Where these answers come from
- Everything on this page about structured outputs, the option shape, Zod and Pydantic, the
StructuredOutputtool and error handling: Get structured output from agents, read November 22, 2026. - The install step it points at: Agent SDK quickstart, named by that page and linked from it.
No agent was run to write this page, and the example outputs are Anthropic's own from its documentation, not captures from a session.
Common questions
How do I get structured output from the Claude Agent SDK?
Define a JSON Schema for the shape you want and pass it to query() through the outputFormat option in TypeScript or output_format in Python. When the agent finishes, the result message carries a structured_output field with validated data that matches your schema.
Can the agent still use tools with structured outputs?
Yes. The agent can use any tools it needs, such as Grep to search a codebase and Bash to run git commands, and still return validated JSON at the end. Anthropic's TODO example does exactly that.
What happens when the output does not match the schema?
The SDK re-prompts the agent to try again. If no valid output remains after the retry limit, the run ends with the error_max_structured_output_retries subtype, and a single-shot query() throws after yielding that error result.
Why is there a StructuredOutput tool call I never defined?
Claude Code adds that tool to the session when you set outputFormat or output_format, and the agent calls it to return its answer. Read the validated data from structured_output on the result message, and skip StructuredOutput calls if your application logs tool calls.