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:
Jonathan Amsterdam 2025-06-04 09:36:17 -04:00
commit 12761ffcb6

View file

@ -9,8 +9,9 @@ import (
"encoding/json"
"fmt"
"reflect"
"strings"
"sync"
"github.com/modelcontextprotocol/go-sdk/internal/util"
)
func assert(cond bool, msg string) {
@ -135,32 +136,11 @@ func jsonNames(t reflect.Type) map[string]bool {
}
m := map[string]bool{}
for i := range t.NumField() {
if n, ok := jsonName(t.Field(i)); ok {
m[n] = true
info := util.FieldJSONInfo(t.Field(i))
if !info.Omit {
m[info.Name] = true
}
}
jsonNamesMap.Store(t, m)
return m
}
// 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.
//
// Copied from jsonschema/validate.go.
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
}