Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/mcp_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 "bytes"
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "log/slog"
15 "net/url"
16 "path/filepath"
17 "runtime"
18 "slices"
19 "strings"
20 "sync"
21 "sync/atomic"
22 "testing"
23 "testing/synctest"
24 "time"
25
26 "github.com/google/go-cmp/cmp"
27 "github.com/google/jsonschema-go/jsonschema"
28 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
29 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
30 )
31
32 type hiParams struct {
33 Name string
34 }
35
36 // TODO(jba): after schemas are stateless (WIP), this can be a variable.
37 func greetTool() *Tool { return &Tool{Name: "greet", Description: "say hi"} }
38
39 func sayHi(ctx context.Context, req *CallToolRequest, args hiParams) (*CallToolResult, any, error) {
40 if err := req.Session.Ping(ctx, nil); err != nil {
41 return nil, nil, fmt.Errorf("ping failed: %v", err)
42 }
43 return &CallToolResult{Content: []Content{&TextContent{Text: "hi " + args.Name}}}, nil, nil
44 }
45
46 var codeReviewPrompt = &Prompt{
47 Name: "code_review",
48 Description: "do a code review",
49 Arguments: []*PromptArgument{{Name: "Code", Required: true}},
50 }
51
52 func codReviewPromptHandler(_ context.Context, req *GetPromptRequest) (*GetPromptResult, error) {
53 return &GetPromptResult{
54 Description: "Code review prompt",
55 Messages: []*PromptMessage{
56 {Role: "user", Content: &TextContent{Text: "Please review the following code: " + req.Params.Arguments["Code"]}},
57 },
58 }, nil
59 }
60
61 // TODO(maciej-kisiel): split this test into multiple test cases that target specific functionality.
62 func TestEndToEnd(t *testing.T) {
63 synctest.Test(t, func(t *testing.T) {
64 ctx := context.Background()
65 var ct, st Transport = NewInMemoryTransports()
66
67 // Channels to check if notification callbacks happened.
68 // These test asynchronous sending of notifications after a small delay (see
69 // Server.sendNotification).
70 notificationChans := map[string]chan int{}
71 for _, name := range []string{"initialized", "roots", "tools", "prompts", "resources", "progress_server", "progress_client", "resource_updated", "subscribe", "unsubscribe", "elicitation_complete"} {
72 notificationChans[name] = make(chan int, 1)
73 }
74
75 waitForNotification := func(t *testing.T, name string) {
76 t.Helper()
77 time.Sleep(notificationDelay * 2)
78 <-notificationChans[name]
79 }
80
81 sopts := &ServerOptions{
82 InitializedHandler: func(context.Context, *InitializedRequest) {
83 notificationChans["initialized"] <- 0
84 },
85 RootsListChangedHandler: func(context.Context, *RootsListChangedRequest) {
86 notificationChans["roots"] <- 0
87 },
88 ProgressNotificationHandler: func(context.Context, *ProgressNotificationServerRequest) {
89 notificationChans["progress_server"] <- 0
90 },
91 SubscribeHandler: func(context.Context, *SubscribeRequest) error {
92 notificationChans["subscribe"] <- 0
93 return nil
94 },
95 UnsubscribeHandler: func(context.Context, *UnsubscribeRequest) error {
96 notificationChans["unsubscribe"] <- 0
97 return nil
98 },
99 }
100 s := NewServer(testImpl, sopts)
101 AddTool(s, &Tool{
102 Name: "greet",
103 Description: "say hi",
104 }, sayHi)
105 AddTool(s, &Tool{Name: "fail", InputSchema: &jsonschema.Schema{Type: "object"}},
106 func(context.Context, *CallToolRequest, map[string]any) (*CallToolResult, any, error) {
107 return nil, nil, errTestFailure
108 })
109 s.AddPrompt(codeReviewPrompt, codReviewPromptHandler)
110 s.AddPrompt(&Prompt{Name: "fail"}, func(_ context.Context, _ *GetPromptRequest) (*GetPromptResult, error) {
111 return nil, errTestFailure
112 })
113 s.AddResource(resource1, readHandler)
114 s.AddResource(resource2, readHandler)
115
116 // Connect the server.
117 ss, err := s.Connect(ctx, st, nil)
118 if err != nil {
119 t.Fatal(err)
120 }
121 if got := slices.Collect(s.Sessions()); len(got) != 1 {
122 t.Errorf("after connection, Clients() has length %d, want 1", len(got))
123 }
124
125 loggingMessages := make(chan *LoggingMessageParams, 100) // big enough for all logging
126 opts := &ClientOptions{
127 CreateMessageHandler: func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error) {
128 return &CreateMessageResult{Model: "aModel", Content: &TextContent{}}, nil
129 },
130 ElicitationHandler: func(ctx context.Context, req *ElicitRequest) (*ElicitResult, error) {
131 return &ElicitResult{
132 Action: "accept",
133 Content: map[string]any{
134 "name": "Test User",
135 "email": "[email protected]",
136 },
137 }, nil
138 },
139 ToolListChangedHandler: func(context.Context, *ToolListChangedRequest) {
140 notificationChans["tools"] <- 0
141 },
142 PromptListChangedHandler: func(context.Context, *PromptListChangedRequest) {
143 notificationChans["prompts"] <- 0
144 },
145 ResourceListChangedHandler: func(context.Context, *ResourceListChangedRequest) {
146 notificationChans["resources"] <- 0
147 },
148 LoggingMessageHandler: func(_ context.Context, req *LoggingMessageRequest) {
149 loggingMessages <- req.Params
150 },
151 ProgressNotificationHandler: func(context.Context, *ProgressNotificationClientRequest) {
152 notificationChans["progress_client"] <- 0
153 },
154 ResourceUpdatedHandler: func(context.Context, *ResourceUpdatedNotificationRequest) {
155 notificationChans["resource_updated"] <- 0
156 },
157 ElicitationCompleteHandler: func(_ context.Context, req *ElicitationCompleteNotificationRequest) {
158 notificationChans["elicitation_complete"] <- 0
159 },
160 }
161 c := NewClient(testImpl, opts)
162 rootAbs, err := filepath.Abs(filepath.FromSlash("testdata/files"))
163 if err != nil {
164 t.Fatal(err)
165 }
166 c.AddRoots(&Root{URI: "file://" + rootAbs})
167
168 // Connect the client.
169 cs, err := c.Connect(ctx, ct, nil)
170 if err != nil {
171 t.Fatal(err)
172 }
173
174 waitForNotification(t, "initialized")
175 if err := cs.Ping(ctx, nil); err != nil {
176 t.Fatalf("ping failed: %v", err)
177 }
178
179 // ===== prompts =====
180 t.Log("Testing prompts")
181 {
182 res, err := cs.ListPrompts(ctx, nil)
183 if err != nil {
184 t.Fatalf("prompts/list failed: %v", err)
185 }
186 wantPrompts := []*Prompt{
187 {
188 Name: "code_review",
189 Description: "do a code review",
190 Arguments: []*PromptArgument{{Name: "Code", Required: true}},
191 },
192 {Name: "fail"},
193 }
194 if diff := cmp.Diff(wantPrompts, res.Prompts); diff != "" {
195 t.Fatalf("prompts/list mismatch (-want +got):\n%s", diff)
196 }
197
198 gotReview, err := cs.GetPrompt(ctx, &GetPromptParams{Name: "code_review", Arguments: map[string]string{"Code": "1+1"}})
199 if err != nil {
200 t.Fatal(err)
201 }
202 wantReview := &GetPromptResult{
203 Description: "Code review prompt",
204 Messages: []*PromptMessage{{
205 Content: &TextContent{Text: "Please review the following code: 1+1"},
206 Role: "user",
207 }},
208 }
209 if diff := cmp.Diff(wantReview, gotReview); diff != "" {
210 t.Errorf("prompts/get 'code_review' mismatch (-want +got):\n%s", diff)
211 }
212
213 if _, err := cs.GetPrompt(ctx, &GetPromptParams{Name: "fail"}); err == nil || !strings.Contains(err.Error(), errTestFailure.Error()) {
214 t.Errorf("fail returned unexpected error: got %v, want containing %v", err, errTestFailure)
215 }
216
217 s.AddPrompt(&Prompt{Name: "T"}, nil)
218 waitForNotification(t, "prompts")
219 s.RemovePrompts("T")
220 waitForNotification(t, "prompts")
221 }
222
223 // ===== tools =====
224 t.Log("Testing tools")
225 {
226 // ListTools is tested in client_list_test.go.
227 gotHi, err := cs.CallTool(ctx, &CallToolParams{
228 Name: "greet",
229 Arguments: map[string]any{"Name": "user"},
230 })
231 if err != nil {
232 t.Fatal(err)
233 }
234 wantHi := &CallToolResult{
235 Content: []Content{
236 &TextContent{Text: "hi user"},
237 },
238 }
239 if diff := cmp.Diff(wantHi, gotHi, ctrCmpOpts...); diff != "" {
240 t.Errorf("tools/call 'greet' mismatch (-want +got):\n%s", diff)
241 }
242
243 gotFail, err := cs.CallTool(ctx, &CallToolParams{
244 Name: "fail",
245 Arguments: map[string]any{},
246 })
247 // Counter-intuitively, when a tool fails, we don't expect an RPC error for
248 // call tool: instead, the failure is embedded in the result.
249 if err != nil {
250 t.Fatal(err)
251 }
252 wantFail := &CallToolResult{
253 IsError: true,
254 Content: []Content{
255 &TextContent{Text: errTestFailure.Error()},
256 },
257 }
258 if diff := cmp.Diff(wantFail, gotFail, ctrCmpOpts...); diff != "" {
259 t.Errorf("tools/call 'fail' mismatch (-want +got):\n%s", diff)
260 }
261
262 // Check output schema validation.
263 badout := &Tool{
264 Name: "badout",
265 OutputSchema: &jsonschema.Schema{
266 Type: "object",
267 Properties: map[string]*jsonschema.Schema{
268 "x": {Type: "string"},
269 },
270 },
271 }
272 AddTool(s, badout, func(_ context.Context, _ *CallToolRequest, arg map[string]any) (*CallToolResult, map[string]any, error) {
273 return nil, map[string]any{"x": 1}, nil
274 })
275 _, err = cs.CallTool(ctx, &CallToolParams{Name: "badout"})
276 wantMsg := `has type "integer", want "string"`
277 if err == nil || !strings.Contains(err.Error(), wantMsg) {
278 t.Errorf("\ngot %q\nwant error message containing %q", err, wantMsg)
279 }
280
281 // Check tools-changed notifications.
282 s.AddTool(&Tool{Name: "T", InputSchema: &jsonschema.Schema{Type: "object"}}, nopHandler)
283 waitForNotification(t, "tools")
284 s.RemoveTools("T")
285 waitForNotification(t, "tools")
286 }
287
288 // ===== resources =====
289 t.Log("Testing resources")
290 //TODO: fix for Windows
291 if runtime.GOOS != "windows" {
292 wantResources := []*Resource{resource2, resource1}
293 lrres, err := cs.ListResources(ctx, nil)
294 if err != nil {
295 t.Fatal(err)
296 }
297 if diff := cmp.Diff(wantResources, lrres.Resources); diff != "" {
298 t.Errorf("resources/list mismatch (-want, +got):\n%s", diff)
299 }
300
301 template := &ResourceTemplate{
302 Name: "rt",
303 MIMEType: "text/template",
304 URITemplate: "file:///{+filename}", // the '+' means that filename can contain '/'
305 }
306 s.AddResourceTemplate(template, readHandler)
307 tres, err := cs.ListResourceTemplates(ctx, nil)
308 if err != nil {
309 t.Fatal(err)
310 }
311 if diff := cmp.Diff([]*ResourceTemplate{template}, tres.ResourceTemplates); diff != "" {
312 t.Errorf("resources/list mismatch (-want, +got):\n%s", diff)
313 }
314
315 for _, tt := range []struct {
316 uri string
317 mimeType string // "": not found; "text/plain": resource; "text/template": template
318 fail bool // non-nil error returned
319 }{
320 {"file:///info.txt", "text/plain", false},
321 {"file:///fail.txt", "", false},
322 {"file:///template.txt", "text/template", false},
323 {"file:///../private.txt", "", true}, // not found: escaping disallowed
324 } {
325 rres, err := cs.ReadResource(ctx, &ReadResourceParams{URI: tt.uri})
326 if err != nil {
327 if code := errorCode(err); code == CodeResourceNotFound {
328 if tt.mimeType != "" {
329 t.Errorf("%s: not found but expected it to be", tt.uri)
330 }
331 } else if !tt.fail {
332 t.Errorf("%s: unexpected error %v", tt.uri, err)
333 }
334 } else {
335 if tt.fail {
336 t.Errorf("%s: unexpected success", tt.uri)
337 } else if g, w := len(rres.Contents), 1; g != w {
338 t.Errorf("got %d contents, wanted %d", g, w)
339 } else {
340 c := rres.Contents[0]
341 if got := c.URI; got != tt.uri {
342 t.Errorf("got uri %q, want %q", got, tt.uri)
343 }
344 if got := c.MIMEType; got != tt.mimeType {
345 t.Errorf("%s: got MIME type %q, want %q", tt.uri, got, tt.mimeType)
346 }
347 }
348 }
349 }
350
351 s.AddResource(&Resource{URI: "http://U"}, nil)
352 waitForNotification(t, "resources")
353 s.RemoveResources("http://U")
354 waitForNotification(t, "resources")
355 }
356
357 // ===== roots =====
358 t.Log("Testing roots")
359 {
360 rootRes, err := ss.ListRoots(ctx, &ListRootsParams{})
361 if err != nil {
362 t.Fatal(err)
363 }
364 gotRoots := rootRes.Roots
365 wantRoots := slices.Collect(c.roots.all())
366 if diff := cmp.Diff(wantRoots, gotRoots); diff != "" {
367 t.Errorf("roots/list mismatch (-want +got):\n%s", diff)
368 }
369
370 c.AddRoots(&Root{URI: "U"})
371 waitForNotification(t, "roots")
372 c.RemoveRoots("U")
373 waitForNotification(t, "roots")
374 }
375
376 // ===== sampling =====
377 t.Log("Testing sampling")
378 {
379 // TODO: test that a client that doesn't have the handler returns CodeUnsupportedMethod.
380 res, err := ss.CreateMessage(ctx, &CreateMessageParams{})
381 if err != nil {
382 t.Fatal(err)
383 }
384 if g, w := res.Model, "aModel"; g != w {
385 t.Errorf("got %q, want %q", g, w)
386 }
387 }
388
389 // ===== logging =====
390 t.Log("Testing logging")
391 {
392 want := []*LoggingMessageParams{
393 {
394 Logger: "test",
395 Level: "warning",
396 Data: map[string]any{
397 "msg": "first",
398 "name": "Pat",
399 "logtest": true,
400 },
401 },
402 {
403 Logger: "test",
404 Level: "alert",
405 Data: map[string]any{
406 "msg": "second",
407 "count": 2.0,
408 "logtest": true,
409 },
410 },
411 }
412
413 check := func(t *testing.T) {
414 t.Helper()
415 var got []*LoggingMessageParams
416 // Read messages from this test until we've seen all we expect.
417 for len(got) < len(want) {
418 p := <-loggingMessages
419 // Ignore logging from other tests.
420 if m, ok := p.Data.(map[string]any); ok && m["logtest"] != nil {
421 delete(m, "time")
422 got = append(got, p)
423 }
424 }
425 if diff := cmp.Diff(want, got); diff != "" {
426 t.Errorf("mismatch (-want, +got):\n%s", diff)
427 }
428 }
429
430 // Use the LoggingMessage method directly.
431 t.Log("Testing logging (direct)")
432 {
433 mustLog := func(level LoggingLevel, data any) {
434 t.Helper()
435 if err := ss.Log(ctx, &LoggingMessageParams{
436 Logger: "test",
437 Level: level,
438 Data: data,
439 }); err != nil {
440 t.Fatal(err)
441 }
442 }
443
444 // Nothing should be logged until the client sets a level.
445 mustLog("info", "before")
446 if err := cs.SetLoggingLevel(ctx, &SetLoggingLevelParams{Level: "warning"}); err != nil {
447 t.Fatal(err)
448 }
449 mustLog("warning", want[0].Data)
450 mustLog("debug", "nope") // below the level
451 mustLog("info", "negative") // below the level
452 mustLog("alert", want[1].Data)
453 check(t)
454 }
455
456 // Use the slog handler.
457 t.Log("Testing logging (handler)")
458 {
459 // We can't check the "before SetLevel" behavior because it's already been set.
460 // Not a big deal: that check is in LoggingMessage anyway.
461 logger := slog.New(NewLoggingHandler(ss, &LoggingHandlerOptions{LoggerName: "test"}))
462 logger.Warn("first", "name", "Pat", "logtest", true)
463 logger.Debug("nope") // below the level
464 logger.Info("negative") // below the level
465 logger.Log(ctx, LevelAlert, "second", "count", 2, "logtest", true)
466 check(t)
467 }
468 }
469
470 // ===== progress =====
471 t.Log("Testing progress")
472 {
473 ss.NotifyProgress(ctx, &ProgressNotificationParams{
474 ProgressToken: "token-xyz",
475 Message: "progress update",
476 Progress: 0.5,
477 Total: 2,
478 })
479 waitForNotification(t, "progress_client")
480
481 cs.NotifyProgress(ctx, &ProgressNotificationParams{
482 ProgressToken: "token-abc",
483 Message: "progress update",
484 Progress: 1,
485 Total: 2,
486 })
487 waitForNotification(t, "progress_server")
488 }
489
490 // ===== resource_subscriptions =====
491 t.Log("Testing resource_subscriptions")
492 {
493 err := cs.Subscribe(ctx, &SubscribeParams{
494 URI: "test",
495 })
496 if err != nil {
497 t.Fatal(err)
498 }
499 synctest.Wait()
500 <-notificationChans["subscribe"]
501
502 s.ResourceUpdated(ctx, &ResourceUpdatedNotificationParams{
503 URI: "test",
504 })
505 waitForNotification(t, "resource_updated")
506
507 err = cs.Unsubscribe(ctx, &UnsubscribeParams{
508 URI: "test",
509 })
510 if err != nil {
511 t.Fatal(err)
512 }
513 waitForNotification(t, "unsubscribe")
514
515 // Verify the client does not receive the update after unsubscribing.
516 s.ResourceUpdated(ctx, &ResourceUpdatedNotificationParams{
517 URI: "test",
518 })
519 synctest.Wait()
520 select {
521 case <-notificationChans["resource_updated"]:
522 t.Fatalf("resource updated after unsubscription")
523 default:
524 // Expected: no notification received
525 }
526 }
527
528 // ===== elicitation =====
529 t.Log("Testing elicitation")
530 {
531 result, err := ss.Elicit(ctx, &ElicitParams{
532 Message: "Please provide information",
533 })
534 if err != nil {
535 t.Fatal(err)
536 }
537 if result.Action != "accept" {
538 t.Errorf("got action %q, want %q", result.Action, "accept")
539 }
540 }
541
542 // Disconnect.
543 cs.Close()
544 if err := ss.Wait(); err != nil {
545 t.Errorf("server failed: %v", err)
546 }
547
548 // After disconnecting, neither client nor server should have any
549 // connections.
550 for range s.Sessions() {
551 t.Errorf("unexpected client after disconnection")
552 }
553 })
554 }
555
556 // Registry of values to be referenced in tests.
557 var (
558 errTestFailure = errors.New("mcp failure")
559
560 resource1 = &Resource{
561 Name: "public",
562 MIMEType: "text/plain",
563 URI: "file:///info.txt",
564 }
565 resource2 = &Resource{
566 Name: "public", // names are not unique IDs
567 MIMEType: "text/plain",
568 URI: "file:///fail.txt",
569 }
570 resource3 = &Resource{
571 Name: "info",
572 MIMEType: "text/plain",
573 URI: "embedded:info",
574 }
575 readHandler = fileResourceHandler("testdata/files")
576 )
577
578 var embeddedResources = map[string]string{
579 "info": "This is the MCP test server.",
580 }
581
582 func handleEmbeddedResource(_ context.Context, req *ReadResourceRequest) (*ReadResourceResult, error) {
583 u, err := url.Parse(req.Params.URI)
584 if err != nil {
585 return nil, err
586 }
587 if u.Scheme != "embedded" {
588 return nil, fmt.Errorf("wrong scheme: %q", u.Scheme)
589 }
590 key := u.Opaque
591 text, ok := embeddedResources[key]
592 if !ok {
593 return nil, fmt.Errorf("no embedded resource named %q", key)
594 }
595 return &ReadResourceResult{
596 Contents: []*ResourceContents{
597 {URI: req.Params.URI, MIMEType: "text/plain", Text: text},
598 },
599 }, nil
600 }
601
602 // errorCode returns the code associated with err.
603 // If err is nil, it returns 0.
604 // If there is no code, it returns -1.
605 func errorCode(err error) int64 {
606 if err == nil {
607 return 0
608 }
609 var werr *jsonrpc.Error
610 if errors.As(err, &werr) {
611 return werr.Code
612 }
613 return -1
614 }
615
616 // basicConnection returns a new basic client-server connection, with the server
617 // configured via the provided function.
618 //
619 // The caller should cancel either the client connection or server connection
620 // when the connections are no longer needed.
621 //
622 // The returned func cleans up by closing the client and waiting for the server
623 // to shut down.
624 func basicConnection(t *testing.T, config func(*Server)) (*ClientSession, *ServerSession, func()) {
625 return basicClientServerConnection(t, nil, nil, config)
626 }
627
628 // basicClientServerConnection creates a basic connection between client and
629 // server. If either client or server is nil, empty implementations are used.
630 //
631 // The provided function may be used to configure features on the resulting
632 // server, prior to connection.
633 //
634 // The caller should cancel either the client connection or server connection
635 // when the connections are no longer needed.
636 //
637 // The returned func cleans up by closing the client and waiting for the server
638 // to shut down.
639 func basicClientServerConnection(t *testing.T, client *Client, server *Server, config func(*Server)) (*ClientSession, *ServerSession, func()) {
640 t.Helper()
641
642 ctx := context.Background()
643 ct, st := NewInMemoryTransports()
644
645 if server == nil {
646 server = NewServer(testImpl, nil)
647 }
648 if config != nil {
649 config(server)
650 }
651 ss, err := server.Connect(ctx, st, nil)
652 if err != nil {
653 t.Fatal(err)
654 }
655 t.Cleanup(func() { _ = ss.Close() })
656
657 if client == nil {
658 client = NewClient(testImpl, nil)
659 }
660 cs, err := client.Connect(ctx, ct, nil)
661 if err != nil {
662 t.Fatal(err)
663 }
664 t.Cleanup(func() { _ = cs.Close() })
665
666 return cs, ss, func() {
667 cs.Close()
668 ss.Wait()
669 }
670 }
671
672 func TestServerClosing(t *testing.T) {
673 cs, ss, cleanup := basicConnection(t, func(s *Server) {
674 AddTool(s, greetTool(), sayHi)
675 })
676 defer cleanup()
677
678 ctx := context.Background()
679 var wg sync.WaitGroup
680 wg.Go(func() {
681 if err := cs.Wait(); err != nil {
682 t.Errorf("server connection failed: %v", err)
683 }
684 })
685 if _, err := cs.CallTool(ctx, &CallToolParams{
686 Name: "greet",
687 Arguments: map[string]any{"Name": "user"},
688 }); err != nil {
689 t.Fatalf("after connecting: %v", err)
690 }
691 ss.Close()
692 wg.Wait()
693 if _, err := cs.CallTool(ctx, &CallToolParams{
694 Name: "greet",
695 Arguments: map[string]any{"name": "user"},
696 }); !errors.Is(err, ErrConnectionClosed) {
697 t.Errorf("after disconnection, got error %v, want EOF", err)
698 }
699 }
700
701 func TestCancellation(t *testing.T) {
702 synctest.Test(t, func(t *testing.T) {
703 var (
704 start = make(chan struct{})
705 cancelled = make(chan struct{}, 1) // don't block the request
706 )
707 slowTool := func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
708 start <- struct{}{}
709 select {
710 case <-ctx.Done():
711 cancelled <- struct{}{}
712 case <-time.After(5 * time.Second):
713 return nil, nil, nil
714 }
715 return nil, nil, nil
716 }
717 cs, _, cleanup := basicConnection(t, func(s *Server) {
718 AddTool(s, &Tool{Name: "slow", InputSchema: &jsonschema.Schema{Type: "object"}}, slowTool)
719 })
720 defer cleanup()
721
722 ctx, cancel := context.WithCancel(context.Background())
723 go cs.CallTool(ctx, &CallToolParams{Name: "slow"})
724 <-start
725 cancel()
726
727 <-cancelled
728 })
729 }
730
731 func TestMiddleware(t *testing.T) {
732 ctx := context.Background()
733 ct, st := NewInMemoryTransports()
734
735 s := NewServer(testImpl, nil)
736 ss, err := s.Connect(ctx, st, nil)
737 if err != nil {
738 t.Fatal(err)
739 }
740 // Wait for the server to exit after the client closes its connection.
741 t.Cleanup(func() { _ = ss.Close() })
742
743 var sbuf, cbuf bytes.Buffer
744 sbuf.WriteByte('\n')
745 cbuf.WriteByte('\n')
746
747 // "1" is the outer middleware layer, called first; then "2" is called, and finally
748 // the default dispatcher.
749 s.AddSendingMiddleware(traceCalls[*ServerSession](&sbuf, "S1"), traceCalls[*ServerSession](&sbuf, "S2"))
750 s.AddReceivingMiddleware(traceCalls[*ServerSession](&sbuf, "R1"), traceCalls[*ServerSession](&sbuf, "R2"))
751
752 c := NewClient(testImpl, nil)
753 c.AddSendingMiddleware(traceCalls[*ClientSession](&cbuf, "S1"), traceCalls[*ClientSession](&cbuf, "S2"))
754 c.AddReceivingMiddleware(traceCalls[*ClientSession](&cbuf, "R1"), traceCalls[*ClientSession](&cbuf, "R2"))
755
756 cs, err := c.Connect(ctx, ct, nil)
757 if err != nil {
758 t.Fatal(err)
759 }
760 t.Cleanup(func() { _ = cs.Close() })
761
762 if _, err := cs.ListTools(ctx, nil); err != nil {
763 t.Fatal(err)
764 }
765 if _, err := ss.ListRoots(ctx, nil); err != nil {
766 t.Fatal(err)
767 }
768
769 wantServer := `
770 R1 >initialize
771 R2 >initialize
772 R2 <initialize
773 R1 <initialize
774 R1 >notifications/initialized
775 R2 >notifications/initialized
776 R2 <notifications/initialized
777 R1 <notifications/initialized
778 R1 >tools/list
779 R2 >tools/list
780 R2 <tools/list
781 R1 <tools/list
782 S1 >roots/list
783 S2 >roots/list
784 S2 <roots/list
785 S1 <roots/list
786 `
787 if diff := cmp.Diff(wantServer, sbuf.String()); diff != "" {
788 t.Errorf("server mismatch (-want, +got):\n%s", diff)
789 }
790
791 wantClient := `
792 S1 >initialize
793 S2 >initialize
794 S2 <initialize
795 S1 <initialize
796 S1 >notifications/initialized
797 S2 >notifications/initialized
798 S2 <notifications/initialized
799 S1 <notifications/initialized
800 S1 >tools/list
801 S2 >tools/list
802 S2 <tools/list
803 S1 <tools/list
804 R1 >roots/list
805 R2 >roots/list
806 R2 <roots/list
807 R1 <roots/list
808 `
809 if diff := cmp.Diff(wantClient, cbuf.String()); diff != "" {
810 t.Errorf("client mismatch (-want, +got):\n%s", diff)
811 }
812 }
813
814 type safeBuffer struct {
815 mu sync.Mutex
816 buf bytes.Buffer
817 }
818
819 func (b *safeBuffer) Write(data []byte) (int, error) {
820 b.mu.Lock()
821 defer b.mu.Unlock()
822 return b.buf.Write(data)
823 }
824
825 func (b *safeBuffer) Bytes() []byte {
826 b.mu.Lock()
827 defer b.mu.Unlock()
828 return b.buf.Bytes()
829 }
830
831 func TestNoJSONNull(t *testing.T) {
832 ctx := context.Background()
833 var ct, st Transport = NewInMemoryTransports()
834
835 // Collect logs, to sanity check that we don't write JSON null anywhere.
836 var logbuf safeBuffer
837 ct = &LoggingTransport{Transport: ct, Writer: &logbuf}
838
839 s := NewServer(testImpl, nil)
840 ss, err := s.Connect(ctx, st, nil)
841 if err != nil {
842 t.Fatal(err)
843 }
844
845 c := NewClient(testImpl, nil)
846 cs, err := c.Connect(ctx, ct, nil)
847 if err != nil {
848 t.Fatal(err)
849 }
850 if _, err := cs.ListTools(ctx, nil); err != nil {
851 t.Fatal(err)
852 }
853 if _, err := cs.ListPrompts(ctx, nil); err != nil {
854 t.Fatal(err)
855 }
856 if _, err := cs.ListResources(ctx, nil); err != nil {
857 t.Fatal(err)
858 }
859 if _, err := cs.ListResourceTemplates(ctx, nil); err != nil {
860 t.Fatal(err)
861 }
862 if _, err := ss.ListRoots(ctx, nil); err != nil {
863 t.Fatal(err)
864 }
865
866 cs.Close()
867 ss.Wait()
868
869 logs := logbuf.Bytes()
870 if i := bytes.Index(logs, []byte("null")); i >= 0 {
871 start := max(i-20, 0)
872 end := min(i+20, len(logs))
873 t.Errorf("conformance violation: MCP logs contain JSON null: %s", "..."+string(logs[start:end])+"...")
874 }
875 }
876
877 // traceCalls creates a middleware function that prints the method before and after each call
878 // with the given prefix.
879 func traceCalls[S Session](w io.Writer, prefix string) Middleware {
880 return func(h MethodHandler) MethodHandler {
881 return func(ctx context.Context, method string, req Request) (Result, error) {
882 fmt.Fprintf(w, "%s >%s\n", prefix, method)
883 defer fmt.Fprintf(w, "%s <%s\n", prefix, method)
884 return h(ctx, method, req)
885 }
886 }
887 }
888
889 func nopHandler(context.Context, *CallToolRequest) (*CallToolResult, error) {
890 return nil, nil
891 }
892
893 func TestKeepAlive(t *testing.T) {
894 synctest.Test(t, func(t *testing.T) {
895 ctx := context.Background()
896
897 ct, st := NewInMemoryTransports()
898
899 serverOpts := &ServerOptions{
900 KeepAlive: 100 * time.Millisecond,
901 }
902 s := NewServer(testImpl, serverOpts)
903 AddTool(s, greetTool(), sayHi)
904
905 ss, err := s.Connect(ctx, st, nil)
906 if err != nil {
907 t.Fatal(err)
908 }
909 defer ss.Close()
910
911 clientOpts := &ClientOptions{
912 KeepAlive: 100 * time.Millisecond,
913 }
914 c := NewClient(testImpl, clientOpts)
915 cs, err := c.Connect(ctx, ct, nil)
916 if err != nil {
917 t.Fatal(err)
918 }
919 defer cs.Close()
920
921 // Wait for a few keepalive cycles to ensure pings are working.
922 // With synctest, this advances simulated time instantly.
923 time.Sleep(300 * time.Millisecond)
924
925 // Test that the connection is still alive by making a call
926 result, err := cs.CallTool(ctx, &CallToolParams{
927 Name: "greet",
928 Arguments: map[string]any{"Name": "user"},
929 })
930 if err != nil {
931 t.Fatalf("call failed after keepalive: %v", err)
932 }
933 if len(result.Content) == 0 {
934 t.Fatal("expected content in result")
935 }
936 if textContent, ok := result.Content[0].(*TextContent); !ok || textContent.Text != "hi user" {
937 t.Fatalf("unexpected result: %v", result.Content[0])
938 }
939 })
940 }
941
942 func TestKeepAliveMethodNotFound(t *testing.T) {
943 synctest.Test(t, func(t *testing.T) {
944 ctx := context.Background()
945
946 ct, st := NewInMemoryTransports()
947
948 // Server that rejects ping with method-not-found, simulating a
949 // server that does not implement the optional ping method.
950 s := NewServer(testImpl, nil)
951 AddTool(s, greetTool(), sayHi)
952 s.AddReceivingMiddleware(func(next MethodHandler) MethodHandler {
953 return func(ctx context.Context, method string, req Request) (Result, error) {
954 if method == "ping" {
955 return nil, jsonrpc2.ErrMethodNotFound
956 }
957 return next(ctx, method, req)
958 }
959 })
960 ss, err := s.Connect(ctx, st, nil)
961 if err != nil {
962 t.Fatal(err)
963 }
964 defer ss.Close()
965
966 clientOpts := &ClientOptions{
967 KeepAlive: 50 * time.Millisecond,
968 }
969 c := NewClient(testImpl, clientOpts)
970 cs, err := c.Connect(ctx, ct, nil)
971 if err != nil {
972 t.Fatal(err)
973 }
974 defer cs.Close()
975
976 // Advance past several keepalive cycles.
977 time.Sleep(200 * time.Millisecond)
978
979 // The session should still be alive despite the server not
980 // supporting ping.
981 result, err := cs.CallTool(ctx, &CallToolParams{
982 Name: "greet",
983 Arguments: map[string]any{"Name": "user"},
984 })
985 if err != nil {
986 t.Fatalf("call failed after keepalive with method-not-found: %v", err)
987 }
988 if len(result.Content) == 0 {
989 t.Fatal("expected content in result")
990 }
991 if textContent, ok := result.Content[0].(*TextContent); !ok || textContent.Text != "hi user" {
992 t.Fatalf("unexpected result: %v", result.Content[0])
993 }
994 })
995 }
996
997 func TestElicitationUnsupportedMethod(t *testing.T) {
998 ctx := context.Background()
999 ct, st := NewInMemoryTransports()
1000
1001 // Server
1002 s := NewServer(testImpl, nil)
1003 ss, err := s.Connect(ctx, st, nil)
1004 if err != nil {
1005 t.Fatal(err)
1006 }
1007 defer ss.Close()
1008
1009 // Client without ElicitationHandler
1010 c := NewClient(testImpl, &ClientOptions{
1011 CreateMessageHandler: func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error) {
1012 return &CreateMessageResult{Model: "aModel", Content: &TextContent{}}, nil
1013 },
1014 })
1015 cs, err := c.Connect(ctx, ct, nil)
1016 if err != nil {
1017 t.Fatal(err)
1018 }
1019 defer cs.Close()
1020
1021 // Test that elicitation fails when no handler is provided
1022 _, err = ss.Elicit(ctx, &ElicitParams{
1023 Message: "This should fail",
1024 RequestedSchema: &jsonschema.Schema{
1025 Type: "object",
1026 Properties: map[string]*jsonschema.Schema{
1027 "test": {Type: "string"},
1028 },
1029 },
1030 })
1031
1032 if err == nil {
1033 t.Error("expected error when ElicitationHandler is not provided, got nil")
1034 }
1035 if code := errorCode(err); code != -1 {
1036 t.Errorf("got error code %d, want -1", code)
1037 }
1038 if !strings.Contains(err.Error(), "does not support elicitation") {
1039 t.Errorf("error should mention unsupported elicitation, got: %v", err)
1040 }
1041 }
1042
1043 func anyPtr[T any](v T) *any {
1044 var a any = v
1045 return &a
1046 }
1047
1048 func TestElicitationSchemaValidation(t *testing.T) {
1049 ctx := context.Background()
1050 ct, st := NewInMemoryTransports()
1051
1052 s := NewServer(testImpl, nil)
1053 ss, err := s.Connect(ctx, st, nil)
1054 if err != nil {
1055 t.Fatal(err)
1056 }
1057 defer ss.Close()
1058
1059 c := NewClient(testImpl, &ClientOptions{
1060 ElicitationHandler: func(context.Context, *ElicitRequest) (*ElicitResult, error) {
1061 return &ElicitResult{Action: "accept", Content: map[string]any{"test": "value"}}, nil
1062 },
1063 })
1064 cs, err := c.Connect(ctx, ct, nil)
1065 if err != nil {
1066 t.Fatal(err)
1067 }
1068 defer cs.Close()
1069
1070 // Test valid schemas - these should not return errors
1071 validSchemas := []struct {
1072 name string
1073 schema *jsonschema.Schema
1074 }{
1075 {
1076 name: "nil schema",
1077 schema: nil,
1078 },
1079 {
1080 name: "empty object schema",
1081 schema: &jsonschema.Schema{
1082 Type: "object",
1083 },
1084 },
1085 {
1086 name: "simple string property",
1087 schema: &jsonschema.Schema{
1088 Type: "object",
1089 Properties: map[string]*jsonschema.Schema{
1090 "name": {Type: "string"},
1091 },
1092 },
1093 },
1094 {
1095 name: "string with valid formats",
1096 schema: &jsonschema.Schema{
1097 Type: "object",
1098 Properties: map[string]*jsonschema.Schema{
1099 "email": {Type: "string", Format: "email"},
1100 "website": {Type: "string", Format: "uri"},
1101 "birthday": {Type: "string", Format: "date"},
1102 "created": {Type: "string", Format: "date-time"},
1103 },
1104 },
1105 },
1106 {
1107 name: "string with constraints",
1108 schema: &jsonschema.Schema{
1109 Type: "object",
1110 Properties: map[string]*jsonschema.Schema{
1111 "name": {Type: "string", MinLength: ptr(1), MaxLength: ptr(100)},
1112 },
1113 },
1114 },
1115 {
1116 name: "number with constraints",
1117 schema: &jsonschema.Schema{
1118 Type: "object",
1119 Properties: map[string]*jsonschema.Schema{
1120 "age": {Type: "integer", Minimum: ptr(0.0), Maximum: ptr(150.0)},
1121 "score": {Type: "number", Minimum: ptr(0.0), Maximum: ptr(100.0)},
1122 },
1123 },
1124 },
1125 {
1126 name: "boolean with default",
1127 schema: &jsonschema.Schema{
1128 Type: "object",
1129 Properties: map[string]*jsonschema.Schema{
1130 "enabled": {Type: "boolean", Default: json.RawMessage("true")},
1131 },
1132 },
1133 },
1134 {
1135 name: "single select untitled enum",
1136 schema: &jsonschema.Schema{
1137 Type: "object",
1138 Properties: map[string]*jsonschema.Schema{
1139 "status": {
1140 Type: "string",
1141 Enum: []any{
1142 "active",
1143 "inactive",
1144 "pending",
1145 },
1146 },
1147 },
1148 },
1149 },
1150 {
1151 name: "legacy titled enum",
1152 schema: &jsonschema.Schema{
1153 Type: "object",
1154 Properties: map[string]*jsonschema.Schema{
1155 "priority": {
1156 Type: "string",
1157 Enum: []any{
1158 "high",
1159 "medium",
1160 "low",
1161 },
1162 Extra: map[string]any{
1163 "enumNames": []any{"High Priority", "Medium Priority", "Low Priority"},
1164 },
1165 },
1166 },
1167 },
1168 },
1169 {
1170 name: "single select titled enum",
1171 schema: &jsonschema.Schema{
1172 Type: "object",
1173 Properties: map[string]*jsonschema.Schema{
1174 "priority": {
1175 Type: "string",
1176 OneOf: []*jsonschema.Schema{
1177 {
1178 Const: anyPtr("high"),
1179 Title: "High Priority",
1180 },
1181 {
1182 Const: anyPtr("medium"),
1183 Title: "Medium Priority",
1184 },
1185 {
1186 Const: anyPtr("low"),
1187 Title: "Low Priority",
1188 },
1189 },
1190 },
1191 },
1192 },
1193 },
1194 {
1195 name: "multi select untitled enum",
1196 schema: &jsonschema.Schema{
1197 Type: "object",
1198 Properties: map[string]*jsonschema.Schema{
1199 "status": {
1200 Type: "array",
1201 Items: &jsonschema.Schema{
1202 Type: "string",
1203 Enum: []any{
1204 "active",
1205 "inactive",
1206 "pending",
1207 },
1208 },
1209 },
1210 },
1211 },
1212 },
1213 {
1214 name: "multi select titled enum",
1215 schema: &jsonschema.Schema{
1216 Type: "object",
1217 Properties: map[string]*jsonschema.Schema{
1218 "priority": {
1219 Type: "array",
1220 Items: &jsonschema.Schema{
1221 AnyOf: []*jsonschema.Schema{
1222 {
1223 Const: anyPtr("high"),
1224 Title: "High Priority",
1225 },
1226 {
1227 Const: anyPtr("medium"),
1228 Title: "Medium Priority",
1229 },
1230 {
1231 Const: anyPtr("low"),
1232 Title: "Low Priority",
1233 },
1234 },
1235 },
1236 },
1237 },
1238 },
1239 },
1240 }
1241
1242 for _, tc := range validSchemas {
1243 t.Run("valid_"+tc.name, func(t *testing.T) {
1244 _, err := ss.Elicit(ctx, &ElicitParams{
1245 Message: "Test valid schema: " + tc.name,
1246 RequestedSchema: tc.schema,
1247 })
1248 if err != nil {
1249 t.Errorf("expected no error for valid schema %q, got: %v", tc.name, err)
1250 }
1251 })
1252 }
1253
1254 // Test invalid schemas - these should return errors
1255 invalidSchemas := []struct {
1256 name string
1257 schema *jsonschema.Schema
1258 expectedError string
1259 }{
1260 {
1261 name: "root schema non-object type",
1262 schema: &jsonschema.Schema{
1263 Type: "string",
1264 },
1265 expectedError: "elicit schema must be of type 'object', got \"string\"",
1266 },
1267 {
1268 name: "nested object property",
1269 schema: &jsonschema.Schema{
1270 Type: "object",
1271 Properties: map[string]*jsonschema.Schema{
1272 "user": {
1273 Type: "object",
1274 Properties: map[string]*jsonschema.Schema{
1275 "name": {Type: "string"},
1276 },
1277 },
1278 },
1279 },
1280 expectedError: "elicit schema property \"user\" contains nested properties, only primitive properties are allowed",
1281 },
1282 {
1283 name: "property with explicit object type",
1284 schema: &jsonschema.Schema{
1285 Type: "object",
1286 Properties: map[string]*jsonschema.Schema{
1287 "config": {Type: "object"},
1288 },
1289 },
1290 expectedError: "elicit schema property \"config\" has unsupported type \"object\", only string, number, integer, boolean, and array are allowed",
1291 },
1292 {
1293 name: "array without items",
1294 schema: &jsonschema.Schema{
1295 Type: "object",
1296 Properties: map[string]*jsonschema.Schema{
1297 "items": {Type: "array"},
1298 },
1299 },
1300 expectedError: "elicit schema property \"items\" is array but missing 'items' definition",
1301 },
1302 {
1303 name: "array with integer items",
1304 schema: &jsonschema.Schema{
1305 Type: "object",
1306 Properties: map[string]*jsonschema.Schema{
1307 "items": {Type: "array", Items: &jsonschema.Schema{Type: "integer"}},
1308 },
1309 },
1310 expectedError: "elicit schema property \"items\" items have unsupported type \"integer\"",
1311 },
1312 {
1313 name: "array of generic strings",
1314 schema: &jsonschema.Schema{
1315 Type: "object",
1316 Properties: map[string]*jsonschema.Schema{
1317 "items": {Type: "array", Items: &jsonschema.Schema{Type: "string"}},
1318 },
1319 },
1320 expectedError: "elicit schema property \"items\" items must specify enum for untitled enums",
1321 },
1322 {
1323 name: "unsupported string format",
1324 schema: &jsonschema.Schema{
1325 Type: "object",
1326 Properties: map[string]*jsonschema.Schema{
1327 "phone": {Type: "string", Format: "phone"},
1328 },
1329 },
1330 expectedError: "elicit schema property \"phone\" has unsupported format \"phone\", only email, uri, date, and date-time are allowed",
1331 },
1332 {
1333 name: "unsupported type",
1334 schema: &jsonschema.Schema{
1335 Type: "object",
1336 Properties: map[string]*jsonschema.Schema{
1337 "data": {Type: "null"},
1338 },
1339 },
1340 expectedError: "elicit schema property \"data\" has unsupported type \"null\"",
1341 },
1342 {
1343 name: "string with invalid minLength",
1344 schema: &jsonschema.Schema{
1345 Type: "object",
1346 Properties: map[string]*jsonschema.Schema{
1347 "name": {Type: "string", MinLength: ptr(-1)},
1348 },
1349 },
1350 expectedError: "elicit schema property \"name\" has invalid minLength -1, must be non-negative",
1351 },
1352 {
1353 name: "string with invalid maxLength",
1354 schema: &jsonschema.Schema{
1355 Type: "object",
1356 Properties: map[string]*jsonschema.Schema{
1357 "name": {Type: "string", MaxLength: ptr(-5)},
1358 },
1359 },
1360 expectedError: "elicit schema property \"name\" has invalid maxLength -5, must be non-negative",
1361 },
1362 {
1363 name: "string with maxLength less than minLength",
1364 schema: &jsonschema.Schema{
1365 Type: "object",
1366 Properties: map[string]*jsonschema.Schema{
1367 "name": {Type: "string", MinLength: ptr(10), MaxLength: ptr(5)},
1368 },
1369 },
1370 expectedError: "elicit schema property \"name\" has maxLength 5 less than minLength 10",
1371 },
1372 {
1373 name: "number with maximum less than minimum",
1374 schema: &jsonschema.Schema{
1375 Type: "object",
1376 Properties: map[string]*jsonschema.Schema{
1377 "score": {Type: "number", Minimum: ptr(100.0), Maximum: ptr(50.0)},
1378 },
1379 },
1380 expectedError: "elicit schema property \"score\" has maximum 50 less than minimum 100",
1381 },
1382 {
1383 name: "boolean with invalid default",
1384 schema: &jsonschema.Schema{
1385 Type: "object",
1386 Properties: map[string]*jsonschema.Schema{
1387 "enabled": {Type: "boolean", Default: json.RawMessage(`"not-a-boolean"`)},
1388 },
1389 },
1390 expectedError: "elicit schema property \"enabled\" has invalid default value, must be a bool",
1391 },
1392 {
1393 name: "string with invalid default",
1394 schema: &jsonschema.Schema{
1395 Type: "object",
1396 Properties: map[string]*jsonschema.Schema{
1397 "enabled": {Type: "string", Default: json.RawMessage("true")},
1398 },
1399 },
1400 expectedError: "elicit schema property \"enabled\" has invalid default value, must be a string",
1401 },
1402 {
1403 name: "integer with invalid default",
1404 schema: &jsonschema.Schema{
1405 Type: "object",
1406 Properties: map[string]*jsonschema.Schema{
1407 "enabled": {Type: "integer", Default: json.RawMessage("true")},
1408 },
1409 },
1410 expectedError: "elicit schema property \"enabled\" has default value that cannot be interpreted as an int or float",
1411 },
1412 {
1413 name: "number with invalid default",
1414 schema: &jsonschema.Schema{
1415 Type: "object",
1416 Properties: map[string]*jsonschema.Schema{
1417 "enabled": {Type: "number", Default: json.RawMessage("true")},
1418 },
1419 },
1420 expectedError: "elicit schema property \"enabled\" has default value that cannot be interpreted as an int or float",
1421 },
1422 {
1423 name: "enum with mismatched enumNames length",
1424 schema: &jsonschema.Schema{
1425 Type: "object",
1426 Properties: map[string]*jsonschema.Schema{
1427 "priority": {
1428 Type: "string",
1429 Enum: []any{
1430 "high",
1431 "medium",
1432 "low",
1433 },
1434 Extra: map[string]any{
1435 "enumNames": []any{"High Priority", "Medium Priority"}, // Only 2 names for 3 values
1436 },
1437 },
1438 },
1439 },
1440 expectedError: "elicit schema property \"priority\" has 3 enum values but 2 enumNames, they must match",
1441 },
1442 {
1443 name: "enum with invalid enumNames type",
1444 schema: &jsonschema.Schema{
1445 Type: "object",
1446 Properties: map[string]*jsonschema.Schema{
1447 "status": {
1448 Type: "string",
1449 Enum: []any{
1450 "active",
1451 "inactive",
1452 },
1453 Extra: map[string]any{
1454 "enumNames": "not an array", // Should be array
1455 },
1456 },
1457 },
1458 },
1459 expectedError: "elicit schema property \"status\" has invalid enumNames type, must be an array",
1460 },
1461 {
1462 name: "enum without explicit type",
1463 schema: &jsonschema.Schema{
1464 Type: "object",
1465 Properties: map[string]*jsonschema.Schema{
1466 "priority": {
1467 Enum: []any{
1468 "high",
1469 "medium",
1470 "low",
1471 },
1472 },
1473 },
1474 },
1475 expectedError: "elicit schema property \"priority\" has unsupported type \"\", only string, number, integer, boolean, and array are allowed",
1476 },
1477 {
1478 name: "titled enum without const",
1479 schema: &jsonschema.Schema{
1480 Type: "object",
1481 Properties: map[string]*jsonschema.Schema{
1482 "priority": {
1483 Type: "string",
1484 OneOf: []*jsonschema.Schema{
1485 {
1486 Const: anyPtr("high"),
1487 Title: "High Priority",
1488 },
1489 {
1490 Type: "string",
1491 Title: "Other Priority",
1492 },
1493 },
1494 },
1495 },
1496 },
1497 expectedError: "elicit schema property \"priority\" oneOf has invalid entry: const is required for titled enum entries",
1498 },
1499 {
1500 name: "untyped property",
1501 schema: &jsonschema.Schema{
1502 Type: "object",
1503 Properties: map[string]*jsonschema.Schema{
1504 "data": {},
1505 },
1506 },
1507 expectedError: "elicit schema property \"data\" has unsupported type \"\", only string, number, integer, boolean, and array are allowed",
1508 },
1509 }
1510
1511 for _, tc := range invalidSchemas {
1512 t.Run("invalid_"+tc.name, func(t *testing.T) {
1513 _, err := ss.Elicit(ctx, &ElicitParams{
1514 Message: "Test invalid schema: " + tc.name,
1515 RequestedSchema: tc.schema,
1516 })
1517 if err == nil {
1518 t.Errorf("expected error for invalid schema %q, got nil", tc.name)
1519 return
1520 }
1521 if code := errorCode(err); code != jsonrpc.CodeInvalidParams {
1522 t.Errorf("got error code %d, want %d (CodeInvalidParams)", code, jsonrpc.CodeInvalidParams)
1523 }
1524 if !strings.Contains(err.Error(), tc.expectedError) {
1525 t.Errorf("error message %q does not contain expected text %q", err.Error(), tc.expectedError)
1526 }
1527 })
1528 }
1529 }
1530
1531 func TestElicitContentValidation(t *testing.T) {
1532 ctx := context.Background()
1533 ct, st := NewInMemoryTransports()
1534
1535 s := NewServer(testImpl, nil)
1536 ss, err := s.Connect(ctx, st, nil)
1537 if err != nil {
1538 t.Fatal(err)
1539 }
1540 defer ss.Close()
1541
1542 // Set up a client that exercises valid/invalid elicitation: the returned
1543 // Content from the handler ("potato") is validated against the schemas
1544 // defined in the testcases below.
1545 c := NewClient(testImpl, &ClientOptions{
1546 ElicitationHandler: func(context.Context, *ElicitRequest) (*ElicitResult, error) {
1547 return &ElicitResult{Action: "accept", Content: map[string]any{"test": "potato"}}, nil
1548 },
1549 })
1550 cs, err := c.Connect(ctx, ct, nil)
1551 if err != nil {
1552 t.Fatal(err)
1553 }
1554 defer cs.Close()
1555
1556 testcases := []struct {
1557 name string
1558 schema *jsonschema.Schema
1559 expectedError string
1560 }{
1561 {
1562 name: "string enum with schema not matching content",
1563 schema: &jsonschema.Schema{
1564 Type: "object",
1565 Properties: map[string]*jsonschema.Schema{
1566 "test": {
1567 Type: "string",
1568 OneOf: []*jsonschema.Schema{
1569 {
1570 Const: anyPtr("high"),
1571 Title: "High Priority",
1572 },
1573 },
1574 },
1575 },
1576 },
1577 expectedError: "oneOf: did not validate against any of",
1578 },
1579 {
1580 name: "string enum with schema matching content",
1581 schema: &jsonschema.Schema{
1582 Type: "object",
1583 Properties: map[string]*jsonschema.Schema{
1584 "test": {
1585 Type: "string",
1586 OneOf: []*jsonschema.Schema{
1587 {
1588 Const: anyPtr("potato"),
1589 Title: "Potato Priority",
1590 },
1591 },
1592 },
1593 },
1594 },
1595 expectedError: "",
1596 },
1597 }
1598 for _, tc := range testcases {
1599 t.Run(tc.name, func(t *testing.T) {
1600 _, err := ss.Elicit(ctx, &ElicitParams{
1601 Message: "Test schema: " + tc.name,
1602 RequestedSchema: tc.schema,
1603 })
1604 if tc.expectedError != "" {
1605 if err == nil {
1606 t.Errorf("expected error but got no error: %s", tc.expectedError)
1607 return
1608 }
1609 if !strings.Contains(err.Error(), tc.expectedError) {
1610 t.Errorf("error message %q does not contain expected text %q", err.Error(), tc.expectedError)
1611 }
1612 }
1613 })
1614 }
1615 }
1616
1617 func TestElicitationProgressToken(t *testing.T) {
1618 ctx := context.Background()
1619 ct, st := NewInMemoryTransports()
1620
1621 s := NewServer(testImpl, nil)
1622 ss, err := s.Connect(ctx, st, nil)
1623 if err != nil {
1624 t.Fatal(err)
1625 }
1626 defer ss.Close()
1627
1628 c := NewClient(testImpl, &ClientOptions{
1629 ElicitationHandler: func(context.Context, *ElicitRequest) (*ElicitResult, error) {
1630 return &ElicitResult{Action: "accept"}, nil
1631 },
1632 })
1633 cs, err := c.Connect(ctx, ct, nil)
1634 if err != nil {
1635 t.Fatal(err)
1636 }
1637 defer cs.Close()
1638
1639 params := &ElicitParams{
1640 Message: "Test progress token",
1641 Meta: Meta{},
1642 }
1643 params.SetProgressToken("test-token")
1644
1645 if token := params.GetProgressToken(); token != "test-token" {
1646 t.Errorf("got progress token %v, want %q", token, "test-token")
1647 }
1648
1649 _, err = ss.Elicit(ctx, params)
1650 if err != nil {
1651 t.Fatal(err)
1652 }
1653 }
1654
1655 func TestElicitationCapabilityDeclaration(t *testing.T) {
1656 ctx := context.Background()
1657
1658 t.Run("with handler", func(t *testing.T) {
1659 ct, st := NewInMemoryTransports()
1660
1661 // Client with ElicitationHandler should declare capability
1662 c := NewClient(testImpl, &ClientOptions{
1663 ElicitationHandler: func(context.Context, *ElicitRequest) (*ElicitResult, error) {
1664 return &ElicitResult{Action: "cancel"}, nil
1665 },
1666 })
1667
1668 s := NewServer(testImpl, nil)
1669 ss, err := s.Connect(ctx, st, nil)
1670 if err != nil {
1671 t.Fatal(err)
1672 }
1673 defer ss.Close()
1674
1675 cs, err := c.Connect(ctx, ct, nil)
1676 if err != nil {
1677 t.Fatal(err)
1678 }
1679 defer cs.Close()
1680
1681 // The client should have declared elicitation capability during initialization
1682 // We can verify this worked by successfully making an elicitation call
1683 result, err := ss.Elicit(ctx, &ElicitParams{
1684 Message: "Test capability",
1685 RequestedSchema: &jsonschema.Schema{Type: "object"},
1686 })
1687 if err != nil {
1688 t.Fatalf("elicitation should work when capability is declared, got error: %v", err)
1689 }
1690 if result.Action != "cancel" {
1691 t.Errorf("got action %q, want %q", result.Action, "cancel")
1692 }
1693 })
1694
1695 t.Run("without handler", func(t *testing.T) {
1696 ct, st := NewInMemoryTransports()
1697
1698 // Client without ElicitationHandler should not declare capability
1699 c := NewClient(testImpl, &ClientOptions{
1700 CreateMessageHandler: func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error) {
1701 return &CreateMessageResult{Model: "aModel", Content: &TextContent{}}, nil
1702 },
1703 })
1704
1705 s := NewServer(testImpl, nil)
1706 ss, err := s.Connect(ctx, st, nil)
1707 if err != nil {
1708 t.Fatal(err)
1709 }
1710 defer ss.Close()
1711
1712 cs, err := c.Connect(ctx, ct, nil)
1713 if err != nil {
1714 t.Fatal(err)
1715 }
1716 defer cs.Close()
1717
1718 // Elicitation should fail with UnsupportedMethod
1719 _, err = ss.Elicit(ctx, &ElicitParams{
1720 Message: "This should fail",
1721 RequestedSchema: &jsonschema.Schema{Type: "object"},
1722 })
1723
1724 if err == nil {
1725 t.Error("expected UnsupportedMethod error when no capability declared")
1726 }
1727 if code := errorCode(err); code != -1 {
1728 t.Errorf("got error code %d, want -1", code)
1729 }
1730 })
1731 }
1732
1733 func TestElicitationDefaultValues(t *testing.T) {
1734 ctx := context.Background()
1735 ct, st := NewInMemoryTransports()
1736
1737 s := NewServer(testImpl, nil)
1738 ss, err := s.Connect(ctx, st, nil)
1739 if err != nil {
1740 t.Fatal(err)
1741 }
1742 defer ss.Close()
1743
1744 c := NewClient(testImpl, &ClientOptions{
1745 ElicitationHandler: func(context.Context, *ElicitRequest) (*ElicitResult, error) {
1746 return &ElicitResult{Action: "accept", Content: map[string]any{"default": "response"}}, nil
1747 },
1748 })
1749 cs, err := c.Connect(ctx, ct, nil)
1750 if err != nil {
1751 t.Fatal(err)
1752 }
1753 defer cs.Close()
1754
1755 testcases := []struct {
1756 name string
1757 schema *jsonschema.Schema
1758 expected map[string]any
1759 }{
1760 {
1761 name: "boolean with default",
1762 schema: &jsonschema.Schema{
1763 Type: "object",
1764 Properties: map[string]*jsonschema.Schema{
1765 "key": {Type: "boolean", Default: json.RawMessage("true")},
1766 },
1767 },
1768 expected: map[string]any{"key": true, "default": "response"},
1769 },
1770 {
1771 name: "string with default",
1772 schema: &jsonschema.Schema{
1773 Type: "object",
1774 Properties: map[string]*jsonschema.Schema{
1775 "key": {Type: "string", Default: json.RawMessage("\"potato\"")},
1776 },
1777 },
1778 expected: map[string]any{"key": "potato", "default": "response"},
1779 },
1780 {
1781 name: "integer with default",
1782 schema: &jsonschema.Schema{
1783 Type: "object",
1784 Properties: map[string]*jsonschema.Schema{
1785 "key": {Type: "integer", Default: json.RawMessage("123")},
1786 },
1787 },
1788 expected: map[string]any{"key": float64(123), "default": "response"},
1789 },
1790 {
1791 name: "number with default",
1792 schema: &jsonschema.Schema{
1793 Type: "object",
1794 Properties: map[string]*jsonschema.Schema{
1795 "key": {Type: "number", Default: json.RawMessage("89.7")},
1796 },
1797 },
1798 expected: map[string]any{"key": float64(89.7), "default": "response"},
1799 },
1800 {
1801 name: "enum with default",
1802 schema: &jsonschema.Schema{
1803 Type: "object",
1804 Properties: map[string]*jsonschema.Schema{
1805 "key": {Type: "string", Enum: []any{"one", "two"}, Default: json.RawMessage("\"one\"")},
1806 },
1807 },
1808 expected: map[string]any{"key": "one", "default": "response"},
1809 },
1810 }
1811 for _, tc := range testcases {
1812 t.Run(tc.name, func(t *testing.T) {
1813 res, err := ss.Elicit(ctx, &ElicitParams{
1814 Message: "Test schema with defaults: " + tc.name,
1815 RequestedSchema: tc.schema,
1816 })
1817 if err != nil {
1818 t.Fatalf("expected no error for default schema %q, got: %v", tc.name, err)
1819 }
1820 if diff := cmp.Diff(tc.expected, res.Content); diff != "" {
1821 t.Errorf("%s: did not get expected value, -want +got:\n%s", tc.name, diff)
1822 }
1823 })
1824 }
1825 }
1826
1827 func TestKeepAliveFailure(t *testing.T) {
1828 synctest.Test(t, func(t *testing.T) {
1829 ctx := context.Background()
1830
1831 // This test doesn't pinpoint keepalive detected failures well due to the fact that in-memory transports
1832 // propagate `io.EOF` synchronously, causing the transport level connection to be closed immediately.
1833 // TODO: propose better transports that would allow testing this scenario precisely.
1834 ct, st := NewInMemoryTransports()
1835
1836 // Server without keepalive (to test one-sided keepalive)
1837 s := NewServer(testImpl, nil)
1838 AddTool(s, greetTool(), sayHi)
1839 ss, err := s.Connect(ctx, st, nil)
1840 if err != nil {
1841 t.Fatal(err)
1842 }
1843
1844 // Client with short keepalive
1845 clientOpts := &ClientOptions{
1846 KeepAlive: 50 * time.Millisecond,
1847 }
1848 c := NewClient(testImpl, clientOpts)
1849 cs, err := c.Connect(ctx, ct, nil)
1850 if err != nil {
1851 t.Fatal(err)
1852 }
1853 defer cs.Close()
1854
1855 // Let the connection establish properly first
1856 synctest.Wait()
1857
1858 // simulate ping failure
1859 ss.Close()
1860
1861 time.Sleep(100 * time.Millisecond)
1862 synctest.Wait()
1863
1864 _, err = cs.CallTool(ctx, &CallToolParams{
1865 Name: "greet",
1866 Arguments: map[string]any{"Name": "user"},
1867 })
1868 if err != nil && (errors.Is(err, ErrConnectionClosed) || strings.Contains(err.Error(), "connection closed")) {
1869 return // Test passed
1870 }
1871
1872 t.Errorf("expected connection to be closed by keepalive, but it wasn't. Last error: %v", err)
1873 })
1874 }
1875
1876 // TestKeepAliveFailure_Logged verifies that a keepalive ping failure is
1877 // reported via the configured slog.Logger instead of being silently dropped.
1878 // Regression test for #218.
1879 func TestKeepAliveFailure_Logged(t *testing.T) {
1880 synctest.Test(t, func(t *testing.T) {
1881 ctx := context.Background()
1882
1883 ct, st := NewInMemoryTransports()
1884
1885 // Server without keepalive.
1886 s := NewServer(testImpl, nil)
1887 AddTool(s, greetTool(), sayHi)
1888 ss, err := s.Connect(ctx, st, nil)
1889 if err != nil {
1890 t.Fatal(err)
1891 }
1892
1893 // Client with a short keepalive and a logger that writes to a
1894 // buffer so we can assert on its output.
1895 var buf bytes.Buffer
1896 clientOpts := &ClientOptions{
1897 KeepAlive: 50 * time.Millisecond,
1898 Logger: slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelError})),
1899 }
1900 c := NewClient(testImpl, clientOpts)
1901 cs, err := c.Connect(ctx, ct, nil)
1902 if err != nil {
1903 t.Fatal(err)
1904 }
1905 defer cs.Close()
1906
1907 synctest.Wait()
1908
1909 // Trigger a ping failure by closing the server side.
1910 ss.Close()
1911
1912 time.Sleep(100 * time.Millisecond)
1913 synctest.Wait()
1914
1915 got := buf.String() // slog serializes Write calls internally
1916 if !strings.Contains(got, "keepalive ping failed") {
1917 t.Errorf("expected keepalive failure to be logged, got log output:\n%s", got)
1918 }
1919 })
1920 }
1921
1922 func TestAddTool_DuplicateNoPanicAndNoDuplicate(t *testing.T) {
1923 // Adding the same tool pointer twice should not panic and should not
1924 // produce duplicates in the server's tool list.
1925 cs, _, cleanup := basicConnection(t, func(s *Server) {
1926 // Use two distinct Tool instances with the same name but different
1927 // descriptions to ensure the second replaces the first
1928 // This case was written specifically to reproduce a bug where duplicate tools where causing jsonschema errors
1929 t1 := &Tool{Name: "dup", Description: "first", InputSchema: &jsonschema.Schema{Type: "object"}}
1930 t2 := &Tool{Name: "dup", Description: "second", InputSchema: &jsonschema.Schema{Type: "object"}}
1931 s.AddTool(t1, nopHandler)
1932 s.AddTool(t2, nopHandler)
1933 })
1934 defer cleanup()
1935
1936 ctx := context.Background()
1937 res, err := cs.ListTools(ctx, nil)
1938 if err != nil {
1939 t.Fatal(err)
1940 }
1941 var count int
1942 var gotDesc string
1943 for _, tt := range res.Tools {
1944 if tt.Name == "dup" {
1945 count++
1946 gotDesc = tt.Description
1947 }
1948 }
1949 if count != 1 {
1950 t.Fatalf("expected exactly one 'dup' tool, got %d", count)
1951 }
1952 if gotDesc != "second" {
1953 t.Fatalf("expected replaced tool to have description %q, got %q", "second", gotDesc)
1954 }
1955 }
1956
1957 func TestSynchronousNotifications(t *testing.T) {
1958 synctest.Test(t, func(t *testing.T) {
1959 var toolsChanged atomic.Int32
1960 clientOpts := &ClientOptions{
1961 ToolListChangedHandler: func(ctx context.Context, req *ToolListChangedRequest) {
1962 toolsChanged.Add(1)
1963 },
1964 CreateMessageHandler: func(ctx context.Context, req *CreateMessageRequest) (*CreateMessageResult, error) {
1965 // See the comment after "from server" below.
1966 if n := toolsChanged.Load(); n != 1 {
1967 return nil, fmt.Errorf("got %d tools-changed notification, wanted 1", n)
1968 }
1969 // TODO(rfindley): investigate the error returned from this test if
1970 // CreateMessageResult is new(CreateMessageResult): it's a mysterious
1971 // unmarshalling error that we should improve.
1972 return &CreateMessageResult{Content: &TextContent{}}, nil
1973 },
1974 }
1975 client := NewClient(testImpl, clientOpts)
1976
1977 var rootsChanged atomic.Bool
1978 serverOpts := &ServerOptions{
1979 RootsListChangedHandler: func(_ context.Context, req *RootsListChangedRequest) {
1980 rootsChanged.Store(true)
1981 },
1982 }
1983 server := NewServer(testImpl, serverOpts)
1984 addTool := func(s *Server) {
1985 AddTool(s, &Tool{Name: "tool"}, func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
1986 if !rootsChanged.Load() {
1987 return nil, nil, fmt.Errorf("didn't get root change notification")
1988 }
1989 return new(CallToolResult), nil, nil
1990 })
1991 }
1992 cs, ss, cleanup := basicClientServerConnection(t, client, server, addTool)
1993 defer cleanup()
1994
1995 t.Log("from client")
1996 {
1997 client.AddRoots(&Root{Name: "myroot", URI: "file://foo"})
1998 res, err := cs.CallTool(context.Background(), &CallToolParams{Name: "tool"})
1999 if err != nil {
2000 t.Fatalf("CallTool failed: %v", err)
2001 }
2002 if res.IsError {
2003 t.Errorf("tool error: %v", res.Content[0].(*TextContent).Text)
2004 }
2005 }
2006
2007 t.Log("from server")
2008 {
2009 // Despite all this tool-changed activity, we expect only one notification.
2010 for range 10 {
2011 server.RemoveTools("tool")
2012 addTool(server)
2013 }
2014
2015 time.Sleep(notificationDelay * 2) // Wait for delayed notification.
2016 if _, err := ss.CreateMessage(context.Background(), new(CreateMessageParams)); err != nil {
2017 t.Errorf("CreateMessage failed: %v", err)
2018 }
2019 }
2020
2021 })
2022 }
2023
2024 func TestNoDistributedDeadlock(t *testing.T) {
2025 synctest.Test(t, func(t *testing.T) {
2026 // This test verifies that calls are asynchronous, and so it's not possible
2027 // to have a distributed deadlock.
2028 //
2029 // The setup creates potential deadlock for both the client and server: the
2030 // client sends a call to tool1, which itself calls createMessage, which in
2031 // turn calls tool2, which calls ping.
2032 //
2033 // If the server were not asynchronous, the call to tool2 would hang. If the
2034 // client were not asynchronous, the call to ping would hang.
2035 //
2036 // Such a scenario is unlikely in practice, but is still theoretically
2037 // possible, and in any case making tool calls asynchronous by default
2038 // delegates synchronization to the user.
2039 clientOpts := &ClientOptions{
2040 CreateMessageHandler: func(ctx context.Context, req *CreateMessageRequest) (*CreateMessageResult, error) {
2041 req.Session.CallTool(ctx, &CallToolParams{Name: "tool2"})
2042 return &CreateMessageResult{Content: &TextContent{}}, nil
2043 },
2044 }
2045 client := NewClient(testImpl, clientOpts)
2046 cs, _, cleanup := basicClientServerConnection(t, client, nil, func(s *Server) {
2047 AddTool(s, &Tool{Name: "tool1"}, func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
2048 req.Session.CreateMessage(ctx, new(CreateMessageParams))
2049 return new(CallToolResult), nil, nil
2050 })
2051 AddTool(s, &Tool{Name: "tool2"}, func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) {
2052 req.Session.Ping(ctx, nil)
2053 return new(CallToolResult), nil, nil
2054 })
2055 })
2056 defer cleanup()
2057
2058 if _, err := cs.CallTool(context.Background(), &CallToolParams{Name: "tool1"}); err != nil {
2059 // should not deadlock
2060 t.Fatalf("CallTool failed: %v", err)
2061 }
2062 })
2063 }
2064
2065 var testImpl = &Implementation{Name: "test", Version: "v1.0.0"}
2066
2067 // This test checks that when we use pointer types for tools, we get the same
2068 // schema as when using the non-pointer types. It is too much of a footgun for
2069 // there to be a difference (see #199 and #200).
2070 //
2071 // If anyone asks, we can add an option that controls how pointers are treated.
2072 func TestPointerArgEquivalence(t *testing.T) {
2073 type input struct {
2074 In string `json:",omitempty"`
2075 }
2076 type output struct {
2077 Out string
2078 }
2079 cs, _, cleanup := basicConnection(t, func(s *Server) {
2080 // Add two equivalent tools, one of which operates in the 'pointer' realm,
2081 // the other of which does not.
2082 //
2083 // We handle a few different types of results, to assert they behave the
2084 // same in all cases.
2085 AddTool(s, &Tool{Name: "pointer"}, func(_ context.Context, req *CallToolRequest, in *input) (*CallToolResult, *output, error) {
2086 switch in.In {
2087 case "":
2088 return nil, nil, fmt.Errorf("must provide input")
2089 case "nil":
2090 return nil, nil, nil
2091 case "empty":
2092 return &CallToolResult{}, nil, nil
2093 case "ok":
2094 return &CallToolResult{}, &output{Out: "foo"}, nil
2095 default:
2096 panic("unreachable")
2097 }
2098 })
2099 AddTool(s, &Tool{Name: "nonpointer"}, func(_ context.Context, req *CallToolRequest, in input) (*CallToolResult, output, error) {
2100 switch in.In {
2101 case "":
2102 return nil, output{}, fmt.Errorf("must provide input")
2103 case "nil":
2104 return nil, output{}, nil
2105 case "empty":
2106 return &CallToolResult{}, output{}, nil
2107 case "ok":
2108 return &CallToolResult{}, output{Out: "foo"}, nil
2109 default:
2110 panic("unreachable")
2111 }
2112 })
2113 })
2114 defer cleanup()
2115
2116 ctx := context.Background()
2117 tools, err := cs.ListTools(ctx, nil)
2118 if err != nil {
2119 t.Fatal(err)
2120 }
2121 if got, want := len(tools.Tools), 2; got != want {
2122 t.Fatalf("got %d tools, want %d", got, want)
2123 }
2124 t0 := tools.Tools[0]
2125 t1 := tools.Tools[1]
2126
2127 // First, check that the tool schemas don't differ.
2128 if diff := cmp.Diff(t0.InputSchema, t1.InputSchema); diff != "" {
2129 t.Errorf("input schemas do not match (-%s +%s):\n%s", t0.Name, t1.Name, diff)
2130 }
2131 if diff := cmp.Diff(t0.OutputSchema, t1.OutputSchema); diff != "" {
2132 t.Errorf("output schemas do not match (-%s +%s):\n%s", t0.Name, t1.Name, diff)
2133 }
2134
2135 // Then, check that we handle empty input equivalently.
2136 for _, args := range []any{nil, struct{}{}} {
2137 r0, err := cs.CallTool(ctx, &CallToolParams{Name: t0.Name, Arguments: args})
2138 if err != nil {
2139 t.Fatal(err)
2140 }
2141 r1, err := cs.CallTool(ctx, &CallToolParams{Name: t1.Name, Arguments: args})
2142 if err != nil {
2143 t.Fatal(err)
2144 }
2145 if diff := cmp.Diff(r0, r1, ctrCmpOpts...); diff != "" {
2146 t.Errorf("CallTool(%v) with no arguments mismatch (-%s +%s):\n%s", args, t0.Name, t1.Name, diff)
2147 }
2148 }
2149
2150 // Then, check that we handle different types of output equivalently.
2151 for _, in := range []string{"nil", "empty", "ok"} {
2152 t.Run(in, func(t *testing.T) {
2153 r0, err := cs.CallTool(ctx, &CallToolParams{Name: t0.Name, Arguments: input{In: in}})
2154 if err != nil {
2155 t.Fatal(err)
2156 }
2157 r1, err := cs.CallTool(ctx, &CallToolParams{Name: t1.Name, Arguments: input{In: in}})
2158 if err != nil {
2159 t.Fatal(err)
2160 }
2161 if diff := cmp.Diff(r0, r1, ctrCmpOpts...); diff != "" {
2162 t.Errorf("CallTool({\"In\": %q}) mismatch (-%s +%s):\n%s", in, t0.Name, t1.Name, diff)
2163 }
2164 })
2165 }
2166 }
2167
2168 // ptr is a helper function to create pointers for schema constraints
2169 func ptr[T any](v T) *T {
2170 return &v
2171 }
2172
2173 func TestComplete(t *testing.T) {
2174 completionValues := []string{"python", "pytorch", "pyside"}
2175
2176 serverOpts := &ServerOptions{
2177 CompletionHandler: func(_ context.Context, request *CompleteRequest) (*CompleteResult, error) {
2178 return &CompleteResult{
2179 Completion: CompletionResultDetails{
2180 Values: completionValues,
2181 },
2182 }, nil
2183 },
2184 }
2185 server := NewServer(testImpl, serverOpts)
2186 cs, _, cleanup := basicClientServerConnection(t, nil, server, func(s *Server) {})
2187 defer cleanup()
2188
2189 result, err := cs.Complete(context.Background(), &CompleteParams{
2190 Argument: CompleteParamsArgument{
2191 Name: "language",
2192 Value: "py",
2193 },
2194 Ref: &CompleteReference{
2195 Type: "ref/prompt",
2196 Name: "code_review",
2197 },
2198 })
2199 if err != nil {
2200 t.Fatal(err)
2201 }
2202
2203 if diff := cmp.Diff(completionValues, result.Completion.Values); diff != "" {
2204 t.Errorf("Complete() mismatch (-want +got):\n%s", diff)
2205 }
2206 }
2207
2208 // TestEmbeddedStructResponse performs a tool call to verify that a struct with
2209 // an embedded pointer generates a correct, flattened JSON schema and that its
2210 // response is validated successfully.
2211 func TestEmbeddedStructResponse(t *testing.T) {
2212 type foo struct {
2213 ID string `json:"id"`
2214 Name string `json:"name"`
2215 }
2216
2217 // bar embeds foo
2218 type bar struct {
2219 *foo // Embedded - should flatten in JSON
2220 Extra string `json:"extra"`
2221 }
2222
2223 type response struct {
2224 Data bar `json:"data"`
2225 }
2226
2227 // testTool demonstrates an embedded struct in its response.
2228 testTool := func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, response, error) {
2229 response := response{
2230 Data: bar{
2231 foo: &foo{
2232 ID: "foo",
2233 Name: "Test Foo",
2234 },
2235 Extra: "additional data",
2236 },
2237 }
2238 return nil, response, nil
2239 }
2240 ctx := context.Background()
2241 clientTransport, serverTransport := NewInMemoryTransports()
2242 server := NewServer(&Implementation{Name: "testServer", Version: "v1.0.0"}, nil)
2243 AddTool(server, &Tool{
2244 Name: "test_embedded_struct",
2245 }, testTool)
2246
2247 serverSession, err := server.Connect(ctx, serverTransport, nil)
2248 if err != nil {
2249 t.Fatal(err)
2250 }
2251 defer serverSession.Close()
2252
2253 client := NewClient(&Implementation{Name: "test-client"}, nil)
2254 clientSession, err := client.Connect(ctx, clientTransport, nil)
2255 if err != nil {
2256 t.Fatal(err)
2257 }
2258 defer clientSession.Close()
2259
2260 _, err = clientSession.CallTool(ctx, &CallToolParams{
2261 Name: "test_embedded_struct",
2262 })
2263 if err != nil {
2264 t.Errorf("CallTool() failed: %v", err)
2265 }
2266 }
2267
2268 func TestToolErrorMiddleware(t *testing.T) {
2269 ctx := context.Background()
2270 ct, st := NewInMemoryTransports()
2271
2272 s := NewServer(testImpl, nil)
2273 AddTool(s, &Tool{
2274 Name: "greet",
2275 Description: "say hi",
2276 }, sayHi)
2277 AddTool(s, &Tool{Name: "fail", InputSchema: &jsonschema.Schema{Type: "object"}},
2278 func(context.Context, *CallToolRequest, map[string]any) (*CallToolResult, any, error) {
2279 return nil, nil, errTestFailure
2280 })
2281
2282 var middleErr error
2283 s.AddReceivingMiddleware(func(h MethodHandler) MethodHandler {
2284 return func(ctx context.Context, method string, req Request) (Result, error) {
2285 res, err := h(ctx, method, req)
2286 if err == nil {
2287 if ctr, ok := res.(*CallToolResult); ok {
2288 middleErr = ctr.GetError()
2289 }
2290 }
2291 return res, err
2292 }
2293 })
2294 _, err := s.Connect(ctx, st, nil)
2295 if err != nil {
2296 t.Fatal(err)
2297 }
2298 client := NewClient(&Implementation{Name: "test-client"}, nil)
2299 clientSession, err := client.Connect(ctx, ct, nil)
2300 if err != nil {
2301 t.Fatal(err)
2302 }
2303 defer clientSession.Close()
2304
2305 _, err = clientSession.CallTool(ctx, &CallToolParams{
2306 Name: "greet",
2307 Arguments: map[string]any{"Name": "al"},
2308 })
2309 if err != nil {
2310 t.Errorf("CallTool() failed: %v", err)
2311 }
2312 if middleErr != nil {
2313 t.Errorf("middleware got error %v, want nil", middleErr)
2314 }
2315 res, err := clientSession.CallTool(ctx, &CallToolParams{
2316 Name: "fail",
2317 })
2318 if err != nil {
2319 t.Errorf("CallTool() failed: %v", err)
2320 }
2321 if !res.IsError {
2322 t.Fatal("want error, got none")
2323 }
2324 // Clients can't see the error, because it isn't marshaled.
2325 if err := res.GetError(); err != nil {
2326 t.Fatalf("got %v, want nil", err)
2327 }
2328 if middleErr != errTestFailure {
2329 t.Errorf("middleware got err %v, want errTestFailure", middleErr)
2330 }
2331 }
2332
2333 func TestSetErrorPreservesContent(t *testing.T) {
2334 for _, tt := range []struct {
2335 name string
2336 content []Content
2337 err error
2338 wantContent string
2339 }{
2340 {
2341 name: "nil content",
2342 err: errors.New("internal failure"),
2343 wantContent: "internal failure",
2344 },
2345 {
2346 name: "empty slice content",
2347 content: []Content{},
2348 err: errors.New("internal failure"),
2349 wantContent: "internal failure",
2350 },
2351 {
2352 name: "existing content preserved",
2353 content: []Content{&TextContent{Text: "user-friendly msg"}},
2354 err: errors.New("db timeout"),
2355 wantContent: "user-friendly msg",
2356 },
2357 } {
2358 t.Run(tt.name, func(t *testing.T) {
2359 res := CallToolResult{Content: tt.content}
2360 res.SetError(tt.err)
2361 if !res.IsError {
2362 t.Fatal("want IsError=true")
2363 }
2364 if got := res.Content[0].(*TextContent).Text; got != tt.wantContent {
2365 t.Errorf("Content text = %q, want %q", got, tt.wantContent)
2366 }
2367 if got := res.GetError(); got != tt.err {
2368 t.Errorf("GetError() = %v, want %v", got, tt.err)
2369 }
2370 })
2371 }
2372 }
2373
2374 var ctrCmpOpts = []cmp.Option{cmp.AllowUnexported(CallToolResult{})}