mastra-structured-output
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Make a Mastra agent return a typed, schema-validated object instead of text, with structuredOutput on generate() or stream(), response.object, objectStream, a separate structuring model, jsonPromptInjection, and errorStrategy fallbacks. Use this skill whenever the user wants JSON output, typed results, data extraction, classification labels, or form-like answers from an agent, or when tools and structured output conflict on a model. Triggers on structuredOutput, response.object, stream.object, objectStream, object-result, jsonPromptInjection, errorStrategy, fallbackValue, usedFallbackValue, structuring model, useAgent, response_format, JSON schema output, Zod output schema, Valibot, ArkType, deprecated output option. Also triggers when an agent step in a workflow must return typed data, or when Gemini errors with function calling and a JSON response mime type.
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 0 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 97
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/core/dist/docs/ and the installed StructuredOutputOptions type.
- Very specific: line 98
Write the schema: Keep it flat where possible.
- Very specific: line 100
Check tools: If the agent has tools, test the model with both.
- Very specific: line 101
Set
errorStrategy: Use 'fallback' with a safe fallbackValue on user-facing paths, and branch on usedFallbackValue. - Very specific: line 136
Using the deprecated
outputoption: Use structuredOutput without a model for the same behavior. - Very specific: line 137
Parsing
response.textwithJSON.parse: Read response.object. It is already validated and typed. - Very specific: line 138
Treating a fallback as a real answer: Check response.usedFallbackValue under errorStrategy: 'fallback'.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Structured Output
Get a validated, typed object from an agent by passing a schema in structuredOutput and reading response.object.
When to use
- The caller needs data, not prose: extraction, classification, summaries with fixed fields, UI payloads
- Reading
response.objector streaming partial objects withobjectStream - An agent step in a workflow must return typed data for the next step
- Tools and structured output fail together on a model
- Large schemas cost too many tokens per step
- Deciding what happens when the model returns an invalid object
When NOT to use
- Tool input and output schemas (use
mastra-tools) - General agent setup and
generate()/stream()basics (usemastra-agents) - Stream chunk types and stream consumption in general (use
mastra-streaming) - Labeling inputs with a dedicated classifier primitive (use
mastra-classifier) - Validating or rewriting output with processors and guardrails (use
mastra-processors-guardrails) - Workflow step wiring beyond the agent step itself (use
mastra-workflows) - Picking a model that supports native JSON output (use
mastra-models)
Required inputs
- The target shape: fields, types, required versus optional, enums
- Schema library in the project (Zod, Valibot, ArkType, or plain JSON Schema)
- Whether the agent also calls tools in the same run
- Whether the caller needs partial results while streaming
- What to do on invalid output: throw, warn, or return a fallback
The framework: schema in, object out
import { z } from 'zod'
const response = await testAgent.generate('Help me plan my day.', {
structuredOutput: {
schema: z.array(
z.object({
name: z.string(),
activities: z.array(z.string()),
}),
),
},
})
console.log(response.object) // typed from the schemaThe schema is input. The object is output. response.object is already parsed and validated, so do not parse it again. response.text is still available.
Schemas: any Standard JSON Schema library (Zod, Valibot through toStandardJsonSchema, ArkType) or a plain JSON Schema object. Zod gives type inference and runtime validation.
Four ways the schema reaches the model
| Mode | How | Cost | Use when |
| Native (default) | Provider response_format | One call | The model supports native JSON output |
jsonPromptInjection: 'auto' | Native if supported, else inline injection | One call | You do not know the model's capability |
jsonPromptInjection: 'inline' | 'system' | true | Schema text injected into the prompt | One call, more input tokens | Model rejects tools plus response_format |
model: 'provider/model' | A second structuring agent converts the main answer | Two calls | Main model is weak at structuring, or uses tools heavily |
'inline' adds to the latest user message. true or 'system' adds to the system message.
Errors
errorStrategy | Behavior |
'strict' (default) | Throws on validation or structuring failure |
'warn' | Logs a warning and continues |
'fallback' | Returns fallbackValue and sets response.usedFallbackValue: true |
fallbackValue never went through the schema. Check usedFallbackValue before trusting the object.
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/core/dist/docs/and the installedStructuredOutputOptionstype. Otherwise fetchhttps://mastra.ai/docs/agents/structured-output.mdandhttps://mastra.ai/reference/agents/generate.md. Trust these over memory. - Write the schema. Keep it flat where possible. Use enums for labels. Add
.describe()on ambiguous fields. - Call with
structuredOutput: { schema }and readresponse.object(orawait stream.object). - Check tools. If the agent has tools, test the model with both. On errors or tools never being called, pick a workaround:
jsonPromptInjection: 'auto', a structuringmodel, orprepareStep. - Set
errorStrategy. Use'fallback'with a safefallbackValueon user-facing paths, and branch onusedFallbackValue. - Trim tokens. With prompt injection and a large schema, set
instructionsto a compact field description. - Stream if needed. Iterate
stream.objectStreamfor partial objects. Readawait stream.objectfor the final one. - In workflows, pass
structuredOutputtocreateStep(agent, {...})or.agent(agent, {...})so the step'soutputSchemamatches. - Test with real inputs, including edge cases that tempt the model to add prose or skip fields.
Deep dive: tools plus structured output
Some provider APIs cannot combine function calling and response_format in one call. This is a model limitation, not a Mastra one. Gemini 2.5 with tools fails with Function calling with a response mime type: 'application/json' is unsupported unless you set jsonPromptInjection: true.
Option 1, let Mastra choose:
structuredOutput: { schema, jsonPromptInjection: 'auto' }Option 2, a separate structuring model. The main agent does all steps including tool calls. The structuring model only builds the object. Add useAgent: true to let it see conversation memory.
const response = await testAgent.generate('Tell me about TypeScript.', {
structuredOutput: {
schema: yourSchema,
model: 'openai/gpt-6.1-sol',
},
})Option 3, split steps with prepareStep: call tools in step 0 with toolChoice: 'required', then return tools: undefined and structuredOutput for later steps (see references/examples.md).
Failure patterns
- Using the deprecated
outputoption. UsestructuredOutputwithout amodelfor the same behavior. - Parsing
response.textwithJSON.parse. Readresponse.object. It is already validated and typed. - Treating a fallback as a real answer. Check
response.usedFallbackValueundererrorStrategy: 'fallback'. - Tools never called once structured output is on. The model cannot combine them. Use
jsonPromptInjection: 'auto', a structuringmodel, orprepareStep. - Gemini 2.5 JSON mime type error with tools. Set
jsonPromptInjection: true. - Huge token bills per step. Prompt injection embeds the full schema every call. Add a compact
instructionsstring that lists every field. instructionsset with native structured output. It has no effect without injection or a structuring model.- Structuring model ignores earlier turns. It only sees the current response. Set
useAgent: truewith memory. - Reading
stream.objectbefore the stream finishes. Await it, or consumeobjectStreamfor partials. model: 'openai:gpt-...'or a provider object for the structuring model. Use a router string such as'openai/gpt-6.1-sol'.
Output format
A finished structured output delivery contains:
- The schema in a shared module (for example
src/mastra/schemas/<name>.ts) so callers and tests import the same type - The
generate()/stream()call, workflow step, or route usingstructuredOutput - An explicit
errorStrategy, withusedFallbackValuehandled when using'fallback' - A note on the chosen mode (native, injection, or structuring model) and why
- A test or Studio run showing a valid object for representative inputs
Reference files
references/api.md-structuredOutputoptions, result fields, stream fields, workflow step usage.references/examples.md- Extraction with fallback, streaming partial objects, tools plus structuring model,prepareStepsplit, workflow agent step.references/checklist.md- Checklist for typed agent output.
Live docs
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

