Structured Output via Tool Use & JSON Schemas
CoreEnforce structured output using tool use and JSON schemas · Difficulty 3/5
For automated pipelines, you need guaranteed Structured Output -- not narrative text that might vary. Tool use with JSON schemas is the most reliable approach.
Approaches (Least to Most Reliable)
--output-format json --json-schema -- guaranteed for CLIWhy Tool Use Wins
Tool use with JSON schemas guarantees schema-compliant output. The model MUST return data matching the schema, eliminating JSON syntax errors entirely. However, it does NOT prevent semantic errors (e.g., line items that don't sum to total, values in wrong fields).
Schema Design Best Practices
Key Takeaways
- ✓Tool use with JSON schemas eliminates syntax errors but not semantic errors
- ✓Make fields optional/nullable when source data may not contain the information
- ✓Use enum + 'other' + detail string pattern for extensible categories
- ✓Prompt-based formatting is unreliable for automated pipelines
Glossary Terms
Guaranteed formatted output (typically JSON) from Claude. The most reliable method is to define a schema as a tool and set tool_choice to force its use — Claude's tool_use blocks are always valid JSON. Alternatively, use --output-format json with --json-schema in Claude Code CLI.
A content block type in Claude's response indicating the model wants to call a specific tool. Contains 'id', 'name', and 'input' fields. The agent must execute the tool and return results in a tool_result content block for the conversation to continue.
Related Concepts
Test Yourself1 of 1
Your CI pipeline runs the Claude Code CLI using CLAUDE.md to provide project context for code reviews. However, developers report that integrating findings into your workflow is difficult — Claude produces narrative paragraphs that must be manually copied into PR comments. Your team wants to automatically post each finding as a separate inline PR comment at the relevant code location. What's the most effective approach?