Skip to content

Proposal: Add AddToolForType for Runtime Type Support #371

@rebaz94

Description

@rebaz94

Currently, AddTool[In, Out any] only works with generics, requiring compile-time types. This blocks use cases where types are generated or resolved dynamically at runtime.

This is similar to the issue for jsonschema.ForType, where passing a reflect.Type enabled runtime flexibility.

1. New Function: AddToolForType

Introduce new function like:

func AddToolForType(
    s *Server,
    t *Tool,
    in, out reflect.Type,
    h ToolHandlerFor[map[string]any, any],
)
  • Input type: Always handled as an object.
  • Output type: Explicitly marked as structured or not, ensuring schemas are validated even when the handler returns any.

2. Option to Use Output Schema for any Types

Alternatively, we can extend the existing API by adding a configuration option:

type AddToolOpt struct {
    UseOutputSchemaForAnyType bool
}

Usage in ToolFor:

func ToolFor[In, Out any](
    t *Tool,
    h ToolHandlerFor[In, Out],
    opt ...AddToolOpt,
)

Then update schema resolution:

var (
    elemZero       any // only non-nil if Out is a pointer type
    outputResolved *jsonschema.Resolved
)
if reflect.TypeFor[Out]() != reflect.TypeFor[any]() || (tt.OutputSchema != nil && opts.UseOutputSchemaForAnyType) {
    var err error
    elemZero, err = setSchema[Out](&tt.OutputSchema, &outputResolved)
    if err != nil {
        return nil, nil, fmt.Errorf("output schema: %v", err)
    }
}

This addition would provide flexibility for dynamic type handling while keeping the validation and schema generation consistent with the generic approach.

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalA proposal for an a new API or behavior. See CONTRIBUTING.md.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions