applySchema validates whether data is valid JSON according to the provided schema, after applying schema defaults. Returns the JSON value augmented with defaults.
(data json.RawMessage, resolved *jsonschema.Resolved)
| 67 | // |
| 68 | // Returns the JSON value augmented with defaults. |
| 69 | func applySchema(data json.RawMessage, resolved *jsonschema.Resolved) (json.RawMessage, error) { |
| 70 | // TODO: use reflection to create the struct type to unmarshal into. |
| 71 | // Separate validation from assignment. |
| 72 | |
| 73 | // Use default JSON marshalling for validation. |
| 74 | // |
| 75 | // This avoids inconsistent representation due to custom marshallers, such as |
| 76 | // time.Time (issue #449). |
| 77 | // |
| 78 | // Additionally, unmarshalling into a map ensures that the resulting JSON is |
| 79 | // at least {}, even if data is empty. For example, arguments is technically |
| 80 | // an optional property of callToolParams, and we still want to apply the |
| 81 | // defaults in this case. |
| 82 | // |
| 83 | // TODO(rfindley): in which cases can resolved be nil? |
| 84 | if resolved != nil { |
| 85 | v := make(map[string]any) |
| 86 | if len(data) > 0 { |
| 87 | if err := internaljson.Unmarshal(data, &v); err != nil { |
| 88 | return nil, fmt.Errorf("unmarshaling arguments: %w", err) |
| 89 | } |
| 90 | } |
| 91 | if err := resolved.ApplyDefaults(&v); err != nil { |
| 92 | return nil, fmt.Errorf("applying schema defaults:\n%w", err) |
| 93 | } |
| 94 | if err := resolved.Validate(&v); err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | // We must re-marshal with the default values applied. |
| 98 | var err error |
| 99 | data, err = json.Marshal(v) |
| 100 | if err != nil { |
| 101 | return nil, fmt.Errorf("marshalling with defaults: %v", err) |
| 102 | } |
| 103 | } |
| 104 | return data, nil |
| 105 | } |
| 106 | |
| 107 | // validateToolName checks whether name is a valid tool name, reporting a |
| 108 | // non-nil error if not. |
searching dependent graphs…