How Automatic OpenAPI 3.1 to LLM Tool Conversion Works
Converting an OpenAPI 3.1 specification into LLM function calling tool definitions maps HTTP endpoints (paths and HTTP methods) into callable tool objects (name, description, and JSON Schema parameters), while preserving routing metadata (path, query, body) so your Node.js/TypeScript orchestrator can execute the HTTP request cleanly when the model emits a tool_call.
- OpenAPI 3.1 uses full JSON Schema Draft 2020-12: Unlike OpenAPI 3.0’s custom
nullable: truekeyword, OpenAPI 3.1 expresses nullable fields using type arrays (type: ["string", "null"]). Converters must dereferencepointers, flattenallOfcompositions, and strip unsupported JSON Schema keywords (format,examples,,) before passing schemas to strict LLM tool compilers. * Mergepath,query, andrequestBodyinto one flat arguments schema: LLM tool calls produce a single JSON object of arguments, so your converter combines path parameters, query parameters, and request body fields into one top-levelpropertiesobject while tracking where each parameter belongs during HTTP execution. * Enforce strict tool schemas (: true): Production tool execution requiresadditionalProperties: falseon every object schema and every property key listed inrequired(converting optional API fields into nullable fields["type", "null"]). ## Steps to Automatically Convert OpenAPI 3.1 Specs into Tool Definitions 1. Load and dereferenceschemas: Parse the OpenAPI 3.1 JSON/YAML document and resolve internal/components/schemas/...and/components/parameters/...references with cycle detection.
- Filter operations and generate canonical tool names: Select only safe, model-relevant endpoints (skipping deprecated or internal admin routes) and normalize
operationId(or<method>_<path>) into valid[a-zA-Z0-9_-]{1,64}identifiers. - Normalize parameter and body schemas for strict JSON Schema: Convert OpenAPI 3.1 schemas into strict object definitions (
additionalProperties: false, fullrequiredarrays, nullable types for optional parameters) and keep a parallel lookup map ofpathParams,queryParams, andbodyParams. - Dispatch validated tool arguments back to HTTP: When the LLM invokes a tool, validate the JSON arguments, interpolate
{pathParam}segments, append query parameters, attach the JSON body, and return the HTTP response as arole: "tool"message.
TypeScript Example: End-to-End OpenAPI 3.1 Converter and HTTP Tool Executor
import OpenAI from "openai";
const openai = new OpenAI();
interface OpenApi31Param {
name: string;
in: "path" | "query" | "header" | "cookie";
required?: boolean;
description?: string;
schema?: Record<string, unknown>;
}
interface OpenApi31Op {
operationId?: string;
summary?: string;
description?: string;
deprecated?: boolean;
parameters?: OpenApi31Param[];
requestBody?: {
required?: boolean;
content?: {
"application/json"?: {
schema?: Record<string, unknown>;
};
};
};
}
export interface OpenApi31Document {
servers?: Array<{ url: string }>;
components?: {
schemas?: Record<string, Record<string, unknown>>;
};
paths: Record<string, Record<string, OpenApi31Op>>;
}
export interface BoundApiTool {
definition: OpenAI.Chat.Completions.ChatCompletionTool;
method: string;
pathTemplate: string;
pathParams: Set<string>;
queryParams: Set<string>;
bodyParams: Set<string>;
}
function dereference(
node: Record<string, unknown>,
doc: OpenApi31Document,
visited = new Set<string>()
): Record<string, unknown> {
const ref = node.$ref;
if (typeof ref !== "string" || !ref.startsWith("#/")) {
return node;
}
if (visited.has(ref)) {
return { type: "object" };
}
visited.add(ref);
let target: unknown = doc;
for (const segment of ref.slice(2).split("/")) {
if (target && typeof target === "object" && segment in target) {
target = (target as Record<string, unknown>)[segment];
} else {
return { type: "object" };
}
}
if (!target || typeof target !== "object") {
return { type: "object" };
}
const { $ref: _drop, ...overrides } = node;
return {
...dereference(target as Record<string, unknown>, doc, visited),
...overrides,
};
}
function makeNullable(typeValue: unknown): unknown {
if (Array.isArray(typeValue)) {
return typeValue.includes("null") ? typeValue : [...typeValue, "null"];
}
if (typeof typeValue === "string" && typeValue !== "null") {
return [typeValue, "null"];
}
return typeValue;
}
function toStrictJsonSchema(
raw: Record<string, unknown> | undefined,
doc: OpenApi31Document,
visited = new Set<string>()
): Record<string, unknown> {
if (!raw) {
return { type: "object", properties: {}, required: [], additionalProperties: false };
}
const schema = dereference(raw, doc, visited);
const clean: Record<string, unknown> = {};
if (typeof schema.description === "string") clean.description = schema.description;
if (Array.isArray(schema.enum)) clean.enum = schema.enum;
if (schema.type) clean.type = schema.type;
if (schema.type === "array" && schema.items && typeof schema.items === "object") {
clean.items = toStrictJsonSchema(
schema.items as Record<string, unknown>,
doc,
new Set(visited)
);
}
if (schema.type === "object" || schema.properties) {
clean.type = "object";
const props = (schema.properties ?? {}) as Record<string, Record<string, unknown>>;
const reqSet = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []);
const nextProps: Record<string, unknown> = {};
const keys = Object.keys(props);
for (const key of keys) {
const normalizedChild = toStrictJsonSchema(props[key], doc, new Set(visited));
if (!reqSet.has(key) && normalizedChild.type) {
normalizedChild.type = makeNullable(normalizedChild.type);
}
nextProps[key] = normalizedChild;
}
clean.properties = nextProps;
clean.required = keys;
clean.additionalProperties = false;
}
return clean;
}
export function compileOpenApi31Tools(doc: OpenApi31Document): Map<string, BoundApiTool> {
const registry = new Map<string, BoundApiTool>();
const supportedMethods = new Set(["get", "post", "put", "patch", "delete"]);
for (const [pathTemplate, pathItem] of Object.entries(doc.paths ?? {})) {
for (const [methodKey, op] of Object.entries(pathItem ?? {})) {
if (!supportedMethods.has(methodKey.toLowerCase()) || !op || op.deprecated) continue;
const method = methodKey.toUpperCase();
const rawName = op.operationId?.trim() || `${method}_${pathTemplate}`;
const name = rawName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
const properties: Record<string, unknown> = {};
const required: string[] = [];
const pathParams = new Set<string>();
const queryParams = new Set<string>();
const bodyParams = new Set<string>();
for (const param of op.parameters ?? []) {
if (param.in !== "path" && param.in !== "query") continue;
const schema = toStrictJsonSchema(
{ description: param.description, ...(param.schema ?? { type: "string" }) },
doc
);
if (!param.required && schema.type) {
schema.type = makeNullable(schema.type);
}
properties[param.name] = schema;
required.push(param.name);
if (param.in === "path") pathParams.add(param.name);
if (param.in === "query") queryParams.add(param.name);
}
const bodySchema = op.requestBody?.content?.["application/json"]?.schema;
if (bodySchema) {
const normalizedBody = toStrictJsonSchema(bodySchema, doc);
const bodyProps = (normalizedBody.properties ?? {}) as Record<string, unknown>;
for (const [key, propSchema] of Object.entries(bodyProps)) {
properties[key] = propSchema;
if (!required.includes(key)) required.push(key);
bodyParams.add(key);
}
}
const description =
[op.summary, op.description].filter(Boolean).join(" — ") || `${method}${pathTemplate}`;
registry.set(name, {
definition: {
type: "function",
function: {
name,
description,
strict: true,
parameters: {
type: "object",
properties,
required,
additionalProperties: false,
},
},
},
method,
pathTemplate,
pathParams,
queryParams,
bodyParams,
});
}
}
return registry;
}
export async function executeBoundApiTool(
binding: BoundApiTool,
argsJson: string,
baseUrl: string,
authHeaders: Record<string, string>
): Promise<string> {
const args = JSON.parse(argsJson) as Record<string, unknown>;
let resolvedPath = binding.pathTemplate;
for (const key of binding.pathParams) {
const val = args[key];
if (val === null || val === undefined) {
throw new Error(`Missing required path parameter: ${key}`); } resolvedPath = resolvedPath.replace(`{${key}}`, encodeURIComponent(String(val)));
}
const url = new URL(resolvedPath, baseUrl);
for (const key of binding.queryParams) {
const val = args[key];
if (val !== null && val !== undefined) {
url.searchParams.set(key, String(val));
}
}
const bodyPayload: Record<string, unknown> = {};
for (const key of binding.bodyParams) {
if (args[key] !== null && args[key] !== undefined) {
bodyPayload[key] = args[key];
}
}
const res = await fetch(url.toString(), {
method: binding.method,
headers: {
"Content-Type": "application/json",
...authHeaders,
},
body: binding.bodyParams.size > 0 ? JSON.stringify(bodyPayload) : undefined,
});
return await res.text();
}
Helpful Tips for Production OpenAPI Tool Conversion
- Strip unsupported JSON Schema keywords before enabling
: true: OpenAPI 3.1 specs frequently containformat: "uuid",pattern,minLength,default, orexamplefields that some LLM strict schema compilers reject—strip unsupported keywords during normalization and move those rules into the property’sdescription. - Namespace colliding parameter names across
path,query, andbody: If an endpoint has both a path parameteridand a body fieldid, prefix keys during compilation (for example,path_idandbody_id) so merging them into one flat arguments object never overwrites a key. - Restrict exposed operations by tag or RBAC scope per request: Filter
compileOpenApi31Toolsdynamically based on the authenticated user’s permissions and active workflow so the LLM never sees unauthorized endpoints or wastes context tokens on irrelevant routes.
You must log in or register to comment.
