PUBLIC BETA OFFER

Save 50% off on an Eligible Learning PlanValid for 1-month plan, 3-month plan, 12-month plan · Code LPXBETA50 · Ends Dec 6, 2026

Enforce structured output using tool use and JSON schemas

Choose a structured proposal channel and validate source meaning after shape checks.

Distinguish prompted JSON, tool-input schemas, final-output schemas, and adapter result locations. A teaching metadata extraction preserves absent values and out-of-taxonomy content, then requires source and business checks before authorized enrichment.

Knowledge domain
Prompt Engineering & Structured Output
Topics & tags
Published
Author
LearningPathX Editorial TeamContent version 1.0
Resources

Enforce structured output using tool use and JSON schemas

Learning objectives

Choose a structured output mechanism, design fields that represent missing and ambiguous information, and validate meaning after structural checks. Handle tool-call extraction without confusing a model proposal with completed execution.

Separate the output mechanisms

A prompt asking for JSON is an instruction. A tool's input schema describes arguments for a tool call. A supported strict tool mode can constrain those arguments, while a supported final-output schema constrains the final response payload. These mechanisms have related goals but different response locations and execution paths.

In the supplied Messages API pattern, inspect the response's content blocks for tool_use, then identify the tool by name and the call by ID. The structured extraction is in that block's input. Do not assume the first block is text or that every response contains exactly one call. The application validates and handles the proposal, then returns the corresponding tool result when continuing the tool loop.

For a pure extraction tool, handling may simply mean accepting validated data into the workflow. For a tool with side effects, schema compliance does not authorize the action. A tool call and an actual successful write are different events.

Claude Code's described print-mode interface combines -p, --output-format json, and --json-schema; its schema payload is in structured_output rather than ordinary result text. Use the actual SDK or CLI surface supported by the deployment. MCP tool results instead use their protocol's result fields, including structuredContent and any supported outputSchema; an adapter must map these deliberately. A raw API request does not discover project MCP configuration by itself.

Request the appropriate kind of tool use

Request-level choice Intended behavior
{"type":"auto"} The model may respond with text or request a tool
{"type":"any"} Request at least one available tool; the model selects it
{"type":"tool","name":"extract_metadata"} Request that named tool

These are configuration fragments, not complete API requests. In the supplied source snapshot, Claude Mythos Preview rejects any and named tool choices with a reported HTTP 400 configuration error; the listed alternatives are auto and none. Manual extended thinking (thinking.type: "enabled") also rejects those forced choices, while adaptive thinking permits them only on supported model/API combinations. Here, none disables tool requests. Switching to auto makes a tool request optional, so it cannot preserve a mandatory-extraction guarantee. Select a compatible configuration or redesign the stage instead of silently weakening that requirement. A forced choice selects a proposal channel; it does not establish that extraction succeeded, that the chosen document type was correct, or that the application executed a tool.

With multiple document-specific extractors, any can require selection among the available schemas. Include a supported unknown or unsupported-document route when classification is unresolved. Otherwise a mandatory selection can force a wrong schema onto a document that matches none of the choices. Verify the chosen type against evidence, not just the returned tool name.

Design a truthful data contract

Required presence and nullable value are different properties. A required string must be present and contain a string. A required field whose type includes null must be present but can explicitly record missing information. An optional non-nullable string can be absent; if present, it must be a string. Follow the supported schema subset and the consuming application's missingness convention.

Use enums for stable categories, unclear for insufficient evidence, and other for a known category outside the enumerated set. Give other a detail field and enforce its condition in application logic if the deployed schema subset does not express it. A natural-language description saying “required for other” is not automatically an executable conditional constraint.

This illustrative extraction tool uses explicit nulls:

{
  "name": "extract_metadata",
  "description": "Extract only metadata stated in the supplied document; use null for absent values.",
  "strict": true,
  "input_schema": {
    "type": "object",
    "properties": {
      "document_id": {"type": "string"},
      "company_name": {"type": ["string", "null"]},
      "founded_year": {"type": ["integer", "null"]},
      "category": {"type": "string", "enum": ["invoice", "receipt", "other", "unclear"]},
      "category_detail": {"type": ["string", "null"]}
    },
    "required": ["document_id", "company_name", "founded_year", "category", "category_detail"],
    "additionalProperties": false
  }
}

Support for strict tools and these schema features must be checked in the target interface. Validate the schema before a run. Do not “fix” an unsupported schema by silently removing the missing-value path while continuing to promise truthful extraction.

Worked example: extract before enriching

The supplied teaching document is identified as DOC-R7 and contains: “Acme Services. This is an internal maintenance memo.” It states no founding year and is neither an invoice nor a receipt. The expected proposed input is:

{
  "document_id": "DOC-R7",
  "company_name": "Acme Services",
  "founded_year": null,
  "category": "other",
  "category_detail": "Internal maintenance memo"
}

The application checks the schema, matches the document ID to the actual source, verifies each extracted value, and requires a nonempty detail for other. Only then does it mark metadata accepted and start an authorized enrichment stage. If the ID is wrong, the source is missing, or validation fails, enrichment remains pending.

Keep original extraction separate from later enrichment. A later lookup of a founding year must carry its own provenance; it cannot retroactively become a value stated in the memo. After accepting metadata, change the tool-choice configuration for the next stage as needed instead of forcing extraction repeatedly.

Validate semantics and normalization

A schema can require numbers for line items and a total without verifying their relationship. Under a teaching contract with no tax, discounts, or other adjustments, items of 1,200 and 800 cents must sum to 2,000 cents. A total of 2,100 is structurally numeric but semantically inconsistent. If tax is allowed, that simpler sum rule is insufficient; include the actual components and arithmetic policy.

Define normalization explicitly: currency unit, decimal precision, date interpretation, and whether the source reports an approximate value. Do not infer a timezone or reorder an ambiguous date merely to fit a string format. Preserve the raw value and flag unresolved interpretation when necessary. The source notes that format annotations may not be enforced by the described structured-output implementation, so use the appropriate application-level validator as well.

Handle non-success outcomes

Supported strict output constraints reduce formatting failures; they do not promise that every request succeeds on its first attempt. Invalid schemas, unsupported features, interrupted or truncated responses, refusals, and exhausted validation retries require explicit handling. Inspect the documented completion status before consuming the payload.

Keep a bounded retry policy. Feed a correctable validation error back with the relevant source, then validate the revised result again. Do not replace a failed structured extraction with unmarked free-form text in a field that downstream code assumes is validated. Retain the last error and route unresolved cases appropriately.

Bound schema and tool-choice claims precisely

Exact interface details here are attributed to the supplied source snapshot. Its original cited anchor attachments were not available, and no current API/SDK/CLI/MCP call was performed. A schema constrains only what it actually declares: a required property name or enum can constrain those tokens, but a free string is not automatically canonicalized for casing, spelling or truth. Supported constraints can express some conditional rules; do not generalize the described Claude Code format-annotation limitation to every JSON Schema validator.

Use the supplied glossary as the terminology registry and a starting point for source anchors, not as the primary knowledge base or final leaf-level anchor registry. Its entries are the contract source for terminology fields. The relevant Dxx domain knowledge documents are the primary factual sources and govern conflicts with glossary content, including D04 for these structured-output interfaces. An anchor candidate flag marks a candidate, and the glossary quality summary is a preflight summary; neither alone establishes factual adoption or final approval.

The source describes auto as the default tool choice. A named choice must exactly match a tool identifier actually exposed in the request. Choice, argument schema, per-turn cardinality, total iterations, authority and actual execution are separate controls. The source examples place disable_parallel_tool_use inside tool_choice, whereas later prose calls it request-level. That placement inconsistency needs the actual supported API contract; this article does not certify both placements. Its intended single-call-per-turn restriction does not cap the number of future turns or prove the chosen schema/facts correct.

A forced weather proposal is not weather retrieval

The source weather sample uses a dated model identifier and omits strict: true. Do not assume current model availability or strictness from that sample. The following is a complete illustrative tool definition, to be used only where the actual model/API supports these fields:

{
  "name": "get_weather",
  "description": "Request current weather for the supplied city; the application must call its actual weather provider.",
  "strict": true,
  "input_schema": {
    "type": "object",
    "properties": {"location": {"type": "string", "minLength": 1}},
    "required": ["location"],
    "additionalProperties": false
  }
}

For supplied user text "What is the weather in London, UK?" and supported named choice {"type":"tool","name":"get_weather"}, an expected content block is {"type":"tool_use","id":"example-call-1","name":"get_weather","input":{"location":"London, UK"}}. That example ID is illustrative, not an actual API identifier. It contains arguments only. The authorized application would validate name/id/input, call the configured provider and return the corresponding real tool result. Until it does so, current weather is unknown; a missing provider, unsupported model/thinking combination or failed call leaves retrieval pending. No temperature or successful weather service result is invented.

Complete semantic rejection examples

Under a declared invoice policy, line_items are per-line integer USD-cent amounts after quantity multiplication, with no tax/discount/fees and no further rounding. A structurally valid but wrong object is {"currency":"USD","unit":"cent","line_items":[1200,800],"total":2100}. The expected structural outcome is acceptance if the declared schema permits these fields/types; the expected business outcome is rejection because 1200 + 800 = 2000. A source-supported correction is {"currency":"USD","unit":"cent","line_items":[1200,800],"total":2000}. If the source includes tax, this simple rule must be replaced with that actual component policy; type alone cannot determine the correction.

For an explicitly supplied contact source, "Email: [email protected]; phone: +1-202-555-0100," the object {"email":"+1-202-555-0100","phone":"[email protected]"} may pass a two-string schema while failing field assignment. Expected corrected data is {"email":"[email protected]","phone":"+1-202-555-0100"}, justified by that source and appropriate application validators. If the email is absent/ambiguous, retain missingness rather than infer it from a phone number or a format annotation. These are expected comparisons, not executed validators.

Optional omission is a different contract

The earlier tool deliberately uses required nullable fields. For a different omission policy, this complete illustrative schema requires only the known company name:

{
  "type": "object",
  "properties": {
    "company_name": {"type": "string", "minLength": 1},
    "founded_year": {"type": "integer"},
    "headquarters": {"type": "string", "minLength": 1}
  },
  "required": ["company_name"],
  "additionalProperties": false
}

For source "Acme Services is the company named in this memo," expected output is {"company_name":"Acme Services"}: unknown optional fields stay absent. Under this schema, present integer founded_year is structurally permitted but still needs actual source support; omitted founded_year is permitted, null founded_year is rejected, and "unknown" as founded_year is rejected as wrong type. Missing company_name or an empty company_name is rejected. By contrast, the earlier required nullable policy accepts explicit null for its absent year, requires that key to remain present and rejects omission. Empty strings are not substitutes for unknown; under the earlier extraction policy, empty entities would need a separately declared empty-array meaning rather than implying missing extraction succeeded. Omission/null reduces pressure to invent facts but does not prevent hallucination automatically.

The source's role example allows only admin/user/guest; its optional details string does not create an other role. Align the actual enum and consumer policy before illustrating extension.

Coherent fallback and input examples

For a ticket proposal, this illustrative definition declares required fields instead of relying on example correlation. input_examples is a source-interface feature to verify, not a universal MCP/SDK field:

{
  "name": "create_ticket",
  "description": "Propose a ticket only. Do not create it without separately authorized application dispatch.",
  "input_schema": {
    "type": "object",
    "properties": {
      "title": {"type": "string", "minLength": 1},
      "priority": {"type": "string", "enum": ["critical", "high", "unclear"]},
      "category": {"type": "string", "enum": ["bug", "feature", "other", "unclear"]},
      "category_detail": {"type": ["string", "null"]},
      "labels": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["title", "priority", "category", "category_detail", "labels"],
    "additionalProperties": false
  },
  "input_examples": [
    {"title":"Login unavailable to all users; no workaround","priority":"critical","category":"bug","category_detail":null,"labels":["authentication"]},
    {"title":"Request for office relocation","priority":"unclear","category":"other","category_detail":"Workplace logistics request","labels":[]},
    {"title":"Unclear report","priority":"unclear","category":"unclear","category_detail":null,"labels":[]}
  ]
}

Declare that labels [] means no labels established by evidence. Application checks require a nonempty meaningful detail for other and null detail for standard/unclear cases in this teaching policy. Other with null/empty detail is rejected even if the base schema accepts it. Unclear records insufficient evidence; other records known content outside the standard taxonomy. These examples teach expected correlations, neither enforce the conditional rule nor create any ticket.

Distinct extraction paths and real handoffs

Under an illustrative classifier, these complete definitions use separate strict schemas, only where the actual interface supports them:

[
  {"name":"extract_invoice","description":"Extract vendor and the USD-major-unit total only from a document explicitly labeled as an invoice.","strict":true,"input_schema":{"type":"object","properties":{"vendor":{"type":"string"},"total":{"type":"number"}},"required":["vendor","total"],"additionalProperties":false}},
  {"name":"extract_receipt","description":"Extract merchant and the stated date only from a document explicitly labeled as a receipt.","strict":true,"input_schema":{"type":"object","properties":{"merchant":{"type":"string"},"date":{"type":"string"}},"required":["merchant","date"],"additionalProperties":false}}
]

The invoice total is in USD major units under this teaching policy; it does not infer cents or convert currencies. The receipt date is normalized only under the later declared unambiguous date policy. For source "Invoice from Acme; total USD 20," expected candidate is extract_invoice input {"vendor":"Acme","total":20}, with amount/currency interpretation separately declared. For "Receipt from Corner Shop dated 2026-11-20," expected candidate is extract_receipt input {"merchant":"Corner Shop","date":"2026-11-20"}. For "Unlabeled internal memo," neither required vendor/total nor merchant/date should be invented: use an explicitly supported unknown route or leave classification pending. These are complete expected arguments under the two declared schemas, not actual attached documents or measured model choices. The any setting alone does not prove correct selection.

The metadata example intentionally replaces the source's inconsistent entities/timestamp versus extracted_entities fields with one stated contract. DOC-R7 is an application-supplied document identity, not a claimed UUID. No timestamp/confidence is inferred from the memo. If confidence is added, define what it measures and encode its actual range, for example a declared numeric 0–1 range with explicit bounds; a description alone is not enforcement and a score is not calibrated truth.

After accepted extraction, an agents definition does not prove a worker launched. Each actually invoked enrichment worker needs the validated payload, source provenance, task/criteria and unresolved questions. Only independent authorized paths may overlap; dependencies retain order. Worker intermediate results remain in that worker while its final message returns. Missing final results stay pending. The ideal parallel slowest-task pattern excludes dispatch, aggregation, waits, retries and resource contention; actual elapsed time includes them and total worker cost remains relevant. No measured speedup is claimed.

Keep protocol and SDK representations coherent

The abbreviation MCP denotes Model Context Protocol in the adopted glossary. That expansion alone establishes no automatic discovery, server/client behavior, parameter validation or permission to invoke a tool; the result and adapter contracts below remain source-interface-specific.

MCP server results use their actual structuredContent and declared outputSchema; where the described compatibility path includes TextContent, serialize the same actual data there rather than a second independently invented result. For example, an actual structured result {"status":"not_found"} would be mirrored as that identical JSON string in TextContent. Shape does not prove underlying fact or success. Model arguments/input_schema and server results/outputSchema are separate boundaries.

MCP adapter steps here are conceptual: register/discover the intended server under the actual client, map its identifier to the exact name exposed in the model tool list, validate the matching call, dispatch through the authorized authenticated transport, then preserve the associated actual result. Claude Code's .mcp.json is client-specific. Do not combine source list_tools/call_tool spellings, input-schema keys or transport with a universal raw Messages API auto-discovery claim. An unavailable mapping/transport or failed call remains explicit; forcing a name grants no server authority.

The source SDK final-output concept is {type:"json_schema",schema:rawJsonSchema} via TypeScript outputFormat or Python output_format. It describes Zod conversion with z.toJSONSchema(schema,{target:"draft-7"}) and Pydantic .model_json_schema() as conversion to JSON Schema. Its raw-schema helper differs from directly passing a Zod object, and source package imports/undefined agent.query fragments are inconsistent. Treat those caller/import fragments as conceptual until an actual supported package/type/signature is established. The source helper transform default true is compatibility assistance, not universal feature support or business validation. Do not invent a current import or executable SDK constructor from this material.

A later source paragraph calls the final-output field output_format for both Python and TypeScript, whereas its earlier declaration uses TypeScript outputFormat and Python output_format. Preserve this naming conflict and check the actual supported SDK contract instead of treating one generic spelling as universal.

Complete headless shape and failure handling

A POSIX-shell illustration with the source-established string schema form and actual input route is:

claude -p "Extract function names only from the supplied text." --output-format json --json-schema '{"type":"array","items":{"type":"string"}}' < module.txt

If module.txt contains def parse_count(value): return value, an expected relevant envelope excerpt is {"structured_output":["parse_count"]}; actual session/usage metadata is separate. Check completion before reading that member. Missing input, malformed schema or failed generation is not an empty successful extraction. The snapshot invalid-schema diagnostic is Error: --json-schema is not a valid JSON Schema with validator details. This command was not run.

The source attributes invalid-schema/format-history differences to Claude Code before v2.1.205. Keep that CLI release history separate from unknown SDK versions. Its error/condition label error_max_structured_output_retries does not establish a public settable option or common behavior across every interface. Separate supplied-schema startup rejection, generated shape mismatch, bounded retry exhaustion and semantic failure; correct and revalidate the relevant layer. Preserve real errors instead of accepting unmarked partial/free-form output.

Complete normalization policies and expected cases

For this date-only teaching policy, accept explicitly unambiguous Gregorian YYYY-MM-DD and English DD Month YYYY, validate calendar days, and output YYYY-MM-DD without adding time or timezone. Do not interpret slash-order ambiguity. No expiry or date arithmetic is performed. Each row has an application-supplied source_id identifying that invented source fixture, including the missing-value fixture; it is not an invented document fact:

Raw input Expected complete result
20 November 2026 {"source_id":"date-fixture-1","raw":"20 November 2026","date":"2026-11-20","status":"normalized"}
2026-11-20 {"source_id":"date-fixture-2","raw":"2026-11-20","date":"2026-11-20","status":"normalized"}
03/04/2026 {"source_id":"date-fixture-3","raw":"03/04/2026","date":null,"status":"ambiguous"}
2026-02-30 {"source_id":"date-fixture-4","raw":"2026-02-30","date":null,"status":"invalid"}
null {"source_id":"date-fixture-5","raw":null,"date":null,"status":"missing"}

Retain the raw value and source. A timestamp policy would separately need timezone/offset and actual conversion rules; ISO wording alone cannot supply those. These are expected outputs, not actual parser tests.

Currency notation is not economic conversion. Under a declared USD decimal notation with cents, "USD 1,234.50" is expected to become {"raw":"USD 1,234.50","currency":"USD","amount_minor":123450,"status":"normalized"}; the monetary amount is unchanged, while its numeric representation changes from 1,234.50 USD to 123,450 US cents.

For a separate fictional conversion exercise, supply source EUR 10.00, rate 1.20 USD per EUR, source label "provided teaching fixture," rate date 2026-11-20, integer-cent target and half-up cent rounding. Expected result is {"source_currency":"EUR","source_amount_minor":1000,"target_currency":"USD","target_amount_minor":1200,"rate":1.20,"rate_source":"provided teaching fixture","rate_date":"2026-11-20","status":"converted_example"}, since 10.00 × 1.20 = 12.00 USD. This is supplied arithmetic, not a live rate or financial result.

Without a valid supplied rate/source/date, retain {"source_currency":"EUR","source_amount_minor":1000,"target_currency":"USD","target_amount_minor":null,"status":"missing_conversion_evidence"}. Prompt instructions and string format do not validate the economic fact; application checks must enforce the declared units/rate/rounding and preserve uncertainty.

Give priority examples an explicit business basis

For the create_ticket examples only, declare a teaching rule: critical requires a confirmed core login outage affecting all users with no workaround; high requires a confirmed substantial partial impact; unclear means the impact evidence is insufficient. This is not a universal incident severity policy. Category bug/feature/other/unclear remains a separate classification. Expected complete proposals below follow the earlier schema and detail/labels rules, and create no ticket:

[
  {"source":"Confirmed login outage affects every user and has no workaround.","expected_input":{"title":"Login unavailable to all users; no workaround","priority":"critical","category":"bug","category_detail":null,"labels":["authentication"]}},
  {"source":"Confirmed export defect affects a substantial subset of users; login works and a documented manual export workaround remains.","expected_input":{"title":"Partial export defect with workaround","priority":"high","category":"bug","category_detail":null,"labels":["export"]}},
  {"source":"Request to relocate the office; no incident impact evidence supplied.","expected_input":{"title":"Request for office relocation","priority":"unclear","category":"other","category_detail":"Workplace logistics request","labels":[]}},
  {"source":"Something seems wrong; no specific behavior or impact supplied.","expected_input":{"title":"Unclear report","priority":"unclear","category":"unclear","category_detail":null,"labels":[]}}
]

An isolated "Login returns 500" without observed population/workaround evidence does not meet this critical rule; retain priority:unclear or obtain the missing facts. The critical example above assumes its stated confirmation, not a real measured outage. A shape-valid critical field cannot supply that evidence. For date normalization, the earlier source_id values identify five distinct supplied fixtures; retaining source identity does not prove an unseen document was read. No expiry boundary or time interval is inferred from these date-only transformations.

Complete company cases and the actual legacy claim

Use the optional-omission schema above for the following separate invented source fixtures. Each candidate payload is complete for its row; these are expected local shape/source checks, not actual model extractions or executed validators:

Exact supplied source Complete candidate payload Expected result under the optional-omission schema
Acme Services was founded in 2001 and has headquarters in London. {"company_name":"Acme Services","founded_year":2001,"headquarters":"London"} Accept shape and these source-stated fields; no further company facts are established.
Acme Services is the company named in this memo. No year or headquarters is stated. {"company_name":"Acme Services"} Accept omission; retain year/headquarters as unknown.
Acme Services is named; no year is stated. {"company_name":"Acme Services","founded_year":null} Reject shape: this optional integer property does not allow null. Correct omission-policy payload is {"company_name":"Acme Services"}.
Acme Services is named; no year is stated. {"company_name":"Acme Services","founded_year":"unknown"} Reject shape: the string is not an integer. Correct omission-policy payload is {"company_name":"Acme Services"}.
Acme Services is named; no year is stated. {"company_name":"Acme Services","founded_year":2001} Shape may accept the integer, but reject source support: the year is not stated. Correct omission-policy payload is {"company_name":"Acme Services"}.
Acme Services was founded in 2001. {"founded_year":2001} Reject missing required company_name; source-supported correction is {"company_name":"Acme Services","founded_year":2001}.

The earlier distinct required-nullable extract_metadata schema instead expects the complete DOC-R7 object already shown, including founded_year:null and every other required field. Removing its founded_year key is rejected, whereas the explicit null is permitted by that schema and records the source's missing year. A present integer value in either contract still needs the source evidence; nullable and optional do not verify facts.

The supplied Claude Code snapshot reports that before v2.1.205 invalid schemas could be silently ignored and unstructured text returned. It also reports earlier clients treating a schema containing format as invalid, with some source passages describing the same unstructured fallback. In the later described behavior, malformed schemas fail startup with the stated diagnostic, whereas accepted format annotations still do not enforce email/date/URL validity. These are attributed historical CLI reports, not verified current behavior or an SDK-wide version guarantee. Keep the actual client's version, startup result and payload state; never accept a legacy free-text fallback as a validated structured result.

Summary

Structured output establishes a data shape. Tool choice establishes how a proposal is requested. Application checks establish source consistency, business validity, and readiness for the next stage. Preserve these boundaries, including truthful missingness and explicit non-success outcomes.

PUBLIC BETA OFFER

Save 50% off on an Eligible Learning Plan

Valid for 1-month plan, 3-month plan, 12-month plan · Code LPXBETA50 · Ends Dec 6, 2026

Ready to put this into practice?

Start guided practice →