| | | 1 | | using System.Collections; |
| | | 2 | | using Shared.Contracts.Mcp; |
| | | 3 | | |
| | | 4 | | namespace UIBlazor.Processors; |
| | | 5 | | |
| | | 6 | | public static class SchemaProcessor |
| | | 7 | | { |
| | | 8 | | private const int _maxDepth = 5; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Deserializes a JsonElement representing a JSON Schema into a JsonSchemaProperty object graph. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="schemaElement">The JsonElement containing the schema.</param> |
| | | 14 | | /// <param name="currentDepth">The current recursion depth (used internally).</param> |
| | | 15 | | /// <param name="maxDepth">The maximum allowed nesting depth.</param> |
| | | 16 | | /// <returns>A JsonSchemaProperty object representing the schema, or null if the input is invalid.</returns> |
| | | 17 | | public static JsonSchemaProperty? DeserializeSchema(JsonElement? schemaElement, int currentDepth = 0, int maxDepth = |
| | | 18 | | { |
| | 97 | 19 | | if (!schemaElement.HasValue || schemaElement.Value.ValueKind != JsonValueKind.Object) |
| | | 20 | | { |
| | 33 | 21 | | return null; |
| | | 22 | | } |
| | | 23 | | |
| | 64 | 24 | | if (currentDepth > maxDepth) |
| | | 25 | | { |
| | 2 | 26 | | return null; |
| | | 27 | | } |
| | | 28 | | |
| | 62 | 29 | | var schema = schemaElement.Value; |
| | 62 | 30 | | var property = new JsonSchemaProperty(); |
| | | 31 | | |
| | 62 | 32 | | if (schema.TryGetProperty("type", out var typeElement)) |
| | | 33 | | { |
| | 52 | 34 | | property.Type = typeElement.GetString(); |
| | | 35 | | } |
| | | 36 | | |
| | 62 | 37 | | if (schema.TryGetProperty("description", out var descriptionElement)) |
| | | 38 | | { |
| | 5 | 39 | | property.Description = descriptionElement.GetString(); |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | // Handle constraints |
| | 62 | 43 | | if (schema.TryGetProperty("enum", out var enumElement) && enumElement.ValueKind == JsonValueKind.Array) |
| | | 44 | | { |
| | 6 | 45 | | property.EnumValues = []; |
| | 48 | 46 | | foreach (var val in enumElement.EnumerateArray()) |
| | | 47 | | { |
| | | 48 | | // Store raw values, conversion happens later if needed |
| | 18 | 49 | | property.EnumValues.Add(val.Clone()); |
| | | 50 | | } |
| | | 51 | | } |
| | | 52 | | |
| | 62 | 53 | | if (schema.TryGetProperty("minimum", out var minElement)) |
| | | 54 | | { |
| | 3 | 55 | | property.Minimum = minElement.GetDouble(); |
| | | 56 | | } |
| | 62 | 57 | | if (schema.TryGetProperty("maximum", out var maxElement)) |
| | | 58 | | { |
| | 3 | 59 | | property.Maximum = maxElement.GetDouble(); |
| | | 60 | | } |
| | 62 | 61 | | if (schema.TryGetProperty("minLength", out var minLengthElement)) |
| | | 62 | | { |
| | 3 | 63 | | property.MinLength = minLengthElement.GetInt32(); |
| | | 64 | | } |
| | 62 | 65 | | if (schema.TryGetProperty("maxLength", out var maxLengthElement)) |
| | | 66 | | { |
| | 3 | 67 | | property.MaxLength = maxLengthElement.GetInt32(); |
| | | 68 | | } |
| | 62 | 69 | | if (schema.TryGetProperty("pattern", out var patternElement)) |
| | | 70 | | { |
| | 2 | 71 | | property.Pattern = patternElement.GetString(); |
| | | 72 | | } |
| | 62 | 73 | | if (schema.TryGetProperty("required", out var requiredElement) && requiredElement.ValueKind == JsonValueKind.Arr |
| | | 74 | | { |
| | 13 | 75 | | property.Required = [.. requiredElement.EnumerateArray().Select(r => r.ToString())]; |
| | | 76 | | } |
| | | 77 | | |
| | | 78 | | // Recursively handle nested structures |
| | 62 | 79 | | if (property.Type == "object" && schema.TryGetProperty("properties", out var propsElement) && propsElement.Value |
| | | 80 | | { |
| | 10 | 81 | | property.Properties = []; |
| | 54 | 82 | | foreach (var prop in propsElement.EnumerateObject()) |
| | | 83 | | { |
| | 17 | 84 | | var nestedProp = DeserializeSchema(prop.Value, currentDepth + 1, maxDepth); |
| | 17 | 85 | | if (nestedProp != null) |
| | | 86 | | { |
| | 17 | 87 | | property.Properties[prop.Name] = nestedProp; |
| | | 88 | | } |
| | | 89 | | } |
| | | 90 | | } |
| | | 91 | | |
| | 62 | 92 | | if (property.Type == "array" && schema.TryGetProperty("items", out var itemsElement)) |
| | | 93 | | { |
| | 5 | 94 | | property.Items = DeserializeSchema(itemsElement, currentDepth + 1, maxDepth); |
| | | 95 | | } |
| | | 96 | | |
| | 62 | 97 | | return property; |
| | | 98 | | } |
| | | 99 | | |
| | | 100 | | /// <summary> |
| | | 101 | | /// Build a readable schema description for LLM prompt |
| | | 102 | | /// </summary> |
| | | 103 | | public static string BuildSchemaDescription(string toolName, McpToolConfig toolConfig) |
| | | 104 | | { |
| | | 105 | | try |
| | | 106 | | { |
| | 27 | 107 | | var schemaElement = toolConfig.InputSchema; |
| | 27 | 108 | | var schemaProperty = DeserializeSchema(schemaElement); |
| | 27 | 109 | | if (schemaProperty == null) |
| | | 110 | | { |
| | 24 | 111 | | return string.Empty; |
| | | 112 | | } |
| | | 113 | | |
| | 3 | 114 | | var sb = new StringBuilder(); |
| | 3 | 115 | | var exampleObj = GenerateObjectExample(schemaProperty); |
| | | 116 | | |
| | 3 | 117 | | sb.AppendLine("For example:"); |
| | 3 | 118 | | sb.AppendLine($"<function name=\"{toolName}\">"); |
| | 3 | 119 | | sb.AppendLine(JsonUtils.Serialize(exampleObj)); |
| | 3 | 120 | | sb.AppendLine("</function>"); |
| | | 121 | | |
| | 3 | 122 | | sb.AppendLine("*Properties schema:*"); |
| | 3 | 123 | | AppendSchemaDescription(sb, schemaProperty, parentPath: ""); |
| | | 124 | | |
| | 3 | 125 | | return sb.ToString(); |
| | | 126 | | } |
| | 0 | 127 | | catch (Exception) |
| | | 128 | | { |
| | 0 | 129 | | return string.Empty; |
| | | 130 | | } |
| | 27 | 131 | | } |
| | | 132 | | |
| | | 133 | | public static void AppendSchemaDescription(StringBuilder sb, JsonSchemaProperty prop, string parentPath, int depth = |
| | | 134 | | { |
| | 23 | 135 | | if (prop.Properties != null) |
| | | 136 | | { |
| | 78 | 137 | | foreach (var nestedPropKvp in prop.Properties) |
| | | 138 | | { |
| | 20 | 139 | | var required = prop.Required is not null |
| | 20 | 140 | | ? prop.Required.Contains(nestedPropKvp.Key) |
| | 20 | 141 | | : false; |
| | 20 | 142 | | var currentPath = string.IsNullOrEmpty(parentPath) ? nestedPropKvp.Key : $"{parentPath}.{nestedPropKvp.K |
| | 20 | 143 | | var nestedProp = nestedPropKvp.Value; |
| | | 144 | | |
| | 20 | 145 | | var typeInfo = nestedProp.Type ?? "unknown"; |
| | 20 | 146 | | if (nestedProp.EnumValues != null && nestedProp.EnumValues.Count > 0) |
| | | 147 | | { |
| | 7 | 148 | | typeInfo += $" (enum: {string.Join(", ", nestedProp.EnumValues.Select(v => v.ToString()))})"; |
| | | 149 | | } |
| | 22 | 150 | | if (nestedProp.Minimum.HasValue) typeInfo += $" (min: {nestedProp.Minimum.Value})"; |
| | 22 | 151 | | if (nestedProp.Maximum.HasValue) typeInfo += $" (max: {nestedProp.Maximum.Value})"; |
| | 22 | 152 | | if (nestedProp.MinLength.HasValue) typeInfo += $" (minLen: {nestedProp.MinLength.Value})"; |
| | 22 | 153 | | if (nestedProp.MaxLength.HasValue) typeInfo += $" (maxLen: {nestedProp.MaxLength.Value})"; |
| | 22 | 154 | | if (!string.IsNullOrEmpty(nestedProp.Pattern)) typeInfo += $" (pattern: {nestedProp.Pattern})"; |
| | | 155 | | |
| | 20 | 156 | | var requiredStr = required ? "REQUIRED" : "(optional)"; |
| | 20 | 157 | | sb.AppendLine($"{currentPath} : [{typeInfo}] {nestedProp.Description ?? ""} {requiredStr}"); |
| | | 158 | | |
| | | 159 | | // Recurse for nested objects |
| | 20 | 160 | | if (nestedProp.Type?.ToLowerInvariant() == "object") |
| | | 161 | | { |
| | 3 | 162 | | AppendSchemaDescription(sb, nestedProp, currentPath, depth + 1); |
| | | 163 | | } |
| | | 164 | | } |
| | | 165 | | } |
| | 4 | 166 | | else if (prop.Type?.ToLowerInvariant() == "array" && prop.Items != null) |
| | | 167 | | { |
| | | 168 | | // Describe the array item type |
| | 3 | 169 | | var itemTypeInfo = prop.Items.Type ?? "unknown"; |
| | 3 | 170 | | if (prop.Items.EnumValues != null && prop.Items.EnumValues.Count > 0) |
| | | 171 | | { |
| | 3 | 172 | | itemTypeInfo += $" (enum: {string.Join(", ", prop.Items.EnumValues.Select(v => v.ToString()))})"; |
| | | 173 | | } |
| | | 174 | | // ... potentially add minItems, maxItems if schema defines them ... |
| | 3 | 175 | | sb.AppendLine($"{parentPath}[] : [array of {itemTypeInfo}] {prop.Description ?? ""}"); |
| | | 176 | | |
| | | 177 | | // If the item itself is an object, recurse |
| | 3 | 178 | | if (prop.Items.Type?.ToLowerInvariant() == "object") |
| | | 179 | | { |
| | 1 | 180 | | var itemPath = $"{parentPath}[]_item"; // Represent the item placeholder |
| | 1 | 181 | | AppendSchemaDescription(sb, prop.Items, itemPath, depth + 1); |
| | | 182 | | } |
| | | 183 | | } |
| | 23 | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Генерирует объект для передачи в MCP с заполненными данными для простого примера |
| | | 188 | | /// </summary> |
| | | 189 | | public static object? GenerateExample(JsonSchemaProperty? schemaProperty, int depth = 0) |
| | | 190 | | { |
| | 28 | 191 | | if (schemaProperty == null || depth > _maxDepth) |
| | | 192 | | { |
| | 2 | 193 | | return new Dictionary<string, object?>(); |
| | | 194 | | } |
| | | 195 | | |
| | 26 | 196 | | return schemaProperty.Type?.ToLowerInvariant() switch |
| | 26 | 197 | | { |
| | 8 | 198 | | "string" => GetEnumOrDefault(schemaProperty, "sample_string"), |
| | 5 | 199 | | "number" => GetEnumOrDefault(schemaProperty, 0.1), |
| | 6 | 200 | | "integer" => GetEnumOrDefault(schemaProperty, 0), |
| | 5 | 201 | | "boolean" => GetEnumOrDefault(schemaProperty, true), |
| | 0 | 202 | | "array" => new List<object?> { GenerateExample(schemaProperty.Items, depth + 1) }, |
| | 2 | 203 | | "object" => GenerateObjectExample(schemaProperty, depth), |
| | 0 | 204 | | _ => "unknown_type" |
| | 26 | 205 | | }; |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | private static object? GetEnumOrDefault(JsonSchemaProperty schemaProperty, object defaultValue) |
| | | 209 | | { |
| | 24 | 210 | | return schemaProperty.EnumValues is { Count: > 0 } |
| | 24 | 211 | | ? $"One of strings: {string.Join(',', schemaProperty.EnumValues)}" |
| | 24 | 212 | | : defaultValue; |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | private static Dictionary<string, object?> GenerateObjectExample(JsonSchemaProperty schemaProperty, int depth = 0) |
| | | 216 | | { |
| | 5 | 217 | | var obj = new Dictionary<string, object?>(); |
| | 5 | 218 | | if (schemaProperty.Properties != null) |
| | | 219 | | { |
| | 20 | 220 | | foreach (var (key, value) in schemaProperty.Properties) |
| | | 221 | | { |
| | 6 | 222 | | obj[key] = GenerateExample(value, depth + 1); |
| | | 223 | | } |
| | | 224 | | } |
| | 5 | 225 | | return obj; |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | /// <summary> |
| | | 229 | | /// Validates and converts arguments based on the schema definition. |
| | | 230 | | /// </summary> |
| | | 231 | | /// <param name="schemaProperty">The root schema property definition.</param> |
| | | 232 | | /// <param name="inputArgs">The input arguments dictionary.</param> |
| | | 233 | | /// <param name="currentDepth">The current recursion depth (used internally).</param> |
| | | 234 | | /// <param name="maxDepth">The maximum allowed nesting depth.</param> |
| | | 235 | | /// <returns>A dictionary with validated and correctly typed arguments.</returns> |
| | | 236 | | public static Dictionary<string, object> ValidateAndConvertArguments(JsonSchemaProperty? schemaProperty, IReadOnlyDi |
| | | 237 | | { |
| | 53 | 238 | | var result = new Dictionary<string, object>(); |
| | | 239 | | |
| | 53 | 240 | | if (schemaProperty?.Properties == null || currentDepth > maxDepth) |
| | | 241 | | { |
| | | 242 | | // If no properties defined or max depth reached, pass through original args or return empty |
| | | 243 | | // For MCP, we likely want to pass through only known valid keys if possible, otherwise just return input on |
| | | 244 | | // Returning empty here if no properties are defined might be safer depending on use case. |
| | | 245 | | // Let's assume if properties are null, we cannot validate further and return empty. |
| | 4 | 246 | | return result; |
| | | 247 | | } |
| | | 248 | | |
| | 200 | 249 | | foreach (var propDefKvp in schemaProperty.Properties) |
| | | 250 | | { |
| | 51 | 251 | | var argName = propDefKvp.Key; |
| | 51 | 252 | | var propDef = propDefKvp.Value; |
| | | 253 | | |
| | 51 | 254 | | if (inputArgs.TryGetValue(argName, out var inputValue)) |
| | | 255 | | { |
| | 49 | 256 | | result[argName] = ConvertValueBySchema(inputValue, propDef, currentDepth, maxDepth); |
| | | 257 | | } |
| | | 258 | | } |
| | | 259 | | |
| | 49 | 260 | | return result; |
| | | 261 | | } |
| | | 262 | | |
| | | 263 | | private static object ConvertValueBySchema(object inputValue, JsonSchemaProperty propDef, int currentDepth, int maxD |
| | | 264 | | { |
| | 55 | 265 | | if (currentDepth > maxDepth) |
| | | 266 | | { |
| | 0 | 267 | | return inputValue; // Return as is if max depth hit |
| | | 268 | | } |
| | | 269 | | |
| | 55 | 270 | | var expectedType = propDef.Type?.ToLowerInvariant(); |
| | 55 | 271 | | var convertedValue = expectedType switch |
| | 55 | 272 | | { |
| | 14 | 273 | | "integer" => TryConvertTo<int>(inputValue, out var intVal) ? (object?)intVal ?? inputValue : inputValue, |
| | 5 | 274 | | "number" => TryConvertTo<double>(inputValue, out var doubleVal) ? (object?)doubleVal ?? inputValue : inputVa |
| | 15 | 275 | | "boolean" => TryConvertTo<bool>(inputValue, out var boolVal) ? (object?)boolVal ?? inputValue : inputValue, |
| | 9 | 276 | | "string" => inputValue?.ToString() ?? string.Empty, |
| | 5 | 277 | | "array" => ConvertArrayValue(inputValue, propDef.Items, currentDepth, maxDepth), |
| | 5 | 278 | | "object" => ConvertObjectValue(inputValue, propDef, currentDepth, maxDepth), |
| | 2 | 279 | | _ => inputValue // Default: return as is if type is unknown or null |
| | 55 | 280 | | }; |
| | | 281 | | |
| | 55 | 282 | | return convertedValue; |
| | | 283 | | } |
| | | 284 | | |
| | | 285 | | private static bool TryConvertTo<T>(object value, out T? result) where T : struct |
| | | 286 | | { |
| | 34 | 287 | | result = null; |
| | | 288 | | try |
| | | 289 | | { |
| | 34 | 290 | | if (value is T directValue) |
| | | 291 | | { |
| | 4 | 292 | | result = directValue; |
| | 4 | 293 | | return true; |
| | | 294 | | } |
| | 30 | 295 | | else if (value is string stringValue) |
| | | 296 | | { |
| | 23 | 297 | | if (typeof(T) == typeof(int) && int.TryParse(stringValue, out var intParsed)) |
| | | 298 | | { |
| | 2 | 299 | | result = (T)(object)intParsed; |
| | 2 | 300 | | return true; |
| | | 301 | | } |
| | 21 | 302 | | else if (typeof(T) == typeof(double) && double.TryParse(stringValue, out var doubleParsed)) |
| | | 303 | | { |
| | 1 | 304 | | result = (T)(object)doubleParsed; |
| | 1 | 305 | | return true; |
| | | 306 | | } |
| | 20 | 307 | | else if (typeof(T) == typeof(bool) && bool.TryParse(stringValue, out var boolParsed)) |
| | | 308 | | { |
| | 6 | 309 | | result = (T)(object)boolParsed; |
| | 6 | 310 | | return true; |
| | | 311 | | } |
| | | 312 | | } |
| | 21 | 313 | | } |
| | 0 | 314 | | catch |
| | | 315 | | { |
| | | 316 | | // Parsing failed |
| | 0 | 317 | | } |
| | 21 | 318 | | return false; |
| | 13 | 319 | | } |
| | | 320 | | |
| | | 321 | | private static object ConvertArrayValue(object inputValue, JsonSchemaProperty? itemSchema, int currentDepth, int max |
| | | 322 | | { |
| | 5 | 323 | | if (inputValue is JsonElement jsonEl && jsonEl.ValueKind == JsonValueKind.Array) |
| | | 324 | | { |
| | 1 | 325 | | var list = new List<object>(); |
| | 8 | 326 | | foreach (var item in jsonEl.EnumerateArray()) |
| | | 327 | | { |
| | 3 | 328 | | var convertedItem = itemSchema != null ? ConvertValueBySchema(item, itemSchema, currentDepth + 1, maxDep |
| | 3 | 329 | | list.Add(convertedItem); |
| | | 330 | | } |
| | 1 | 331 | | return list; |
| | | 332 | | } |
| | 4 | 333 | | else if (inputValue is IEnumerable enumerable && !(inputValue is string)) |
| | | 334 | | { |
| | 1 | 335 | | var list = new List<object>(); |
| | 8 | 336 | | foreach (var item in enumerable) |
| | | 337 | | { |
| | 3 | 338 | | var convertedItem = itemSchema != null ? ConvertValueBySchema(item!, itemSchema, currentDepth + 1, maxDe |
| | 3 | 339 | | list.Add(convertedItem); |
| | | 340 | | } |
| | 1 | 341 | | return list; |
| | | 342 | | } |
| | 3 | 343 | | else if (inputValue is string inputValueStr) |
| | | 344 | | { |
| | 3 | 345 | | var trimmed = inputValueStr.Trim(); |
| | 3 | 346 | | if (trimmed.StartsWith('[') && trimmed.EndsWith(']')) |
| | | 347 | | { |
| | | 348 | | try |
| | | 349 | | { |
| | 2 | 350 | | var deInputValueStr = JsonSerializer.Deserialize<IEnumerable<object>>(trimmed) ?? []; |
| | 2 | 351 | | var list = new List<object>(); |
| | 16 | 352 | | foreach (var item in deInputValueStr) |
| | | 353 | | { |
| | 6 | 354 | | var convertedItem = itemSchema != null ? ConvertValueBySchema(item!, itemSchema, currentDepth + |
| | 6 | 355 | | list.Add(convertedItem); |
| | | 356 | | } |
| | 2 | 357 | | return list; |
| | | 358 | | } |
| | 0 | 359 | | catch |
| | | 360 | | { |
| | 0 | 361 | | return inputValue; |
| | | 362 | | } |
| | | 363 | | } |
| | | 364 | | } |
| | | 365 | | // Fallback: return as is if conversion fails |
| | 1 | 366 | | return inputValue; |
| | 2 | 367 | | } |
| | | 368 | | |
| | | 369 | | private static object ConvertObjectValue(object inputValue, JsonSchemaProperty propDef, int currentDepth, int maxDep |
| | | 370 | | { |
| | | 371 | | // Assuming inputValue is a dictionary-like object (e.g., Dictionary<string, object>, JsonElement object) |
| | 5 | 372 | | if (inputValue is Dictionary<string, object> dict) |
| | | 373 | | { |
| | 4 | 374 | | return ValidateAndConvertArguments(propDef, dict, currentDepth + 1, maxDepth); |
| | | 375 | | } |
| | 1 | 376 | | else if (inputValue is JsonElement jsonEl && jsonEl.ValueKind == JsonValueKind.Object) |
| | | 377 | | { |
| | 1 | 378 | | var tempDict = new Dictionary<string, object>(); |
| | 6 | 379 | | foreach (var prop in jsonEl.EnumerateObject()) |
| | | 380 | | { |
| | 2 | 381 | | tempDict[prop.Name] = prop.Value; // Pass raw JsonElement down for conversion |
| | | 382 | | } |
| | 1 | 383 | | return ValidateAndConvertArguments(propDef, tempDict, currentDepth + 1, maxDepth); |
| | | 384 | | } |
| | | 385 | | // Fallback: return as is if conversion fails |
| | 0 | 386 | | return inputValue; |
| | | 387 | | } |
| | | 388 | | } |