schema to LangChainMCPAgent when you need validated data. The agent completes the task first, then asks the model to convert the final text and validates the result with Zod.
Return a typed result
Installzod, set OPENAI_API_KEY, and run:
z.infer<typeof ProjectSummary>. It does not return the raw final text.
Choose a structured-output method
run() consumes stream() internally, so both methods use the same conversion path.
Read the return value from stream()
A for await loop cannot read an async generator’s return value. Call next() until done when you need the validated result:
Handle structured events
streamEvents() adds the schema description to the task so the agent gathers the required fields. It yields the underlying LangChain v2 events first, then custom conversion events:
streamEvents() returns void; store the on_structured_output payload yourself.
Handle validation boundaries
LangChainMCPAgent uses withStructuredOutput(schema) when the model implements it. Otherwise, it prompts the same model to format JSON. It validates the result and retries conversion up to three times, including the previous validation error in later attempts.
After three failures, the conversion error includes:
run() and stream() wrap that message in Failed to generate structured output: .... streamEvents() emits the message in on_structured_output_error.
Required fields fail validation when they are null, undefined, an empty string, or an empty array, even if a broad Zod schema would otherwise accept the empty value. Mark genuinely missing values as optional or nullable.