jsonchema: support additional keywords

Support additional (extra) keywords beyond those specified in the
`Schema` type. The current behavior is additional keywords are dropped.

To follow up:

- There are similar util functions in `mcp/util.go` which don't seem to
be used. Maybe we should move it to `internal/util` instead of
`jsonchema/util.go` package?
- The method `[Un]MarshalJSON` is only on `pointer receiver`, is this
intended? (that means it will only work if we [un]marshal pointer to the
`Schema` instance)
- The fix is using the [un]marshalStructWithMap from `mcp/util.go` and
there are requirements for the function to work properly but these are
not strictly checked e.g. need `json:"-"` tag for the Extra field.

Fixes #69.
This commit is contained in:
Albert Sundjaja 2025-07-01 21:02:26 +10:00 • committed by GitHub
commit bfb9215d16
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -127,6 +127,9 @@ type Schema struct {
// https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7
Format string `json:"format,omitempty"`
// Extra allows for additional keywords beyond those specified.
Extra map[string]any `json:"-"`
// computed fields
// This schema's base schema.
@ -236,7 +239,7 @@ func (s *Schema) MarshalJSON() ([]byte, error) {
Type: typ,
schemaWithoutMethods: (*schemaWithoutMethods)(s),
}
return json.Marshal(ms)
return marshalStructWithMap(&ms, "Extra")
}
func (s *Schema) UnmarshalJSON(data []byte) error {
@ -269,7 +272,7 @@ func (s *Schema) UnmarshalJSON(data []byte) error {
}{
schemaWithoutMethods: (*schemaWithoutMethods)(s),
}
if err := json.Unmarshal(data, &ms); err != nil {
if err := unmarshalStructWithMap(data, &ms, "Extra"); err != nil {
return err
}
// Unmarshal "type" as either Type or Types.