# How to convert OpenAPI operations into tool function schemas

> Turn each OpenAPI operation into a function schema with one flat input object, inline $ref and merge allOf first, and validate each schema before a model sees it.

Source: https://voxgig.com/howto/openapi-operations-to-tool-function-schemas

- Audience: agent-builder
- Level: intermediate
- Languages: typescript, python
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Write a build-time script that inlines every local $ref, merges allOf parts into one property list, and cuts a reference cycle off with a plain object. Fold path, query, header and body arguments into one flat object, record where each goes, and refuse a name that two locations share. Validate each schema with Ajv, commit the output, and unfold each call with the recorded binding.

---
## You will need

Node 22 or later and an OpenAPI 3 document. The sample's `helpdesk.json` has five operations, a
required header and a path parameter declared by `$ref`, an `allOf` of three schemas that refers
to itself, a `oneOf`, and two enums. `package.json` pins `@voxgig/apidef` 8.32.4 with 8.33.1
beside it, openapi-mcp-generator, Ajv, and `openapi-fetch`.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [@voxgig/apidef](https://github.com/voxgig/apidef/blob/main/docs/reference/model.md) | You want tools grouped by entity, with arguments read from one model | Enum values and `oneOf` alternatives are gone, so the schema accepts values the API refuses | The model must be told which values are allowed |
| [A hand-written converter script](https://spec.openapis.org/oas/v3.0.3.html#schema-object) | You want output you can read, correct, and commit before any model sees it | Every `$ref`, `allOf` and name clash is your code to handle and to test | The document changes daily and nobody reviews the output |
| [Kiota](https://learn.microsoft.com/en-us/openapi/kiota/using) | Kiota builds your client, and the tool schemas come from the same document | No tool output, so a converter still reads the document beside the client | The tool schemas are the whole job, with no client to build |
| [openapi-mcp-generator](https://github.com/harsha-iiiv/openapi-mcp-generator) | A library call that builds tools from the document at start-up | The body stays nested under `requestBody`, and nobody reads the result before a model does | You need flat arguments or a reviewed tool list |
| [openapi-typescript and openapi-fetch](https://openapi-ts.dev/openapi-fetch/api) | A TypeScript agent that sends each tool call by method and path | Types only, so the tool schemas come from a converter like this page's | You ship the tools to more than TypeScript |

Voxgig maintains apidef, one of the five rows. Kiota is Microsoft's, `openapi-typescript` and
`openapi-fetch` come from the `openapi-ts` project, and the converter script is yours.

The trade-off is freshness against review. A build-time file can be read and corrected, and it
goes stale when nobody reruns it. openapi-mcp-generator converts at start-up, so its output
cannot go stale but reaches the model unread. apidef sits between them: one model, one tool per
entity operation, and less of the schema.

## Inline references and merge allOf before folding

`convert.mjs` inlines every local `$ref` and merges each `allOf` before it folds anything. A
`$ref` replaces the node it sits in, as OpenAPI 3.0.3 says it must.[^1]

```js title="convert.mjs"
export function inline(doc, schema, stack = []) {
  if (Array.isArray(schema)) return schema.map((s) => inline(doc, s, stack))
  if (schema === null || typeof schema !== 'object') return schema
  if (Object.hasOwn(schema, '$ref')) {
    const ref = schema.$ref
    const name = ref.split('/').pop()
    if (stack.includes(ref)) return { type: 'object', description: `${name}, not expanded: the schema refers to itself.` }
    return inline(doc, lookup(doc, ref), [...stack, ref])
  }
  const out = {}
  for (const [k, v] of Object.entries(schema)) {
    if (k === 'allOf') continue
    out[k] = k === 'properties' ? Object.fromEntries(Object.entries(v).map(([p, s]) => [p, inline(doc, s, stack)])) : inline(doc, v, stack)
  }
  if (Array.isArray(schema.allOf)) {
    for (const part of schema.allOf.map((s) => inline(doc, s, stack))) mergeInto(out, part)
  }
  // OpenAPI 3.0 marks a null with nullable: true, a keyword JSON Schema does not have.
  if (typeof out.nullable === 'boolean' && typeof out.type === 'string') {
    if (out.nullable) {
      out.type = [out.type, 'null']
      if (Array.isArray(out.enum) && !out.enum.includes(null)) out.enum = [...out.enum, null]
    }
    delete out.nullable
  }
  return out
}
```

`stack` holds the references being expanded, so `subtasks`, an array of `TicketInput` inside
`TicketInput`, ends in a described object rather than a stack overflow. `mergeInto` adds up
properties and `required` lists, and throws when two parts define one property differently.
A `nullable: true` becomes a `null` in the type, because JSON Schema has no `nullable` keyword.
Read-only properties are dropped, since a caller never sends them. Then each parameter and each
body property becomes one argument:

```bash
node convert.mjs helpdesk.json tools/hand-written.json
```

```text output
listTickets   X-Workspace-Id* (header), status (query), limit (query)
createTicket  X-Workspace-Id* (header), title* (body), body (body), status (body), priority (body), assignee (body), due (body), parent_id (body), subtasks (body)
getTicket     ticketId* (path), X-Workspace-Id* (header)
deleteTicket  ticketId* (path), X-Workspace-Id* (header)
updateTicket  ticketId* (path), X-Workspace-Id* (header), title* (body), body (body), status (body), priority (body), assignee (body), due (body), parent_id (body), subtasks (body)
```

An asterisk marks a required argument. The location in brackets is the binding the script writes
beside each schema, and the dispatcher reads it later. A query parameter named like a body field
fails the build with `title is both query and body`, which a test pins.

## Emit tools from apidef's entity model

`apidef-tools.mjs` reads the model `@voxgig/apidef` builds and writes one tool per entity
operation. Path arguments come from each operation's `g.params`, header and query arguments from
`g.header` and `g.query`, and body fields from `bf`, typed by the entity's fields.

```js title="apidef-tools.mjs"
// apidef's validator tokens, as JSON Schema. `$ANY` is a field whose schema had no `type`
// keyword, such as a oneOf, so it becomes the schema that accepts anything.
const TYPES = {
  '`$STRING`': { type: 'string' },
  '`$INTEGER`': { type: 'integer' },
  '`$NUMBER`': { type: 'number' },
  '`$BOOLEAN`': { type: 'boolean' },
  '`$ARRAY`': { type: 'array' },
  '`$OBJECT`': { type: 'object' },
  '`$ANY`': {},
}
```

```bash
node apidef-tools.mjs helpdesk.json tools/apidef.json
```

```text output
ticket_create  x_workspace_id* (header), assignee (body), body (body), due (body), parent_id (body), priority (body), status (body), subtasks (body), title* (body)
ticket_list    x_workspace_id* (header), limit (query), status (query)
ticket_load    x_workspace_id* (header), id* (path)
ticket_remove  x_workspace_id* (header), id* (path)
ticket_update  x_workspace_id* (header), id* (path), assignee (body), body (body), due (body), parent_id (body), priority (body), status (body), subtasks (body), title* (body)
```

The three-part `allOf` arrives merged into one field list, and the recursion did not loop. Three
things are gone. `status` is a plain string, because the model keeps no enum value. `assignee`
accepts anything: apidef types a field with its
[`validator` function](https://github.com/voxgig/apidef/blob/v8.32.4/ts/src/utility.ts#L1037),
which reads the `type` keyword, and a `oneOf` has none. Tests that add `type: object` to
`Assignee`, or rename the field `assignee_id`, get `$OBJECT` and a guessed `$STRING`.

The header is renamed `x_workspace_id`, so the binding keeps the wire name, `X-Workspace-Id`.
8.33.1 gives the same model and tools. `withDocumentEnums` in the same file copies each
argument's `enum` back from the document, found by method, path and wire name, and a test
shows the schema refuse `burning` with it and accept it without.

## Score the four tool sets with one validator

`compare.mjs` compiles every schema with Ajv in
[strict mode](https://ajv.js.org/strict-mode.html), which refuses unknown keywords, and tries
four scripted `createTicket` calls against each set, rewritten into that set's own argument
names.

```bash
node compare.mjs
```

```text output
                          hand-written  naive         apidef        openapi-mcp-generator
tools                     5             5             5             5
schemas ajv compiles      5             4             5             5
createTicket arguments    9             0             9             2
a good call               accepted      accepted      accepted      accepted
status "burning"          refused       accepted      accepted      refused
assignee kind "robot"     refused       accepted      accepted      refused
no title                  refused       accepted      refused       refused
subtasks items            object, noted absent        any items     object, cut
naive: listTickets: can't resolve reference #/components/schemas/Status from id #
openapi-mcp-generator logged 6 times: Cycle detected in schema, returning generic object to break recursion.
hand-written createTicket: X-Workspace-Id title body status priority assignee due parent_id subtasks
naive createTicket: (no arguments)
apidef 8.32.4 createTicket: x_workspace_id assignee body due parent_id priority status subtasks title
openapi-mcp-generator createTicket: X-Workspace-Id requestBody
apidef 8.33.1 against 8.32.4: same model yes, same tools yes
```

The naive column is `naive.mjs`, the converter to avoid: its `createTicket` takes no arguments,
so it accepts every call, and its `listTickets` does not compile. openapi-mcp-generator keeps the
`allOf`, the enums and the `oneOf`, and nests the body under one `requestBody` argument, the line
in its
[`extract-tools.ts`](https://github.com/harsha-iiiv/openapi-mcp-generator/blob/v5.0.1/src/parser/extract-tools.ts#L479)
that reads `properties['requestBody'] = bodySchema`. Its README says `dereference` defaults to
`false`, and this run sets it to `true`, as its command line does.

## Unfold a call and send it with openapi-fetch

`call.mjs` replaces the model with a script of five calls, validates each against its tool
schema, and sends it through `openapi-fetch` to a stand-in on 127.0.0.1. The stand-in validates
bodies against the document's schemas with its own Ajv instance.

```bash
node call.mjs
```

```text output
createTicket (hand-written)  POST /v1/tickets workspace=ws_1 body={"title":"Printer on fire","assignee":{"kind":"team","team_id":"t_9"}}
                             -> 201
ticket_create (apidef)       POST /v1/tickets workspace=ws_1 body={"title":"Printer on fire","assignee":{"kind":"team","team_id":"t_9"}}
                             -> 201
createTicket (hand-written)  schema refused: args/status must be equal to one of the allowed values; nothing sent
ticket_create (apidef)       POST /v1/tickets workspace=ws_1 body={"title":"Printer on fire","status":"burning"}
                             -> 400 body/status must be equal to one of the allowed values
getTicket (hand-written)     refused before sending: getTicket: ticketId is not a usable path segment
```

The fourth call is the cost of the apidef row: its schema let `burning` through, and the server
refused it a round trip later. The last call is the dispatcher refusing `..`, which survives
`encodeURIComponent` and would move the request to another path. The dispatcher also checks each
path, query and header argument against the `type` in its schema. It sends an integer, a number
or a boolean in the path as its string form, so `7` for an integer `ticketId` becomes the
segment `7`.

## Check it worked

Twenty-eight tests cover both converters, the refusals, both apidef releases, and the enum
remedy. They also compile a nullable field and a two-schema cycle in strict mode, and check the
comparison table, the dispatch of typed arguments, the stand-in's routes, and the record.

```bash
node --test tools.test.mjs
```

```text output
1..28
# tests 28
# suites 0
# pass 28
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

Look for `# pass 28`. The test named `the comparison table` fails if any cell of the table changes.

## When it goes wrong

The converter dies with `RangeError: Maximum call stack size exceeded`. It inlines references
with no record of where it has been, and `TicketInput` refers to itself. `inlineWithoutGuard` in
`naive.mjs` does exactly that, and a test expects the `RangeError`. Carry the stack of expanded
references, as `inline` does.

The model sends `x_workspace_id` and the server answers 400. A tool built from apidef's names
sent the argument name as the header name. Unfold with the binding, which keeps the wire name.

The model sends an `assignee` of the wrong shape, although every schema compiled. In the apidef
tools that argument is the empty schema, so nothing tells the model what shape to send. Read the committed tool file before
an agent does.

## Get tool schemas when Kiota or openapi-typescript builds the client

Kiota writes clients, not tools. Its
[command list](https://learn.microsoft.com/en-us/openapi/kiota/using) names eight commands, from
`search` to `logout`. They find and download API descriptions, generate and update clients,
show paths and languages, and sign in and out. A Kiota team keeps
`kiota generate` for the client and runs a converter such as `convert.mjs` over the same
OpenAPI description for the tools.

The client's types are a poor source for those schemas. Kiota
["doesn't generate a type specific to the operation for request headers"](https://learn.microsoft.com/en-us/openapi/kiota/query-parameters-request-headers),
so the required `X-Workspace-Id` would have no type to read. Its
[models page](https://learn.microsoft.com/en-us/openapi/kiota/models) requires a discriminator
on a `oneOf` with an object child, which `Assignee` lacks.

`openapi-typescript` writes types only, and `openapi-fetch` then sends by method and path, which
is what `dispatch.mjs` does with the binding. The generated `operations` type groups each
operation's inputs by location:

```bash
head -15 records/openapi-typescript.txt
```

```text output
openapi-typescript 7.13.0, operations["createTicket"] without its responses:
    createTicket: {
        parameters: {
            query?: never;
            header: {
                "X-Workspace-Id": components["parameters"]["Workspace"];
            };
            path?: never;
            cookie?: never;
        };
        requestBody: {
            content: {
                "application/json": components["schemas"]["TicketInput"];
            };
        };
```

That split is the binding the converter writes, so a flat call unfolds into these four groups and
the body.

## When not to do this

Do not convert at run time where nobody will read the result. openapi-mcp-generator's output is
correct on this document, and an `allOf` written by another team can still give a tool the model
cannot fill.

Do not build tool schemas from apidef's model alone when the API takes enums or alternatives. The
model is right about entities and silent about allowed values, so copy the enums from the
document, as `withDocumentEnums` does, or accept a 400 for each value the model invents. The
`oneOf` stays lost either way.

Kiota is the stronger pick where the tools sit beside a typed client in several languages: its
[overview](https://learn.microsoft.com/en-us/openapi/kiota/overview) lists seven. `openapi-fetch`
suits a TypeScript agent with one document, where the dispatcher here is the whole client.

## Related how-tos

- [Derive MCP tool names and schemas from a semantic model](/howto/derive-tool-schemas-from-a-semantic-model)

- [Map one tool definition to MCP, OpenAI, Claude, and Gemini](/howto/convert-tool-definitions-between-mcp-openai-claude-gemini)

- [Cut the tool count for an API with hundreds of operations](/howto/reduce-tool-count-for-a-large-api)

- [Decide whether to generate or hand-write an MCP server](/howto/generate-or-hand-write-an-mcp-server)

- [Build a tool-calling loop with the Claude Agent SDK](/howto/tool-calling-loop-with-the-claude-agent-sdk)

- [Run an agent loop against a mock API in tests](/howto/run-an-agent-loop-against-a-mock-api)

## Last verified

Verified 2026-11-22 against Node 22.23.5, `@voxgig/apidef` 8.32.4 and 8.33.1,
openapi-mcp-generator 5.0.1, Ajv 8.20.0 and `openapi-fetch` 0.17.0, which the captured commands
run. `record.sh` ran `openapi-typescript` 7.13.0 with TypeScript 5.9.3 once. Kiota was not run:
its part rests on the using, models, and query parameters pages of its documentation, read on
the same day. Everything here runs in Node, though the leaf lists Python too. No model was
called: the calls are a script.

[^1]: The rule has an edition. [OpenAPI 3.0.3](https://spec.openapis.org/oas/v3.0.3.html#reference-object)
says a Reference Object cannot be extended with additional properties and any properties added
SHALL be ignored, so a `description` beside a `$ref` is ignored. [OpenAPI 3.1.1](https://spec.openapis.org/oas/v3.1.1.html#reference-object)
keeps that sentence, adds a `summary` and a `description` that override the target's, and notes
that the restriction does not apply to a Schema Object that contains `$ref`. The same sibling is
dropped in one edition and read in the next.