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
|
|
@ -16,6 +16,8 @@ import (
|
|||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/internal/util"
|
||||
)
|
||||
|
||||
// The value of the "$schema" keyword for the version that we can validate.
|
||||
|
|
@ -688,7 +690,8 @@ func properties(v reflect.Value) iter.Seq2[string, reflect.Value] {
|
|||
for name, sf := range structPropertiesOf(v.Type()) {
|
||||
val := v.FieldByIndex(sf.Index)
|
||||
if val.IsZero() {
|
||||
if tag, ok := sf.Tag.Lookup("json"); ok && (strings.Contains(tag, "omitempty") || strings.Contains(tag, "omitzero")) {
|
||||
info := util.FieldJSONInfo(sf)
|
||||
if info.Settings["omitempty"] || info.Settings["omitzero"] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
|
@ -740,30 +743,11 @@ func structPropertiesOf(t reflect.Type) propertyMap {
|
|||
}
|
||||
props := map[string]reflect.StructField{}
|
||||
for _, sf := range reflect.VisibleFields(t) {
|
||||
if name, ok := jsonName(sf); ok {
|
||||
props[name] = sf
|
||||
info := util.FieldJSONInfo(sf)
|
||||
if !info.Omit {
|
||||
props[info.Name] = sf
|
||||
}
|
||||
}
|
||||
structProperties.Store(t, props)
|
||||
return props
|
||||
}
|
||||
|
||||
// jsonName returns the name for f as would be used by [json.Marshal].
|
||||
// That is the name in the json struct tag, or the field name if there is no tag.
|
||||
// If f is not exported or the tag is "-", jsonName returns "", false.
|
||||
func jsonName(f reflect.StructField) (string, bool) {
|
||||
if !f.IsExported() {
|
||||
return "", false
|
||||
}
|
||||
if tag, ok := f.Tag.Lookup("json"); ok {
|
||||
name, _, found := strings.Cut(tag, ",")
|
||||
// "-" means omit, but "-," means the name is "-"
|
||||
if name == "-" && !found {
|
||||
return "", false
|
||||
}
|
||||
if name != "" {
|
||||
return name, true
|
||||
}
|
||||
}
|
||||
return f.Name, true
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue