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

@ -26,6 +26,7 @@ func TestGoRoundTrip(t *testing.T) {
{Const: Ptr(any(map[string]any{}))},
{Default: mustMarshal(1)},
{Default: mustMarshal(nil)},
{Extra: map[string]any{"test": "value"}},
} {
data, err := json.Marshal(s)
if err != nil {
@ -64,11 +65,19 @@ func TestJSONRoundTrip(t *testing.T) {
`{"$vocabulary":{"b":true, "a":false}}`,
`{"$vocabulary":{"a":false,"b":true}}`,
},
{`{"unk":0}`, `{}`}, // unknown fields are dropped, unfortunately
{`{"unk":0}`, `{"unk":0}`}, // unknown fields are not dropped
{
// known and unknown fields are not dropped
// note that the order will be by the declaration order in the anonymous struct inside MarshalJSON
`{"comment":"test","type":"example","unk":0}`,
`{"type":"example","comment":"test","unk":0}`,
},
{`{"extra":0}`, `{"extra":0}`}, // extra is not a special keyword and should not be dropped
{`{"Extra":0}`, `{"Extra":0}`}, // Extra is not a special keyword and should not be dropped
} {
var s Schema
mustUnmarshal(t, []byte(tt.in), &s)
data, err := json.Marshal(s)
data, err := json.Marshal(&s)
if err != nil {
t.Fatal(err)
}