| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | |
| 9 | jsonschema "github.com/santhosh-tekuri/jsonschema/v6" |
| 10 | ) |
| 11 | |
| 12 | const toolSchemaResource = "urn:reasonix:tool-schema" |
| 13 | |
| 14 | // ValidateToolSchema compiles a provider-visible tool parameter schema without |
| 15 | // resolving external resources. MCP schemas default to draft-07 when they do |
| 16 | // not declare a dialect; explicit $schema declarations still take precedence. |
| 17 | func ValidateToolSchema(raw json.RawMessage) error { |
| 18 | decoder := json.NewDecoder(bytes.NewReader(raw)) |
| 19 | decoder.UseNumber() |
| 20 | var doc any |
| 21 | if err := decoder.Decode(&doc); err != nil { |
| 22 | return fmt.Errorf("invalid JSON: %w", err) |
| 23 | } |
| 24 | if err := decoder.Decode(&struct{}{}); err != io.EOF { |
| 25 | if err == nil { |
| 26 | return fmt.Errorf("invalid JSON: multiple values") |
| 27 | } |
| 28 | return fmt.Errorf("invalid JSON: %w", err) |
| 29 | } |
| 30 | obj, ok := doc.(map[string]any) |
| 31 | if !ok { |
| 32 | return fmt.Errorf("root must be an object") |
| 33 | } |
| 34 | // MCP tools/list and the Anthropic tool contract both require the root |
| 35 | // schema to describe an object; anything else can 400 the whole request. |
| 36 | // CanonicalizeSchema makes an omitted root type explicit before validation, |
| 37 | // so a missing or non-"object" type here is a genuinely incompatible schema. |
| 38 | switch typ := obj["type"].(type) { |
| 39 | case string: |
| 40 | if typ != "object" { |
| 41 | return fmt.Errorf("root type must be %q, got %q", "object", typ) |
| 42 | } |
| 43 | case nil: |
| 44 | return fmt.Errorf("root schema must declare type %q", "object") |
| 45 | default: |
| 46 | return fmt.Errorf("root type must be %q, got %s", "object", schemaJSONString(typ)) |
| 47 | } |
| 48 | |
| 49 | compiler := jsonschema.NewCompiler() |
| 50 | // The default loader resolves file:// refs from local disk. Externally |
| 51 | // supplied MCP schemas must never reach the filesystem or network, so |
| 52 | // drop the loader entirely: registered resources and the embedded |
| 53 | // metaschemas still resolve, every other URL fails compilation. |
| 54 | compiler.UseLoader(nil) |
| 55 | compiler.DefaultDraft(jsonschema.Draft7) |
| 56 | if err := compiler.AddResource(toolSchemaResource, doc); err != nil { |
| 57 | return fmt.Errorf("load schema: %w", err) |
| 58 | } |
| 59 | if _, err := compiler.Compile(toolSchemaResource); err != nil { |
| 60 | return fmt.Errorf("compile schema: %w", err) |
| 61 | } |
| 62 | return nil |
| 63 | } |
| 64 |