|
| 1 | +// Copyright 2025 Author(s) of MCP Any |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package tool |
| 5 | + |
| 6 | +import ( |
| 7 | + "github.com/mcpany/core/server/pkg/logging" |
| 8 | + "google.golang.org/protobuf/types/known/structpb" |
| 9 | +) |
| 10 | + |
| 11 | +// SanitizeJSONSchema attempts to fix common schema issues that cause strict MCP clients to fail. |
| 12 | +// It takes a raw map[string]interface{} (or compatible) and returns a *structpb.Struct. |
| 13 | +func SanitizeJSONSchema(schema any) (*structpb.Struct, error) { |
| 14 | + if schema == nil { |
| 15 | + return nil, nil |
| 16 | + } |
| 17 | + |
| 18 | + schemaMap, ok := schema.(map[string]interface{}) |
| 19 | + if !ok { |
| 20 | + // If it's not a map, we can't really sanitize it easily, but it might be valid if it's not an object type. |
| 21 | + // However, for MCP InputSchema, it should be an object. |
| 22 | + // Let's try to convert it as is. |
| 23 | + return convertJSONSchemaToStruct(schema) |
| 24 | + } |
| 25 | + |
| 26 | + // 1. Fix missing "type": "object" if "properties" is present |
| 27 | + if _, hasProperties := schemaMap["properties"]; hasProperties { |
| 28 | + if _, hasType := schemaMap["type"]; !hasType { |
| 29 | + logging.GetLogger().Warn("Sanitizing schema: adding missing 'type': 'object' because 'properties' is present") |
| 30 | + schemaMap["type"] = "object" |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // 2. Recursively sanitize properties |
| 35 | + if props, ok := schemaMap["properties"].(map[string]interface{}); ok { |
| 36 | + for k, v := range props { |
| 37 | + if vMap, ok := v.(map[string]interface{}); ok { |
| 38 | + // Recursively sanitize |
| 39 | + sanitizedV, err := SanitizeJSONSchema(vMap) |
| 40 | + if err == nil && sanitizedV != nil { |
| 41 | + props[k] = sanitizedV.AsMap() |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // 3. Handle top-level oneOf/anyOf/allOf if they are not supported by some clients? |
| 48 | + // The issue #10606 says: "input_schema does not support oneOf, allOf, or anyOf at the top level" |
| 49 | + // If we detect this at the top level, what can we do? |
| 50 | + // We could try to merge them if possible, or just pick the first one? |
| 51 | + // Merging is hard. Picking the first one is lossy. |
| 52 | + // For now, let's just log a warning if we see it at the top level. |
| 53 | + // Note: We need to know if this is the "top level" of the Tool's InputSchema. |
| 54 | + // Since this function is recursive, we might need a context or just assume the caller handles the top-level check. |
| 55 | + // But `SanitizeJSONSchema` is likely called on the root schema. |
| 56 | + |
| 57 | + // Let's convert back to structpb |
| 58 | + return structpb.NewStruct(schemaMap) |
| 59 | +} |
0 commit comments