Claude Agent SDKclaude-agent-sdk 0.2.157 · Python 3.10+
Dashboard
0%

Structured output

output_format is the option that takes a JSON Schema and makes a run return data as well as text. The result then carries structured_output matching the schema, beside the usual answer.

Last updated: 20 Oct, 2026 · Claude Agent SDK

A subagent hands its parent a sentence. Everything the desk has produced so far has been text for a person to read. The shop's order system wants fields it can store.

Writing the schema with Pydantic

The option takes plain JSON Schema, and Pydantic can write it for you. model_json_schema() gives the schema and model_validate() turns the result back into an object.

python
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel
from shop_desk import ShopDesk
from shop_tools import shop


class OrderAnswer(BaseModel):
    order_id: str
    answer: str


# both fields are required, so a run that cannot fill one of them fails
schema = OrderAnswer.model_json_schema()
python
from flags import flags

# the schema itself is what travels, as one flag with the JSON inside it
print(schema["required"])
print(flags(ClaudeAgentOptions(output_format={"type": "json_schema", "schema": schema})))

The SDK sends the schema to Claude Code as --json-schema. Claude Code validates the output against it and asks the model again on a mismatch, up to a retry limit: structured-outputs.

Shaping the result in the desk

shop_desk.py gains shape and replaces finish, and jsonschema, which the SDK already depends on, is added to its imports.

Exampleshop_desk.py, the imports now
from pathlib import Path

import jsonschema
from claude_agent_sdk import ClaudeAgentOptions, ProcessError, Transport
Exampleshop_desk.py, a new method
    def shape(self, text):
        found = ORDER.findall(" ".join(self.said))
        data = {"order_id": found[-1] if found else None, "answer": text}

        # a field the schema does not name is dropped rather than sent along
        schema = self.options.output_format["schema"]
        data = {k: v for k, v in data.items() if k in schema.get("properties", {})}

        # Claude Code would ask the model again here; the desk fails at once
        try:
            jsonschema.validate(data, schema)
        except jsonschema.ValidationError as error:
            return {"subtype": "error_max_structured_output_retries", "is_error": True,
                    "errors": [error.message]}
        return {"structured_output": data}
Exampleshop_desk.py, the end of finish
        # shaping can fail, which turns a success into an error, so read is_error after it
        if ok and self.options.output_format:
            result.update(self.shape(text))
        await self.send(result)
        self.failed = ProcessError("Command failed", exit_code=1) if result["is_error"] else None

Two runs, one schema apart

python
shared = dict(mcp_servers={"shop": shop}, setting_sources=["project"],
              allowed_tools=["mcp__shop__lookup_order"])
shaped = ClaudeAgentOptions(**shared, output_format={"type": "json_schema", "schema": schema})
plain = ClaudeAgentOptions(**shared)


# one question, asked the same way whatever the options carry
async def ask(options):
    async for message in query(prompt="Where is A17?", options=options,
                               transport=ShopDesk(options)):
        if isinstance(message, ResultMessage):
            print(message.subtype, message.structured_output)
Example
await ask(shaped)
Example
await ask(plain)
  • With the schema the result carries a dictionary with both fields filled in, ready to store.
  • Without it the run succeeds and structured_output is None. The text answer is unchanged.
  • The schema did the work. Same question, same tool call, one option between them.

Getting an object back

Example
async for message in query(prompt="Where is A17?", options=shaped,
                           transport=ShopDesk(shaped)):
    if isinstance(message, ResultMessage) and message.structured_output:
        print(OrderAnswer.model_validate(message.structured_output))

model_validate checks the data a second time, in your own process, and hands back a typed object. Schemas are validated as JSON Schema draft-07, so a schema that declares a newer draft is refused at startup.

A schema that cannot be met

Example
# nothing in the shop knows a tracking number, so no answer can satisfy this
wanted = dict(schema["properties"], tracking_number={"type": "string"})
broken = dict(schema, properties=wanted, required=["order_id", "answer", "tracking_number"])

await ask(ClaudeAgentOptions(**shared, output_format={"type": "json_schema", "schema": broken}))

The result's subtype is error_max_structured_output_retries, and then query() raises the way it does at a turn limit. Both happen: the result message arrives first, so a try around the loop still gets to read it.

Reading the result of a shaped run

Subtypestructured_outputWhat it means
successA dictionaryValidated output, ready to use
successNoneThe run finished without producing one. Treat it as a failure
error_max_structured_output_retriesNoneNo valid output survived the retries, or a model fallback withdrew one

Where a schema pays for itself

  • A row to write to a database, where parsing prose would be the slow part.
  • A value another service reads, which needs the same keys every time.
  • A screen that renders fields, so a changed sentence cannot break the layout.
Watch out. A deep schema with many required fields is harder to satisfy than a flat one, and a field the task may not know about should be left out of required. The failure arrives at the end of a run you have already paid for.
Try it yourself
  • Drop answer from the model and run the first example again.
  • Give order_id a min_length of 5 in the Pydantic model and read the error.
  • Ask a question with no order id in it. What does order_id hold?
PreviousSubagents

Little by little, you're building something great.