Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/tool_test.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "reflect"
13 "strings"
14 "testing"
15
16 "github.com/google/jsonschema-go/jsonschema"
17 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
18 )
19
20 func TestApplySchema(t *testing.T) {
21 schema := &jsonschema.Schema{
22 Type: "object",
23 Properties: map[string]*jsonschema.Schema{
24 "x": {Type: "integer", Default: json.RawMessage("3")},
25 },
26 }
27 resolved, err := schema.Resolve(&jsonschema.ResolveOptions{ValidateDefaults: true})
28 if err != nil {
29 t.Fatal(err)
30 }
31
32 type S struct {
33 X int `json:"x"`
34 }
35
36 for _, tt := range []struct {
37 data string
38 v any
39 want any
40 }{
41 {`{"x": 1}`, new(S), &S{X: 1}},
42 {`{}`, new(S), &S{X: 3}}, // default applied
43 {`{"x": 0}`, new(S), &S{X: 0}},
44 {`{"x": 1}`, new(map[string]any), &map[string]any{"x": 1.0}},
45 {`{}`, new(map[string]any), &map[string]any{"x": 3.0}}, // default applied
46 {`{"x": 0}`, new(map[string]any), &map[string]any{"x": 0.0}},
47 } {
48 raw := json.RawMessage(tt.data)
49 raw, err = applySchema(raw, resolved)
50 if err != nil {
51 t.Fatal(err)
52 }
53 if err := json.Unmarshal(raw, &tt.v); err != nil {
54 t.Fatal(err)
55 }
56 if !reflect.DeepEqual(tt.v, tt.want) {
57 t.Errorf("got %#v, want %#v", tt.v, tt.want)
58 }
59 }
60 }
61
62 func TestToolErrorHandling(t *testing.T) {
63 // Construct server and add both tools at the top level
64 server := NewServer(testImpl, nil)
65
66 // Create a tool that returns a structured error
67 structuredErrorHandler := func(ctx context.Context, req *CallToolRequest, args map[string]any) (*CallToolResult, any, error) {
68 return nil, nil, &jsonrpc.Error{
69 Code: jsonrpc.CodeInvalidParams,
70 Message: "internal server error",
71 }
72 }
73
74 // Create a tool that returns a regular error
75 regularErrorHandler := func(ctx context.Context, req *CallToolRequest, args map[string]any) (*CallToolResult, any, error) {
76 return nil, nil, fmt.Errorf("tool execution failed")
77 }
78
79 AddTool(server, &Tool{Name: "error_tool", Description: "returns structured error"}, structuredErrorHandler)
80 AddTool(server, &Tool{Name: "regular_error_tool", Description: "returns regular error"}, regularErrorHandler)
81
82 // Connect server and client once
83 ct, st := NewInMemoryTransports()
84 _, err := server.Connect(context.Background(), st, nil)
85 if err != nil {
86 t.Fatal(err)
87 }
88
89 client := NewClient(testImpl, nil)
90 cs, err := client.Connect(context.Background(), ct, nil)
91 if err != nil {
92 t.Fatal(err)
93 }
94 defer cs.Close()
95
96 // Test that structured JSON-RPC errors are returned directly
97 t.Run("structured_error", func(t *testing.T) {
98 // Call the tool
99 _, err = cs.CallTool(context.Background(), &CallToolParams{
100 Name: "error_tool",
101 Arguments: map[string]any{},
102 })
103
104 // Should get the structured error directly
105 if err == nil {
106 t.Fatal("expected error, got nil")
107 }
108
109 var wireErr *jsonrpc.Error
110 if !errors.As(err, &wireErr) {
111 t.Fatalf("expected jsonrpc.Error, got %[1]T: %[1]v", err)
112 }
113
114 if wireErr.Code != jsonrpc.CodeInvalidParams {
115 t.Errorf("expected error code %d, got %d", jsonrpc.CodeInvalidParams, wireErr.Code)
116 }
117 })
118
119 // Test that regular errors are embedded in tool results
120 t.Run("regular_error", func(t *testing.T) {
121 // Call the tool
122 result, err := cs.CallTool(context.Background(), &CallToolParams{
123 Name: "regular_error_tool",
124 Arguments: map[string]any{},
125 })
126 // Should not get an error at the protocol level
127 if err != nil {
128 t.Fatalf("unexpected protocol error: %v", err)
129 }
130
131 // Should get a result with IsError=true
132 if !result.IsError {
133 t.Error("expected IsError=true, got false")
134 }
135
136 // Should have error message in content
137 if len(result.Content) == 0 {
138 t.Error("expected error content, got empty")
139 }
140
141 if textContent, ok := result.Content[0].(*TextContent); !ok {
142 t.Error("expected TextContent")
143 } else if !strings.Contains(textContent.Text, "tool execution failed") {
144 t.Errorf("expected error message in content, got: %s", textContent.Text)
145 }
146 })
147 }
148
149 func TestValidateToolName(t *testing.T) {
150 t.Run("valid", func(t *testing.T) {
151 validTests := []struct {
152 label string
153 toolName string
154 }{
155 {"simple alphanumeric names", "getUser"},
156 {"names with underscores", "get_user_profile"},
157 {"names with dashes", "user-profile-update"},
158 {"names with dots", "admin.tools.list"},
159 {"mixed character names", "DATA_EXPORT_v2.1"},
160 {"single character names", "a"},
161 {"128 character names", strings.Repeat("a", 128)},
162 }
163 for _, test := range validTests {
164 t.Run(test.label, func(t *testing.T) {
165 if err := validateToolName(test.toolName); err != nil {
166 t.Errorf("validateToolName(%q) = %v, want nil", test.toolName, err)
167 }
168 })
169 }
170 })
171
172 t.Run("invalid", func(t *testing.T) {
173 invalidTests := []struct {
174 label string
175 toolName string
176 wantErrContaining string
177 }{
178 {"empty names", "", "tool name cannot be empty"},
179 {"names longer than 128 characters", strings.Repeat("a", 129), "tool name exceeds maximum length of 128 characters (current: 129)"},
180 {"names with spaces", "get user profile", `tool name contains invalid characters: " "`},
181 {"names with commas", "get,user,profile", `tool name contains invalid characters: ","`},
182 {"names with forward slashes", "user/profile/update", `tool name contains invalid characters: "/"`},
183 {"names with other special chars", "[email protected]", `tool name contains invalid characters: "@"`},
184 {"names with multiple invalid chars", "user name@domain,com", `tool name contains invalid characters: " ", "@", ","`},
185 {"names with unicode characters", "user-ñame", `tool name contains invalid characters: "ñ"`},
186 }
187 for _, test := range invalidTests {
188 t.Run(test.label, func(t *testing.T) {
189 if err := validateToolName(test.toolName); err == nil || !strings.Contains(err.Error(), test.wantErrContaining) {
190 t.Errorf("validateToolName(%q) = %v, want error containing %q", test.toolName, err, test.wantErrContaining)
191 }
192 })
193 }
194
195 })
196
197 }