Skip to content

Commit c132621

Browse files
authored
jsonschema: marshal to bools (#247)
Marshal the empty schema to true, and its negation to false. This is technically a breaking behavior change, but a properly written consumer of JSON Schema will not notice. For #244. Fixes #230.
1 parent bb9087d commit c132621

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

jsonschema/schema.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ func (s *Schema) MarshalJSON() ([]byte, error) {
204204
if err := s.basicChecks(); err != nil {
205205
return nil, err
206206
}
207+
207208
// Marshal either Type or Types as "type".
208209
var typ any
209210
switch {
@@ -219,7 +220,19 @@ func (s *Schema) MarshalJSON() ([]byte, error) {
219220
Type: typ,
220221
schemaWithoutMethods: (*schemaWithoutMethods)(s),
221222
}
222-
return marshalStructWithMap(&ms, "Extra")
223+
bs, err := marshalStructWithMap(&ms, "Extra")
224+
if err != nil {
225+
return nil, err
226+
}
227+
// Marshal {} as true and {"not": {}} as false.
228+
// It is wasteful to do this here instead of earlier, but much easier.
229+
switch {
230+
case bytes.Equal(bs, []byte(`{}`)):
231+
bs = []byte("true")
232+
case bytes.Equal(bs, []byte(`{"not":true}`)):
233+
bs = []byte("false")
234+
}
235+
return bs, nil
223236
}
224237

225238
func (s *Schema) UnmarshalJSON(data []byte) error {

jsonschema/schema_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ func TestJSONRoundTrip(t *testing.T) {
5454
for _, tt := range []struct {
5555
in, want string
5656
}{
57-
{`true`, `{}`}, // boolean schemas become object schemas
58-
{`false`, `{"not":{}}`},
59-
{`{"type":"", "enum":null}`, `{}`}, // empty fields are omitted
57+
{`true`, `true`},
58+
{`false`, `false`},
59+
{`{"type":"", "enum":null}`, `true`}, // empty fields are omitted
6060
{`{"minimum":1}`, `{"minimum":1}`},
6161
{`{"minimum":1.0}`, `{"minimum":1}`}, // floating-point integers lose their fractional part
6262
{`{"minLength":1.0}`, `{"minLength":1}`}, // some floats are unmarshaled into ints, but you can't tell

mcp/testdata/conformance/server/tools.txtar

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,7 @@ greet
5959
"type": "string"
6060
}
6161
},
62-
"additionalProperties": {
63-
"not": {}
64-
}
62+
"additionalProperties": false
6563
},
6664
"name": "greet"
6765
}

0 commit comments

Comments
 (0)