Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/server_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 "log"
12 "log/slog"
13 "slices"
14 "strings"
15 "testing"
16 "time"
17
18 "github.com/google/go-cmp/cmp"
19 "github.com/google/jsonschema-go/jsonschema"
20 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
21 )
22
23 type testItem struct {
24 Name string
25 Value string
26 }
27
28 type testListParams struct {
29 Cursor string
30 }
31
32 func (p *testListParams) cursorPtr() *string {
33 return &p.Cursor
34 }
35
36 type testListResult struct {
37 Items []*testItem
38 NextCursor string
39 }
40
41 func (r *testListResult) nextCursorPtr() *string {
42 return &r.NextCursor
43 }
44
45 var allTestItems = []*testItem{
46 {"alpha", "val-A"},
47 {"bravo", "val-B"},
48 {"charlie", "val-C"},
49 {"delta", "val-D"},
50 {"echo", "val-E"},
51 {"foxtrot", "val-F"},
52 {"golf", "val-G"},
53 {"hotel", "val-H"},
54 {"india", "val-I"},
55 {"juliet", "val-J"},
56 {"kilo", "val-K"},
57 }
58
59 // getCursor encodes a string input into a URL-safe base64 cursor,
60 // fatally logging any encoding errors.
61 func getCursor(input string) string {
62 cursor, err := encodeCursor(input)
63 if err != nil {
64 log.Fatalf("encodeCursor(%s) error = %v", input, err)
65 }
66 return cursor
67 }
68
69 func TestServerPaginateBasic(t *testing.T) {
70 testCases := []struct {
71 name string
72 initialItems []*testItem
73 inputCursor string
74 inputPageSize int
75 wantFeatures []*testItem
76 wantNextCursor string
77 wantErr bool
78 }{
79 {
80 name: "FirstPage_DefaultSize_Full",
81 initialItems: allTestItems,
82 inputCursor: "",
83 inputPageSize: 5,
84 wantFeatures: allTestItems[0:5],
85 wantNextCursor: getCursor("echo"), // Based on last item of first page
86 wantErr: false,
87 },
88 {
89 name: "SecondPage_DefaultSize_Full",
90 initialItems: allTestItems,
91 inputCursor: getCursor("echo"),
92 inputPageSize: 5,
93 wantFeatures: allTestItems[5:10],
94 wantNextCursor: getCursor("juliet"), // Based on last item of second page
95 wantErr: false,
96 },
97 {
98 name: "SecondPage_DefaultSize_Full_OutOfOrder",
99 initialItems: append(allTestItems[5:], allTestItems[0:5]...),
100 inputCursor: getCursor("echo"),
101 inputPageSize: 5,
102 wantFeatures: allTestItems[5:10],
103 wantNextCursor: getCursor("juliet"), // Based on last item of second page
104 wantErr: false,
105 },
106 {
107 name: "SecondPage_DefaultSize_Full_Duplicates",
108 initialItems: append(allTestItems, allTestItems[0:5]...),
109 inputCursor: getCursor("echo"),
110 inputPageSize: 5,
111 wantFeatures: allTestItems[5:10],
112 wantNextCursor: getCursor("juliet"), // Based on last item of second page
113 wantErr: false,
114 },
115 {
116 name: "LastPage_Remaining",
117 initialItems: allTestItems,
118 inputCursor: getCursor("juliet"),
119 inputPageSize: 5,
120 wantFeatures: allTestItems[10:11], // Only 1 item left
121 wantNextCursor: "", // No more pages
122 wantErr: false,
123 },
124 {
125 name: "PageSize_1",
126 initialItems: allTestItems,
127 inputCursor: "",
128 inputPageSize: 1,
129 wantFeatures: allTestItems[0:1],
130 wantNextCursor: getCursor("alpha"),
131 wantErr: false,
132 },
133 {
134 name: "PageSize_All",
135 initialItems: allTestItems,
136 inputCursor: "",
137 inputPageSize: len(allTestItems), // Page size equals total
138 wantFeatures: allTestItems,
139 wantNextCursor: "", // No more pages
140 wantErr: false,
141 },
142 {
143 name: "PageSize_LargerThanAll",
144 initialItems: allTestItems,
145 inputCursor: "",
146 inputPageSize: len(allTestItems) + 5, // Page size larger than total
147 wantFeatures: allTestItems,
148 wantNextCursor: "",
149 wantErr: false,
150 },
151 {
152 name: "EmptySet",
153 initialItems: nil,
154 inputCursor: "",
155 inputPageSize: 5,
156 wantFeatures: nil,
157 wantNextCursor: "",
158 wantErr: false,
159 },
160 {
161 name: "InvalidCursor",
162 initialItems: allTestItems,
163 inputCursor: "not-a-valid-gob-base64-cursor",
164 inputPageSize: 5,
165 wantFeatures: nil, // Should be nil for error cases
166 wantNextCursor: "",
167 wantErr: true,
168 },
169 {
170 name: "AboveNonExistentID",
171 initialItems: allTestItems,
172 inputCursor: getCursor("dne"), // A UID that doesn't exist
173 inputPageSize: 5,
174 wantFeatures: allTestItems[4:9], // Should return elements above UID.
175 wantNextCursor: getCursor("india"),
176 wantErr: false,
177 },
178 }
179
180 for _, tc := range testCases {
181 t.Run(tc.name, func(t *testing.T) {
182 fs := newFeatureSet(func(t *testItem) string { return t.Name })
183 fs.add(tc.initialItems...)
184 params := &testListParams{Cursor: tc.inputCursor}
185 gotResult, err := paginateList(fs, tc.inputPageSize, params, &testListResult{}, func(res *testListResult, items []*testItem) {
186 res.Items = items
187 })
188 if (err != nil) != tc.wantErr {
189 t.Errorf("paginateList(%s) error, got %v, wantErr %v", tc.name, err, tc.wantErr)
190 }
191 if tc.wantErr {
192 return
193 }
194 if diff := cmp.Diff(tc.wantFeatures, gotResult.Items); diff != "" {
195 t.Errorf("paginateList(%s) mismatch (-want +got):\n%s", tc.name, diff)
196 }
197 if tc.wantNextCursor != gotResult.NextCursor {
198 t.Errorf("paginateList(%s) nextCursor, got %v, want %v", tc.name, gotResult.NextCursor, tc.wantNextCursor)
199 }
200 })
201 }
202 }
203
204 func TestServerPaginateVariousPageSizes(t *testing.T) {
205 fs := newFeatureSet(func(t *testItem) string { return t.Name })
206 fs.add(allTestItems...)
207 // Try all possible page sizes, ensuring we get the correct list of items.
208 for pageSize := 1; pageSize < len(allTestItems)+1; pageSize++ {
209 var gotItems []*testItem
210 var nextCursor string
211 wantChunks := slices.Collect(slices.Chunk(allTestItems, pageSize))
212 index := 0
213 // Iterate through all pages, comparing sub-slices to the paginated list.
214 for {
215 params := &testListParams{Cursor: nextCursor}
216 gotResult, err := paginateList(fs, pageSize, params, &testListResult{}, func(res *testListResult, items []*testItem) {
217 res.Items = items
218 })
219 if err != nil {
220 t.Fatalf("paginateList() unexpected error for pageSize %d, cursor %q: %v", pageSize, nextCursor, err)
221 }
222 if diff := cmp.Diff(wantChunks[index], gotResult.Items); diff != "" {
223 t.Errorf("paginateList mismatch (-want +got):\n%s", diff)
224 }
225 gotItems = append(gotItems, gotResult.Items...)
226 nextCursor = gotResult.NextCursor
227 if nextCursor == "" {
228 break
229 }
230 index++
231 }
232
233 if len(gotItems) != len(allTestItems) {
234 t.Fatalf("paginateList() returned %d items, want %d", len(allTestItems), len(gotItems))
235 }
236 }
237 }
238
239 func TestServerCapabilities(t *testing.T) {
240 tool := &Tool{Name: "t", InputSchema: &jsonschema.Schema{Type: "object"}}
241 testCases := []struct {
242 name string
243 configureServer func(s *Server)
244 serverOpts ServerOptions
245 wantCapabilities *ServerCapabilities
246 }{
247 {
248 name: "no capabilities",
249 configureServer: func(s *Server) {},
250 wantCapabilities: &ServerCapabilities{
251 Logging: &LoggingCapabilities{},
252 },
253 },
254 {
255 name: "with prompts",
256 configureServer: func(s *Server) {
257 s.AddPrompt(&Prompt{Name: "p"}, nil)
258 },
259 wantCapabilities: &ServerCapabilities{
260 Logging: &LoggingCapabilities{},
261 Prompts: &PromptCapabilities{ListChanged: true},
262 },
263 },
264 {
265 name: "with resources",
266 configureServer: func(s *Server) {
267 s.AddResource(&Resource{URI: "file:///r"}, nil)
268 },
269 wantCapabilities: &ServerCapabilities{
270 Logging: &LoggingCapabilities{},
271 Resources: &ResourceCapabilities{ListChanged: true},
272 },
273 },
274 {
275 name: "with resource templates",
276 configureServer: func(s *Server) {
277 s.AddResourceTemplate(&ResourceTemplate{URITemplate: "file:///rt"}, nil)
278 },
279 wantCapabilities: &ServerCapabilities{
280 Logging: &LoggingCapabilities{},
281 Resources: &ResourceCapabilities{ListChanged: true},
282 },
283 },
284 {
285 name: "with resource subscriptions",
286 configureServer: func(s *Server) {
287 s.AddResourceTemplate(&ResourceTemplate{URITemplate: "file:///rt"}, nil)
288 },
289 serverOpts: ServerOptions{
290 SubscribeHandler: func(context.Context, *SubscribeRequest) error {
291 return nil
292 },
293 UnsubscribeHandler: func(context.Context, *UnsubscribeRequest) error {
294 return nil
295 },
296 },
297 wantCapabilities: &ServerCapabilities{
298 Logging: &LoggingCapabilities{},
299 Resources: &ResourceCapabilities{ListChanged: true, Subscribe: true},
300 },
301 },
302 {
303 name: "with tools",
304 configureServer: func(s *Server) {
305 s.AddTool(tool, nil)
306 },
307 wantCapabilities: &ServerCapabilities{
308 Logging: &LoggingCapabilities{},
309 Tools: &ToolCapabilities{ListChanged: true},
310 },
311 },
312 {
313 name: "with completions",
314 configureServer: func(s *Server) {},
315 serverOpts: ServerOptions{
316 CompletionHandler: func(context.Context, *CompleteRequest) (*CompleteResult, error) {
317 return nil, nil
318 },
319 },
320 wantCapabilities: &ServerCapabilities{
321 Logging: &LoggingCapabilities{},
322 Completions: &CompletionCapabilities{},
323 },
324 },
325 {
326 name: "all capabilities",
327 configureServer: func(s *Server) {
328 s.AddPrompt(&Prompt{Name: "p"}, nil)
329 s.AddResource(&Resource{URI: "file:///r"}, nil)
330 s.AddResourceTemplate(&ResourceTemplate{URITemplate: "file:///rt"}, nil)
331 s.AddTool(tool, nil)
332 },
333 serverOpts: ServerOptions{
334 SubscribeHandler: func(context.Context, *SubscribeRequest) error {
335 return nil
336 },
337 UnsubscribeHandler: func(context.Context, *UnsubscribeRequest) error {
338 return nil
339 },
340 CompletionHandler: func(context.Context, *CompleteRequest) (*CompleteResult, error) {
341 return nil, nil
342 },
343 },
344 wantCapabilities: &ServerCapabilities{
345 Completions: &CompletionCapabilities{},
346 Logging: &LoggingCapabilities{},
347 Prompts: &PromptCapabilities{ListChanged: true},
348 Resources: &ResourceCapabilities{ListChanged: true, Subscribe: true},
349 Tools: &ToolCapabilities{ListChanged: true},
350 },
351 },
352 {
353 name: "has features",
354 configureServer: func(s *Server) {},
355 serverOpts: ServerOptions{
356 HasPrompts: true,
357 HasResources: true,
358 HasTools: true,
359 },
360 wantCapabilities: &ServerCapabilities{
361 Logging: &LoggingCapabilities{},
362 Prompts: &PromptCapabilities{ListChanged: true},
363 Resources: &ResourceCapabilities{ListChanged: true},
364 Tools: &ToolCapabilities{ListChanged: true},
365 },
366 },
367 {
368 name: "empty capabilities",
369 configureServer: func(s *Server) {},
370 serverOpts: ServerOptions{
371 Capabilities: &ServerCapabilities{},
372 },
373 wantCapabilities: &ServerCapabilities{},
374 },
375 {
376 name: "no logging",
377 configureServer: func(s *Server) {},
378 serverOpts: ServerOptions{
379 Capabilities: &ServerCapabilities{
380 Tools: &ToolCapabilities{ListChanged: true},
381 },
382 },
383 wantCapabilities: &ServerCapabilities{
384 Tools: &ToolCapabilities{ListChanged: true},
385 },
386 },
387 {
388 name: "no list",
389 configureServer: func(s *Server) {},
390 serverOpts: ServerOptions{
391 Capabilities: &ServerCapabilities{
392 Tools: &ToolCapabilities{ListChanged: false},
393 Prompts: &PromptCapabilities{ListChanged: false},
394 },
395 },
396 wantCapabilities: &ServerCapabilities{
397 Tools: &ToolCapabilities{ListChanged: false},
398 Prompts: &PromptCapabilities{ListChanged: false},
399 },
400 },
401 {
402 name: "adding tools-list",
403 configureServer: func(s *Server) {
404 s.AddTool(tool, nil)
405 },
406 serverOpts: ServerOptions{
407 Capabilities: &ServerCapabilities{
408 Logging: &LoggingCapabilities{},
409 },
410 },
411 wantCapabilities: &ServerCapabilities{
412 Logging: &LoggingCapabilities{},
413 Tools: &ToolCapabilities{ListChanged: true},
414 },
415 },
416 {
417 name: "adding tools-no list",
418 configureServer: func(s *Server) {
419 s.AddTool(tool, nil)
420 },
421 serverOpts: ServerOptions{
422 Capabilities: &ServerCapabilities{
423 Tools: &ToolCapabilities{ListChanged: false},
424 },
425 },
426 wantCapabilities: &ServerCapabilities{
427 Tools: &ToolCapabilities{ListChanged: false},
428 },
429 },
430 {
431 name: "experimental preserved",
432 configureServer: func(s *Server) {},
433 serverOpts: ServerOptions{
434 Capabilities: &ServerCapabilities{
435 Experimental: map[string]any{"custom": "value"},
436 Logging: &LoggingCapabilities{},
437 },
438 },
439 wantCapabilities: &ServerCapabilities{
440 Experimental: map[string]any{"custom": "value"},
441 Logging: &LoggingCapabilities{},
442 },
443 },
444 {
445 name: "extensions preserved",
446 configureServer: func(s *Server) {},
447 serverOpts: func() ServerOptions {
448 caps := &ServerCapabilities{
449 Logging: &LoggingCapabilities{},
450 }
451 caps.AddExtension("io.example/ext1", map[string]any{"key": "value"})
452 caps.AddExtension("io.example/ext2", nil)
453 return ServerOptions{Capabilities: caps}
454 }(),
455 wantCapabilities: &ServerCapabilities{
456 Extensions: map[string]any{
457 "io.example/ext1": map[string]any{"key": "value"},
458 "io.example/ext2": map[string]any{},
459 },
460 Logging: &LoggingCapabilities{},
461 },
462 },
463 }
464
465 for _, tc := range testCases {
466 t.Run(tc.name, func(t *testing.T) {
467 server := NewServer(testImpl, &tc.serverOpts)
468 tc.configureServer(server)
469 gotCapabilities := server.capabilities()
470 if diff := cmp.Diff(tc.wantCapabilities, gotCapabilities); diff != "" {
471 t.Errorf("capabilities() mismatch (-want +got):\n%s", diff)
472 }
473 })
474 }
475 }
476
477 func TestServerAddResourceTemplate(t *testing.T) {
478 tests := []struct {
479 name string
480 template string
481 expectPanic bool
482 }{
483 {"ValidFileTemplate", "file:///{a}/{b}", false},
484 {"ValidCustomScheme", "myproto:///{a}", false},
485 {"EmptyVariable", "file:///{}/{b}", true},
486 {"UnclosedVariable", "file:///{a", true},
487 }
488
489 for _, tt := range tests {
490 t.Run(tt.name, func(t *testing.T) {
491 rt := ResourceTemplate{URITemplate: tt.template}
492
493 defer func() {
494 if r := recover(); r != nil {
495 if !tt.expectPanic {
496 t.Errorf("%s: unexpected panic: %v", tt.name, r)
497 }
498 } else {
499 if tt.expectPanic {
500 t.Errorf("%s: expected panic but did not panic", tt.name)
501 }
502 }
503 }()
504
505 s := NewServer(testImpl, nil)
506 s.AddResourceTemplate(&rt, nil)
507 })
508 }
509 }
510
511 // panicks reports whether f() panics.
512 func panics(f func()) (b bool) {
513 defer func() {
514 b = recover() != nil
515 }()
516 f()
517 return false
518 }
519
520 func TestAddTool(t *testing.T) {
521 // AddTool should panic if In or Out are not JSON objects.
522 s := NewServer(testImpl, nil)
523 if !panics(func() {
524 AddTool(s, &Tool{Name: "T1"}, func(context.Context, *CallToolRequest, string) (*CallToolResult, any, error) { return nil, nil, nil })
525 }) {
526 t.Error("bad In: expected panic")
527 }
528 if panics(func() {
529 AddTool(s, &Tool{Name: "T2"}, func(context.Context, *CallToolRequest, map[string]any) (*CallToolResult, any, error) {
530 return nil, nil, nil
531 })
532 }) {
533 t.Error("good In: expected no panic")
534 }
535 if !panics(func() {
536 AddTool(s, &Tool{Name: "T2"}, func(context.Context, *CallToolRequest, map[string]any) (*CallToolResult, int, error) {
537 return nil, 0, nil
538 })
539 }) {
540 t.Error("bad Out: expected panic")
541 }
542 }
543
544 func TestAddToolNameValidation(t *testing.T) {
545 tests := []struct {
546 label string
547 name string
548 wantLogContaining string
549 }{
550 {
551 label: "empty name",
552 name: "",
553 wantLogContaining: `tool name cannot be empty`,
554 },
555 {
556 label: "long name",
557 name: strings.Repeat("a", 129),
558 wantLogContaining: "exceeds maximum length of 128 characters",
559 },
560 {
561 label: "name with spaces",
562 name: "get user profile",
563 wantLogContaining: `tool name contains invalid characters: \" \"`,
564 },
565 {
566 label: "name with multiple invalid chars",
567 name: "user name@domain,com",
568 wantLogContaining: `tool name contains invalid characters: \" \", \"@\", \",\"`,
569 },
570 {
571 label: "name with unicode",
572 name: "tool-ñame",
573 wantLogContaining: `tool name contains invalid characters: \"ñ\"`,
574 },
575 {
576 label: "valid name",
577 name: "valid-tool_name.123",
578 wantLogContaining: "", // No log expected
579 },
580 }
581 for _, test := range tests {
582 t.Run(test.label, func(t *testing.T) {
583 var buf bytes.Buffer
584 s := NewServer(testImpl, &ServerOptions{
585 Logger: slog.New(slog.NewTextHandler(&buf, nil)),
586 })
587
588 // Use the generic AddTool as it also calls validateToolName.
589 AddTool(s, &Tool{Name: test.name}, func(context.Context, *CallToolRequest, any) (*CallToolResult, any, error) {
590 return nil, nil, nil
591 })
592
593 logOutput := buf.String()
594 if test.wantLogContaining != "" {
595 if !strings.Contains(logOutput, test.wantLogContaining) {
596 t.Errorf("log output =\n%s\nwant containing %q", logOutput, test.wantLogContaining)
597 }
598 } else {
599 if logOutput != "" {
600 t.Errorf("expected empty log output, got %q", logOutput)
601 }
602 }
603 })
604 }
605 }
606
607 type schema = jsonschema.Schema
608
609 func testToolForSchema[In, Out any](t *testing.T, tool *Tool, in string, out Out, wantIn, wantOut any, wantErrContaining string) {
610 t.Helper()
611 th := func(context.Context, *CallToolRequest, In) (*CallToolResult, Out, error) {
612 return nil, out, nil
613 }
614 gott, goth, err := toolForErr(tool, th, nil)
615 if err != nil {
616 t.Fatal(err)
617 }
618 if diff := cmp.Diff(wantIn, gott.InputSchema); diff != "" {
619 t.Errorf("input: mismatch (-want, +got):\n%s", diff)
620 }
621 if diff := cmp.Diff(wantOut, gott.OutputSchema); diff != "" {
622 t.Errorf("output: mismatch (-want, +got):\n%s", diff)
623 }
624 ctr := &CallToolRequest{
625 Params: &CallToolParamsRaw{
626 Arguments: json.RawMessage(in),
627 },
628 }
629 result, err := goth(context.Background(), ctr)
630 if wantErrContaining != "" {
631 // Input validation errors are returned as tool results with IsError=true,
632 // not as Go errors. Check both possibilities.
633 if err != nil {
634 if !strings.Contains(err.Error(), wantErrContaining) {
635 t.Errorf("got error %q, want containing %q", err, wantErrContaining)
636 }
637 } else if result != nil && result.IsError {
638 text := result.Content[0].(*TextContent).Text
639 if !strings.Contains(text, wantErrContaining) {
640 t.Errorf("got tool error %q, want containing %q", text, wantErrContaining)
641 }
642 } else {
643 t.Errorf("got no error, want error containing %q", wantErrContaining)
644 }
645 } else if err != nil {
646 t.Errorf("got error %v, want no error", err)
647 }
648
649 if gott.OutputSchema != nil && err == nil && !result.IsError {
650 // Check that structured content matches exactly.
651 unstructured := result.Content[0].(*TextContent).Text
652 structured := string(result.StructuredContent.(json.RawMessage))
653 if diff := cmp.Diff(unstructured, structured); diff != "" {
654 t.Errorf("Unstructured content does not match structured content exactly (-unstructured +structured):\n%s", diff)
655 }
656 }
657 }
658
659 // TestClientRootCapabilities verifies that the server correctly observes
660 // RootsV2 for various client capability configurations. This tests the fix
661 // for #607.
662 func TestClientRootCapabilities(t *testing.T) {
663 testCases := []struct {
664 name string
665 capabilities *string // JSON for the capabilities field; nil means omit the field
666 wantRootsV2 *RootCapabilities
667 }{
668 {
669 name: "capabilities field omitted",
670 capabilities: nil,
671 wantRootsV2: nil,
672 },
673 {
674 name: "empty capabilities",
675 capabilities: ptr(`{}`),
676 wantRootsV2: nil,
677 },
678 {
679 name: "capabilities with no roots",
680 capabilities: ptr(`{"sampling": {}}`),
681 wantRootsV2: nil,
682 },
683 {
684 name: "capabilities with empty roots",
685 capabilities: ptr(`{"roots": {}}`),
686 wantRootsV2: &RootCapabilities{ListChanged: false},
687 },
688 {
689 name: "capabilities with roots without listChanged",
690 capabilities: ptr(`{"roots": {"listChanged": false}}`),
691 wantRootsV2: &RootCapabilities{ListChanged: false},
692 },
693 {
694 name: "capabilities with roots with listChanged",
695 capabilities: ptr(`{"roots": {"listChanged": true}}`),
696 wantRootsV2: &RootCapabilities{ListChanged: true},
697 },
698 }
699
700 for _, tc := range testCases {
701 t.Run(tc.name, func(t *testing.T) {
702 ctx := context.Background()
703
704 // Create a minimal server.
705 impl := &Implementation{Name: "testServer", Version: "v1.0.0"}
706 s := NewServer(impl, nil)
707
708 // Connect the server.
709 cTransport, sTransport := NewInMemoryTransports()
710 ss, err := s.Connect(ctx, sTransport, nil)
711 if err != nil {
712 t.Fatal(err)
713 }
714
715 // Connect the client JSON-RPC connection (raw, no client).
716 cConn, err := cTransport.Connect(ctx)
717 if err != nil {
718 t.Fatal(err)
719 }
720
721 // Build initialize params, optionally including capabilities.
722 var initParams json.RawMessage
723 if tc.capabilities != nil {
724 initParams = json.RawMessage(`{
725 "protocolVersion": "2025-11-25",
726 "capabilities": ` + *tc.capabilities + `,
727 "clientInfo": {"name": "TestClient", "version": "1.0.0"}
728 }`)
729 } else {
730 initParams = json.RawMessage(`{
731 "protocolVersion": "2025-11-25",
732 "clientInfo": {"name": "TestClient", "version": "1.0.0"}
733 }`)
734 }
735
736 initReq, err := jsonrpc2.NewCall(jsonrpc2.Int64ID(1), "initialize", initParams)
737 if err != nil {
738 t.Fatal(err)
739 }
740
741 if err := cConn.Write(ctx, initReq); err != nil {
742 t.Fatalf("Write failed: %v", err)
743 }
744
745 // Read the initialize response.
746 msg, err := cConn.Read(ctx)
747 if err != nil {
748 t.Fatalf("Read failed: %v", err)
749 }
750 resp, ok := msg.(*jsonrpc2.Response)
751 if !ok {
752 t.Fatalf("expected Response, got %T", msg)
753 }
754 if resp.Error != nil {
755 t.Fatalf("initialize failed: %v", resp.Error)
756 }
757
758 // Verify that the server session has the correct RootsV2 value.
759 params := ss.InitializeParams()
760 if params == nil {
761 t.Fatal("InitializeParams is nil")
762 }
763
764 var gotRootsV2 *RootCapabilities
765 if params.Capabilities != nil {
766 gotRootsV2 = params.Capabilities.RootsV2
767 }
768 if diff := cmp.Diff(tc.wantRootsV2, gotRootsV2); diff != "" {
769 t.Errorf("RootsV2 mismatch (-want +got):\n%s", diff)
770 }
771
772 // Close the client connection.
773 if err := cConn.Close(); err != nil {
774 t.Fatalf("Stream.Close failed: %v", err)
775 }
776 ss.Wait()
777 })
778 }
779 }
780
781 // TODO: move this to tool_test.go
782 func TestToolForSchemas(t *testing.T) {
783 // Validate that toolForErr handles schemas properly.
784 type in struct {
785 P int `json:"p,omitempty"`
786 }
787 type out struct {
788 B bool `json:"b,omitempty"`
789 }
790
791 var (
792 falseSchema = &schema{Not: &schema{}}
793 inSchema = &schema{
794 Type: "object",
795 AdditionalProperties: falseSchema,
796 Properties: map[string]*schema{"p": {Type: "integer"}},
797 PropertyOrder: []string{"p"},
798 }
799 inSchema2 = &schema{
800 Type: "object",
801 AdditionalProperties: falseSchema,
802 Properties: map[string]*schema{"p": {Type: "string"}},
803 }
804 inSchema3 = &schema{
805 Type: "object",
806 AdditionalProperties: falseSchema,
807 Properties: map[string]*schema{}, // empty map is preserved
808 }
809 outSchema = &schema{
810 Type: "object",
811 AdditionalProperties: falseSchema,
812 Properties: map[string]*schema{"b": {Type: "boolean"}},
813 PropertyOrder: []string{"b"},
814 }
815 outSchema2 = &schema{
816 Type: "object",
817 AdditionalProperties: falseSchema,
818 Properties: map[string]*schema{"b": {Type: "integer"}},
819 PropertyOrder: []string{"b"},
820 }
821 )
822
823 // Infer both schemas.
824 testToolForSchema[in](t, &Tool{}, `{"p":3}`, out{true}, inSchema, outSchema, "")
825 // Validate the input schema: expect an error if it's wrong.
826 // We can't test that the output schema is validated, because it's typed.
827 testToolForSchema[in](t, &Tool{}, `{"p":"x"}`, out{true}, inSchema, outSchema, `want "integer"`)
828 // Ignore type any for output.
829 testToolForSchema[in, any](t, &Tool{}, `{"p":3}`, 0, inSchema, nil, "")
830 // Input is still validated.
831 testToolForSchema[in, any](t, &Tool{}, `{"p":"x"}`, 0, inSchema, nil, `want "integer"`)
832 // Tool sets input schema: that is what's used.
833 testToolForSchema[in, any](t, &Tool{InputSchema: inSchema2}, `{"p":3}`, 0, inSchema2, nil, `want "string"`)
834 // Tool sets input schema, empty properties map.
835 testToolForSchema[in, any](t, &Tool{InputSchema: inSchema3}, `{}`, 0, inSchema3, nil, "")
836 // Tool sets output schema: that is what's used, and validation happens.
837 testToolForSchema[in, any](t, &Tool{OutputSchema: outSchema2}, `{"p":3}`, out{true},
838 inSchema, outSchema2, `want "integer"`)
839
840 // Check a slightly more complicated case.
841 type weatherOutput struct {
842 Summary string
843 AsOf time.Time
844 Source string
845 }
846 testToolForSchema[any](t, &Tool{}, `{}`, weatherOutput{},
847 &schema{Type: "object"},
848 &schema{
849 Type: "object",
850 Required: []string{"Summary", "AsOf", "Source"},
851 AdditionalProperties: falseSchema,
852 Properties: map[string]*schema{
853 "Summary": {Type: "string"},
854 "AsOf": {Type: "string"},
855 "Source": {Type: "string"},
856 },
857 PropertyOrder: []string{"Summary", "AsOf", "Source"},
858 },
859 "")
860 }
861
862 // TestServerCapabilitiesOverWire verifies that server capabilities are
863 // correctly sent over the wire during initialization.
864 func TestServerCapabilitiesOverWire(t *testing.T) {
865 tool := &Tool{Name: "test-tool", InputSchema: &jsonschema.Schema{Type: "object"}}
866
867 testCases := []struct {
868 name string
869 serverOpts *ServerOptions
870 configureServer func(s *Server)
871 wantCapabilities *ServerCapabilities
872 }{
873 {
874 name: "Default capabilities",
875 serverOpts: nil,
876 configureServer: func(s *Server) {},
877 wantCapabilities: &ServerCapabilities{
878 Logging: &LoggingCapabilities{},
879 },
880 },
881 {
882 name: "Custom Capabilities with tools",
883 serverOpts: &ServerOptions{
884 Capabilities: &ServerCapabilities{
885 Tools: &ToolCapabilities{ListChanged: false},
886 },
887 },
888 configureServer: func(s *Server) {},
889 wantCapabilities: &ServerCapabilities{
890 Tools: &ToolCapabilities{ListChanged: false},
891 },
892 },
893 {
894 name: "Dynamic tool capability",
895 serverOpts: &ServerOptions{
896 Capabilities: &ServerCapabilities{
897 Logging: &LoggingCapabilities{},
898 },
899 },
900 configureServer: func(s *Server) {
901 s.AddTool(tool, nil)
902 },
903 wantCapabilities: &ServerCapabilities{
904 Logging: &LoggingCapabilities{},
905 Tools: &ToolCapabilities{ListChanged: true},
906 },
907 },
908 {
909 name: "Extensions over wire",
910 serverOpts: func() *ServerOptions {
911 caps := &ServerCapabilities{
912 Logging: &LoggingCapabilities{},
913 }
914 caps.AddExtension("io.example/ext", map[string]any{"key": "value"})
915 return &ServerOptions{Capabilities: caps}
916 }(),
917 configureServer: func(s *Server) {},
918 wantCapabilities: &ServerCapabilities{
919 Extensions: map[string]any{
920 "io.example/ext": map[string]any{"key": "value"},
921 },
922 Logging: &LoggingCapabilities{},
923 },
924 },
925 }
926
927 for _, tc := range testCases {
928 t.Run(tc.name, func(t *testing.T) {
929 ctx := context.Background()
930
931 // Create server.
932 impl := &Implementation{Name: "testServer", Version: "v1.0.0"}
933 server := NewServer(impl, tc.serverOpts)
934 tc.configureServer(server)
935
936 // Connect client and server.
937 cTransport, sTransport := NewInMemoryTransports()
938 ss, err := server.Connect(ctx, sTransport, nil)
939 if err != nil {
940 t.Fatal(err)
941 }
942 defer ss.Close()
943
944 client := NewClient(&Implementation{Name: "testClient", Version: "v1.0.0"}, nil)
945 cs, err := client.Connect(ctx, cTransport, nil)
946 if err != nil {
947 t.Fatal(err)
948 }
949 defer cs.Close()
950
951 // Check that the client received the expected capabilities.
952 initResult := cs.InitializeResult()
953 if initResult == nil {
954 t.Fatal("InitializeResult is nil")
955 }
956
957 if diff := cmp.Diff(tc.wantCapabilities, initResult.Capabilities); diff != "" {
958 t.Errorf("Capabilities mismatch (-want +got):\n%s", diff)
959 }
960 })
961 }
962 }