Skip to main content
Pass a Zod 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

Install zod, set OPENAI_API_KEY, and run:
A successful call returns 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:
Tool steps are yielded before conversion. Conversion begins only after the agent produces non-empty final text.

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:
Progress events are emitted every two seconds while conversion is still running. 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.
Conversion runs only when the agent produces non-empty final text. If no final text exists, run() and stream() currently return "No output generated" even when schema is set. Treat that string as an unsuccessful structured result.

Next steps