-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathJsonSchema.kt
More file actions
79 lines (67 loc) · 2.87 KB
/
Copy pathJsonSchema.kt
File metadata and controls
79 lines (67 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package net.portswigger.mcp.schema
import io.modelcontextprotocol.kotlin.sdk.types.ToolSchema
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import kotlin.reflect.KClass
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
fun getJsonSchemaForProperty(kType: kotlin.reflect.KType): JsonElement {
return when (kType.classifier) {
String::class ->
JsonObject(mapOf("type" to JsonPrimitive("string")))
Int::class, Long::class ->
JsonObject(mapOf("type" to JsonPrimitive("integer")))
Float::class, Double::class ->
JsonObject(mapOf("type" to JsonPrimitive("number")))
Boolean::class ->
JsonObject(mapOf("type" to JsonPrimitive("boolean")))
List::class, Array::class -> {
val argType = kType.arguments.firstOrNull()?.type
val itemsSchema = when {
argType != null -> getJsonSchemaForProperty(argType)
else -> JsonObject(mapOf("type" to JsonPrimitive("object")))
}
JsonObject(mapOf("type" to JsonPrimitive("array"), "items" to itemsSchema))
}
Map::class -> {
val valueType = kType.arguments.getOrNull(1)?.type
val valueSchema = when {
valueType != null -> getJsonSchemaForProperty(valueType)
else -> JsonObject(mapOf("type" to JsonPrimitive("object")))
}
JsonObject(mapOf("type" to JsonPrimitive("object"), "additionalProperties" to valueSchema))
}
else ->
JsonObject(mapOf("type" to JsonPrimitive("object")))
}
}
fun KClass<*>.asInputSchema(): ToolSchema {
val properties = mutableMapOf<String, JsonElement>()
val required = mutableListOf<String>()
val parameters = primaryConstructor?.parameters?.associateBy { it.name }.orEmpty()
for (prop in memberProperties) {
val schema = getJsonSchemaForProperty(prop.returnType).jsonObject.toMutableMap()
if (prop.returnType.isMarkedNullable) {
schema["type"] = JsonArray(listOf(schema.getValue("type"), JsonPrimitive("null")))
}
when (prop.name) {
"targetPort" -> {
schema["minimum"] = JsonPrimitive(1)
schema["maximum"] = JsonPrimitive(65535)
}
"count" -> schema["minimum"] = JsonPrimitive(1)
"offset", "length" -> schema["minimum"] = JsonPrimitive(0)
}
properties[prop.name] = JsonObject(schema)
if (parameters[prop.name]?.isOptional == false) {
required.add(prop.name)
}
}
return ToolSchema(
properties = JsonObject(properties),
required = required
)
}