Skip to content

Commit 6786412

Browse files
authored
fix(ai-sdk)!: disable output validation in createToolFactory (#2465)
`createToolFactory` validated (and transformed) procedure outputs, but its types described the output schema's **input** side. The AI SDK also treats a tool's output as that input side, so the runtime was the odd one out: ```ts const t = createToolFactory()(os.output(z.string().transform((s) => s.length)).handler(() => 'hello')) // InferToolOutput<typeof t> is `string`, but `await t.execute(...)` returned `5` ``` In AI SDK v7, `asSchema` turns a schema into JSON Schema from its input side (`jsonSchema.input(...)`, or Zod with `io: 'input'`). `validateUIMessages` also checks stored tool outputs by running `outputSchema`'s `validate`. So a stored, already-transformed output (`5`) failed `safeValidateUIMessages` against `z.string()`. The AI SDK never validates what `execute` returns while a tool runs. ## Changes - `createToolFactory` now disables output validation as well as input validation. The tool outputs what the handler returns (the schema input), matching `implementToolFactory` and plain AI SDK tools. The types are unchanged; they were already the input side. - Docs: the Tool Factory section now notes that tool outputs aren't validated or transformed. The streaming section says "declared with `asyncIteratorObject`" instead of "validated with". ## Breaking change `createToolFactory` tools no longer validate or transform procedure outputs, including each event of an `asyncIteratorObject` output. An invalid handler result now reaches the model unchanged instead of throwing `Output validation failed`. ## Tests In `tool.test.ts`: - A transforming output schema now returns the handler's value (`'hello'`), and that stored output passes `safeValidateUIMessages`. - Streamed events are no longer validated against the yield schema. - Removed the two tests that asserted output validation errors. I checked that the new tests fail against `main`'s `tool.ts`. `pnpm check`, `pnpm docs:validate` and `pnpm test` pass.
1 parent ce8dfeb commit 6786412

3 files changed

Lines changed: 42 additions & 31 deletions

File tree

‎apps/content/docs/integrations/ai-sdk.mdx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,13 @@ const getWeatherTool = createTool(getWeatherProcedure, {
200200
})
201201
```
202202

203+
:::info
204+
Like plain AI SDK tools, the tool does not validate its output: it returns what the handler returns, without applying the output schema's transforms.
205+
:::
206+
203207
### Streaming Tool Outputs
204208

205-
When a procedure outputs an [AsyncIteratorObject](/docs/async-iterator-object), either validated with `asyncIteratorObject` or produced by an `async function*` handler, the resulting tool streams every event as a [preliminary tool result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results): each event replaces the tool output in the UI, and the last event becomes the final tool result sent to the model.
209+
When a procedure outputs an [AsyncIteratorObject](/docs/async-iterator-object), either declared with `asyncIteratorObject` or produced by an `async function*` handler, the resulting tool streams every event as a [preliminary tool result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results): each event replaces the tool output in the UI, and the last event becomes the final tool result sent to the model.
206210

207211
```ts
208212
import { asyncIteratorObject, os } from '@orpc/server'

‎packages/ai-sdk/src/tool.test.ts‎

Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { asyncIteratorObject, oc, type } from '@orpc/contract'
22
import { OpenAPIJsonSerializer } from '@orpc/openapi'
33
import { os } from '@orpc/server'
4-
import { generateText } from 'ai'
4+
import { generateText, safeValidateUIMessages } from 'ai'
55
import { MockLanguageModelV4 } from 'ai/test'
66
import * as z from 'zod'
77

@@ -274,7 +274,7 @@ describe('implementToolFactory', () => {
274274
})
275275
})
276276

277-
it('the AI SDK does not validate execute results against outputSchema, so oRPC must validate output itself', async () => {
277+
it('the AI SDK does not validate execute results against outputSchema', async () => {
278278
const contract = oc.input(inputSchema).output(outputSchema)
279279

280280
const greet = implementToolFactory()(contract, {
@@ -539,17 +539,34 @@ describe('createToolFactory', () => {
539539
expect(handler).toHaveBeenCalledWith(expect.objectContaining({ input: 'invalid' }), 'invalid')
540540
})
541541

542-
it('keeps output validation enabled because the AI SDK does not validate execute results', async () => {
543-
const procedure = os
544-
.input(inputSchema)
545-
.output(outputSchema)
546-
.handler(() => ({ greeting: 123 }) as any)
542+
it('disable output validation at oRPC level, so stored outputs pass validateUIMessages', async () => {
543+
const procedure = os.output(z.string().transform((s) => s.length)).handler(() => 'hello')
547544

548545
const tool = createToolFactory()(procedure)
549546

550-
await expect(tool.execute?.({ name: 'Alice' }, { abortSignal } as any)).rejects.toThrow(
551-
'Output validation failed',
552-
)
547+
const output = await tool.execute?.(undefined, { abortSignal } as any)
548+
expect(output).toBe('hello')
549+
550+
const result = await safeValidateUIMessages({
551+
messages: [
552+
{
553+
id: 'message-1',
554+
role: 'assistant',
555+
parts: [
556+
{
557+
type: 'tool-tool',
558+
toolCallId: 'call-1',
559+
state: 'output-available',
560+
input: {},
561+
output,
562+
},
563+
],
564+
},
565+
],
566+
tools: { tool },
567+
})
568+
569+
expect(result.success).toBe(true)
553570
})
554571

555572
describe('async iterator output', () => {
@@ -600,19 +617,7 @@ describe('createToolFactory', () => {
600617
expect(finallyCalled).toBe(true)
601618
})
602619

603-
it('rejects when handler ignores the declared iterator schema', async () => {
604-
const procedure = os
605-
.input(inputSchema)
606-
.output(asyncIteratorObject(yieldSchema))
607-
.handler(async () => ({ message: 'not an iterator' }) as any)
608-
609-
const tool = createToolFactory()(procedure)
610-
611-
const iterator = (tool as any).execute({ name: 'Alice' }, { abortSignal })
612-
await expect(iterator.next()).rejects.toThrow('Output validation failed')
613-
})
614-
615-
it('validates each streamed event against the yield schema', async () => {
620+
it('does not validate streamed events against the yield schema', async () => {
616621
const procedure = os
617622
.input(inputSchema)
618623
.output(asyncIteratorObject(yieldSchema))
@@ -623,9 +628,12 @@ describe('createToolFactory', () => {
623628

624629
const tool = createToolFactory()(procedure)
625630

626-
const iterator = (tool as any).execute({ name: 'Alice' }, { abortSignal })
627-
await expect(iterator.next()).resolves.toEqual({ done: false, value: { message: 'one' } })
628-
await expect(iterator.next()).rejects.toThrow('AsyncIteratorObject validation failed')
631+
const outputs: unknown[] = []
632+
for await (const output of (tool as any).execute({ name: 'Alice' }, { abortSignal })) {
633+
outputs.push(output)
634+
}
635+
636+
expect(outputs).toEqual([{ message: 'one' }, { message: 123 }])
629637
})
630638

631639
it('streams events when the handler is an async generator without an output schema', async () => {

‎packages/ai-sdk/src/tool.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -332,14 +332,13 @@ export function createToolFactory<TInitialContext extends Context = object>(
332332
const toolOptions = resolveMaybeOptionalOptions(rest)
333333

334334
/**
335-
* The AI SDK already validates input against the tool's `inputSchema`,
336-
* so input validation is disabled at the oRPC level to avoid validating twice.
337-
* Output validation stays enabled because the AI SDK does not validate
338-
* the value returned from `execute` against the tool's `outputSchema`.
335+
* The AI SDK validates input itself, and treats outputs as the output schema's
336+
* input side (e.g. in `validateUIMessages`), so oRPC validates neither.
339337
*/
340338
const disabledValidation = new Procedure({
341339
...procedure['~orpc'],
342340
disableInputValidation: true,
341+
disableOutputValidation: true,
343342
})
344343

345344
/**

0 commit comments

Comments
 (0)