Generate JSON schemas and LLM function calling schemas from Java and Kotlin code β including classes you don't own.
Quick Links:
- Documentation Index
- KSP Configuration Guide
- Java Annotation Processor Guide β including Jackson-backed Java enum names
- Serialization-Based Schema Generation
- 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:
- First-class support for OpenAI/Anthropic function calling format
- Automatic strict mode and parameter validation
- 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) via 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 JSON Schema DSL section β
Table of contents:
- Why kt-schema?
- Choosing Your Approach
- Quick Start
- Runtime schema generation
- What Gets Generated
- Examples
- Using @Schema and @Description annotations
- 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 OpenAI/Anthropic-compatible function schemas 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, Claude, 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.
Β² via Jackson's @JsonEnumDefaultValue, placed on an enum constant β shown as default on that enum's own schema
in the generated output. @JsonProperty(defaultValue = "...") is also recognized and populates the property
internally, but neither processor's standard generated resource surfaces it, since both mark every property
required regardless of default presence (KSP/APT can't evaluate a real Kotlin/Java default-value expression at
compile time, unlike reflection) β 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") val street: String,
@Description("City or town name") val city: String,
@Description("Postal or ZIP code") val zipCode: String,
@Description("Two-letter ISO country code; defaults to US") val country: String = "US",
)Note: KDoc comments on classes can also be used as descriptions.
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.
Note
If your classes are @Serializable, use the Serialization-Based Generator instead β it works
on all platforms without reflection.
For JVM-only scenarios with classes you don't own or can't annotate, use
ReflectionClassJsonSchemaGenerator
and
ReflectionFunctionCallingSchemaGenerator
with Kotlin reflection.
Primary use case: Third-party library classes
The compile-time (KSP) approach requires you to annotate classes with @Schema, which isn't possible for:
- Library classes (Spring entities, Ktor models, database classes)
- Framework-provided models
- Classes from dependencies you don't control
Runtime generation solves this by using reflection to analyze any class at runtime.
Important
Limitations:
- KDoc annotations are not available at runtime
- Function parameter defaults (e.g.,
fun foo(x: Int = 5)) cannot be extracted via reflection - Data class property defaults (e.g.,
data class Config(val port: Int = 8080)) ARE supported
// Works with ANY class, even from third-party libraries
import com.thirdparty.library.User // Not your code!
val generator = me.kpavlov.kt.schema.generator.json.ReflectionClassJsonSchemaGenerator.Default
val schema: JsonSchema = generator.generateSchema(User::class)
val schemaString: String = generator.generateSchemaString(User::class)Add dependency: me.kpavlov.kt.schema:kt-schema-generator-json:<version>
Schemas follow JSON Schema Draft 2020-12 format. Example (pretty-printed):
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "com.example.Address",
"type": "object",
"properties": {
"street": {
"type": "string",
"description": "Street address, including house number"
},
"city": {
"type": "string",
"description": "City or town name"
},
"zipCode": {
"type": "string",
"description": "Postal or ZIP code"
},
"country": {
"type": "string",
"description": "Two-letter ISO country code; defaults to US",
"default": "US"
}
},
"required": [
"street",
"city",
"zipCode"
],
"additionalProperties": false,
"description": "A postal address for deliveries and billing."
}- Enums are
type: stringwithenum: []and carry@Descriptionasdescription. - Object properties include their inferred type schema and, when present, property-level
@Descriptionasdescription. - Default values are automatically extracted and included in the schema when using runtime reflection (e.g.,
val country: String = "US"β"default": "US"). Note: KSP (compile-time) tracks which properties have defaults but cannot extract the actual values. - Nullable properties are emitted as a union including
null. - Collections:
List<T>/Set<T>β{ "type":"array", "items": T };Map<String, V>β{ "type":"object", "additionalProperties": V }. kotlin.Any/ unbound generic type parameters (e.g.,T) map to the empty schema{}, which accepts any JSON value.- Named types (nested objects, enums, sealed classes) are deduplicated in a
$defssection and referenced via$refat every usage site.
Here's a practical example of a product model with various property types:
@Description("A purchasable product with pricing and inventory info.")
@Schema
data class Product(
@Description("Unique identifier for the product")
val id: Long,
@Description("Human-readable product name")
val name: String,
@Description("Optional detailed description of the product")
val description: String?,
@Description("Unit price expressed as a decimal number")
val price: Double,
@Description("Whether the product is currently in stock")
val inStock: Boolean = true,
@Description("List of tags for categorization and search")
val tags: List<String> = emptyList(),
)Use the generated extensions:
val schema = Product::class.jsonSchemaString
val schemaObject = Product::class.jsonSchemaGenerated JSON schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "com.example.Product",
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "Unique identifier for the product"
},
"name": {
"type": "string",
"description": "Human-readable product name"
},
"description": {
"type": [
"string",
"null"
],
"description": "Optional detailed description of the product"
},
"price": {
"type": "number",
"description": "Unit price expressed as a decimal number"
},
"inStock": {
"type": "boolean",
"description": "Whether the product is currently in stock"
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of tags for categorization and search"
}
},
"required": [
"id",
"name",
"description",
"price"
],
"additionalProperties": false,
"description": "A purchasable product with pricing and inventory info."
}Enums are supported with descriptions on both the enum class and individual values:
@Description("Current lifecycle status of an entity.")
@Schema
enum class Status {
@Description("Entity is active and usable")
ACTIVE,
@Description("Entity is inactive or disabled")
INACTIVE,
@Description("Entity is pending activation or approval")
PENDING,
}Generated JSON schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "com.example.Status",
"type": "string",
"enum": [
"ACTIVE",
"INACTIVE",
"PENDING"
],
"description": "Current lifecycle status of an entity."
}You can compose schemas by nesting annotated classes:
@Description("A person with a first and last name and age.")
@Schema
data class Person(
@Description("Given name of the person")
val firstName: String,
@Description("Family name of the person")
val lastName: String,
@Description("Age of the person in years")
val age: Int,
)
@Description("An order placed by a customer containing multiple items.")
@Schema
data class Order(
@Description("Unique order identifier")
val id: String,
@Description("The customer who placed the order")
val customer: Person,
@Description("Destination address for shipment")
val shippingAddress: Address,
@Description("List of items included in the order")
val items: List<Product>,
@Description("Current status of the order")
val status: Status,
)The generated schema for Order will automatically include definitions for all nested types (Person, Address,
Product, Status) in the $defs section, with appropriate $ref pointers to link them together. This makes it easy
to build complex, composable data models.
Generic classes are supported, with type parameters resolved at usage sites:
@Description("A generic container that wraps content with optional metadata.")
@Schema
data class Container<T>(
@Description("The wrapped content value")
val content: T,
@Description("Arbitrary metadata key-value pairs")
val metadata: Map<String, Any> = emptyMap(),
)Generic type parameters are resolved at the usage site. Unbound type parameters (like T) and kotlin.Any-typed
properties map to {} β the empty JSON Schema that accepts any JSON value. For more specific typing, instantiate the
generic class with concrete types when you need them.
The library automatically generates JSON schemas for Kotlin sealed class hierarchies using oneOf:
@Description("Multicellular eukaryotic organism of the kingdom Metazoa")
@Schema
sealed class Animal {
/**
* Animal's name
*/
@Description("Animal's name")
abstract val name: String
@Schema(withSchemaObject = true)
data class Dog(
@Description("Animal's name")
override val name: String,
) : Animal()
// @SerialName overrides the emitted type name for this subtype only (see below)
@SerialName("Cat")
@Schema(withSchemaObject = true)
data class Cat(
@Description("Animal's name")
override val name: String,
) : Animal()
}val generator = ReflectionClassJsonSchemaGenerator.Default
val schema = generator.generateSchema(Animal::class)
println(schema.encodeToString(Json { prettyPrint = true }))Generated JSON schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "me.kpavlov.kt.schema.integration.type.Animal",
"description": "Multicellular eukaryotic organism of the kingdom Metazoa",
"type": "object",
"additionalProperties": false,
"oneOf": [
{
"$ref": "#/$defs/Cat"
},
{
"$ref": "#/$defs/me.kpavlov.kt.schema.integration.type.Animal.Dog"
}
],
"$defs": {
"Cat": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "Cat"
},
"name": {
"type": "string",
"description": "Animal's name"
}
},
"required": [
"type",
"name"
],
"additionalProperties": false
},
"me.kpavlov.kt.schema.integration.type.Animal.Dog": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "me.kpavlov.kt.schema.integration.type.Animal.Dog"
},
"name": {
"type": "string",
"description": "Animal's name"
}
},
"required": [
"type",
"name"
],
"additionalProperties": false
}
}
}Key features:
oneOfwith$ref: Each sealed subclass is stored in$defsand referenced via$ref- Fully qualified names by default:
$defskeys and discriminatorconstvalues use fully qualified class names (e.g.,com.example.Animal.Dog) to avoid collisions across packages - Name overrides: a subtype annotated with
@SerialName/@JsonTypeName(or another recognized name-override annotation) uses that short name instead of its FQN β likeCatabove, overridden via@SerialName("Cat") - Discriminator property: A
typefield with aconstvalue is automatically added to each subtype for runtime dispatch - Property inheritance: Base class properties are included in each subtype
- Type safety: Each subtype gets its own schema definition
Use @SchemaIgnore to exclude specific sealed subtypes from the generated schema.
The class remains fully functional at runtime β only schema generation is affected:
@Schema
sealed class Event {
data class Click(val x: Int, val y: Int) : Event()
@SchemaIgnore
data class Internal(val trace: String) : Event()
}The Internal subtype will not appear in the oneOf composition or $defs.
For serialization-based generation, use @SerialSchemaIgnore (which carries @SerialInfo):
@Serializable
sealed class Event {
@Serializable
data class Click(val x: Int, val y: Int) : Event()
@Serializable
@SerialSchemaIgnore
data class Internal(val trace: String) : Event()
}Jackson's @JsonIgnoreType is also recognized automatically. Custom ignore annotations can be
registered via kt-schema.properties:
introspector.annotations.ignore.names=SchemaIgnore,SerialSchemaIgnore,JsonIgnoreType,MyCustomIgnoreMark classes with @Schema to generate extension properties for them:
@Schema // Uses default schema type "json"
data class Address(val street: String, val city: String)
@Schema("json") // Explicitly specify schema type
data class Person(val name: String, val age: Int)@Schema parameters:
value = "json": Schema type (only JSON currently supported)withSchemaObject = false: GeneratejsonSchema: JsonObjectproperty ( see Advanced Configuration)
Note: jsonSchemaString is always generated. jsonSchema requires withSchemaObject = true.
Use @Description on classes and properties to add human-readable documentation to your schemas:
@Description("A purchasable product with pricing info")
@Schema
data class Product(
@Description("Unique identifier for the product") val id: Long,
@Description("Human-readable product name") val name: String,
@Description("Optional detailed description of the product") val description: String?,
@Description("Unit price expressed as a decimal number") val price: Double,
)Tip: With the recommended compiler flag -Xannotation-default-target=param-property, a bare @Description on a
primary constructor parameter also applies to the property. If you do not enable the flag, use @param:Description for
constructor-declared properties.
Modern LLMs (OpenAI GPT-4, Anthropic Claude, etc.) use structured function calling to interact with your code. They require a specific JSON schema format that describes available functions, their parameters, and types.
LLM APIs need to know:
- What functions are available and what they do
- Parameter names, types, and descriptions
- Which parameters are required
- Type constraints (enums, formats, ranges)
This library automatically generates schemas that comply with the OpenAI function calling specification, making it easy to expose Kotlin functions to LLMs.
@Description("Get current weather for a location")
fun getWeather(
@Description("City and country, e.g. 'London, UK'")
location: String,
@Description("Temperature unit")
unit: String = "celsius"
): WeatherInfo {
return WeatherInfo(20.0, unit)
}
val generator = ReflectionFunctionCallingSchemaGenerator.Default
val schema = generator.generateSchema(::getWeather)The generated schema follows the LLM function calling format:
{
"type": "function",
"name": "getWeather",
"description": "Get current weather for a location",
"strict": true,
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country, e.g. 'London, UK'"
},
"unit": {
"type": "string",
"description": "Temperature unit"
}
},
"required": [
"location",
"unit"
],
"additionalProperties": false
}
}- Automatic extraction: Function name and descriptions from
@Descriptionannotations - Default values: Property defaults in nested data classes are automatically extracted (e.g.,
data class Config(val port: Int = 8080)) - Strict mode:
strict: trueenables OpenAI's strict mode for reliable parsing - Union types: Nullable parameters use
["string", "null"]instead ofnullable: true - Required by default: All parameters marked as required (OpenAI structured outputs requirement)
- Type safety: Proper JSON Schema types from Kotlin types (Int β integer, String β string, etc.)
Note: Function parameter defaults (e.g.,
unit: String = "celsius") cannot be extracted via reflection, but nested data class property defaults are fully supported.
// Define your functions
@Description("Search the knowledge base")
fun searchKnowledge(
@Description("Search query") query: String,
@Description("Max results") limit: Int = 10
): String = TODO()
@Description("Calculate order total with tax")
fun calculateTotal(
@Description("Item prices") prices: List<Double>,
@Description("Tax rate as decimal") taxRate: Double = 0.0
): Double = TODO()
// Generate schemas
val generator = ReflectionFunctionCallingSchemaGenerator.Default
val schemas = listOf(::searchKnowledge, ::calculateTotal)
.map { generator.generateSchema(it) }
// Serialize to JSON
val jsonSchemas = schemas.map { Json.encodeToString(it) }
// Or get as JsonObject
val schemaObjects = schemas.map { it.encodeToJsonObject() }The generated schemas can be sent to any LLM API that supports function calling (OpenAI, Anthropic, etc.). Integration with specific LLM providers requires their respective client libraries.
Nullable parameters are represented as union types:
@Description("Update user profile")
fun updateProfile(
@Description("User ID") userId: String,
@Description("New name, if changing") name: String? = null,
@Description("New email, if changing") email: String? = null
): Boolean = TODO("does not matter")// ...Generates:
{
"properties": {
"userId": {
"type": "string",
"description": "User ID"
},
"name": {
"type": [
"string",
"null"
],
"description": "New name, if changing"
},
"email": {
"type": [
"string",
"null"
],
"description": "New email, if changing"
}
},
"required": [
"userId",
"name",
"email"
]
}Note: Even nullable parameters are in required array. The null type in the union indicates optionality.
For more details on function calling schemas and OpenAI compatibility, see kt-schema-json/README.md.
Generate function schemas at compile time with zero runtime overhead. KSP generates type-safe extensions for all your annotated functions, with APIs that reflect where functions actually live in your code.
Annotate package-level functions to generate top-level schema accessors:
@Schema
@Description("Sends a greeting message to a person")
fun greetPerson(
@Description("Name of the person to greet")
name: String,
@Description("Optional greeting prefix (e.g., 'Hello', 'Hi')")
greeting: String = "Hello",
): String = "$greeting, $name!"
// Generated: top-level functions
val schema = greetPersonJsonSchemaString()Annotate class methods to generate KClass extensions on the containing class:
class UserService {
@Schema
@Description("Registers a new user in the system")
fun registerUser(
@Description("Username for the new account")
username: String,
@Description("Email address")
email: String,
): String = "User registered"
}
// Generated: KClass extension on UserService
val schema = UserService::class.registerUserJsonSchemaString()Annotate companion methods to generate KClass extensions on the companion object itself:
class DatabaseConnection {
companion object {
@Schema
@Description("Creates a new database connection")
fun create(
@Description("Database host")
host: String,
@Description("Database port")
port: Int = 5432,
): DatabaseConnection = TODO()
}
}
// Generated: KClass extension on companion object
val schema = DatabaseConnection.Companion::class.createJsonSchemaString()This API correctly reflects that companion functions belong to the companion object, not the parent class.
Annotate object methods to generate KClass extensions on the object type:
object ConfigurationManager {
@Schema
@Description("Loads configuration from a file")
fun loadConfig(
@Description("Configuration file path")
filePath: String,
@Description("Whether to create file if it doesn't exist")
createIfMissing: Boolean = false,
): Map<String, String> = TODO()
}
// Generated: KClass extension on object
val schema = ConfigurationManager::class.loadConfigJsonSchemaString()KSP generates schema accessor functions that match where your functions live:
| Function Type | Annotate | Generated API | Example |
|---|---|---|---|
| Top-level | Package function | Top-level accessor | greetPersonJsonSchemaString() |
| Instance | Class method | KClass extension |
UserService::class.registerUserJsonSchemaString() |
| Companion | Companion method | Companion::class extension |
DatabaseConnection.Companion::class.createJsonSchemaString() |
| Object | Object method | Object::class extension |
ConfigurationManager::class.loadConfigJsonSchemaString() |
For each annotated function, you get:
- Always:
{functionName}JsonSchemaString(): Stringβ returns the schema as a JSON string - Optional:
{functionName}JsonSchema(): FunctionCallingSchemaβ returns the schema object (requireswithSchemaObject = true)
Generated schemas follow the OpenAI function calling format:
{
"type": "function",
"name": "greetPerson",
"description": "Sends a greeting message to a person",
"strict": true,
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the person to greet"
},
"greeting": {
"type": "string",
"description": "Optional greeting prefix"
}
},
"required": [
"name",
"greeting"
],
"additionalProperties": false
}
}OpenAI Strict Mode: All parameters are marked as required by default, even those with default values. This ensures compatibility with OpenAI Structured Outputs.
| Feature | KSP (Compile-time) | Reflection (Runtime) |
|---|---|---|
| Performance | Zero runtime cost | Small reflection overhead |
| Platforms | Multiplatform | JVM only |
| Default values | Tracked but not extracted (KSP limitation) | Fully extracted from data classes |
| When to use | Your annotated functions | Third-party functions, dynamic scenarios |
Suspend functions work identically to regular functions. The generated schemas don't expose the suspend modifierβthey describe parameter types only:
@Schema
@Description("Fetches user data asynchronously")
suspend fun fetchUserData(
@Description("User ID to fetch") userId: Long,
): UserData = TODO()
// Generated API works the same way
val schema = fetchUserDataJsonSchemaString()You don't need to change your existing code!
kt-schema recognizes description annotations from multiple frameworks by their simple name, allowing you to generate schemas from code that uses annotations from other libraries.
The library automatically recognizes these description annotations by default:
| Annotation | Simple Name | Library/Framework | Example |
|---|---|---|---|
me.kpavlov.kt.schema.Description |
Description |
kt-schema | @Description("User name") |
ai.koog.agents.core.tools.annotations.LLMDescription |
LLMDescription |
Koog AI agents | @LLMDescription("Query text") |
com.fasterxml.jackson.annotation.JsonPropertyDescription |
JsonPropertyDescription |
Jackson | @JsonPropertyDescription("Email") |
com.fasterxml.jackson.annotation.JsonClassDescription |
JsonClassDescription |
Jackson | @JsonClassDescription("User model") |
dev.langchain4j.model.output.structured.P |
P |
LangChain4j | @P("Search query") |
Beyond descriptions, kt-schema also recognizes name overrides and ignore markers by default:
Name overrides β matched by fully qualified name (case-sensitive):
| Annotation | Maps to |
|---|---|
com.fasterxml.jackson.annotation.JsonProperty |
property name in properties/required |
com.fasterxml.jackson.annotation.JsonTypeName |
polymorphic subtype name ($defs key + discriminator const) |
Ignore markers β matched by simple name (case-insensitive), regardless of package:
| Annotation | Maps to |
|---|---|
JsonIgnore (any package) |
excludes the property/field from the schema |
Default values β matched by fully qualified name (case-sensitive); mainly useful for the KSP and Java APT processors, which can't evaluate a real Kotlin/Java default-value expression at compile time:
| Annotation | Maps to |
|---|---|
com.fasterxml.jackson.annotation.JsonEnumDefaultValue |
the enum constant it's placed on becomes that enum type's default (on the enum's own schema, in $defs) |
com.fasterxml.jackson.annotation.JsonProperty(defaultValue=..) |
the property's default value, internally |
Note
The @JsonEnumDefaultValue-derived default always appears in the generated output, since it's a property of
the enum's own schema. @JsonProperty(defaultValue = "...") is recognized and populates the property internally,
but doesn't appear in β or exclude the property from required in β the KSP/APT processors' standard generated
resource, since both mark every property required regardless of default presence. It does apply when building a
schema through TypeGraphToJsonSchemaTransformer with a non-strict JsonSchemaConfig yourself.
Each annotation category (description, name-override, ignore) is configured with its own list of recognized names. Within a list, entries containing a dot are matched case-sensitively against the fully qualified name; entries without a dot are matched case-insensitively against the simple name. This means:
- β No code changes needed to generate schemas from existing annotated classes
- β Can migrate between annotation libraries without modifying code
- β Generate schemas for third-party code that uses different annotations
- β Use your preferred annotation library while still getting schema generation
Note
Multi-framework annotation recognition applies to the KSP processor, the Java APT processor
(via AptIntrospectionContext, which recognizes the same Jackson defaults), and reflection-based generators.
The serialization-based generator (SerializationClassJsonSchemaGenerator) can only access annotations marked
with @SerialInfo β see Custom description extraction for details.
Annotation detection is configurable via kt-schema.properties loaded from the classpath.
The configuration file is optional β if not provided or fails to load, the library uses sensible defaults.
By default, the library recognizes:
Description annotations: Description, LLMDescription, JsonPropertyDescription, JsonClassDescription, P Description attributes: value, description Ignore annotations: SchemaIgnore, SerialSchemaIgnore, JsonIgnoreType, JsonIgnore Name-override annotations: kotlinx.serialization.SerialName, com.fasterxml.jackson.annotation.JsonProperty, com.fasterxml.jackson.annotation.JsonTypeName Name-override attributes: value Enum-default annotations: com.fasterxml.jackson.annotation.JsonEnumDefaultValue Default-value annotations: com.fasterxml.jackson.annotation.JsonProperty Default-value attributes: defaultValue
Note
Annotation names containing a dot (e.g., kotlinx.serialization.SerialName) are matched
case-sensitively against the annotation's fully qualified name. Names without a dot
are matched case-insensitively by simple name.
To customize, place kt-schema.properties in your project's resources:
# Add your custom annotations to the defaults
introspector.annotations.description.names=Description,MyCustomAnnotation,DocString
introspector.annotations.description.attributes=value,description,text
# Name-override annotations (use FQN for precise matching)
introspector.annotations.name.names=kotlinx.serialization.SerialName
introspector.annotations.name.attributes=value
# Default-value annotations (use FQN for precise matching)
introspector.annotations.enumDefault.names=com.fasterxml.jackson.annotation.JsonEnumDefaultValue
introspector.annotations.defaultValue.names=com.fasterxml.jackson.annotation.JsonProperty
introspector.annotations.defaultValue.attributes=defaultValueNote: The library falls back to built-in defaults if the configuration file is missing or cannot be loaded.
// Your custom annotation
package com.mycompany.annotations
annotation class ApiDoc(val text: String)
// Usage in your models
@ApiDoc(text = "Customer profile information")
data class Customer(
@ApiDoc(text = "Unique customer identifier")
val id: Long,
val name: String
)Update kt-schema.properties:
introspector.annotations.description.names=Description,ApiDoc
introspector.annotations.description.attributes=value,description,textNow the schema generator will recognize @ApiDoc and extract descriptions from its text parameter.
If your project already uses Jackson for JSON serialization, you can generate schemas from existing Jackson-annotated classes without any modifications. This is particularly useful for REST APIs and Spring Boot applications where Jackson annotations are already present.
// Existing code with Jackson annotations - NO CHANGES NEEDED!
@JsonClassDescription("Customer profile data")
data class Customer(
@JsonPropertyDescription("Unique customer ID")
val id: Long,
@JsonPropertyDescription("Full name")
val name: String,
@JsonPropertyDescription("Contact email")
val email: String
)
// Generate JSON schema without modifying the code
val generator = me.kpavlov.kt.schema.generator.json.ReflectionClassJsonSchemaGenerator.Default
val schema = generator.generateSchema(Customer::class)
// Schema includes all Jackson descriptions!LangChain4j uses the @P annotation for parameter descriptions in AI function calling. The library recognizes these
annotations automatically, enabling seamless integration with existing LangChain4j codebases.
// Code using LangChain4j annotations
data class SearchQuery(
@P("Search terms")
val query: String,
@P("Maximum results to return")
val limit: Int = 10
)
// Generate schema for LLM function calling
val generator = ReflectionFunctionCallingSchemaGenerator.Default
val schema = generator.generateSchema(SearchQuery::class.constructors.first())Koog AI framework uses @LLMDescription for documenting agent tools and parameters. The library supports both the
verbose description = syntax and the shorthand form, making migration from Koog straightforward.
@LLMDescription(description = "Product with pricing information")
@Schema
data class Product(
@LLMDescription(description = "Product identifier")
val id: Long,
@LLMDescription("Product name")
val name: String,
@LLMDescription("Unit price")
val price: Double,
)If multiple description annotations are present on the same element, the first matching annotation in source-code
order wins. There is no special priority for @Description over other recognized annotations β whichever recognized
annotation appears first on the declaration is used.
Tip: For predictability, place only one description annotation per element. If you use @Description from
kotlinx-schema alongside another recognized annotation, put @Description first in source order to ensure it wins.
For manual schema construction, use the kt-schema-json module. It provides type-safe Kotlin models compliant with the JSON Schema Draft 2020-12 specification and a DSL for building JSON Schema definitions programmatically, with full kotlinx-serialization support.
dependencies {
implementation("me.kpavlov.kt.schemakt-schema-json:<version>")
}Quick Example:
val schema = jsonSchema {
property("id") {
required = true
string { format = "uuid" }
}
property("email") {
required = true
string { format = "email" }
}
property("age") {
integer {
minimum = 0.0
maximum = 150.0
}
}
// Polymorphic types with discriminators
property("role") {
oneOf {
discriminator(propertyName = "type") {
"admin" mappedTo "#/definitions/AdminRole"
"user" mappedTo {
property("type") { string { constValue = "user" } }
property("permissions") { array { ofString() } }
}
}
}
}
}Features:
- β Type-safe property definitions (string, number, integer, boolean, array, object, reference)
- β Polymorphism: oneOf, anyOf, allOf with elegant discriminator support
- β Type-safe enums: Native Kotlin types (List, List, etc.) instead of JsonElement
- β Constraints: required, nullable, enum, const, min/max, format validation
- β Nested schemas and arrays of complex types
- β Full kotlinx-serialization integration
- β Kotlin Multiplatform support
π For comprehensive documentation, see kt-schema-json/README.md covering:
- Complete DSL reference and type-safe enum API
- Polymorphism patterns (oneOf, anyOf, allOf) with discriminators
- Generic properties with heterogeneous enums
- Working with nested objects and arrays
- Serialization/deserialization examples
- Function calling schema for LLM APIs
For build instructions, development setup, and contribution guidelines, see CONTRIBUTING.md.
- Kotlin 2.2+
- KSP 2 for compile-time KSP generation
- 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.
