diff --git a/mcp/struct_schema.go b/mcp/struct_schema.go index 321fc7fd6..4001b59bd 100644 --- a/mcp/struct_schema.go +++ b/mcp/struct_schema.go @@ -2,6 +2,7 @@ package mcp import ( "encoding/json" + "errors" "fmt" "reflect" "strings" @@ -20,7 +21,7 @@ func schemaFor[T any]() (*jsonschema.Schema, error) { schema, err := jsonschema.For[T](opts) if err != nil { - if !isJSONSchemaTagOptionError(err) { + if !isJSONSchemaTagOptionError(err) || !supportsSchemaTagFallback(reflect.TypeFor[T]()) { return nil, err } @@ -38,13 +39,68 @@ func isJSONSchemaTagOptionError(err error) bool { return strings.Contains(err.Error(), "tag must not begin with 'WORD='") } +func supportsSchemaTagFallback(t reflect.Type) bool { + return supportsSchemaTagFallbackType(t, make(map[reflect.Type]bool)) +} + +func supportsSchemaTagFallbackType(t reflect.Type, seen map[reflect.Type]bool) bool { + switch t.Kind() { + case reflect.Pointer, reflect.Array, reflect.Slice: + return supportsSchemaTagFallbackType(t.Elem(), seen) + case reflect.Map: + return supportsSchemaTagFallbackType(t.Elem(), seen) + case reflect.Struct: + if seen[t] { + return true + } + seen[t] = true + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if fieldJSONInfo(field).omit { + continue + } + if tag, ok := field.Tag.Lookup("jsonschema"); ok { + for option := range strings.SplitSeq(tag, ",") { + option = strings.TrimSpace(option) + if strings.Contains(option, "=") && !strings.HasPrefix(option, "enum=") { + return false + } + } + } + if !supportsSchemaTagFallbackType(field.Type, seen) { + return false + } + } + } + return true +} + +var errRecursiveSchemaFallback = errors.New("recursive type cannot use schema tag fallback") + func schemaForStructFields(t reflect.Type, opts *jsonschema.ForOptions) (*jsonschema.Schema, error) { + state := schemaFallbackState{active: make(map[reflect.Type]bool)} + return state.schemaForStructFields(t, opts) +} + +type schemaFallbackState struct { + active map[reflect.Type]bool +} + +func (s *schemaFallbackState) schemaForStructFields( + t reflect.Type, + opts *jsonschema.ForOptions, +) (*jsonschema.Schema, error) { if t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() != reflect.Struct { return jsonschema.ForType(t, opts) } + if s.active[t] { + return nil, fmt.Errorf("%w: %s", errRecursiveSchemaFallback, t) + } + s.active[t] = true + defer delete(s.active, t) schema := &jsonschema.Schema{ Type: "object", @@ -57,26 +113,33 @@ func schemaForStructFields(t reflect.Type, opts *jsonschema.ForOptions) (*jsonsc for i := 0; i < structType.NumField(); i++ { field := structType.Field(i) fieldType := field.Type - if field.Anonymous { + info := fieldJSONInfo(field) + if info.omit { + continue + } + if field.Anonymous && !info.explicitName { anonType := fieldType if anonType.Kind() == reflect.Ptr { anonType = anonType.Elem() } if anonType.Kind() == reflect.Struct { + if s.active[anonType] { + return fmt.Errorf("%w: %s", errRecursiveSchemaFallback, anonType) + } + s.active[anonType] = true if err := walk(anonType); err != nil { return err } + delete(s.active, anonType) continue } } - info := fieldJSONInfo(field) - if info.omit { - continue - } - - fieldSchema, err := jsonschema.ForType(fieldType, opts) + fieldSchema, err := s.schemaForFieldType(fieldType, opts) if err != nil { + if errors.Is(err, errRecursiveSchemaFallback) { + return err + } if opts.IgnoreInvalidTypes { continue } @@ -102,6 +165,40 @@ func schemaForStructFields(t reflect.Type, opts *jsonschema.ForOptions) (*jsonsc return schema, nil } +func (s *schemaFallbackState) schemaForFieldType( + t reflect.Type, + opts *jsonschema.ForOptions, +) (*jsonschema.Schema, error) { + schema, err := jsonschema.ForType(t, opts) + if err == nil || !isJSONSchemaTagOptionError(err) || !supportsSchemaTagFallback(t) { + return schema, err + } + + switch t.Kind() { + case reflect.Pointer: + return s.schemaForFieldType(t.Elem(), opts) + case reflect.Struct: + return s.schemaForStructFields(t, opts) + case reflect.Array, reflect.Slice: + items, itemErr := s.schemaForFieldType(t.Elem(), opts) + if itemErr != nil { + return nil, itemErr + } + return &jsonschema.Schema{Type: "array", Items: items}, nil + case reflect.Map: + if t.Key().Kind() != reflect.String { + return nil, err + } + values, valueErr := s.schemaForFieldType(t.Elem(), opts) + if valueErr != nil { + return nil, valueErr + } + return &jsonschema.Schema{Type: "object", AdditionalProperties: values}, nil + default: + return nil, err + } +} + func applyStructFieldTags(t reflect.Type, schema *jsonschema.Schema) { if schema == nil || schema.Properties == nil { return @@ -118,7 +215,11 @@ func applyStructFieldTags(t reflect.Type, schema *jsonschema.Schema) { for i := 0; i < structType.NumField(); i++ { field := structType.Field(i) fieldType := field.Type - if field.Anonymous { + info := fieldJSONInfo(field) + if info.omit { + continue + } + if field.Anonymous && !info.explicitName { anonType := fieldType if anonType.Kind() == reflect.Ptr { anonType = anonType.Elem() @@ -129,11 +230,6 @@ func applyStructFieldTags(t reflect.Type, schema *jsonschema.Schema) { } } - info := fieldJSONInfo(field) - if info.omit { - continue - } - prop, ok := schema.Properties[info.name] if !ok { continue @@ -146,12 +242,32 @@ func applyStructFieldTags(t reflect.Type, schema *jsonschema.Schema) { if len(enums) > 0 { prop.Enum = enums } + applyStructFieldTagsToType(fieldType, prop) } } walk(t) } +func applyStructFieldTagsToType(t reflect.Type, schema *jsonschema.Schema) { + if schema == nil { + return + } + + switch t.Kind() { + case reflect.Pointer: + applyStructFieldTagsToType(t.Elem(), schema) + case reflect.Struct: + applyStructFieldTags(t, schema) + case reflect.Array, reflect.Slice: + applyStructFieldTagsToType(t.Elem(), schema.Items) + case reflect.Map: + if t.Key().Kind() == reflect.String { + applyStructFieldTagsToType(t.Elem(), schema.AdditionalProperties) + } + } +} + func fieldSchemaAnnotations(field reflect.StructField) (string, []any) { description := "" var enums []any @@ -201,9 +317,10 @@ func parseJSONSchemaTag(tag string) (string, []any) { } type jsonFieldInfo struct { - omit bool - name string - settings map[string]bool + omit bool + explicitName bool + name string + settings map[string]bool } func fieldJSONInfo(field reflect.StructField) jsonFieldInfo { @@ -223,6 +340,7 @@ func fieldJSONInfo(field reflect.StructField) jsonFieldInfo { } if name != "" { info.name = name + info.explicitName = true } if rest != "" { info.settings = map[string]bool{} diff --git a/mcp/struct_schema_test.go b/mcp/struct_schema_test.go index c2ac984ba..1a6eab0cf 100644 --- a/mcp/struct_schema_test.go +++ b/mcp/struct_schema_test.go @@ -8,44 +8,142 @@ import ( "github.com/stretchr/testify/require" ) -func TestSchemaFor_JSONSchemaDescriptionTag(t *testing.T) { - type GetUserInfoRequest struct { +func TestSchemaFor_JSONSchemaEnumTagSpacing(t *testing.T) { + type withLeadingSpace struct { Name string `json:"name" jsonschema_description:"User name to query" jsonschema:" enum=Alice,enum=Bob"` } + type withoutLeadingSpace struct { + Name string `json:"name" jsonschema_description:"User name to query" jsonschema:"enum=Alice,enum=Bob"` + } - tool := NewTool("get_user_info", - WithInputSchema[GetUserInfoRequest](), - ) - require.NotNil(t, tool.RawInputSchema) + tests := []struct { + name string + schema func() json.RawMessage + }{ + { + name: "leading space", + schema: func() json.RawMessage { + return NewTool("get_user_info", WithInputSchema[withLeadingSpace]()).RawInputSchema + }, + }, + { + name: "no leading space", + schema: func() json.RawMessage { + return NewTool("get_user_info", WithInputSchema[withoutLeadingSpace]()).RawInputSchema + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + raw := test.schema() + require.NotNil(t, raw) + + var schema map[string]any + require.NoError(t, json.Unmarshal(raw, &schema)) + + properties := schema["properties"].(map[string]any) + nameProp := properties["name"].(map[string]any) + assert.Equal(t, "User name to query", nameProp["description"]) + assert.ElementsMatch(t, []any{"Alice", "Bob"}, nameProp["enum"]) + }) + } +} + +func TestSchemaFor_UnsupportedJSONSchemaOptionReturnsError(t *testing.T) { + type request struct { + Name string `json:"name" jsonschema:"description=User name"` + } + + _, err := SchemaForRaw[request]() + require.ErrorContains(t, err, "tag must not begin with 'WORD='") +} + +func TestSchemaFor_NamedAnonymousStructTags(t *testing.T) { + type Embedded struct { + Mode string `json:"mode" jsonschema_description:"Run mode" jsonschema:"enum=fast,enum=safe"` + } + type request struct { + Embedded `json:"embedded"` + } + + raw, err := SchemaForRaw[request]() + require.NoError(t, err) var schema map[string]any - require.NoError(t, json.Unmarshal(tool.RawInputSchema, &schema)) + require.NoError(t, json.Unmarshal(raw, &schema)) properties := schema["properties"].(map[string]any) - nameProp := properties["name"].(map[string]any) + assert.NotContains(t, properties, "mode") + embedded := properties["embedded"].(map[string]any) + embeddedProperties := embedded["properties"].(map[string]any) + mode := embeddedProperties["mode"].(map[string]any) + assert.Equal(t, "Run mode", mode["description"]) + assert.ElementsMatch(t, []any{"fast", "safe"}, mode["enum"]) +} + +func TestSchemaFor_RecursiveTaggedStructReturnsError(t *testing.T) { + type node struct { + Kind string `json:"kind" jsonschema:"enum=branch,enum=leaf"` + Next *node `json:"next,omitempty"` + } - assert.Equal(t, "User name to query", nameProp["description"]) - assert.ElementsMatch(t, []any{"Alice", "Bob"}, nameProp["enum"]) + _, err := SchemaForRaw[node]() + require.ErrorIs(t, err, errRecursiveSchemaFallback) + + type EmbeddedNode struct { + Kind string `json:"kind" jsonschema:"enum=branch,enum=leaf"` + *EmbeddedNode + } + + _, err = SchemaForRaw[EmbeddedNode]() + require.ErrorIs(t, err, errRecursiveSchemaFallback) } -func TestSchemaFor_JSONSchemaEnumTagWithoutLeadingSpace(t *testing.T) { - type GetUserInfoRequest struct { - Name string `json:"name" jsonschema_description:"User name to query" jsonschema:"enum=Alice,enum=Bob"` +func TestSchemaFor_NestedStructTags(t *testing.T) { + type mode struct { + Name string `json:"name" jsonschema_description:"Run mode" jsonschema:"enum=fast,enum=safe"` + } + type request struct { + Primary mode `json:"primary"` + Secondary mode `json:"secondary"` + Optional *mode `json:"optional"` + Modes []mode `json:"modes"` + ByName map[string]mode `json:"byName"` } - tool := NewTool("get_user_info", - WithInputSchema[GetUserInfoRequest](), - ) - require.NotNil(t, tool.RawInputSchema) + raw, err := SchemaForRaw[request]() + require.NoError(t, err) var schema map[string]any - require.NoError(t, json.Unmarshal(tool.RawInputSchema, &schema)) + require.NoError(t, json.Unmarshal(raw, &schema)) + + properties, ok := schema["properties"].(map[string]any) + require.True(t, ok) + + assertModeSchema := func(t *testing.T, nested any) { + t.Helper() + nestedSchema, ok := nested.(map[string]any) + require.True(t, ok) + nestedProperties, ok := nestedSchema["properties"].(map[string]any) + require.True(t, ok) + modeName, ok := nestedProperties["name"].(map[string]any) + require.True(t, ok) + assert.Equal(t, "Run mode", modeName["description"]) + assert.ElementsMatch(t, []any{"fast", "safe"}, modeName["enum"]) + } - properties := schema["properties"].(map[string]any) - nameProp := properties["name"].(map[string]any) + for _, name := range []string{"primary", "secondary", "optional"} { + assertModeSchema(t, properties[name]) + } + + modes, ok := properties["modes"].(map[string]any) + require.True(t, ok) + assertModeSchema(t, modes["items"]) - assert.Equal(t, "User name to query", nameProp["description"]) - assert.ElementsMatch(t, []any{"Alice", "Bob"}, nameProp["enum"]) + byName, ok := properties["byName"].(map[string]any) + require.True(t, ok) + assertModeSchema(t, byName["additionalProperties"]) } func TestSchemaFor_StructuredInputOutputExampleTags(t *testing.T) {