@@ -16,9 +16,11 @@ import kotlin.reflect.KParameter
1616import kotlin.reflect.KType
1717import kotlin.reflect.full.findAnnotation
1818import kotlin.reflect.full.hasAnnotation
19+ import kotlin.reflect.full.instanceParameter
1920import kotlin.reflect.full.valueParameters
2021import kotlin.reflect.typeOf
2122import kotlin.text.get
23+ import kotlin.text.set
2224
2325/* *
2426 * Extension function to register tools from class methods annotated with [McpTool].
@@ -104,17 +106,30 @@ public fun <T : Any> Server.registerToolFromAnnotatedFunction(
104106 ) { request ->
105107 try {
106108
107- // Use reflection to call the annotated function with the provided arguments
108- val result = try {
109- val arguments = function.valueParameters.map { param ->
110- val paramName = param.name ? : " param${param.index} "
111- val jsonValue = request.arguments[paramName]
112- convertJsonValueToKotlinType(jsonValue, param.type)
113- }
114- function.call(instance, * arguments.toTypedArray())
115- } catch (e: Exception ) {
116- throw IllegalArgumentException (" Error invoking function ${function.name} : ${e.message} " , e)
117- }
109+ // Use reflection to call the annotated function with the provided arguments
110+ val result = try {
111+ val arguments = mutableMapOf<KParameter , Any ?>()
112+
113+ // Map instance parameter if required
114+ function.instanceParameter?.let { arguments[it] = instance }
115+
116+ // Map value parameters
117+ function.valueParameters.forEach { param ->
118+ val paramName = param.name ? : " param${param.index} "
119+ val jsonValue = request.arguments[paramName]
120+ // Use the provided value or the default value if the parameter is optional
121+ if (jsonValue != null ) {
122+ arguments[param] = convertJsonValueToKotlinType(jsonValue, param.type)
123+ } else if (! param.isOptional) {
124+ throw IllegalArgumentException (" Missing required parameter: $paramName " )
125+ }
126+ }
127+
128+ // Call the function using callBy
129+ function.callBy(arguments)
130+ } catch (e: Exception ) {
131+ throw IllegalArgumentException (" Error invoking function ${function.name} : ${e.message} " , e)
132+ }
118133
119134 // Handle the result
120135 when (result) {
0 commit comments