go-sdk/internal/jsonschema/schema_test.go
Jonathan Amsterdam 3434e57007 internal/mcp/internal/jsonschema: schema definition
The first of several CLs providing JSON Schema validation.

Replace the existing Schema type with one that has all the keywords
of the most current version of the JSON Schema spec, called 2020-12.

The 2020-12 spec can be represented type-safely in Go with one exception:
the "type" keyword can be either a string or a []string. To handle this
safely, both Type and Types fields are defined. Custom
JSONMarshal/Unmarshal methods handle the conversion. We need the
unmarshal anyway because "true" and "false" are valid schemas.

Unfortunately, the MCP spec uses the older "draft7" version of JSON
Schema, but the two are close enough for code generation to work.
I confirmed that the protocol generator produces the identical output.

Change-Id: I44f6ea2f3a3f8498979946f69dfb7f50afa1acad
Reviewed-on: https://go-review.googlesource.com/c/tools/+/667855
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
2025-04-25 08:33:53 -07:00

40 lines
964 B
Go

// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package jsonschema
import (
"encoding/json"
"testing"
)
func TestMarshal(t *testing.T) {
for _, s := range []*Schema{
{Type: "null"},
{Types: []string{"null", "number"}},
{Type: "string", MinLength: Ptr(20.0)},
{Minimum: Ptr(20.0)},
{Items: &Schema{Type: "integer"}},
{Const: Ptr(any(0))},
{Const: Ptr(any(nil))},
{Const: Ptr(any([]int{}))},
{Const: Ptr(any(map[string]any{}))},
} {
data, err := json.Marshal(s)
if err != nil {
t.Fatal(err)
}
t.Logf("marshal: %s", data)
var got *Schema
if err := json.Unmarshal(data, &got); err != nil {
t.Fatal(err)
}
if !Equal(got, s) {
t.Errorf("got %+v, want %+v", got, s)
if got.Const != nil && s.Const != nil {
t.Logf("Consts: got %#v (%[1]T), want %#v (%[2]T)", *got.Const, *s.Const)
}
}
}
}