Skip to content

feat(tools): 添加 GetAnySlice 和 RequireAnySlice 方法 #433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions mcp/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,32 @@ func (r CallToolRequest) RequireBool(key string) (bool, error) {
return false, fmt.Errorf("required argument %q not found", key)
}

// GetAnySlice returns a []any slice argument by key, or the default value if not found
func (r CallToolRequest) GetAnySlice(key string, defaultValue []any) []any {
args := r.GetArguments()
if val, ok := args[key]; ok {
switch v := val.(type) {
case []any:
return v
}
}
return defaultValue
}

// RequireAnySlice returns a []any slice argument by key, or an error if not found or not convertible to []any slice
func (r CallToolRequest) RequireAnySlice(key string) ([]any, error) {
args := r.GetArguments()
if val, ok := args[key]; ok {
switch v := val.(type) {
case []any:
return v, nil
default:
return nil, fmt.Errorf("argument %q is not an any slice", key)
}
}
return nil, fmt.Errorf("required argument %q not found", key)
}

// GetStringSlice returns a string slice argument by key, or the default value if not found
func (r CallToolRequest) GetStringSlice(key string, defaultValue []string) []string {
args := r.GetArguments()
Expand Down
13 changes: 13 additions & 0 deletions mcp/tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,19 @@ func TestCallToolRequestHelperFunctions(t *testing.T) {
_, err = req.RequireBool("missing_val")
assert.Error(t, err)

// Test GetAnySlice
assert.Equal(t, []any{"one", "two", "three"}, req.GetAnySlice("string_slice_val", nil))
assert.Equal(t, []any{1, 2, 3}, req.GetAnySlice("int_slice_val", nil))
assert.Equal(t, []any{1.1, 2.2, 3.3}, req.GetAnySlice("float_slice_val", nil))

// Test RequireAnySlice
as, err := req.RequireAnySlice("string_slice_val")
assert.NoError(t, err)
assert.Equal(t, []any{"one", "two", "three"}, as)
_, err = req.RequireAnySlice("missing_val")
assert.Error(t, err)
assert.Equal(t, []any{true, false, true}, req.GetAnySlice("bool_slice_val", nil))

// Test GetStringSlice
assert.Equal(t, []string{"one", "two", "three"}, req.GetStringSlice("string_slice_val", nil))
assert.Equal(t, []string{"default"}, req.GetStringSlice("missing_val", []string{"default"}))
Expand Down