internal/mcp: unify json tag parsing
Do a thorough job of parsing json struct tags. Move the code to a place where both mcp and jsonschema can use it. Change-Id: I6c86308834706b12a1e22cd96ae120590f49d3f4 Reviewed-on: https://go-review.googlesource.com/c/tools/+/678757 LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
parent
b1eb3c8804
commit
12761ffcb6
1 changed files with 101 additions and 97 deletions
|
|
@ -9,8 +9,8 @@ package jsonschema
|
|||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/internal/util"
|
||||
)
|
||||
|
||||
// For constructs a JSON schema object for the given type argument.
|
||||
|
|
@ -108,19 +108,19 @@ func typeSchema(t reflect.Type) (*Schema, error) {
|
|||
|
||||
for i := range t.NumField() {
|
||||
field := t.Field(i)
|
||||
name, required, include := parseField(field)
|
||||
if !include {
|
||||
info := util.FieldJSONInfo(field)
|
||||
if info.Omit {
|
||||
continue
|
||||
}
|
||||
if s.Properties == nil {
|
||||
s.Properties = make(map[string]*Schema)
|
||||
}
|
||||
s.Properties[name], err = typeSchema(field.Type)
|
||||
s.Properties[info.Name], err = typeSchema(field.Type)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if required {
|
||||
s.Required = append(s.Required, name)
|
||||
if !info.Settings["omitempty"] && !info.Settings["omitzero"] {
|
||||
s.Required = append(s.Required, info.Name)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -133,23 +133,3 @@ func typeSchema(t reflect.Type) (*Schema, error) {
|
|||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func parseField(f reflect.StructField) (name string, required, include bool) {
|
||||
if !f.IsExported() {
|
||||
return "", false, false
|
||||
}
|
||||
name = f.Name
|
||||
required = true
|
||||
if tag, ok := f.Tag.Lookup("json"); ok {
|
||||
props := strings.Split(tag, ",")
|
||||
if props[0] != "" {
|
||||
if props[0] == "-" {
|
||||
return "", false, false
|
||||
}
|
||||
name = props[0]
|
||||
}
|
||||
// TODO: support 'omitzero' as well.
|
||||
required = !slices.Contains(props[1:], "omitempty")
|
||||
}
|
||||
return name, required, true
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue