Skip to main content
guidesSource-backed

Structured Output from Claude Agent SDK Workflows

A practical walkthrough of structured outputs in the Claude Agent SDK: defining a JSON Schema via the outputFormat option, reading validated structured_output, type-safe schemas with Zod or Pydantic, and handling validation failures.

by JPette1783·added 2026-06-05·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/agent-sdk/structured-outputs, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/structured-output-from-claude-agent-sdk-workflows.mdx
Safety notes
If validation does not succeed within the retry limit, the result is an error (error_max_structured_output_retries), not structured data; handle that subtype., Structured outputs constrain the final result shape, not what tools the agent may use; tool permissions still apply., Keep schemas focused: deeply nested schemas with many required fields are harder to satisfy and more likely to fail.
Privacy notes
The agent may use tools (search, bash) to gather data before producing output; that activity sends data to the provider and any tools you allow., Validated output is returned to your application in the final result message; handle it like any data you persist or display., Do not embed secrets in schema field descriptions; they are sent to the model as part of the request.
Author
JPette1783
Submitted by
JPette1783
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup. Have accounts and credentials ready first.

0/3 ready
Account & credentials1Install & runtime2

Safety & privacy surface

Safety & privacy surface

3 safety and 3 privacy notes across 5 risk areas. Review closely: credentials & tokens, permissions & scopes, third-party handling.

5 areas
  • SafetyGeneralIf validation does not succeed within the retry limit, the result is an error (error_max_structured_output_retries), not structured data; handle that subtype.
  • SafetyPermissions & scopesStructured outputs constrain the final result shape, not what tools the agent may use; tool permissions still apply.
  • SafetyGeneralKeep schemas focused: deeply nested schemas with many required fields are harder to satisfy and more likely to fail.
  • PrivacyThird-party handlingThe agent may use tools (search, bash) to gather data before producing output; that activity sends data to the provider and any tools you allow.
  • PrivacyData retentionValidated output is returned to your application in the final result message; handle it like any data you persist or display.
  • PrivacyCredentials & tokensDo not embed secrets in schema field descriptions; they are sent to the model as part of the request.

Safety notes

  • If validation does not succeed within the retry limit, the result is an error (error_max_structured_output_retries), not structured data; handle that subtype.
  • Structured outputs constrain the final result shape, not what tools the agent may use; tool permissions still apply.
  • Keep schemas focused: deeply nested schemas with many required fields are harder to satisfy and more likely to fail.

Privacy notes

  • The agent may use tools (search, bash) to gather data before producing output; that activity sends data to the provider and any tools you allow.
  • Validated output is returned to your application in the final result message; handle it like any data you persist or display.
  • Do not embed secrets in schema field descriptions; they are sent to the model as part of the request.

Prerequisites

  • The Claude Agent SDK installed for Python or TypeScript.
  • A JSON Schema for the output shape, or Zod (TypeScript) / Pydantic (Python) to generate one.
  • Configured provider credentials for the SDK.

Schema details

Install type
copy
Troubleshooting
No
Full copyable content
## Overview

Structured outputs let you define the exact shape of data an Agent SDK workflow
returns. The agent can use any tools it needs, and you still get validated JSON
matching your schema at the end. The SDK validates the output and re-prompts on
mismatch.

## Quick start

Pass a JSON Schema via `outputFormat` (TypeScript) / `output_format` (Python). The
final result message includes a `structured_output` field with validated data.

```typescript
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.structured_output) {
    console.log(message.structured_output);
  }
}
```

## Type-safe schemas

Generate the JSON Schema from Zod (`z.toJSONSchema(...)`) or Pydantic
(`.model_json_schema()`), then validate the response with `safeParse()` /
`model_validate()` for a fully typed object. The SDK supports standard JSON Schema
features: basic types, `enum`, `const`, `required`, nested objects, and `$ref`.

## Works with multi-step tool use

The agent can run tools (for example Grep to find TODOs, Bash for git blame)
across multiple turns, then return one structured result. Make fields that might
be unavailable optional so the agent can omit them.

## Handle validation failures

Check the result `subtype`:

- `success` - output generated and validated.
- `error_max_structured_output_retries` - the agent could not produce valid output
  after multiple attempts; fall back or retry with a simpler prompt/schema.

```typescript
if (msg.type === "result") {
  if (msg.subtype === "success" && msg.structured_output) { /* use it */ }
  else if (msg.subtype === "error_max_structured_output_retries") { /* handle failure */ }
}
```

## Tips

- Keep schemas focused; start simple and add complexity as needed.
- Make optional anything the task might not provide.
- Use clear prompts so the agent knows what output to produce.
- Note: structured output is not streamed; it appears only in the final result.

## Source

- Get structured output from agents: https://code.claude.com/docs/en/agent-sdk/structured-outputs

About this resource

Overview

Structured outputs let you define the exact shape of data an Agent SDK workflow returns. The agent can use any tools it needs, and you still get validated JSON matching your schema at the end. The SDK validates the output and re-prompts on mismatch.

Quick start

Pass a JSON Schema via outputFormat (TypeScript) / output_format (Python). The final result message includes a structured_output field with validated data.

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.structured_output) {
    console.log(message.structured_output);
  }
}

Type-safe schemas

Generate the JSON Schema from Zod (z.toJSONSchema(...)) or Pydantic (.model_json_schema()), then validate the response with safeParse() / model_validate() for a fully typed object. The SDK supports standard JSON Schema features: basic types, enum, const, required, nested objects, and $ref.

Works with multi-step tool use

The agent can run tools (for example Grep to find TODOs, Bash for git blame) across multiple turns, then return one structured result. Make fields that might be unavailable optional so the agent can omit them.

Handle validation failures

Check the result subtype:

  • success - output generated and validated.
  • error_max_structured_output_retries - the agent could not produce valid output after multiple attempts; fall back or retry with a simpler prompt/schema.
if (msg.type === "result") {
  if (msg.subtype === "success" && msg.structured_output) { /* use it */ }
  else if (msg.subtype === "error_max_structured_output_retries") { /* handle failure */ }
}

Tips

  • Keep schemas focused; start simple and add complexity as needed.
  • Make optional anything the task might not provide.
  • Use clear prompts so the agent knows what output to produce.
  • Note: structured output is not streamed; it appears only in the final result.

Source

Source citations

Add this badge to your README

Show that Structured Output from Claude Agent SDK Workflows is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/structured-output-from-claude-agent-sdk-workflows.svg)](https://heyclau.de/entry/guides/structured-output-from-claude-agent-sdk-workflows)

How it compares

Structured Output from Claude Agent SDK Workflows side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Source provenance, Submitter).

Field

A practical walkthrough of structured outputs in the Claude Agent SDK: defining a JSON Schema via the outputFormat option, reading validated structured_output, type-safe schemas with Zod or Pydantic, and handling validation failures.

Open dossier

How to design custom tools for the Claude Agent SDK: in-process tool definitions with typed input schemas, permission scoping, structured isError results, and when to reach for an external MCP server instead.

Open dossier

A practical walkthrough of real-time streaming in the Claude Agent SDK: enabling partial messages, reading StreamEvent text and tool-call deltas, the message flow, and building a streaming UI.

Open dossier

A practical walkthrough of using Agent Skills in the Claude Agent SDK: how skills are discovered from the filesystem via settingSources, the skills option to enable or filter them, tool access, and troubleshooting discovery.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceDiffersSource-backedSubmission linkedSource submissionSource-backedSource-backed
SubmitterDiffersJPette1783kiannidevJPette1783JPette1783
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryguidesguidesguidesguides
SourceSource-backedSource-backedSource-backedSource-backed
AuthorJPette1783kiannidevJPette1783JPette1783
Added2026-06-052026-06-142026-06-052026-06-05
Platforms
Harness
Source repo
Safety notesIf validation does not succeed within the retry limit, the result is an error (error_max_structured_output_retries), not structured data; handle that subtype. Structured outputs constrain the final result shape, not what tools the agent may use; tool permissions still apply. Keep schemas focused: deeply nested schemas with many required fields are harder to satisfy and more likely to fail.Tool descriptions are not enforcement—validate destructive inputs inside handlers. Wildcard `mcp__server__*` allowlists expand blast radius; prefer per-tool grants in production. Returning thrown exceptions fails the whole query; use isError responses for recoverable faults.Streaming changes how output is delivered, not what the agent can do; tool permissions and allowedTools still govern actions. Accumulate tool-input JSON deltas and parse the completed JSON; do not act on partial tool input. Partial text is incremental and may be interrupted; handle incomplete streams gracefully in your UI.The skills option is a context filter, not a sandbox: unlisted skills are hidden from the model but their files remain on disk and are reachable via Read and Bash. Skills are model-invoked; pair them with a tight allowedTools list (and dontAsk where appropriate) so an invoked skill cannot use more tools than intended. The allowed-tools frontmatter in SKILL.md does not apply through the SDK; control tool access with the main allowedTools option.
Privacy notesThe agent may use tools (search, bash) to gather data before producing output; that activity sends data to the provider and any tools you allow. Validated output is returned to your application in the final result message; handle it like any data you persist or display. Do not embed secrets in schema field descriptions; they are sent to the model as part of the request.Tool schemas and results enter model context every turn—avoid secrets in descriptions or payloads. Large tool sets increase context usage; defer rarely used tools via tool search. Structured outputs may log to host telemetry—redact customer fields at the handler boundary.Streamed deltas are the same model output as non-streaming; they are sent from the provider over your connection. If you render streamed tool inputs, avoid surfacing sensitive arguments in logs or UI. Structured output is not streamed; it appears only in the final result message.Skill descriptions are loaded so the model can decide when to use them; keep sensitive workflow detail and secrets out of descriptions. Skills sourced from outside your project run their instructions in your sessions; review them before enabling. Skill content is sent to the model provider when a skill is invoked; treat it like any other prompt content.
Prerequisites
  • The Claude Agent SDK installed for Python or TypeScript.
  • A JSON Schema for the output shape, or Zod (TypeScript) / Pydantic (Python) to generate one.
  • Configured provider credentials for the SDK.
  • Claude Agent SDK installed and a running `query` loop in TypeScript or Python.
  • Zod (TS) or JSON Schema (Python) literacy for tool input contracts.
  • A written list of side effects each custom tool may perform.
  • Decision record template for build vs buy on external MCP integrations.
  • The Claude Agent SDK installed for Python or TypeScript.
  • An async loop over query() results in your application.
  • Configured provider credentials for the SDK.
  • The Claude Agent SDK installed for Python or TypeScript.
  • SKILL.md files in .claude/skills/ (project) or ~/.claude/skills/ (user).
  • A cwd that points at or below the directory containing .claude/skills/, within the same repository.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.