Generate JSON schemas and LLM function calling schemas from Java and Kotlin code โ including classes you don't own.
Full documentation lives at kpavlov.github.io/kt-schema. This README is the short tour; each topic below links to its guide.
- Documentation
- KSP Configuration Guide
- Java Annotation Processor Guide โ including Jackson-backed Java enum names
- Serialization-Based Schema Generation
- Runtime Reflection โ any JVM class, including third-party types
- Generated Schemas โ worked examples and the
@Schema/@Descriptionreference - Function Calling โ LLM tool schemas at runtime or compile time
- Validation Constraints โ Jakarta Bean Validation annotations and built-in type ranges
- Configuration โ schema flavours and annotation detection
- JSON Schema DSL
- Project Architecture
Generation Modes:
- Compile-time (Java APT): Zero runtime overhead for plain Java records, classes, interfaces and enums โ no Kotlin required in your code
- Compile-time (KSP): Zero runtime overhead, multiplatform, for your annotated Kotlin classes
- Runtime (Reflection): JVM-only, for any class including third-party libraries
- Runtime (SerialDescriptor): Kotlin serializable classes, including open polymorphism via
SerializersModule
LLM Integration:
- Tool definitions for OpenAI, Anthropic and MCP from Kotlin functions
- Strict mode output: all parameters required,
additionalProperties: false,nullunions for optional values - Function name and description extraction
Flexible Annotation Support:
- Recognizes
@Description,@LLMDescription,@JsonPropertyDescription,@P, and more - Recognizes KDoc (KSP compile-time only)
- Works with annotations from Jackson, LangChain4j, Koog without code changes
Comprehensive Type Support:
- Enums, collections, maps, nested objects, nullability, generics (with star-projection)
- Polymorphic hierarchies โ sealed classes and open polymorphism (via
SerializersModule) with automaticoneOfgeneration and discriminator field - Union types for nullable parameters (
["string", "null"]) - Type constraints (min/max, patterns, formats) from Jakarta Bean Validation annotations, built-in types and the JSON Schema DSL
- Default values (compile-time: tracked but not extracted; runtime: fully extracted)
$ref/$defsdeduplication: named types appear once in$defsand are referenced everywhere via$refkotlin.Any: maps to the empty schema{}(accepts any JSON value)
Developer Experience:
- Type-safe Kotlin DSL for programmatic schema construction
- Works everywhere: JVM, JS, iOS, macOS, Wasm
Tip
Need to build JSON Schemas manually? The kt-schema-json module provides type-safe Kotlin models and DSL compliant with JSON Schema Draft 2020-12, with support for polymorphism, discriminators, and type-safe enums. See the JSON Schema DSL guide.
Table of contents:
- Why kt-schema?
- Choosing Your Approach
- Quick Start
- Runtime schema generation
- What Gets Generated
- Function calling schema generation for LLMs
- Multi-Framework Annotation Support
- JSON Schema DSL
- Building and Contributing
- Requirements
- Code of Conduct
- License
This library solves three key challenges:
- ๐ค LLM Function Calling Integration: Generate tool definitions for OpenAI, Anthropic and MCP directly from Kotlin functions, with proper type definitions and descriptions
- ๐ฆ Third-Party Class Support: Create schemas for library classes without modifying their source code (Spring entities, Ktor models, etc.)
- ๐ Multi-Framework Compatibility: Works with existing annotations from Jackson, LangChain4j, Koog, and more โ no code changes needed
- ๐ค Building LLM-powered applications with structured function calling (OpenAI, Anthropic, MCP)
- ๐ฝ Need schemas for third-party library classes you cannot modify
- โ
Already using
@Description-like annotations from other frameworks - ๐ Want zero runtime overhead with compile-time generation (multiplatform support)
- โ๏ธ Need dynamic schema generation at runtime via reflection (JVM)
| ๐ง KSP Processor | โ Java APT | ๐ฆ Serialization-based | ๐ Runtime Reflection | |
|---|---|---|---|---|
| Platforms | JVM + Multiplatform | JVM only | JVM + Multiplatform | JVM only |
| When generated | Compile-time | Compile-time | Runtime | Runtime |
| Requires annotation processor | Yes (KSP) | Yes (APT) | No | No |
Class must be @Serializable |
No | No | Yes | No |
Annotate class with @Schema |
Required | Not requiredยน | Not required | Not required |
| KDoc extracted to description | โ | โ | โ | โ |
| Extract default values | Partialยฒ | Partialยฒ | โ | โ |
| Third-party classes | โ | โ | โ
(only @Serializable) |
โ any JVM class |
ยน with the rootPackage option โ see Java Annotation Processor Guide.
ยฒ Jackson's @JsonEnumDefaultValue becomes the enum's default. Kotlin/Java default-value expressions can't be
evaluated at compile time, so no property default is emitted โ see
Multi-Framework Annotation Support.
-
Pick KSP when you own the classes, want zero runtime overhead, and target Multiplatform or need KDoc in your schema.
-
Pick Java APT when your code is plain Java (no Kotlin) and you want zero runtime overhead. Supports Java records, classes, interfaces and enums.
-
Pick Serialization-based when your classes are already
@Serializableand you need Multiplatform support without a build-time processor. -
Pick Reflection when you need JVM-only runtime generation for third-party classes, or need to extract data class default values. Works equally well for
@Serializableclasses on JVM.
Refer to the example projects here.
/**
* A postal address for deliveries and billing.
*/
@Schema
data class Address(
@Description("Street address, including house number") @Size(max = 120) val street: String,
@Description("City or town name") @Size(min = 1, max = 80) val city: String,
@Description("Postal or ZIP code") @Pattern(regexp = "[0-9]{5}") val zipCode: String,
@Description("Two-letter ISO country code; defaults to US") @Pattern(regexp = "[A-Z]{2}") val country: String = "US",
)Generated JSON schema (KSP, default strict config)
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "com.example.Address",
"description": "A postal address for deliveries and billing.",
"type": "object",
"properties": {
"street": {
"type": "string",
"description": "Street address, including house number",
"maxLength": 120
},
"city": {
"type": "string",
"description": "City or town name",
"minLength": 1,
"maxLength": 80
},
"zipCode": {
"type": "string",
"description": "Postal or ZIP code",
"pattern": "[0-9]{5}"
},
"country": {
"type": "string",
"description": "Two-letter ISO country code; defaults to US",
"pattern": "[A-Z]{2}"
}
},
"additionalProperties": false,
"required": [
"street",
"city",
"zipCode",
"country"
]
}Note: KDoc comments on classes can also be used as descriptions. Jakarta Bean Validation annotations such as
@Sizeand@PatternbecomemaxLength,minLengthandpatternโ see Validation Constraints.
Add the Google KSP plugin and the processor dependency:
// Multiplatform (KMP)
plugins {
kotlin("multiplatform")
id("com.google.devtools.ksp") version "<ksp-version>"
}
dependencies {
add("kspCommonMainMetadata", "me.kpavlov.kt.schema:kt-schema-ksp:<version>")
implementation("me.kpavlov.kt.schema:kt-schema-annotations:<version>")
}
kotlin {
sourceSets.commonMain.kotlin.srcDir("build/generated/ksp/metadata/commonMain/kotlin")
}For JVM-only projects and full configuration options, see the KSP Configuration Guide.
The me.kpavlov.kt.schema.config processor option selects the schema flavour (strict, lenient, openapi or your
own JsonSchemaConfig) for both KSP and the Java annotation processor. See
Configuration.
For JVM-only scenarios with classes you don't own or can't annotate, ReflectionClassJsonSchemaGenerator builds the
schema from Kotlin reflection at runtime. Add me.kpavlov.kt.schema:kt-schema-generator-json:<version> and call
generateSchema(User::class). See the Runtime Reflection guide.
Schemas follow JSON Schema Draft 2020-12: $id, $defs/$ref deduplication, ["string", "null"] unions for
nullable types, oneOf with a discriminator for sealed hierarchies, and description from @Description or KDoc.
Worked examples for data classes, enums, nested objects, generics and sealed classes, plus the @Schema and
@Description reference, are in the Generated Schemas guide.
ReflectionFunctionCallingSchemaGenerator (runtime) and @Schema on functions (KSP, compile time) produce tool
definitions in the OpenAI Responses API shape, with strict: true, parameter descriptions and ["string", "null"]
unions for nullable parameters. The same parameters object serves as MCP's inputSchema and as Anthropic's
input_schema, except that Anthropic strict tool use rejects numeric and string-length constraints. See the
Function Calling guide.
kt-schema recognizes @Description, Koog's @LLMDescription, Jackson's @JsonPropertyDescription/
@JsonClassDescription, LangChain4j's @P, plus Jackson/kotlinx.serialization name overrides, ignore markers and
discriminators, so existing annotated classes need no changes. Detection is configurable through
kt-schema.properties. See Configuration.
For manual schema construction, the kt-schema-json module provides type-safe models and a DSL for JSON Schema Draft 2020-12. See the JSON Schema DSL guide and kt-schema-json/README.md.
For build instructions, development setup, and contribution guidelines, see CONTRIBUTING.md.
- Kotlin 2.2+
- KSP 2.3.1+ for compile-time KSP generation (earlier KSP2 builds report wrong annotation-argument origins, so
@Schemaparameters can be mistaken for defaults) - kotlinx-serialization-json for JsonObject support
Tip: If you use @Description on primary constructor parameters, enable
-Xannotation-default-target=param-property in Kotlin compiler options so the description applies to the backing
property.
This project and the corresponding community are governed by the Contributor Covenant Code of Conduct. Please make sure you read and adhere to it.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
kt-schema is an independently maintained fork of kotlinx.schema. Konstantin Pavlov originally started the work while at JetBrains.
This project contains modified and unmodified portions of the original work.
Notable changes include renaming the Kotlin packages from kotlinx.schema to me.kpavlov.kt.schema, renaming Maven
coordinates from org.jetbrains.kotlinx to me.kpavlov, and further independent development.
See the LICENSE and NOTICE files for licensing and attribution information.
kt-schema is an independent project and is not affiliated with, endorsed by, or sponsored by JetBrains. "Kotlin" and "JetBrains" are trademarks of their respective owners.
