Schema Forge turns a TypeScript class into a JSON Schema. You mark the class's properties with decorators. Schema Forge then gives you either the plain JSON Schema, or a ready-made tool definition for the OpenAI, Anthropic (Claude) or Google Gemini APIs. A large language model (LLM) reads that tool definition to know which arguments it may send.
The same class can also be the TypeScript type of those arguments, so you describe them in one place. What TypeScript does not keep at run time (whether a property is optional or nullable, the item type of an array, the allowed values of an enum) you add as an option (4.1).
import 'reflect-metadata';
import {
ToolMeta,
ToolProp,
classToOpenAITool,
} from '@firefliesai/schema-forge';
@ToolMeta({
name: 'get_weather',
description: 'Get the current weather for a city',
})
class GetWeatherInput {
@ToolProp({ description: 'City name, for example "Paris"' })
city!: string;
@ToolProp({
description: 'Temperature unit',
enum: ['celsius', 'fahrenheit'],
isOptional: true,
})
unit?: string;
}
const tool = classToOpenAITool(GetWeatherInput);
// {
// type: 'function',
// function: {
// name: 'get_weather',
// description: 'Get the current weather for a city',
// parameters: {
// type: 'object',
// properties: {
// city: {
// description: 'City name, for example "Paris"',
// type: 'string'
// },
// unit: {
// description: 'Temperature unit',
// enum: ['celsius', 'fahrenheit'],
// type: 'string'
// }
// },
// required: ['city']
// }
// }
// }Pass tool in the tools list of an OpenAI request. When the model calls the tool, its arguments should match the schema; only strict mode guarantees it, and then for the schema that was sent (3.3).
- What Schema Forge does (diagram 1: from a class to an LLM tool), and why Schema Forge
- Install and set up
- Quick start
- Describing properties with
@ToolProp - Rules from class-validator (diagram 2: which source wins)
- Schema options
- LLM provider formats
- Errors and warnings
- Migrating from 2.x
- How it works inside (diagram 3: what happens when)
- Limitations
- API reference
- Troubleshooting
Terms used in this README:
| Term | Meaning |
|---|---|
| Tool (the feature is called function calling) | A function your application offers to an LLM. You send the LLM the tool's name, a description and a JSON Schema of its arguments. The LLM answers with a call that has those arguments, and your code runs the function. |
| Structured output | Asking the LLM to answer with JSON that matches a JSON Schema, instead of free text. |
| Strict mode | A provider setting that makes the LLM's output follow the schema exactly. It accepts only part of JSON Schema and adds its own rules (see OpenAI and Anthropic). |
| Decorator | A TypeScript annotation such as @ToolProp() written above a class or property. See TypeScript decorators. |
| Design type | The type TypeScript records for a property when emitDecoratorMetadata is on: String, Number, Boolean, Date, Array, a class, or Object when the type is something else (a union, an interface, …). |
| class-validator | A separate library whose decorators (@IsEmail(), @MaxLength(100), …) validate class instances. Schema Forge only reads these decorators to add rules to the schema; it never runs validation. |
Diagram 1: from a class to an LLM tool. Steps ① and ② happen when the class is defined. Steps ③ and ④ happen when you call a Schema Forge function.
① your class ② stored on the class
┌───────────────────────────┐ ┌────────────────────────┐
│ @ToolMeta (name, desc.) │ │ Schema Forge metadata │
│ @ToolProp on properties │ ──> │ (what you wrote, plus │
│ class-validator (optional)│ │ the design types) │
└───────────────────────────┘ └───────────┬────────────┘
│
v
④ classTo<Provider>…() ③ classToJsonSchema()
┌───────────────────────────┐ ┌────────────────────────┐
│ tool or response format │ │ JSON Schema │
│ for OpenAI, Anthropic or │ <── │ (checked; rules from │
│ Gemini │ │ class-validator added) │
└───────────────────────────┘ └────────────────────────┘
| Step | What happens |
|---|---|
| ① Define the class | You add @ToolMeta to the class and @ToolProp to each property that belongs in the schema. |
| ② Decorators run | @ToolProp records your options and the property's design type. It never throws. |
| ③ Generate the schema | classToJsonSchema builds the schema, adds rules from class-validator, and throws if the schema would not describe the class (see Errors). |
| ④ Format for a provider | A classTo… function wraps the schema in the shape one provider's API expects, and adapts it to what that provider accepts. |
When to use it: you already describe data with classes and decorators (for example the data transfer objects, or DTOs, of a NestJS application; NestJS is a Node.js server framework), you want one class to be both the schema and the TypeScript type, or you send the same tool to several LLM providers.
When something else may fit better: you prefer building schemas with functions instead of classes (Zod or TypeBox), your code base does not use decorators, or property names are only known at run time.
Design choices. Schema Forge has one job: it turns a class into a JSON Schema, and a JSON Schema into tool formats for OpenAI, Anthropic and Gemini, and structured-output formats for OpenAI and Gemini. It does not validate or transform values, and it does not produce OpenAPI documents (the standard format that describes an HTTP API). It has no dependencies of its own; the only package it needs is reflect-metadata, which you install yourself (a peer dependency). It does not depend on any framework, so you can use it in a NestJS project or in plain TypeScript.
Compared with class-validator-jsonschema, which also turns decorated classes into JSON Schema (its version 5.2.0, checked November 2026):
| Schema Forge | class-validator-jsonschema | |
|---|---|---|
| Where the schema comes from | @ToolProp and the design types; class-validator decorators add rules when present |
class-validator decorators, plus its own @JSONSchema() decorator for extra keywords |
| Packages you must install | reflect-metadata (peer dependency) |
class-validator and class-transformer (peer dependencies) |
| Its own dependencies | none | openapi3-ts, lodash.merge, lodash.groupby, reflect-metadata, tslib |
| What you get | JSON Schema, plus tools for OpenAI, Anthropic and Gemini and structured-output formats for OpenAI and Gemini, adapted to what each provider accepts (including OpenAI and Anthropic strict modes) | Schema objects for an OpenAPI document |
| Which properties are in the schema | Only those with @ToolProp (or added with addSchemaProperty), so one class can be an API DTO and a tool input with different fields (section 5.2) |
Every property that has a class-validator decorator |
Why it also reads class-validator decorators. Many classes that become tools already exist as validated DTOs, for example in NestJS. When a class has class-validator decorators, Schema Forge reads them, so a rule such as @MaxLength(100) is written once, and both the validator and the LLM see it. class-validator is still optional: it is an optional peer dependency, and without it everything else works the same (section 5).
npm install @firefliesai/schema-forge reflect-metadata| Package | Needed? | Version | Why |
|---|---|---|---|
reflect-metadata |
Yes (peer dependency) | ^0.1.14 or ^0.2.0 |
Stores what the decorators record. |
class-validator |
Optional (peer dependency) | ^0.14.0 or ^0.15.0 |
Only if you want its rules in the schema (section 5). |
Some package managers do not install peer dependencies on their own; the command above installs reflect-metadata explicitly for that reason.
Install a single copy of Schema Forge. Each installed copy keeps its own metadata, so a property declared through one copy is invisible to another. If a library you use depends on a different version of @firefliesai/schema-forge, deduplicate it or force one version (npm overrides, pnpm overrides, yarn resolutions). When a property was declared only through the other copy, Schema Forge throws instead of leaving it out (section 8).
TypeScript settings. Turn on both options in tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}experimentalDecorators enables the decorator syntax Schema Forge uses. emitDecoratorMetadata makes TypeScript record each property's design type, which Schema Forge reads.
Load reflect-metadata first. Import it once, at the start of your program, before any class with decorators is loaded:
import 'reflect-metadata';The examples in this README use name!: string. The ! tells TypeScript that the property is assigned elsewhere; it is needed when strictPropertyInitialization is on.
import 'reflect-metadata';
import { ToolMeta, ToolProp } from '@firefliesai/schema-forge';
@ToolMeta({ name: 'create_user', description: 'Create a user account' })
class CreateUserInput {
@ToolProp({ description: 'Full name' })
name!: string;
@ToolProp({ description: 'Email address', format: 'email' })
email!: string;
@ToolProp({ description: 'Age in years', isOptional: true })
age?: number;
@ToolProp({
description: 'Role of the user',
enum: ['admin', 'member', 'guest'],
})
role!: string;
}@ToolMetagives the tool its name and description. The provider formats need it; plain JSON Schema does not.@ToolPropputs a property in the schema. A property without@ToolPropis left out.- The type (
string,number) comes from TypeScript.isOptional: trueleaves the property out ofrequired.
import { classToJsonSchema } from '@firefliesai/schema-forge';
const schema = classToJsonSchema(CreateUserInput);
// {
// type: 'object',
// properties: {
// name: { description: 'Full name', type: 'string' },
// email: { description: 'Email address', format: 'email', type: 'string' },
// age: { description: 'Age in years', type: 'number' },
// role: {
// description: 'Role of the user',
// enum: ['admin', 'member', 'guest'],
// type: 'string'
// }
// },
// required: ['name', 'email', 'role']
// }Each provider's API expects a slightly different shape. Pick the function for the SDK (software development kit: the provider's client library) you use:
| You call | With | Schema Forge function | Put the result in |
|---|---|---|---|
| OpenAI Chat Completions API | openai |
classToOpenAITool |
tools: [tool] |
| OpenAI Responses API | openai |
classToOpenAIResponseApiTool |
tools: [tool] |
| Anthropic Messages API | @anthropic-ai/sdk |
classToAnthropicTool |
tools: [tool] |
| Gemini API | @google/genai |
classToGeminiTool |
config.tools: [{ functionDeclarations: [tool] }] |
| Gemini API, legacy SDK | @google/generative-ai (deprecated by Google) |
classToGeminiOldTool |
tools: [{ functionDeclarations: [tool] }] |
| Vertex AI | @google-cloud/vertexai |
classToGeminiVertexTool |
tools: [{ functionDeclarations: [tool] }] |
The model names below are examples; use a current one.
import OpenAI from 'openai';
import Anthropic from '@anthropic-ai/sdk';
import { GoogleGenAI } from '@google/genai';
import {
classToAnthropicTool,
classToGeminiTool,
classToOpenAIResponseApiTool,
classToOpenAITool,
} from '@firefliesai/schema-forge';
const prompt = 'Create a user named Ada Lovelace, ada@example.com, role admin';
// OpenAI, Chat Completions API
const openai = new OpenAI();
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
tools: [classToOpenAITool(CreateUserInput)],
});
const call = completion.choices[0].message.tool_calls?.[0];
if (call?.type === 'function') {
const input: CreateUserInput = JSON.parse(call.function.arguments);
}
// OpenAI, Responses API
const response = await openai.responses.create({
model: 'gpt-4o-mini',
input: prompt,
tools: [classToOpenAIResponseApiTool(CreateUserInput)],
});
const item = response.output[0];
if (item.type === 'function_call') {
const input: CreateUserInput = JSON.parse(item.arguments);
}
// Anthropic
const anthropic = new Anthropic();
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 1000,
messages: [{ role: 'user', content: prompt }],
tools: [classToAnthropicTool(CreateUserInput)],
});
const toolUse = message.content.find((block) => block.type === 'tool_use');
if (toolUse?.type === 'tool_use') {
const input = toolUse.input as CreateUserInput;
}
// Gemini, @google/genai
const gemini = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const result = await gemini.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
config: {
tools: [{ functionDeclarations: [classToGeminiTool(CreateUserInput)] }],
},
});
const input = result.functionCalls?.[0]?.args as unknown as
| CreateUserInput
| undefined;The type annotation on input is a promise about the shape, not a check. In strict mode the provider guarantees that the arguments match the schema it received; rules that Schema Forge moved into a description are not enforced. Without strict mode, the model usually follows the schema, but nothing guarantees it. Your code should still validate what it runs (for example with class-validator).
Schema Forge reads each property's design type. For some TypeScript types that is enough; for others the design type does not say what the value is, and you must add an option.
| TypeScript property | Design type | Schema without extra options | What to add |
|---|---|---|---|
name!: string |
String |
{ type: 'string' } |
nothing |
count!: number |
Number |
{ type: 'number' } |
type: 'integer' (or @IsInt()) for whole numbers |
active!: boolean |
Boolean |
{ type: 'boolean' } |
nothing |
createdAt!: Date |
Date |
{ type: 'string', format: 'date-time' } |
nothing |
address!: Address (a class with @ToolProp properties) |
the class | a nested object with Address's properties |
nothing |
role!: Role (a TypeScript enum) |
String or Number |
{ type: 'string' } or { type: 'number' }, without the allowed values |
enum: Role |
tags!: string[] |
Array |
error: an array needs an item type | items: { type: 'string' } |
addresses!: Address[] |
Array |
error: an array needs an item type | items: { type: Address } |
note?: string | null |
Object |
error: cannot determine the type | type: 'string', nullable: true |
place?: Place | null |
Object |
error: cannot determine the type | type: Place, nullable: true (a class as type declares the nested class) |
when?: Date | null |
Object |
error: cannot determine the type | type: Date, nullable: true (gives format: 'date-time'; String, Number and Boolean work the same way) |
id!: string | number |
Object |
error: cannot determine the type | anyOf: [{ type: 'string' }, { type: 'number' }] |
meta!: Record<string, string> |
Object |
error: cannot determine the type | type: 'object' |
Object is what TypeScript records for a union of different types (string | number; a union of string literals such as 'a' | 'b' records String), a nullable type under strictNullChecks, an interface, a generic, any and unknown. Schema Forge does not guess a type for such a property; generating the schema throws (section 8). A class-validator type decorator such as @IsString() can also supply the type (section 5).
enum Role {
Admin = 'admin',
Member = 'member',
}
class Address {
@ToolProp({ description: 'City name' })
city!: string;
}
class Team {
@ToolProp({ description: 'Tags', items: { type: 'string' } })
tags!: string[];
@ToolProp({ description: 'Main role', enum: Role })
role!: Role;
@ToolProp({ description: 'Roles of the team', enum: Role })
roles!: Role[];
@ToolProp({ description: 'Office address' })
office!: Address;
@ToolProp({ description: 'Other offices', items: { type: Address } })
branches!: Address[];
}
classToJsonSchema(Team).properties;
// {
// tags: { description: 'Tags', items: { type: 'string' }, type: 'array' },
// role: {
// description: 'Main role',
// enum: ['admin', 'member'],
// type: 'string'
// },
// roles: {
// description: 'Roles of the team',
// type: 'array',
// items: { type: 'string', enum: ['admin', 'member'] }
// },
// office: {
// description: 'Office address',
// type: 'object',
// properties: { city: {…} },
// required: ['city']
// },
// branches: {
// description: 'Other offices',
// type: 'array',
// items: {
// type: 'object',
// properties: { city: {…} },
// required: ['city']
// }
// }
// }enumtakes a TypeScript enum or an array of values. On an array property it describes the items.- The type of an enum comes from its values: all strings give
string, all numbersnumber, all booleansboolean, a mix gives a list such as['string', 'number']. - A class used as a property type is expanded into a nested object. A class cannot contain itself, directly or through another class (section 11).
isOptional and nullable answer two different questions:
| Option | Question it answers | Effect on the schema |
|---|---|---|
isOptional: true |
May the caller leave the property out? | The property is not listed in required. It does not by itself allow null. |
nullable: true |
May the value be null? |
null becomes an allowed value: type: 'string' becomes type: ['string', 'null'], and an enum gains null. |
Use both for a property that may be missing or null:
class UpdateProfileInput {
@ToolProp({
description: 'New nickname, or null to remove it',
type: 'string',
nullable: true,
isOptional: true,
})
nickname?: string | null;
}
classToJsonSchema(UpdateProfileInput);
// {
// type: 'object',
// properties: {
// nickname: { description: '…', type: ['string', 'null'] }
// }
// }
// (no `required` list: the only property is optional)A schema that already accepts null (for example one with a { type: 'null' } branch) is left as it is. Otherwise, with anyOf or oneOf, nullable adds a { type: 'null' } branch; with const, allOf, or a composition next to another keyword such as type or enum, the whole property becomes anyOf: [<property>, { type: 'null' }].
| Option | Type | Meaning |
|---|---|---|
description |
string |
Text the LLM reads to understand the property. Recommended on every property. |
type |
'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object', a class, or Date / String / Number / Boolean |
The JSON Schema type, when the design type is not enough. A class declares a nested class; Date also gives format: 'date-time' (4.1). |
enum |
TypeScript enum or array of values | The allowed values. |
items |
{ type: 'string' | 'number' | 'integer' | 'boolean' | 'object' | SomeClass, …constraints } |
The item schema of an array. |
isOptional |
boolean |
Leaves the property out of required. |
nullable |
boolean |
Allows null (4.3). |
format, pattern, minLength, maxLength |
String rules, as in JSON Schema. | |
minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf |
Number rules, as in JSON Schema. | |
minItems, maxItems, uniqueItems |
Array rules, as in JSON Schema. | |
anyOf, oneOf, allOf, const |
Combinations and fixed values, copied to the schema as given. The design type adds no type next to them; a type, items or enum you set is still applied. |
|
title, default, examples, deprecated |
Annotations, copied to the schema as given. |
The output uses JSON Schema Draft 2020-12 keywords. It has no $schema field, because the LLM APIs do not need one.
@ToolMeta({ name, description }) takes the tool's name and description. The provider formats read it; without it, the tool's name is an empty string.
If your class also uses class-validator decorators, Schema Forge adds the rules it can translate (5.3) to the schema. You write a rule once, and both the validator and the LLM see it.
Schema Forge only reads class-validator's decorators to add rules to the JSON Schema; it never runs validation. To validate values, call class-validator's validate() yourself, or validate the arguments against the generated JSON Schema.
import { IsEmail, IsInt, IsPositive, Max, MaxLength } from 'class-validator';
class CreateOrderInput {
@ToolProp({ description: 'Customer email' })
@IsEmail()
email!: string;
@ToolProp({ description: 'Number of items' })
@IsInt()
@IsPositive()
@Max(100)
quantity!: number;
@ToolProp({ description: 'Note for the courier', isOptional: true })
@MaxLength(200)
note?: string;
}
classToJsonSchema(CreateOrderInput).properties;
// {
// email: {
// description: 'Customer email',
// type: 'string',
// format: 'email'
// },
// quantity: {
// description: 'Number of items',
// type: 'integer',
// maximum: 100,
// exclusiveMinimum: 0
// },
// note: {
// description: 'Note for the courier',
// type: 'string',
// maxLength: 200
// }
// }The decorators may be written in any order; Schema Forge reads them when the schema is generated.
Diagram 2: which source wins. Each part of a property's schema comes from one of three sources. When two sources disagree, the higher one wins. Schema Forge prints a warning only when an explicit option and a class-validator rule disagree; class-validator replaces the design type without a warning.
highest 1. explicit options @ToolProp({ … }), updateSchemaProperty(),
propertyOverrides
2. class-validator @IsInt(), @MaxLength(200), @IsEmail(), …
lowest 3. design type what TypeScript recorded (String, Number, …)
For example, @ToolProp({ type: 'number' }) with @IsInt() keeps number and warns. Without the explicit type, the property becomes integer.
class-validator only adds rules to properties that have @ToolProp. A property with class-validator decorators but no @ToolProp is not in the schema. This lets one class be an API DTO and a tool input with different fields, for example an ownerId that your API sets and the LLM must not send.
Two related checks:
- If a class has class-validator decorators but no
@ToolPropat all, generating its schema throws, because the schema would be empty. This usually means the class was copied withPickType,OmitTypeorPartialType(from NestJS), which keep class-validator's metadata but not Schema Forge's. - To check in a test that a class exposes every validated property, use
findUndeclaredValidatedProperties:
import { findUndeclaredValidatedProperties } from '@firefliesai/schema-forge';
expect(findUndeclaredValidatedProperties(CreateOrderInput)).toEqual([]);
// If a property were validated but not declared, the list would name it,
// for example:
// [
// {
// path: 'shipping.ownerId',
// className: 'ShippingInput',
// property: 'ownerId'
// }
// ]A decorator with { each: true } applies its rule to the items of an array (@IsObject({ each: true }) is not translated; set items yourself). When you did not set items and those item rules give no type of their own, the item type is the one they accept:
- The numeric rules (
@Min,@Max,@IsPositive,@IsNegative,@IsDivisibleBy) accept only numbers, so the items arenumber. - The string rules (
@MinLength,@MaxLength,@Length,@Matches,@IsEmail,@IsUrl,@IsUUID) accept only strings, so the items arestring. - Rules of both kinds on the same items give no type.
| class-validator decorator | JSON Schema |
|---|---|
@IsString(), @IsNumber(), @IsInt(), @IsBoolean(), @IsObject() |
type: 'string', 'number', 'integer', 'boolean', 'object' |
@IsArray() |
type: 'array' |
@ArrayMinSize(n), @ArrayMaxSize(n) |
minItems: n, maxItems: n |
@ArrayNotEmpty() |
minItems: 1 |
@ArrayUnique() |
uniqueItems: true |
@ArrayContains([...]) |
items.enum (primitive values only). This is not the same rule: class-validator means "contains these values", items.enum means "only these values" (#44). |
@Min(n), @Max(n) |
minimum: n, maximum: n |
@IsPositive(), @IsNegative() |
exclusiveMinimum: 0, exclusiveMaximum: 0 |
@IsDivisibleBy(n) |
multipleOf with the absolute value of n (not for n = 0) |
@MinLength(n), @MaxLength(n), @Length(min, max) |
minLength, maxLength |
@IsNotEmpty() |
minLength: 1 on a string (or on string items with { each: true }) |
@IsEmail(), @IsUrl(), @IsUUID() |
format: 'email', 'uri', 'uuid' |
@Matches(regex) |
pattern, if the regex has no flags other than u |
@IsEnum(E), @IsIn([...]) |
enum |
When several decorators set the same limit (for example @Length(2, 10) and @MinLength(5)), the strictest value is used. This includes @IsNotEmpty(): with @MinLength(0) the result is minLength: 1.
@IsOptional(), @ValidateIf(), @ValidateNested(), @IsDefined(), @Allow(), @IsDate() and @IsNotEmptyObject() add nothing to the schema and print no warning. @IsOptional() does not make a property optional; use isOptional: true.
Some rules have no JSON Schema keyword: @IsTimeZone(), @IsISO8601(), @IsDateString(), @Matches(/x/i) (a regex with flags) and your own validators. They are not in the schema, so the LLM does not see them. Schema Forge prints a warning for each such rule on each property (console.warn, starting with [schema-forge], once per process). Describe the rule yourself in description, or with format or pattern. Only an explicit format, pattern or enum on the property turns these warnings off; a description does not.
classToJsonSchema(Class, options) and every classTo… function accept these options:
| Option | Default | Effect |
|---|---|---|
additionalProperties: false |
not set | Adds additionalProperties: false to every object that declares properties: the root, nested classes, array items and anyOf / oneOf / allOf branches. Strict modes need closed objects, but forStructuredOutput: true closes them for you; use this option to close objects without strict mode. An object without declared properties (a Record) stays open, because closing it would accept only {}. |
forStructuredOutput: true |
false (true for classToOpenAIResponseApiTool) |
Adapts the schema to the provider's strict mode and sets strict: true: OpenAI's rules for the OpenAI functions (7.1), Anthropic's for classToAnthropicTool (7.2). classToJsonSchema returns only a schema, so it applies the OpenAI changes but sets no strict flag. The Gemini functions do not take this option. |
propertyOverrides |
none | Changes properties for this call only, by path: { 'name': { description: '…' }, 'address.city': { … } }. An override that describes a property holding a class as something else (another type, an enum, a const, a composition, or items that are not a class) replaces the class, whose schema is then not built. A property declared with nullable: true keeps allowing null unless the override sets nullable: false. |
To change a class's schema for every later call, use updateSchemaProperty and addSchemaProperty. Paths may go into nested classes:
import {
addSchemaProperty,
updateSchemaProperty,
} from '@firefliesai/schema-forge';
class Shipment {
@ToolProp({ description: 'Destination' })
destination!: Address;
}
updateSchemaProperty(Shipment, 'destination.city', {
description: 'Destination city',
});
addSchemaProperty(Shipment, 'destination.zip', {
type: 'string',
isOptional: true,
});
// Every later classToJsonSchema(Shipment) has destination.city's new
// description and destination.zip. Address's own schema is not changed.Each classTo… function calls classToJsonSchema and then changes the result to fit one provider. The jsonSchemaTo… functions start from a JSON Schema you already have (7.4): the Gemini ones change it as described in 7.3, while the OpenAI and Anthropic ones do not apply the strict-mode changes, even with { strict: true }.
OpenAI has two APIs and two uses of a schema:
| Purpose | Chat Completions API | Responses API |
|---|---|---|
| Tool | classToOpenAITool |
classToOpenAIResponseApiTool |
| Structured output | classToOpenAIResponseFormatJsonSchema (for response_format) |
classToOpenAIResponseApiTextSchema (for text.format) |
See OpenAI's function calling and structured outputs guides, and migrating to the Responses API.
Strict mode. OpenAI's strict mode requires additionalProperties: false on every object and every property in required; an optional property is written as a type that allows null (see Supported schemas). forStructuredOutput: true does this for you:
forStructuredOutput: true changes |
Example |
|---|---|
Sets strict: true on the tool or format |
|
Adds additionalProperties: false to every object that declares properties |
|
Lists every property in required |
|
Makes each optional property nullable, the same way nullable: true does (4.3) |
age?: number becomes type: ['number', 'null'] |
| Moves the keywords OpenAI strict mode rejects into the property's description | @IsUrl() gives format: 'uri', which becomes description: 'Website\n\n{format: "uri"}' |
These keywords are moved into the description:
- a
formatother thandate-time,time,date,duration,email,hostname,ipv4,ipv6anduuid; uniqueItems,contains,minContains,maxContainsandunevaluatedItemson arrays;minProperties,maxProperties,propertyNamesandunevaluatedPropertieson objects;- a
patternthat uses a lookahead or lookbehind ((?=,(?!,(?<=,(?<!), a named group ((?<name>), a backreference (\1,\k<name>), a word boundary (\b,\B), or any other group that starts with(?except(?:(for example an inline flag such as(?i)). OpenAI rejects a named group, and for the others it returns an empty response that stops at the token limit.
These keywords stay, and OpenAI enforces them: minLength, maxLength, other patterns (non-capturing groups (?:…) and long ranges such as {1,1000} included), minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, minItems, maxItems and patternProperties.
allOf, oneOf and not stay as you wrote them, and so do if / then / else, dependentRequired and dependentSchemas. OpenAI strict mode rejects all of them at any depth, and its error names the property, so you see the problem instead of losing the rule. An object with no declared properties (a free-form object, such as a Record) cannot be closed, so generating the schema throws, naming the property (11).
These lists were checked against the live API (November 2026). OpenAI's guide says minLength, maxLength, pattern, format, number bounds, multipleOf, minItems and maxItems are not supported for fine-tuned models. On the base models, the API accepts and enforces them. A fine-tuned gpt-4o-mini model also accepted minLength, pattern and minimum in strict mode. If your fine-tuned model rejects one of them, remove it. For a rule written only in @ToolProp, set it to undefined in propertyOverrides (for example { name: { minLength: undefined } }). For a rule that a class-validator decorator sets, even when @ToolProp sets it too, delete it from the generated schema before you send it: class-validator fills in a rule the override left empty.
import {
classToOpenAIResponseFormatJsonSchema,
} from '@firefliesai/schema-forge';
const tool = classToOpenAITool(CreateUserInput, {
forStructuredOutput: true,
});
const format = classToOpenAIResponseFormatJsonSchema(CreateUserInput, {
forStructuredOutput: true,
});
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
response_format: format,
});
// A refusal or an empty reply carries no arguments; never parse a default
const message = completion.choices[0].message;
if (message.refusal) throw new Error(`Refused: ${message.refusal}`);
if (!message.content) throw new Error('No structured output in the reply');
const user: CreateUserInput = JSON.parse(message.content);The Responses API tool is strict by default. classToOpenAIResponseApiTool applies the strict changes above and sets strict: true unless you pass forStructuredOutput: false. With forStructuredOutput: false, it sends the schema as declared, with strict: false: optional properties stay optional and every keyword stays. This matches the Responses API, which tries strict mode when strict is left out and keeps best-effort function calling when it is false.
classToAnthropicTool returns { name, description, input_schema }. With additionalProperties: false, the root input_schema is closed too. See defining tools.
Strict tool use. forStructuredOutput: true turns on Anthropic's strict tool use, whose rules differ from OpenAI's (see Anthropic's JSON Schema limitations):
forStructuredOutput: true changes |
Why |
|---|---|
Sets strict: true on the tool |
Turns strict tool use on |
Adds additionalProperties: false to every object that declares properties |
Anthropic requires it |
Keeps required as declared |
Anthropic allows optional properties, so none becomes nullable |
Moves minimum, maximum, exclusiveMinimum, exclusiveMaximum and multipleOf into the description |
Anthropic rejects number bounds |
Moves minLength and maxLength into the description |
Anthropic's guide lists string lengths as unsupported |
Moves maxItems, a minItems other than 0 or 1, uniqueItems, contains, minContains and maxContains into the description |
Anthropic rejects these array rules |
Moves patternProperties, propertyNames, minProperties, maxProperties and unevaluatedProperties into the description |
Anthropic rejects these object rules |
Moves a format other than date-time, time, date, duration, email, hostname, uri, ipv4, ipv6 and uuid into the description |
Anthropic supports only these formats |
Removes the type array next to an enum (a nullable or mixed-type enum), and drops the enum values that this type did not allow |
Anthropic rejects the pair; the enum's values already say which types are allowed |
A keyword moved into the description is written as {keyword: value}, for example 'Quantity\n\n{maximum: 100}', which is how Anthropic's own SDK keeps such rules visible to the model. String lengths are moved, as the guide says, even though the API accepted them on two models (checked November 2026). This way a tool keeps working if Anthropic starts rejecting them.
A pattern is moved into the description when Anthropic would reject it with an HTTP 400 (Bad Request) error, that is when it uses:
- a lookahead, lookbehind, named group, backreference,
\b,\B, or another group that starts with(?except(?:(the same constructs as for OpenAI); - a
{n},{n,}or{n,m}quantifier on a broad set:., a negated class such as[^x],\S,\D,\W, or a class or group that holds one (even^.{1,200}$is rejected); - a quantifier bound above 256.
Anthropic's guide lists large ranges as unsupported without giving a number. When checked (November 2026), {1,2000} alone and {1,1000} next to another quantifier were rejected, and bounds up to 500 passed, so 256 leaves a margin. Other patterns stay, .+ and [a-z]{1,256} included. OpenAI accepted all of these quantifiers, so its patterns are not changed for them.
oneOf and not stay as you wrote them; Anthropic strict mode rejects them, while anyOf and allOf are accepted (Anthropic's guide excludes allOf combined with $ref, which Schema Forge never emits). An object with no declared properties throws, as for OpenAI.
Anthropic also limits a request to 20 strict tools, 24 optional properties and 16 properties with a union type (anyOf or a type array) across all strict schemas. Schema Forge does not count these.
| SDK | Tool | Structured output (responseSchema) |
|---|---|---|
@google/genai (current) |
classToGeminiTool |
classToGeminiResponseSchema |
@google/generative-ai (deprecated by Google) |
classToGeminiOldTool |
classToGeminiOldResponseSchema |
@google-cloud/vertexai |
classToGeminiVertexTool |
classToGeminiVertexResponseSchema |
The Vertex AI functions are implemented but not tested against the real API.
Gemini accepts only part of JSON Schema in these fields. See its function calling guide, and the fields of its Schema type in the API reference (under CachedContent → tools → functionDeclarations → parameters). If a schema has any field that Schema does not have, Gemini rejects the whole request with an HTTP 400 error (Unknown name "uniqueItems" … Cannot find field). The Gemini functions change the schema to fit, as checked against the live API in November 2026:
| JSON Schema from Schema Forge | Sent to Gemini |
|---|---|
type: ['string', 'null'] or a { type: 'null' } branch |
type: 'string', nullable: true |
type: ['string', 'number'] (several types) |
anyOf with one branch per type (next to an anyOf it throws, naming the property: Gemini has no single place for both) |
additionalProperties |
removed |
exclusiveMinimum / exclusiveMaximum |
minimum / maximum on an integer (exclusiveMinimum: 0 becomes minimum: 1); otherwise added to the description |
a string const |
a one-value enum |
an enum whose values are not all non-empty strings |
added to the description (the type stays) |
any other field Gemini does not have, such as multipleOf (from @IsDivisibleBy), uniqueItems, examples, deprecated, readOnly, contains, patternProperties, propertyNames, or a const that is not a string |
added to the description |
"Added to the description" means the keyword and its value are appended to the property's description as {keyword: value}, so the model still reads the rule. oneOf, allOf and not are kept, and their branches are adapted like any other schema: the API accepts them, although its documentation does not list them. The API checks these fields before the request reaches a model, so the result was the same on every model tried (Gemini 2.5 Flash, 2.5 Pro and 3.8 Flash); whether a model follows oneOf, allOf or not is up to the model.
Gemini does not need forStructuredOutput, so the Gemini functions do not take it.
import { classToGeminiResponseSchema } from '@firefliesai/schema-forge';
const structured = await gemini.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
config: {
responseMimeType: 'application/json',
responseSchema: classToGeminiResponseSchema(CreateUserInput),
},
});
// A blocked or empty reply has no text; never parse a default
if (!structured.text) throw new Error('No structured output in the reply');
const user: CreateUserInput = JSON.parse(structured.text);If you already have a JSON Schema, convert it without a class. The OpenAI converters pass the schema as it is. The Anthropic and Gemini converters keep only the root's properties and required (Anthropic also additionalProperties: false); other root keywords, such as the schema's own description or maxProperties, are dropped (#37):
import {
jsonSchemaToAnthropicTool,
jsonSchemaToOpenAITool,
openAIToolToJsonSchema,
} from '@firefliesai/schema-forge';
const searchSchema = {
type: 'object' as const,
properties: {
query: { type: 'string' as const, description: 'Search words' },
},
required: ['query'],
};
const openAITool = jsonSchemaToOpenAITool(searchSchema, {
name: 'search',
description: 'Search documents',
});
// From an OpenAI tool back to JSON Schema, then to Anthropic
const { schema, metadata } = openAIToolToJsonSchema(openAITool);
const anthropicTool = jsonSchemaToAnthropicTool(schema, metadata);These functions do not run the checks of section 8, and for OpenAI and Anthropic the strict option only sets the flag. For strict mode, first call prepareForOpenAIStructuredOutput(schema, true) or prepareForAnthropicStrictTool(schema), then pass { strict: true }.
Schema Forge checks when a schema is generated: when you call classToJsonSchema or a classTo… function. It checks the class you pass and, recursively, the classes nested in it. Defining or decorating a class never throws.
updateSchemaProperty and addSchemaProperty throw when called only for a mistake in their own arguments:
- a path with
__proto__,constructororprototype; - a class named in
typeoritems.type; - an
addSchemaPropertycall with neithertypenorenum; - a path through an array property that has no
items(a path into a nested class is checked later, when the schema is generated).
So a class that has @ToolProp but is never turned into a schema (for example a database model whose shared field decorator adds @ToolProp to every field) cannot break your program when it loads.
To find problems early, generate every tool's schema when your application starts, or in a test.
Problems found while the class is built (a missing type, a missing item type, no @ToolProp, a loop, another installed copy) are collected into one error, named after the class you passed. A problem in a nested class shows its path from that class. An invalid path, an update that names a class, and the strict-mode and Gemini errors are thrown on their own. For a class Order with a property customer: Customer (each problem is one line in the real message; it is wrapped here to fit):
schema-forge: cannot generate a JSON Schema for Order:
- Order.note: cannot determine the JSON Schema type; TypeScript reports
design type Object (a union such as `T | null`, …). Set `type`, `items`
or `enum` in @ToolProp …
- Order.customer → Customer.tags: an array needs an item type. …
| Error message contains | Cause | Fix |
|---|---|---|
cannot determine the JSON Schema type |
The design type is Object (a union, T | null, an interface, a generic, any, unknown, Record), and no option or class-validator decorator gives a type; or there is no design type at all (13). |
Set type, items or enum (and nullable: true if null is allowed), or add a type decorator such as @IsString(). |
an array needs an item type |
An array property has no items, and no class-validator decorator with { each: true } gives the items a type (5.3). |
Set items. |
the class declares no property with @ToolProp |
The class has class-validator decorators but no @ToolProp at all (5.2). |
Add @ToolProp to the properties the schema should have. |
… names the class …, which an update cannot add |
updateSchemaProperty, addSchemaProperty or a propertyOverrides entry named a class in type or items.type. Only @ToolProp declares a nested class and builds its schema; an update would leave the class unbuilt, so the property would lose its shape. |
Declare the property with @ToolProp (items: { type: TheClass } for an array, or the class as its TypeScript type), for example in a subclass. |
refers to its own class / refers back to …, which contains it |
A class contains itself, directly (children: Node[] in Node) or through another class (A.b: B and B.a: A). |
On the property that closes the loop, set type: 'object' (or items: { type: 'object' } for an array). It becomes an object without a fixed shape. |
cannot be used as a property name or path segment |
A path given to updateSchemaProperty, addSchemaProperty or propertyOverrides contains __proto__, constructor or prototype, which would reach an object's prototype instead of a property. updateSchemaProperty and addSchemaProperty throw when called; propertyOverrides when the schema is generated. |
Use a different property name. |
strict mode cannot express |
A free-form object (no declared properties, such as a Record) in OpenAI or Anthropic strict mode (11). |
Declare its properties, or describe it as a string that holds JSON. |
Gemini cannot express |
A type array with several non-null types next to an anyOf (for example a mixed-type enum beside an anyOf), sent to a Gemini function (7.3). |
Put the types into the anyOf branches. |
cannot reach into "…": it is an array without items |
The path of an update, override or added property goes through an array property that has no items. |
Set items on the array property. |
Either type or enum must be specified |
addSchemaProperty was called with neither type nor enum. |
Give it a type or an enum. |
declared by another installed copy of @firefliesai/schema-forge |
Two copies of Schema Forge are installed, and a property was declared through the other copy, whose metadata this copy cannot read (section 2). | Install a single copy (deduplicate, or force one version with your package manager's overrides), or declare the property with this copy's @ToolProp. |
Warnings go to console.warn, start with [schema-forge], and are printed once per message.
| Warning | Meaning |
|---|---|
… from @ToolProp is kept; class-validator says … (… allows … for an enum) |
An explicit option and a class-validator rule disagree. The explicit option is used (5.1). |
class-validator rule "…" has no JSON Schema equivalent |
The rule is not in the schema (5.4). |
3.0.0 throws where 2.x produced a wrong schema, and translates more class-validator rules. Most classes produce the same schema as before. The full list of changes is the 3.0.0 entry of the CHANGELOG.
- Generate the schema of every class you convert (for example by running your tests) and fix each error from section 8.2. The most common one is a property typed
T | nullunderstrictNullChecks: 2.x produced{ "type": "object" }for it, which rejected every string or number sent for it. - Read the
[schema-forge]warnings. A conflict warning means an explicit option now wins over class-validator. A "no JSON Schema equivalent" warning names a rule the schema does not contain. - Compare the schemas. Save the
classToJsonSchemaoutput of each class before and after the upgrade and compare them. The expected differences are listed under "Breaking changes" in the CHANGELOG:exclusiveMinimumfor@IsPositive, the new translations, decorator order, enum types and compositions. - Check the installed copies. If a library depends on another version of Schema Forge, install a single copy (section 2). If that library applies
@ToolPropfor you (for example a shared field decorator), it must stop doing so, or move to 3.0.0, before your service upgrades: otherwise its properties are declared through the other copy, and generating the schema throws. - Update type checks.
JSONSchemaProperty.typemay now be an array orundefined. - Stored metadata. If your code reads
Reflect.getMetadata(JSON_SCHEMA_METADATA_KEY, …)directly: a class-typed property no longer holds its nested class's properties there. They exist only in the generated schema. - class-validator. If you use it, version 0.14 or 0.15 is required. Inference did not work with 0.13 in 2.x either.
- Strict modes. With
forStructuredOutput: true, OpenAI tools and response formats now keep string lengths, the patterns and formats OpenAI supports, number bounds and array sizes, and OpenAI enforces them, so a model can no longer send a value outside them (a rule moved into a description is not enforced).classToAnthropicToolnow applies Anthropic's own strict rules and setsstrict: trueinstead of the OpenAI rules (optional properties stay optional).classToOpenAIResponseApiToolwithforStructuredOutput: falsenow sends the schema as declared (7.1, 7.2). If you callprepareForOpenAIStructuredOutputon a schema you send to Anthropic, switch toprepareForAnthropicStrictTool: the OpenAI helper now keeps rules Anthropic strict mode rejects.
This section is for contributors and for readers who want to know why the rules above exist. You do not need it to use the library.
Diagram 3: what happens when. Steps (1) and (2) run once, when the class is defined. Steps (3) to (8) run every time a schema is generated.
class definition
┌──────────────────────────────────────────────────────────────────────────┐
│ (1) @ToolProp records, per property: the options as written, │
│ which of them were explicit, the design type, a nested class │
│ (2) class-validator records its rules in its own store │
└─────────────────────────────────────┬────────────────────────────────────┘
│
v
classToJsonSchema(Root, options)
┌──────────────────────────────────────────────────────────────────────────┐
│ (3) read Root's stored properties │
│ (4) look for properties another copy of the package declared │
│ -> problem │
│ (5) for each property holding a class: build that class's schema, │
│ with the updates and overrides whose path goes into it │
│ ((3) to (7) again; a class already on the path -> recursion problem) │
│ (6) apply the other recorded updates, then the other propertyOverrides │
│ (7) per property: add class-validator rules (explicit wins), nullable, │
│ check the type -> problems │
│ (8) problems? throw one error : apply options and return │
└──────────────────────────────────────────────────────────────────────────┘
- Why the checks wait for generation. A property's class-validator decorators may run after
@ToolProp(decorators run bottom-up), and a class may be decorated by a shared library without ever being used as a tool. Checking at generation time makes the result independent of decorator order, and means a class is only checked when a schema reaches it. - Precedence (7).
@ToolProprecords which options you set yourself. Inferred rules fill the gaps; a conflicting inferred rule only produces a warning. - Nested classes (5).
@ToolPropstores a reference to a property's class, not its schema. The nested schema is built for each root, so a change to the nested class is always seen, and the path from the root is known for error messages and recursion checks. - Updates into nested classes (5).
updateSchemaProperty(Outer, 'address.city', …)is recorded onOuter. When a schema ofOuteris generated, the update is handed to the build ofAddress's schema and applied there beforeAddress's properties are checked, exactly like an update ofAddress's owncity. ApropertyOverridesentry such as'address.city'goes the same way, at any depth. So an update or override can give a nested property the type it lacks, andAddressitself does not change. A subclass ofOutergets the update too, if itsaddressproperty still holds the same class. Step (6) applies the rest: updates of the class's own properties, and paths into a property whose class is not built. - Another installed copy (4). Metadata is stored under JavaScript symbols created by each copy of the package (
Symbol('jsonSchema')). Two copies create two different symbols with the same name, so one copy cannot read the other's properties. Schema Forge looks for a symbol with the same name that is not its own, and reports the properties only that copy declared, instead of leaving them out silently.
- No recursive schemas. Schema Forge does not emit
$refor$defs, so a class cannot contain itself; describe the closing property astype: 'object'. - No object-level rules.
minProperties,maxProperties,patternPropertiesandpropertyNameshave no option. - class-transformer is not read.
@Type(() => X)does not give array items; setitems. @IsOptional()does not make a property optional. UseisOptional: true.- Strict modes cannot express a free-form object. OpenAI and Anthropic strict modes reject an object that is not closed, and an object without declared properties (a
Record) cannot be closed. So in strict mode, generating the schema throws and names the property. This happens withforStructuredOutput: true, withclassToOpenAIResponseApiTool(strict unlessforStructuredOutput: false), and inprepareForOpenAIStructuredOutputandprepareForAnthropicStrictTool. Declare its properties, or describe it as a string that holds JSON. - The Vertex AI functions are not tested against the real API.
Decorators
| Function | Description |
|---|---|
@ToolMeta({ name?, description? }) |
Class decorator: the tool's name and description, used by the provider formats. |
@ToolProp(options?) |
Property decorator: puts the property in the schema (4.4). |
Generating a schema
| Function | Description |
|---|---|
classToJsonSchema(Class, options?) |
The JSON Schema of a class (section 6). |
prepareForOpenAIStructuredOutput(schema, handleOptionals?) |
The OpenAI strict-mode preparation of 7.1, on a schema you already have. handleOptionals defaults to false, as in 2.x: a property missing from required is then required anyway, and the model has to invent a value for it. Pass true when the schema's required is accurate, so such a property becomes nullable instead (the classTo… functions do). Pass { strict: true } to the jsonSchemaToOpenAI… function as well. |
prepareForAnthropicStrictTool(schema) |
The Anthropic strict-tool preparation of 7.2, on a schema you already have; pass { strict: true } to jsonSchemaToAnthropicTool as well. |
findUndeclaredValidatedProperties(Class) |
Properties with class-validator decorators but no @ToolProp, with their paths (5.2). |
Changing a class's schema permanently
| Function | Description |
|---|---|
updateSchemaProperty(Class, path, updates) |
Changes a property; the path may go into nested classes. |
addSchemaProperty(Class, path, options) |
Adds a property; the path may go into nested classes. |
From a class to a provider format (all take (Class, options?))
| Function | Returns |
|---|---|
classToOpenAITool |
OpenAI Chat Completions tool |
classToOpenAIResponseApiTool |
OpenAI Responses API tool (strict by default) |
classToOpenAIResponseFormatJsonSchema |
OpenAI Chat Completions response_format |
classToOpenAIResponseApiTextSchema |
OpenAI Responses API text.format |
classToAnthropicTool |
Anthropic tool (strict tool use with forStructuredOutput: true) |
classToGeminiTool, classToGeminiResponseSchema |
@google/genai function declaration, response schema |
classToGeminiOldTool, classToGeminiOldResponseSchema |
@google/generative-ai function declaration, response schema |
classToGeminiVertexTool, classToGeminiVertexResponseSchema |
@google-cloud/vertexai function declaration, response schema |
From a JSON Schema to a provider format. The OpenAI and Anthropic converters take (schema, { name, description? }, { strict? }). The Gemini tool converters take (schema, { name, description? }), and the Gemini response-schema converters take (schema, { description? }). strict: true only sets the flag (7.4).
jsonSchemaToOpenAITool, jsonSchemaToOpenAIResponseApiTool (its options.strict is required), jsonSchemaToOpenAIResponseFormat, jsonSchemaToOpenAIResponseApiTextSchema, jsonSchemaToAnthropicTool (for strict tool use, call prepareForAnthropicStrictTool first, then pass { strict: true }), jsonSchemaToGeminiTool, jsonSchemaToGeminiResponseSchema, jsonSchemaToGeminiOldTool, jsonSchemaToGeminiOldResponseSchema, jsonSchemaToGeminiVertexTool, jsonSchemaToGeminiVertexResponseSchema.
From a provider format back to JSON Schema
openAIToolToJsonSchema(tool) and openAIResponseApiToolToJsonSchema(tool) return { schema, metadata }.
Other exports. inferClassValidatorProperties(prototype, propertyName) returns what Schema Forge reads from one property's class-validator decorators. Schema is an object holding the main functions above (an older import style), and classToLLMTool is an older name for classToOpenAITool.
Property 'name' has no initializer and is not definitely assigned in the constructor. ts(2564) — strictPropertyInitialization is on. Write name!: string (section 2).
The error says "no design type (is emitDecoratorMetadata enabled?)" — turn on emitDecoratorMetadata, and make sure your build tool emits decorator metadata. esbuild does not support it, so tools that compile TypeScript with esbuild do not either, unless you add a plugin that emits decorator metadata.
A property is missing from the schema — it has no @ToolProp (5.2), or it was declared through another installed copy of Schema Forge, which 3.0.0 reports as an error (section 8.2).
An optional property rejects null — isOptional does not allow null; add nullable: true (4.3).
Contributions are welcome. Please open an issue or a pull request on GitHub.