Your agent’s create_book tool carries a Zod schema typed in beside BookCreateData, the
parameter type the generator wrote. The API renames year to published and the SDK
regenerates, but the tool still advertises year. The model fills it in, and the SDK forwards
the key to an API that no longer reads it.
What you get
You will end up with one generated SDK method registered as a Vercel AI SDK tool, its input schema lifted from the OpenAPI operation, plus a type check for hand-written schemas. This is for you if you hand an agent a typed client.
Short answer
Build the client once, outside the tool, and make the tool’s input the method’s data parameter
alone. In the Vercel AI SDK, lift that schema from the OpenAPI operation the method came from,
turn nullable into a type array, and pass it to tool through jsonSchema with a validate
function. A hand-written Zod schema validates on its own, but it needs a compile-time check
against the SDK’s type to stay current.
You will need
Node 22 or later, a TypeScript client generated from an OpenAPI document, and that document.
Verified 2026-11-21 against ai 7.0.179, @voxgig/sdkgen 4.44.3, openapi-typescript 7.13.0
and openapi-fetch 0.17.0. The agent loop itself is covered in
build a tool-calling loop with the Claude Agent SDK.
No command here calls a model: the AI SDK’s
MockLanguageModelV4 plays a fixed script
against stand-in servers on 127.0.0.1.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| Fern | Your SDK is Fern’s, or you would rather host generated tools than register them | Needs a Fern account, and a hosted server on the free plan pauses at 1,000 tool calls a month | The tool must run in your own process |
| Hand-written Zod schemas | A few tools whose descriptions you want written for a model | Every field is written twice, and only a type check notices the copy going stale | The API changes often, or you expose many methods |
| openapi-typescript and openapi-fetch | You want types only, with each call addressed by method and path | No runtime schema exists, and the converter turned its types into a schema nothing satisfies | You want entity methods, or retry and timeout features generated |
| sdkgen generated TypeScript client | Your SDK is generated by sdkgen, whose runtime model names each method’s operation | BookCreateData carries no descriptions or limits, and the constructor’s options are typed any | You want a schema read straight from the types |
Voxgig maintains sdkgen, which is one of four rows here and not a recommendation.
A hand-written schema reads best and drifts first. The lifted schema tracks the document, at the
price of a converter you own and a validator you must attach. openapi-fetch needs no runtime
model to find the operation, because the call names it. Fern’s MCP route removes the schema
work and adds a server, which Fern hosts or, from the zip target in its
quickstart, you run. On
the free plan, hosted tool calls pause at 1,000 a
month.
Read what each schema source hands the model
The method is book.create on a client sdkgen generated from a Bookshelf document. show.mjs
builds the tool three ways, passes all three to one generateText call, and prints the
definitions the mock model received.
node show.mjs sdkgen
book.create, generated from POST /books: what the model receives, * = required
hand-written Zod, described as "Add a book"
title* string, minLength 1, described
author string, described
published integer, minimum 0, maximum 9007199254740991, described
subtitle string|null, described
other keys: refused
BookCreateData through ts-json-schema-generator, described as "Add a book"
author string, no description
published number, no description
subtitle string|null, no description
title* string, no description
other keys: refused
lifted from the OpenAPI operation, described as "Add a book to the shelf"
title* string, minLength 1, described
author string, described
published integer, minimum 0, described
subtitle string|null, described
other keys: refused
The converter, ts-json-schema-generator,
reads the type faithfully, and the type is where the losses happened. sdkgen’s model keeps each
field’s description, but BookCreateData carries none, and TypeScript has no integer type, so
published reaches the model as any number. Zod added a bound of its own.1
Lift the schema from the operation the method came from
The generated SDK exports its model as config, and each operation keeps the method and path it
was generated from. That pair is the key back into the document.
// The generated SDK carries its model at run time. Each operation keeps the method and the
// path it was generated from, which is the key back into the OpenAPI document.
export function operationOf(entity, op) {
const entities = config.entity
if (!Object.hasOwn(entities, entity)) throw new Error(`no entity ${entity} in the SDK model`)
const ops = entities[entity].op
if (!Object.hasOwn(ops, op)) throw new Error(`no operation ${entity}.${op} in the SDK model`)
const points = Array.isArray(ops[op].points) ? ops[op].points : []
if (points.length !== 1) throw new Error(`${entity}.${op} has ${points.length} points, expected 1`)
const [point] = points
return { method: point.method, path: point.orig }
}
fromOpenAPI in the same file inlines local $refs, refuses remote and recursive ones, drops
readOnly properties, and sets additionalProperties: false on objects outside an allOf, whose
members would otherwise refuse each other’s keys. It also rewrites nullable, which
OpenAPI 3.0 adds beside JSON Schema rather than taking from it.2
jsonSchema takes an optional
validation function, so the tool gets one compiled by Ajv from the same schema.
// jsonSchema() describes the input to the model and checks nothing unless it is given a
// validate function, so a JSON Schema source gets one compiled from the same schema.
export function validated(schema) {
const check = ajv.compile(schema)
return jsonSchema(schema, {
validate: (value) =>
check(value) ? { success: true, value } : { success: false, error: new Error(ajv.errorsText(check.errors)) },
})
}
// One SDK method as one tool. The client is built once, outside the tool, so the base URL,
// the key, the retry policy and the timeout are never part of what the model can send.
export function createBookTool(client, inputSchema, description) {
return tool({
description,
inputSchema,
execute: async (data) => (await client.Book().create(data)).data(),
})
}
run.mjs calls the tool’s execute once directly, then lets a scripted model make two calls,
the first with an empty title.
node run.mjs
execute, called directly: {"published":1817,"title":"Persuasion","id":"b1"}
generateText, scripted model:
step 1 refused {"title":"","published":1815}: data/title must NOT have fewer than 1 characters
step 2 result {"author":"Jane Austen","published":1815,"subtitle":null,"title":"Emma","id":"b2"}
requests that reached the API: 2, POST /v1/books with the key: 2
The refused call never left the process. The model’s next prompt carried the validator’s
message as an error-text tool result.
Keep a hand-written schema current with the compiler
A Zod schema needs no validator, because the AI SDK checks model input against it. What it lacks
is a link to the API. check-current.ts supplies one: it compiles only while the schema’s
inferred type and BookCreateData agree field for field.
// The tool's input type, as the AI SDK infers it from the Zod schema.
type Input = z.infer<typeof handWritten>
// Fails to compile, naming the keys, when the schema and the SDK's type disagree on a field.
type Missing = Exclude<keyof BookCreateData, keyof Input>
type Extra = Exclude<keyof Input, keyof BookCreateData>
export const noneMissing: [Missing] extends [never] ? true : Missing = true
export const noneExtra: [Extra] extends [never] ? true : Extra = true
drift.mjs runs tsc over that check for the current schema and for one written against an
earlier draft of the API.
node drift.mjs
schema.mjs against BookCreateData: tsc exit 0
schema-stale.mjs against BookCreateData: tsc exit 2
check-stale.ts(12,14): error TS2322: Type 'true' is not assignable to type '"published"'.
check-stale.ts(13,14): error TS2322: Type 'true' is not assignable to type '"year"'.
check-stale.ts(17,57): error TS2322: Type 'BookCreateData' is not assignable to type '{ title: string; author?: string | undefined; year?: number | undefined; subtitle?: string | undefined; }'.
Types of property 'subtitle' are incompatible.
Type 'string | null | undefined' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.
The check sees names and types. It cannot see a description that went stale or a limit the document added, which is the part of drift a hand-written schema keeps.
Build the same tool over openapi-fetch and Fern
openapi-typescript generates runtime-free types, and
openapi-fetch calls by method and path, so client.POST('/books', { body }) already names the
operation to lift. createBookToolFetch in tools.mjs is that tool. Converting its types fails,
though:
node show.mjs openapi-typescript
client.POST('/books'), typed by openapi-typescript: what the model receives, * = required
CreateBookBody through ts-json-schema-generator, described as "Add a book"
not: {} (no input satisfies this schema)
lifted from the OpenAPI operation, described as "Add a book to the shelf"
title* string, minLength 1, described
author string, described
published integer, minimum 0, described
subtitle string|null, described
other keys: refused
ts-json-schema-generator 2.10.0 returns not: {} for an indexed access into an interface with
a required never member, and the body type reaches NewBook through components, where
openapi-typescript writes responses: never. The types
do keep each description, in a @description comment. Lift from the document here too.
Fern was not run, and what follows describes sdk-config.yml, the format its current pages
use. Its retries page
overrides the retry limit per request with an argument after the request,
client.movie.get("tt0111161", { maxRetries: 3 }). Wrap such a method the same way, and pass
the request alone. Its serdeLayer: true
option validates requests and responses inside the SDK, so the tool still needs a schema for the
model. Fern’s other answer is its MCP generator, which turns each operation into one tool, names
it after the operationId unless x-fern-mcp-name overrides that, and keeps credential
parameters out of tool inputs. The AI SDK reads those tools through
createMCPClient.
Keep the client’s options out of the tool input
Typing the tool’s input as the method’s whole parameter list hands the model the knobs.
pitfall.mjs builds that version for both clients. The sdkgen tool spreads an options object
into the constructor, and the openapi-fetch tool passes its input as the second argument, where
baseUrl is a per-call option. The
scripted model names another host and asks for four retries.
node pitfall.mjs
tool input = the whole parameter list, options included
sdk_create_book tool-error api 0 (0 with the key), elsewhere 5 (5 with the key)
fetch_create_book tool-error api 0 (0 with the key), elsewhere 1 (1 with the key)
tool input = the request body only
sdk_create_book tool-result api 1 (1 with the key), elsewhere 0 (0 with the key)
fetch_create_book tool-result api 1 (1 with the key), elsewhere 0 (0 with the key)
The open tools sent the API key to the model’s host, five times for sdkgen because the model switched its retry feature on. The body-only tools dropped both keys, because Zod strips keys a schema does not declare.
Check it worked
node --test tool.test.mjs
1..16
# tests 16
# suites 0
# pass 16
# fail 0
# cancelled 0
# skipped 0
# todo 0
The tests pin each preceding output, including the not: {} schema and the tsc errors on the stale
file, and hold the stand-in to the document’s NewBook schema.
When it goes wrong
A JSON Schema tool executes bad input. The tool reference
says the input schema “is also used to validate the output of the language model” without
saying that a jsonSchema with no validate function checks nothing. Pass a validator, and
check input in any code that calls execute itself, because that call skips validation.
node unchecked.mjs
input: {"title":"Emma","published":1815.5,"shelf":"A3"}
jsonSchema(lifted), no validate, via the model
execute ran; the API received {"published":1815.5,"shelf":"A3","title":"Emma"} and answered 400
validated(lifted), via the model
execute did not run, refused: data must NOT have additional properties, data/published must be integer; the API received nothing
validated(lifted), execute called directly
execute ran; the API received {"published":1815.5,"shelf":"A3","title":"Emma"} and answered 400
The SDK sent shelf and the fractional year as given. The stand-in refuses the year because the
document says integer, and accepts shelf because the document leaves NewBook open, so only
the tool schema refuses both before a request leaves. The model is asked for an id the
server assigns. That happens when the schema is built from config.entity.book.fields, which
lists the entity’s fields with id marked required. Build it from the operation instead.
When not to do this
Do not lift schemas for one or two tools whose descriptions you want to write for a model. The hand-written Zod schema plus the type check is shorter, and the model reads your words rather than the document’s.
Do not use sdkgen’s BookCreateData as the source of a tool schema. It is the right type for the
call and a thin description for a model. The constructor’s options?: any is a cost too: no type
stops a tool that takes the whole parameter list from passing the model’s base URL through.
If you already generate with Fern, its MCP generator is the better choice for many operations at once, since it writes the schemas and keeps credentials out of them. Choose openapi-fetch when you want no generated runtime, because a call that names its own path needs no model to find the operation.
Do not expose a method whose options the model should set. A timeout chosen per call belongs in your code, set from the task, not in the tool input.
Related how-tos
Last verified
Verified 2026-11-21 against Node 22.23.5, ai 7.0.179, zod 4.6.7, ajv 8.20.0,
ts-json-schema-generator 2.10.0, TypeScript 5.9.3, openapi-typescript 7.13.0 and
openapi-fetch 0.17.0, all run. The SDK came from @voxgig/create-sdkgen 0.31.9, which installed
@voxgig/sdkgen 4.44.3 and @voxgig/apidef 8.32.4; sdkgen 4.45.0 with apidef 8.33.1 wrote the
same source. Its compiled output is committed under generated/. Fern’s part comes from its
SDK, MCP generator and pricing pages as fetched that day, because generating with Fern here
would need an account or Docker. Every output block is what the command preceding it printed.
Footnotes
-
Zod’s JSON Schema page shows
z.int()converting to{ type: "integer" }. Zod 4.6.7 wrote a minimum of minus 9007199254740991 and a maximum of plus that figure as well, the safe integer range its API page saysz.int()restricts to. It did the same for this page’sz.number().int(), whose.min(0)replaced the lower bound. MDN gives the figure asNumber.MAX_SAFE_INTEGER, 2^53 minus 1, so a model asked for a year of publication is told it may go to nine quadrillion. ↩︎ Back to text -
OpenAPI 3.0.3 calls its Schema Object an extended subset of a JSON Schema draft, says null is not supported as a type, and offers
nullablein its place. OpenAPI 3.1.0, released on 2021-02-15, made the Schema Object a superset of JSON Schema Draft 2020-12, and the word nullable does not appear in it. The type array the lifting code writes is the form 3.1 adopted. ↩︎ Back to text