Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/error_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 "strings"
12 "sync/atomic"
13 "testing"
14
15 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
16 )
17
18 // TestServerErrors validates that the server returns appropriate error codes
19 // for various invalid requests.
20 func TestServerErrors(t *testing.T) {
21 ctx := context.Background()
22
23 // Set up a server with tools, prompts, and resources for testing
24 cs, _, cleanup := basicConnection(t, func(s *Server) {
25 // Add a tool with required parameters
26 type RequiredParams struct {
27 Name string `json:"name" jsonschema:"the name is required"`
28 }
29 handler := func(ctx context.Context, req *CallToolRequest, args RequiredParams) (*CallToolResult, any, error) {
30 return &CallToolResult{
31 Content: []Content{&TextContent{Text: "success"}},
32 }, nil, nil
33 }
34 AddTool(s, &Tool{Name: "validate", Description: "validates params"}, handler)
35
36 // Add a prompt
37 s.AddPrompt(codeReviewPrompt, codReviewPromptHandler)
38
39 // Add a resource that returns ResourceNotFoundError
40 s.AddResource(
41 &Resource{URI: "file:///test.txt", Name: "test", MIMEType: "text/plain"},
42 func(ctx context.Context, req *ReadResourceRequest) (*ReadResourceResult, error) {
43 return nil, ResourceNotFoundError(req.Params.URI)
44 },
45 )
46 })
47 defer cleanup()
48
49 testCases := []struct {
50 name string
51 executeCall func() error
52 expectedCode int64
53 }{
54 // Note: "missing required param" is tested separately below, because
55 // input validation errors are returned as tool results with IsError=true
56 // rather than JSON-RPC errors (see #450).
57 {
58 name: "unknown tool",
59 executeCall: func() error {
60 _, err := cs.CallTool(ctx, &CallToolParams{
61 Name: "nonexistent_tool",
62 Arguments: map[string]any{},
63 })
64 return err
65 },
66 expectedCode: jsonrpc.CodeInvalidParams,
67 },
68 {
69 name: "unknown prompt",
70 executeCall: func() error {
71 _, err := cs.GetPrompt(ctx, &GetPromptParams{
72 Name: "nonexistent_prompt",
73 Arguments: map[string]string{},
74 })
75 return err
76 },
77 expectedCode: jsonrpc.CodeInvalidParams,
78 },
79 {
80 name: "resource not found",
81 executeCall: func() error {
82 _, err := cs.ReadResource(ctx, &ReadResourceParams{
83 URI: "file:///test.txt",
84 })
85 return err
86 },
87 expectedCode: CodeResourceNotFound,
88 },
89 }
90
91 for _, tc := range testCases {
92 t.Run(tc.name, func(t *testing.T) {
93 err := tc.executeCall()
94 if err == nil {
95 t.Fatal("got nil error, want non-nil")
96 }
97
98 var rpcErr *jsonrpc.Error
99 if !errors.As(err, &rpcErr) {
100 t.Fatalf("got error type %T, want jsonrpc.Error: %v", err, err)
101 }
102
103 if rpcErr.Code != tc.expectedCode {
104 t.Errorf("got error code %d, want %d", rpcErr.Code, tc.expectedCode)
105 }
106
107 if rpcErr.Message == "" {
108 t.Error("got empty error message, want non-empty")
109 }
110 })
111 }
112 }
113
114 // TestInputValidationToolError validates that input validation errors (missing
115 // required params, wrong types) are returned as tool results with IsError=true,
116 // not as JSON-RPC errors. This allows LLMs to see the error and self-correct.
117 // See #450.
118 func TestInputValidationToolError(t *testing.T) {
119 ctx := context.Background()
120
121 type RequiredParams struct {
122 Name string `json:"name" jsonschema:"the name is required"`
123 }
124 handler := func(ctx context.Context, req *CallToolRequest, args RequiredParams) (*CallToolResult, any, error) {
125 return &CallToolResult{
126 Content: []Content{&TextContent{Text: "success"}},
127 }, nil, nil
128 }
129
130 cs, _, cleanup := basicConnection(t, func(s *Server) {
131 AddTool(s, &Tool{Name: "validate", Description: "validates params"}, handler)
132 })
133 defer cleanup()
134
135 // Call the tool with missing required "name" field.
136 result, err := cs.CallTool(ctx, &CallToolParams{
137 Name: "validate",
138 Arguments: map[string]any{},
139 })
140 if err != nil {
141 t.Fatalf("CallTool returned error: %v; want tool result with IsError", err)
142 }
143 if !result.IsError {
144 t.Fatal("got IsError=false, want IsError=true for missing required param")
145 }
146 text := result.Content[0].(*TextContent).Text
147 if !strings.Contains(text, "name") {
148 t.Errorf("error text %q does not mention missing field \"name\"", text)
149 }
150 }
151
152 // TestURLElicitationRequired validates that URL elicitation required errors
153 // are properly created and handled by the client.
154 func TestURLElicitationRequired(t *testing.T) {
155 ctx := context.Background()
156
157 t.Run("error creation", func(t *testing.T) {
158 elicitations := []*ElicitParams{
159 {
160 Mode: "url",
161 Message: "Please authorize",
162 URL: "https://example.com/auth",
163 ElicitationID: "auth-123",
164 },
165 }
166
167 err := URLElicitationRequiredError(elicitations)
168
169 var rpcErr *jsonrpc.Error
170 if !errors.As(err, &rpcErr) {
171 t.Fatalf("got error type %T, want jsonrpc.Error", err)
172 }
173
174 if rpcErr.Code != CodeURLElicitationRequired {
175 t.Errorf("got error code %d, want %d", rpcErr.Code, CodeURLElicitationRequired)
176 }
177
178 if rpcErr.Message != "URL elicitation required" {
179 t.Errorf("got message %q, want 'URL elicitation required'", rpcErr.Message)
180 }
181
182 if rpcErr.Data == nil {
183 t.Fatal("got nil error data, want non-nil")
184 }
185
186 // Verify the elicitations can be unmarshaled from the error data
187 var errorData struct {
188 Elicitations []*ElicitParams `json:"elicitations"`
189 }
190 if err := json.Unmarshal(rpcErr.Data, &errorData); err != nil {
191 t.Fatalf("failed to unmarshal error data: %v", err)
192 }
193
194 if len(errorData.Elicitations) != 1 {
195 t.Fatalf("got %d elicitations, want 1", len(errorData.Elicitations))
196 }
197
198 if errorData.Elicitations[0].URL != "https://example.com/auth" {
199 t.Errorf("got URL %q, want 'https://example.com/auth'", errorData.Elicitations[0].URL)
200 }
201 })
202
203 t.Run("error creation with non-URL mode panics", func(t *testing.T) {
204 defer func() {
205 if r := recover(); r == nil {
206 t.Error("got no panic when creating URLElicitationRequiredError with non-URL mode, want panic")
207 }
208 }()
209
210 // This should panic because mode is "form"
211 URLElicitationRequiredError([]*ElicitParams{
212 {
213 Mode: "form",
214 Message: "This should panic",
215 ElicitationID: "bad-123",
216 },
217 })
218 })
219
220 t.Run("error creation with empty mode panics", func(t *testing.T) {
221 defer func() {
222 if r := recover(); r == nil {
223 t.Error("got no panic when creating URLElicitationRequiredError with empty mode (defaults to form), want panic")
224 }
225 }()
226
227 // This should panic because empty mode defaults to "form"
228 URLElicitationRequiredError([]*ElicitParams{
229 {
230 Message: "This should panic",
231 ElicitationID: "bad-123",
232 },
233 })
234 })
235
236 t.Run("client middleware", func(t *testing.T) {
237 // Declare ss outside so it can be captured in handlers.
238 var ss *ServerSession
239
240 elicitCalled := false
241 elicitURL := ""
242 elicitID := "form-123"
243
244 // Create client with elicitation handler and middleware.
245 client := NewClient(testImpl, &ClientOptions{
246 Capabilities: &ClientCapabilities{
247 Roots: RootCapabilities{ListChanged: true},
248 RootsV2: &RootCapabilities{ListChanged: true},
249 Elicitation: &ElicitationCapabilities{
250 URL: &URLElicitationCapabilities{},
251 },
252 },
253 ElicitationHandler: func(ctx context.Context, req *ElicitRequest) (*ElicitResult, error) {
254 elicitCalled = true
255 elicitURL = req.Params.URL
256
257 // Simulate the server sending elicitation complete notification.
258 // In a real scenario, this would happen out-of-band after the user
259 // completes the form submission.
260 go func() {
261 err := handleNotify(ctx, notificationElicitationComplete,
262 newServerRequest(ss, &ElicitationCompleteParams{
263 ElicitationID: elicitID,
264 }))
265 if err != nil {
266 t.Errorf("failed to send elicitation complete notification: %v", err)
267 }
268 }()
269
270 return &ElicitResult{Action: "accept"}, nil
271 },
272 })
273 // Add URL elicitation middleware for automatic retry.
274 client.AddSendingMiddleware(urlElicitationMiddleware())
275
276 var callCount atomic.Int32
277
278 cs, serverSession, cleanup := basicClientServerConnection(t,
279 client,
280 nil,
281 func(s *Server) {
282 // Tool that requires form submission on first call, succeeds on second.
283 handler := func(ctx context.Context, req *CallToolRequest, args map[string]any) (*CallToolResult, any, error) {
284 if callCount.Add(1) == 1 {
285 // First call: require elicitation.
286 return nil, nil, URLElicitationRequiredError([]*ElicitParams{
287 {
288 Mode: "url",
289 Message: "Please complete the form",
290 URL: "https://example.com/form",
291 ElicitationID: elicitID,
292 },
293 })
294 }
295 // Second call (after retry): return success.
296 return &CallToolResult{
297 Content: []Content{&TextContent{Text: "form submitted"}},
298 }, nil, nil
299 }
300 AddTool(s, &Tool{Name: "submit_form", Description: "requires form submission"}, handler)
301
302 // Tool that returns invalid elicitation mode (form instead of URL).
303 badHandler := func(ctx context.Context, req *CallToolRequest, args map[string]any) (*CallToolResult, any, error) {
304 // Manually construct an error with form mode (bypassing validation).
305 data, _ := json.Marshal(map[string]any{
306 "elicitations": []*ElicitParams{
307 {
308 Mode: "form",
309 Message: "Invalid mode",
310 ElicitationID: "bad-form",
311 },
312 },
313 })
314 return nil, nil, &jsonrpc.Error{
315 Code: CodeURLElicitationRequired,
316 Message: "URL elicitation required",
317 Data: json.RawMessage(data),
318 }
319 }
320 AddTool(s, &Tool{Name: "bad_tool", Description: "returns invalid elicitation"}, badHandler)
321 },
322 )
323 ss = serverSession
324 defer cleanup()
325
326 t.Run("auto-retry after elicitation", func(t *testing.T) {
327 // Reset state for this subtest.
328 elicitCalled = false
329 elicitURL = ""
330 callCount.Store(0)
331
332 // Call the tool that requires URL elicitation.
333 result, err := cs.CallTool(ctx, &CallToolParams{
334 Name: "submit_form",
335 Arguments: map[string]any{},
336 })
337
338 // After automatic retry, the operation should succeed.
339 if err != nil {
340 t.Fatalf("CallTool failed: %v", err)
341 }
342
343 // Verify the elicitation handler was called.
344 if !elicitCalled {
345 t.Error("elicitation handler not called")
346 }
347
348 if elicitURL != "https://example.com/form" {
349 t.Errorf("got elicit URL %q, want 'https://example.com/form'", elicitURL)
350 }
351
352 // Verify the tool was called twice (first attempt + retry).
353 if got, want := callCount.Load(), int32(2); got != want {
354 t.Errorf("CallTool(): with retry, got %d tool calls, want %d", got, want)
355 }
356
357 // Verify we got the successful result.
358 if len(result.Content) != 1 {
359 t.Fatalf("CallTool(): got %d content items, want 1", len(result.Content))
360 }
361
362 textContent, ok := result.Content[0].(*TextContent)
363 if !ok {
364 t.Fatalf("CallTool(): got content type %T, want TextContent", result.Content[0])
365 }
366
367 if textContent.Text != "form submitted" {
368 t.Errorf("CallTool(): got text %q, want 'form submitted'", textContent.Text)
369 }
370 })
371
372 t.Run("reject non-URL mode", func(t *testing.T) {
373 // Call the tool that returns invalid elicitation mode.
374 _, err := cs.CallTool(ctx, &CallToolParams{
375 Name: "bad_tool",
376 Arguments: map[string]any{},
377 })
378
379 // Should get an error about invalid mode.
380 if err == nil {
381 t.Fatal("got nil error for non-URL mode elicitation, want error")
382 }
383
384 if !strings.Contains(err.Error(), "URL mode") {
385 t.Errorf("got error %v, want mention of URL mode", err)
386 }
387 })
388 })
389 }