Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/protocol_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 "encoding/json"
9 "maps"
10 "testing"
11
12 "github.com/google/go-cmp/cmp"
13 )
14
15 func TestParamsMeta(t *testing.T) {
16 // Verify some properties of the Meta field of Params structs.
17 // We use CallToolParams for the test, but the Meta setup of all params types
18 // is identical so they should all behave the same.
19
20 toJSON := func(x any) string {
21 data, err := json.Marshal(x)
22 if err != nil {
23 t.Fatal(err)
24 }
25 return string(data)
26 }
27
28 meta := map[string]any{"m": 1}
29
30 // You can set the embedded Meta field to a literal map.
31 p := &CallToolParams{
32 Meta: meta,
33 Name: "name",
34 }
35
36 // The Meta field marshals properly when it's present.
37 if g, w := toJSON(p), `{"_meta":{"m":1},"name":"name"}`; g != w {
38 t.Errorf("got %s, want %s", g, w)
39 }
40 // ... and when it's absent.
41 p2 := &CallToolParams{Name: "n"}
42 if g, w := toJSON(p2), `{"name":"n"}`; g != w {
43 t.Errorf("got %s, want %s", g, w)
44 }
45
46 // The GetMeta and SetMeta functions work as expected.
47 if g := p.GetMeta(); !maps.Equal(g, meta) {
48 t.Errorf("got %+v, want %+v", g, meta)
49 }
50
51 meta2 := map[string]any{"x": 2}
52 p.SetMeta(meta2)
53 if g := p.GetMeta(); !maps.Equal(g, meta2) {
54 t.Errorf("got %+v, want %+v", g, meta2)
55 }
56
57 // The GetProgressToken and SetProgressToken methods work as expected.
58 if g := p.GetProgressToken(); g != nil {
59 t.Errorf("got %v, want nil", g)
60 }
61
62 p.SetProgressToken("t")
63 if g := p.GetProgressToken(); g != "t" {
64 t.Errorf("got %v, want `t`", g)
65 }
66
67 // The GetProgressToken and SetProgressToken methods work on a params struct that doesn't have a Meta field.
68 if g := p2.GetProgressToken(); g != nil {
69 t.Errorf("got %v, want nil", g)
70 }
71
72 p2.SetProgressToken("t")
73 if g := p2.GetProgressToken(); g != "t" {
74 t.Errorf("got %v, want `t`", g)
75 }
76
77 // You can set a progress token to an int, int32 or int64.
78 p.SetProgressToken(int(1))
79 p.SetProgressToken(int32(1))
80 p.SetProgressToken(int64(1))
81 }
82
83 func TestCompleteReference(t *testing.T) {
84 marshalTests := []struct {
85 name string
86 in CompleteReference // The Go struct to marshal
87 want string // The expected JSON string output
88 wantErr bool // True if json.Marshal is expected to return an error
89 }{
90 {
91 name: "ValidPrompt",
92 in: CompleteReference{Type: "ref/prompt", Name: "my_prompt"},
93 want: `{"type":"ref/prompt","name":"my_prompt"}`,
94 wantErr: false,
95 },
96 {
97 name: "ValidResource",
98 in: CompleteReference{Type: "ref/resource", URI: "file:///path/to/resource.txt"},
99 want: `{"type":"ref/resource","uri":"file:///path/to/resource.txt"}`,
100 wantErr: false,
101 },
102 {
103 name: "ValidPromptEmptyName",
104 in: CompleteReference{Type: "ref/prompt", Name: ""},
105 want: `{"type":"ref/prompt"}`,
106 wantErr: false,
107 },
108 {
109 name: "ValidResourceEmptyURI",
110 in: CompleteReference{Type: "ref/resource", URI: ""},
111 want: `{"type":"ref/resource"}`,
112 wantErr: false,
113 },
114 // Error cases for MarshalJSON
115 {
116 name: "InvalidType",
117 in: CompleteReference{Type: "ref/unknown", Name: "something"},
118 wantErr: true,
119 },
120 {
121 name: "PromptWithURI",
122 in: CompleteReference{Type: "ref/prompt", Name: "my_prompt", URI: "unexpected_uri"},
123 wantErr: true,
124 },
125 {
126 name: "ResourceWithName",
127 in: CompleteReference{Type: "ref/resource", URI: "my_uri", Name: "unexpected_name"},
128 wantErr: true,
129 },
130 {
131 name: "MissingTypeField",
132 in: CompleteReference{Name: "missing"}, // Type is ""
133 wantErr: true,
134 },
135 }
136
137 // Define test cases specifically for Unmarshalling
138 unmarshalTests := []struct {
139 name string
140 in string // The JSON string input
141 want CompleteReference // The expected Go struct output
142 wantErr bool // True if json.Unmarshal is expected to return an error
143 }{
144 {
145 name: "ValidPrompt",
146 in: `{"type":"ref/prompt","name":"my_prompt"}`,
147 want: CompleteReference{Type: "ref/prompt", Name: "my_prompt"},
148 wantErr: false,
149 },
150 {
151 name: "ValidResource",
152 in: `{"type":"ref/resource","uri":"file:///path/to/resource.txt"}`,
153 want: CompleteReference{Type: "ref/resource", URI: "file:///path/to/resource.txt"},
154 wantErr: false,
155 },
156 // Error cases for UnmarshalJSON
157 {
158 name: "UnrecognizedType",
159 in: `{"type":"ref/unknown","name":"something"}`,
160 want: CompleteReference{}, // placeholder, as unmarshal will fail
161 wantErr: true,
162 },
163 {
164 name: "PromptWithURI",
165 in: `{"type":"ref/prompt","name":"my_prompt","uri":"unexpected_uri"}`,
166 want: CompleteReference{}, // placeholder
167 wantErr: true,
168 },
169 {
170 name: "ResourceWithName",
171 in: `{"type":"ref/resource","uri":"my_uri","name":"unexpected_name"}`,
172 want: CompleteReference{}, // placeholder
173 wantErr: true,
174 },
175 {
176 name: "MissingType",
177 in: `{"name":"missing"}`,
178 want: CompleteReference{}, // placeholder
179 wantErr: true,
180 },
181 {
182 name: "InvalidJSON",
183 in: `invalid json`,
184 want: CompleteReference{}, // placeholder
185 wantErr: true, // json.Unmarshal will fail natively
186 },
187 }
188
189 // Run Marshal Tests
190 for _, test := range marshalTests {
191 t.Run("Marshal/"+test.name, func(t *testing.T) {
192 gotBytes, err := json.Marshal(&test.in)
193 if (err != nil) != test.wantErr {
194 t.Errorf("json.Marshal(%v) got error %v (want error %t)", test.in, err, test.wantErr)
195 }
196 if !test.wantErr { // Only check JSON output if marshal was expected to succeed
197 if diff := cmp.Diff(test.want, string(gotBytes)); diff != "" {
198 t.Errorf("json.Marshal(%v) mismatch (-want +got):\n%s", test.in, diff)
199 }
200 }
201 })
202 }
203
204 // Run Unmarshal Tests
205 for _, test := range unmarshalTests {
206 t.Run("Unmarshal/"+test.name, func(t *testing.T) {
207 var got CompleteReference
208 err := json.Unmarshal([]byte(test.in), &got)
209
210 if (err != nil) != test.wantErr {
211 t.Errorf("json.Unmarshal(%q) got error %v (want error %t)", test.in, err, test.wantErr)
212 }
213 if !test.wantErr { // Only check content if unmarshal was expected to succeed
214 if diff := cmp.Diff(test.want, got); diff != "" {
215 t.Errorf("json.Unmarshal(%q) mismatch (-want +got):\n%s", test.in, diff)
216 }
217 }
218 })
219 }
220 }
221
222 func TestCompleteParams(t *testing.T) {
223 // Define test cases specifically for Marshalling
224 marshalTests := []struct {
225 name string
226 in CompleteParams
227 want string // Expected JSON output
228 }{
229 {
230 name: "BasicPromptCompletion",
231 in: CompleteParams{
232 Ref: &CompleteReference{
233 Type: "ref/prompt",
234 Name: "my_prompt",
235 },
236 Argument: CompleteParamsArgument{
237 Name: "language",
238 Value: "go",
239 },
240 },
241 want: `{"argument":{"name":"language","value":"go"},"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
242 },
243 {
244 name: "ResourceCompletionRequest",
245 in: CompleteParams{
246 Ref: &CompleteReference{
247 Type: "ref/resource",
248 URI: "file:///src/main.java",
249 },
250 Argument: CompleteParamsArgument{
251 Name: "class",
252 Value: "MyClas",
253 },
254 },
255 want: `{"argument":{"name":"class","value":"MyClas"},"ref":{"type":"ref/resource","uri":"file:///src/main.java"}}`,
256 },
257 {
258 name: "PromptCompletionEmptyArgumentValue",
259 in: CompleteParams{
260 Ref: &CompleteReference{
261 Type: "ref/prompt",
262 Name: "another_prompt",
263 },
264 Argument: CompleteParamsArgument{
265 Name: "query",
266 Value: "",
267 },
268 },
269 want: `{"argument":{"name":"query","value":""},"ref":{"type":"ref/prompt","name":"another_prompt"}}`,
270 },
271 {
272 name: "PromptCompletionWithContext",
273 in: CompleteParams{
274 Ref: &CompleteReference{
275 Type: "ref/prompt",
276 Name: "my_prompt",
277 },
278 Argument: CompleteParamsArgument{
279 Name: "language",
280 Value: "go",
281 },
282 Context: &CompleteContext{
283 Arguments: map[string]string{
284 "framework": "mcp",
285 "language": "python",
286 },
287 },
288 },
289 want: `{"argument":{"name":"language","value":"go"},"context":{"arguments":{"framework":"mcp","language":"python"}},"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
290 },
291 {
292 name: "PromptCompletionEmptyContextArguments",
293 in: CompleteParams{
294 Ref: &CompleteReference{
295 Type: "ref/prompt",
296 Name: "my_prompt",
297 },
298 Argument: CompleteParamsArgument{
299 Name: "language",
300 Value: "go",
301 },
302 Context: &CompleteContext{
303 Arguments: map[string]string{},
304 },
305 },
306 want: `{"argument":{"name":"language","value":"go"},"context":{},"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
307 },
308 }
309
310 // Define test cases specifically for Unmarshalling
311 unmarshalTests := []struct {
312 name string
313 in string // JSON string input
314 want CompleteParams // Expected Go struct output
315 }{
316 {
317 name: "BasicPromptCompletion",
318 in: `{"argument":{"name":"language","value":"go"},"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
319 want: CompleteParams{
320 Ref: &CompleteReference{Type: "ref/prompt", Name: "my_prompt"},
321 Argument: CompleteParamsArgument{Name: "language", Value: "go"},
322 },
323 },
324 {
325 name: "ResourceCompletionRequest",
326 in: `{"argument":{"name":"class","value":"MyClas"},"ref":{"type":"ref/resource","uri":"file:///src/main.java"}}`,
327 want: CompleteParams{
328 Ref: &CompleteReference{Type: "ref/resource", URI: "file:///src/main.java"},
329 Argument: CompleteParamsArgument{Name: "class", Value: "MyClas"},
330 },
331 },
332 {
333 name: "PromptCompletionWithContext",
334 in: `{"argument":{"name":"language","value":"go"},"context":{"arguments":{"framework":"mcp","language":"python"}},"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
335 want: CompleteParams{
336 Ref: &CompleteReference{Type: "ref/prompt", Name: "my_prompt"},
337 Argument: CompleteParamsArgument{Name: "language", Value: "go"},
338 Context: &CompleteContext{Arguments: map[string]string{
339 "framework": "mcp",
340 "language": "python",
341 }},
342 },
343 },
344 {
345 name: "PromptCompletionEmptyContextArguments",
346 in: `{"argument":{"name":"language","value":"go"},"context":{"arguments":{}},"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
347 want: CompleteParams{
348 Ref: &CompleteReference{Type: "ref/prompt", Name: "my_prompt"},
349 Argument: CompleteParamsArgument{Name: "language", Value: "go"},
350 Context: &CompleteContext{Arguments: map[string]string{}},
351 },
352 },
353 {
354 name: "PromptCompletionNilContext", // JSON `null` for context
355 in: `{"argument":{"name":"language","value":"go"},"context":null,"ref":{"type":"ref/prompt","name":"my_prompt"}}`,
356 want: CompleteParams{
357 Ref: &CompleteReference{Type: "ref/prompt", Name: "my_prompt"},
358 Argument: CompleteParamsArgument{Name: "language", Value: "go"},
359 Context: nil, // Should unmarshal to nil pointer
360 },
361 },
362 }
363
364 // Run Marshal Tests
365 for _, test := range marshalTests {
366 t.Run("Marshal/"+test.name, func(t *testing.T) {
367 got, err := json.Marshal(&test.in) // Marshal takes a pointer
368 if err != nil {
369 t.Fatalf("json.Marshal(CompleteParams) failed: %v", err)
370 }
371 if diff := cmp.Diff(test.want, string(got)); diff != "" {
372 t.Errorf("CompleteParams marshal mismatch (-want +got):\n%s", diff)
373 }
374 })
375 }
376
377 // Run Unmarshal Tests
378 for _, test := range unmarshalTests {
379 t.Run("Unmarshal/"+test.name, func(t *testing.T) {
380 var got CompleteParams
381 if err := json.Unmarshal([]byte(test.in), &got); err != nil {
382 t.Fatalf("json.Unmarshal(CompleteParams) failed: %v", err)
383 }
384 if diff := cmp.Diff(test.want, got); diff != "" {
385 t.Errorf("CompleteParams unmarshal mismatch (-want +got):\n%s", diff)
386 }
387 })
388 }
389 }
390
391 func TestCompleteResult(t *testing.T) {
392 // Define test cases specifically for Marshalling
393 marshalTests := []struct {
394 name string
395 in CompleteResult
396 want string // Expected JSON output
397 }{
398 {
399 name: "BasicCompletionResult",
400 in: CompleteResult{
401 Completion: CompletionResultDetails{
402 Values: []string{"golang", "google", "goroutine"},
403 Total: 10,
404 HasMore: true,
405 },
406 },
407 want: `{"completion":{"hasMore":true,"total":10,"values":["golang","google","goroutine"]}}`,
408 },
409 {
410 name: "CompletionResultNoTotalNoHasMore",
411 in: CompleteResult{
412 Completion: CompletionResultDetails{
413 Values: []string{"only"},
414 HasMore: false,
415 Total: 0,
416 },
417 },
418 want: `{"completion":{"values":["only"]}}`,
419 },
420 {
421 name: "CompletionResultEmptyValues",
422 in: CompleteResult{
423 Completion: CompletionResultDetails{
424 Values: []string{},
425 Total: 0,
426 HasMore: false,
427 },
428 },
429 want: `{"completion":{"values":[]}}`,
430 },
431 }
432
433 // Define test cases specifically for Unmarshalling
434 unmarshalTests := []struct {
435 name string
436 in string // JSON string input
437 want CompleteResult // Expected Go struct output
438 }{
439 {
440 name: "BasicCompletionResult",
441 in: `{"completion":{"hasMore":true,"total":10,"values":["golang","google","goroutine"]}}`,
442 want: CompleteResult{
443 Completion: CompletionResultDetails{
444 Values: []string{"golang", "google", "goroutine"},
445 Total: 10,
446 HasMore: true,
447 },
448 },
449 },
450 {
451 name: "CompletionResultNoTotalNoHasMore",
452 in: `{"completion":{"values":["only"]}}`,
453 want: CompleteResult{
454 Completion: CompletionResultDetails{
455 Values: []string{"only"},
456 HasMore: false,
457 Total: 0,
458 },
459 },
460 },
461 {
462 name: "CompletionResultEmptyValues",
463 in: `{"completion":{"hasMore":false,"total":0,"values":[]}}`,
464 want: CompleteResult{
465 Completion: CompletionResultDetails{
466 Values: []string{},
467 Total: 0,
468 HasMore: false,
469 },
470 },
471 },
472 }
473
474 // Run Marshal Tests
475 for _, test := range marshalTests {
476 t.Run("Marshal/"+test.name, func(t *testing.T) {
477 got, err := json.Marshal(&test.in) // Marshal takes a pointer
478 if err != nil {
479 t.Fatalf("json.Marshal(CompleteResult) failed: %v", err)
480 }
481 if diff := cmp.Diff(test.want, string(got)); diff != "" {
482 t.Errorf("CompleteResult marshal mismatch (-want +got):\n%s", diff)
483 }
484 })
485 }
486
487 // Run Unmarshal Tests
488 for _, test := range unmarshalTests {
489 t.Run("Unmarshal/"+test.name, func(t *testing.T) {
490 var got CompleteResult
491 if err := json.Unmarshal([]byte(test.in), &got); err != nil {
492 t.Fatalf("json.Unmarshal(CompleteResult) failed: %v", err)
493 }
494 if diff := cmp.Diff(test.want, got); diff != "" {
495 t.Errorf("CompleteResult unmarshal mismatch (-want +got):\n%s", diff)
496 }
497 })
498 }
499 }
500
501 // TODO: merge the following 4 tests into content_test.go.
502 func TestToolUseContent_MarshalJSON(t *testing.T) {
503 tests := []struct {
504 name string
505 content *ToolUseContent
506 want string
507 }{
508 {
509 name: "basic tool use",
510 content: &ToolUseContent{
511 ID: "tool_123",
512 Name: "calculator",
513 Input: map[string]any{
514 "operation": "add",
515 "x": 1.0,
516 "y": 2.0,
517 },
518 },
519 want: `{"type":"tool_use","id":"tool_123","name":"calculator","input":{"operation":"add","x":1,"y":2}}`,
520 },
521 {
522 name: "nil input marshals as empty object",
523 content: &ToolUseContent{
524 ID: "tool_456",
525 Name: "no_args_tool",
526 Input: nil,
527 },
528 want: `{"type":"tool_use","id":"tool_456","name":"no_args_tool","input":{}}`,
529 },
530 }
531
532 for _, tt := range tests {
533 t.Run(tt.name, func(t *testing.T) {
534 got, err := tt.content.MarshalJSON()
535 if err != nil {
536 t.Fatalf("MarshalJSON() error = %v", err)
537 }
538 if diff := cmp.Diff(tt.want, string(got)); diff != "" {
539 t.Errorf("mismatch (-want +got):\n%s", diff)
540 }
541 })
542 }
543 }
544
545 func TestToolUseContent_UnmarshalJSON(t *testing.T) {
546 tests := []struct {
547 name string
548 json string
549 want *ToolUseContent
550 }{
551 {
552 name: "basic tool use",
553 json: `{"type":"tool_use","id":"tool_123","name":"calculator","input":{"x":1,"y":2}}`,
554 want: &ToolUseContent{
555 ID: "tool_123",
556 Name: "calculator",
557 Input: map[string]any{
558 "x": 1.0,
559 "y": 2.0,
560 },
561 },
562 },
563 {
564 name: "with meta",
565 json: `{"type":"tool_use","id":"t1","name":"calc","input":{"x":1},"_meta":{"requestId":"req-123"}}`,
566 want: &ToolUseContent{
567 ID: "t1",
568 Name: "calc",
569 Input: map[string]any{"x": 1.0},
570 Meta: Meta{"requestId": "req-123"},
571 },
572 },
573 }
574
575 for _, tt := range tests {
576 t.Run(tt.name, func(t *testing.T) {
577 wire := &wireContent{}
578 if err := json.Unmarshal([]byte(tt.json), wire); err != nil {
579 t.Fatalf("Unmarshal() error = %v", err)
580 }
581 got, err := contentFromWire(wire, map[string]bool{"tool_use": true})
582 if err != nil {
583 t.Fatalf("contentFromWire() error = %v", err)
584 }
585 if diff := cmp.Diff(tt.want, got); diff != "" {
586 t.Errorf("mismatch (-want +got):\n%s", diff)
587 }
588 })
589 }
590 }
591
592 func TestToolResultContent_MarshalJSON(t *testing.T) {
593 tests := []struct {
594 name string
595 content *ToolResultContent
596 want string
597 }{
598 {
599 name: "basic tool result",
600 content: &ToolResultContent{
601 ToolUseID: "tool_123",
602 Content: []Content{&TextContent{Text: "42"}},
603 },
604 want: `{"type":"tool_result","toolUseId":"tool_123","content":[{"type":"text","text":"42"}]}`,
605 },
606 {
607 name: "tool result with error",
608 content: &ToolResultContent{
609 ToolUseID: "tool_456",
610 Content: []Content{&TextContent{Text: "division by zero"}},
611 IsError: true,
612 },
613 want: `{"type":"tool_result","toolUseId":"tool_456","content":[{"type":"text","text":"division by zero"}],"isError":true}`,
614 },
615 {
616 name: "tool result with structured content",
617 content: &ToolResultContent{
618 ToolUseID: "tool_789",
619 Content: []Content{&TextContent{Text: `{"result": 42}`}},
620 StructuredContent: map[string]any{"result": 42.0},
621 },
622 want: `{"type":"tool_result","toolUseId":"tool_789","content":[{"type":"text","text":"{\"result\": 42}"}],"structuredContent":{"result":42}}`,
623 },
624 }
625
626 for _, tt := range tests {
627 t.Run(tt.name, func(t *testing.T) {
628 got, err := tt.content.MarshalJSON()
629 if err != nil {
630 t.Fatalf("MarshalJSON() error = %v", err)
631 }
632 if diff := cmp.Diff(tt.want, string(got)); diff != "" {
633 t.Errorf("mismatch (-want +got):\n%s", diff)
634 }
635 })
636 }
637 }
638
639 func TestToolResultContent_UnmarshalJSON(t *testing.T) {
640 tests := []struct {
641 name string
642 json string
643 want *ToolResultContent
644 }{
645 {
646 name: "basic tool result",
647 json: `{"type":"tool_result","toolUseId":"tool_123","content":[{"type":"text","text":"42"}],"isError":false}`,
648 want: &ToolResultContent{
649 ToolUseID: "tool_123",
650 Content: []Content{&TextContent{Text: "42"}},
651 IsError: false,
652 },
653 },
654 {
655 name: "image nested content",
656 json: `{"type":"tool_result","toolUseId":"t1","content":[{"type":"image","mimeType":"image/png","data":"YWJj"}]}`,
657 want: &ToolResultContent{
658 ToolUseID: "t1",
659 Content: []Content{&ImageContent{MIMEType: "image/png", Data: []byte("abc")}},
660 },
661 },
662 }
663
664 for _, tt := range tests {
665 t.Run(tt.name, func(t *testing.T) {
666 wire := &wireContent{}
667 if err := json.Unmarshal([]byte(tt.json), wire); err != nil {
668 t.Fatalf("Unmarshal() error = %v", err)
669 }
670 got, err := contentFromWire(wire, map[string]bool{"tool_result": true})
671 if err != nil {
672 t.Fatalf("contentFromWire() error = %v", err)
673 }
674 if diff := cmp.Diff(tt.want, got); diff != "" {
675 t.Errorf("mismatch (-want +got):\n%s", diff)
676 }
677 })
678 }
679 }
680
681 func TestSamplingMessage_UnmarshalJSON(t *testing.T) {
682 tests := []struct {
683 name string
684 json string
685 want *SamplingMessage
686 }{
687 {
688 name: "tool_use content",
689 json: `{"content":{"type":"tool_use","id":"tool_1","name":"calc","input":{}},"role":"assistant"}`,
690 want: &SamplingMessage{
691 Role: "assistant",
692 Content: &ToolUseContent{
693 ID: "tool_1",
694 Name: "calc",
695 Input: map[string]any{},
696 },
697 },
698 },
699 {
700 name: "tool_result content",
701 json: `{"content":{"type":"tool_result","toolUseId":"tool_1","content":[{"type":"text","text":"42"}]},"role":"user"}`,
702 want: &SamplingMessage{
703 Role: "user",
704 Content: &ToolResultContent{
705 ToolUseID: "tool_1",
706 Content: []Content{&TextContent{Text: "42"}},
707 },
708 },
709 },
710 }
711
712 for _, tt := range tests {
713 t.Run(tt.name, func(t *testing.T) {
714 var got SamplingMessage
715 if err := json.Unmarshal([]byte(tt.json), &got); err != nil {
716 t.Fatalf("Unmarshal() error = %v", err)
717 }
718 if diff := cmp.Diff(tt.want, &got); diff != "" {
719 t.Errorf("mismatch (-want +got):\n%s", diff)
720 }
721 })
722 }
723 }
724
725 func TestSamplingCapabilities_MarshalUnmarshalJSON(t *testing.T) {
726 tests := []struct {
727 name string
728 caps *SamplingCapabilities
729 json string
730 }{
731 {
732 name: "WithCapabilities",
733 caps: &SamplingCapabilities{
734 Tools: &SamplingToolsCapabilities{},
735 Context: &SamplingContextCapabilities{},
736 },
737 json: `{"context":{},"tools":{}}`,
738 },
739 {
740 name: "EmptyCapabilities",
741 caps: &SamplingCapabilities{},
742 json: `{}`,
743 },
744 }
745
746 for _, tt := range tests {
747 t.Run(tt.name, func(t *testing.T) {
748 gotJson, err := json.Marshal(tt.caps)
749 if err != nil {
750 t.Fatalf("Marshal() error = %v", err)
751 }
752 if diff := cmp.Diff(tt.json, string(gotJson)); diff != "" {
753 t.Errorf("mismatch (-want +got):\n%s", diff)
754 }
755 var gotCaps SamplingCapabilities
756 if err := json.Unmarshal([]byte(tt.json), &gotCaps); err != nil {
757 t.Fatalf("Unmarshal() error = %v", err)
758 }
759 if diff := cmp.Diff(tt.caps, &gotCaps); diff != "" {
760 t.Errorf("mismatch (-want +got):\n%s", diff)
761 }
762 })
763 }
764 }
765
766 func TestCreateMessageWithToolsParams_MarshalUnmarshalJSON(t *testing.T) {
767 params := &CreateMessageWithToolsParams{
768 MaxTokens: 1000,
769 Messages: []*SamplingMessageV2{
770 {
771 Role: "user",
772 Content: []Content{&TextContent{Text: "Calculate 1+1"}},
773 },
774 },
775 Tools: []*Tool{
776 {
777 Name: "calculator",
778 Description: "A calculator tool",
779 InputSchema: map[string]any{
780 "type": "object",
781 "properties": map[string]any{
782 "x": map[string]any{"type": "number"},
783 "y": map[string]any{"type": "number"},
784 },
785 },
786 },
787 },
788 ToolChoice: &ToolChoice{Mode: "auto"},
789 }
790
791 data, err := json.Marshal(params)
792 if err != nil {
793 t.Fatalf("Marshal() error = %v", err)
794 }
795
796 var got CreateMessageWithToolsParams
797 if err := json.Unmarshal(data, &got); err != nil {
798 t.Fatalf("Unmarshal() error = %v", err)
799 }
800
801 if diff := cmp.Diff(params, &got); diff != "" {
802 t.Errorf("mismatch (-want +got):\n%s", diff)
803 }
804 }
805
806 func TestToolChoice_MarshalUnmarshalJSON(t *testing.T) {
807 choices := []ToolChoice{
808 {Mode: "auto"},
809 {Mode: "required"},
810 {Mode: "none"},
811 }
812
813 for _, tc := range choices {
814 data, err := json.Marshal(tc)
815 if err != nil {
816 t.Fatalf("Marshal(%v) error = %v", tc.Mode, err)
817 }
818 var got ToolChoice
819 if err := json.Unmarshal(data, &got); err != nil {
820 t.Fatalf("Unmarshal() error = %v", err)
821 }
822 if diff := cmp.Diff(tc, got); diff != "" {
823 t.Errorf("mismatch (-want +got):\n%s", diff)
824 }
825 }
826 }
827
828 func TestCreateMessageWithToolsResult_MarshalJSON(t *testing.T) {
829 tests := []struct {
830 name string
831 result *CreateMessageWithToolsResult
832 want string
833 }{
834 {
835 name: "single element content",
836 result: &CreateMessageWithToolsResult{
837 Model: "test",
838 Role: "assistant",
839 Content: []Content{&TextContent{Text: "hello"}},
840 },
841 // Single-element Content marshals as object (not array) for backward compat.
842 want: `{"content":{"type":"text","text":"hello"},"model":"test","role":"assistant"}`,
843 },
844 {
845 name: "multiple elements content",
846 result: &CreateMessageWithToolsResult{
847 Model: "test",
848 Role: "assistant",
849 Content: []Content{
850 &TextContent{Text: "thinking..."},
851 &ToolUseContent{
852 ID: "call_1",
853 Name: "calculator",
854 Input: map[string]any{
855 "a": 1.0,
856 "b": 2.0,
857 },
858 },
859 },
860 },
861 // Multiple elements marshal as array.
862 want: `{"content":[{"type":"text","text":"thinking..."},{"type":"tool_use","id":"call_1","name":"calculator","input":{"a":1,"b":2}}],"model":"test","role":"assistant"}`,
863 },
864 }
865
866 for _, tt := range tests {
867 t.Run(tt.name, func(t *testing.T) {
868 got, err := json.Marshal(tt.result)
869 if err != nil {
870 t.Fatalf("Marshal() error = %v", err)
871 }
872 if diff := cmp.Diff(tt.want, string(got)); diff != "" {
873 t.Errorf("mismatch (-want +got):\n%s", diff)
874 }
875 })
876 }
877 }
878
879 func TestCreateMessageWithToolsResult_UnmarshalJSON(t *testing.T) {
880 tests := []struct {
881 name string
882 json string
883 want *CreateMessageWithToolsResult
884 wantErr bool
885 }{
886 {
887 name: "single tool_use content",
888 json: `{"content":{"type":"tool_use","id":"tool_1","name":"calculator","input":{"x":1}},"model":"test-model","role":"assistant","stopReason":"toolUse"}`,
889 want: &CreateMessageWithToolsResult{
890 Model: "test-model",
891 Role: "assistant",
892 StopReason: "toolUse",
893 Content: []Content{
894 &ToolUseContent{
895 ID: "tool_1",
896 Name: "calculator",
897 Input: map[string]any{
898 "x": 1.0,
899 },
900 },
901 },
902 },
903 },
904 {
905 name: "array of tool_use content",
906 json: `{"content":[{"type":"tool_use","id":"t1","name":"calc","input":{"x":1}},{"type":"tool_use","id":"t2","name":"search","input":{"q":"hi"}}],"model":"test","role":"assistant","stopReason":"toolUse"}`,
907 want: &CreateMessageWithToolsResult{
908 Model: "test",
909 Role: "assistant",
910 StopReason: "toolUse",
911 Content: []Content{
912 &ToolUseContent{
913 ID: "t1",
914 Name: "calc",
915 Input: map[string]any{"x": 1.0},
916 },
917 &ToolUseContent{
918 ID: "t2",
919 Name: "search",
920 Input: map[string]any{"q": "hi"},
921 },
922 },
923 },
924 },
925 {
926 name: "empty array",
927 json: `{"content":[],"model":"m","role":"assistant"}`,
928 want: &CreateMessageWithToolsResult{
929 Model: "m",
930 Role: "assistant",
931 Content: []Content{},
932 },
933 },
934 {
935 name: "null content",
936 json: `{"content":null,"model":"m","role":"assistant"}`,
937 wantErr: true,
938 },
939 {
940 name: "rejects tool_result",
941 json: `{"content":{"type":"tool_result","toolUseId":"t1","content":[]},"model":"m","role":"assistant"}`,
942 wantErr: true,
943 },
944 }
945
946 for _, tt := range tests {
947 t.Run(tt.name, func(t *testing.T) {
948 var got CreateMessageWithToolsResult
949 err := json.Unmarshal([]byte(tt.json), &got)
950 if (err != nil) != tt.wantErr {
951 t.Fatalf("Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
952 }
953 if tt.wantErr {
954 return
955 }
956 if diff := cmp.Diff(tt.want, &got); diff != "" {
957 t.Errorf("mismatch (-want +got):\n%s", diff)
958 }
959 })
960 }
961 }
962
963 func TestSamplingMessageV2_MarshalJSON(t *testing.T) {
964 tests := []struct {
965 name string
966 msg *SamplingMessageV2
967 want string
968 }{
969 {
970 name: "empty content",
971 msg: &SamplingMessageV2{
972 Role: "user",
973 Content: []Content{},
974 },
975 want: `{"content":[],"role":"user"}`,
976 },
977 {
978 name: "single content",
979 msg: &SamplingMessageV2{
980 Role: "assistant",
981 Content: []Content{&TextContent{Text: "hello"}},
982 },
983 want: `{"content":{"type":"text","text":"hello"},"role":"assistant"}`,
984 },
985 {
986 name: "multiple content",
987 msg: &SamplingMessageV2{
988 Role: "assistant",
989 // Text + tool_use in the same message (valid per spec for assistant).
990 Content: []Content{
991 &TextContent{Text: "checking weather"},
992 &ToolUseContent{ID: "c1", Name: "weather", Input: map[string]any{"city": "SF"}},
993 },
994 },
995 want: `{"content":[{"type":"text","text":"checking weather"},{"type":"tool_use","id":"c1","name":"weather","input":{"city":"SF"}}],"role":"assistant"}`,
996 },
997 }
998
999 for _, tt := range tests {
1000 t.Run(tt.name, func(t *testing.T) {
1001 got, err := json.Marshal(tt.msg)
1002 if err != nil {
1003 t.Fatalf("Marshal() error = %v", err)
1004 }
1005 if diff := cmp.Diff(tt.want, string(got)); diff != "" {
1006 t.Errorf("mismatch (-want +got):\n%s", diff)
1007 }
1008 })
1009 }
1010 }
1011
1012 func TestSamplingMessageV2_UnmarshalJSON(t *testing.T) {
1013 tests := []struct {
1014 name string
1015 json string
1016 want *SamplingMessageV2
1017 }{
1018 {
1019 name: "single content object",
1020 json: `{"role":"user","content":{"type":"text","text":"hello"}}`,
1021 want: &SamplingMessageV2{
1022 Role: "user",
1023 Content: []Content{
1024 &TextContent{Text: "hello"},
1025 },
1026 },
1027 },
1028 {
1029 name: "multiple content",
1030 json: `{"role":"assistant","content":[{"type":"text","text":"Let me check the weather."},{"type":"tool_use","id":"c1","name":"weather","input":{"city":"SF"}}]}`,
1031 want: &SamplingMessageV2{
1032 Role: "assistant",
1033 // Text + tool_use in the same message (valid per spec for assistant).
1034 Content: []Content{
1035 &TextContent{Text: "Let me check the weather."},
1036 &ToolUseContent{ID: "c1", Name: "weather", Input: map[string]any{"city": "SF"}},
1037 },
1038 },
1039 },
1040 }
1041
1042 for _, tt := range tests {
1043 t.Run(tt.name, func(t *testing.T) {
1044 var got SamplingMessageV2
1045 if err := json.Unmarshal([]byte(tt.json), &got); err != nil {
1046 t.Fatalf("Unmarshal() error = %v", err)
1047 }
1048 if diff := cmp.Diff(tt.want, &got); diff != "" {
1049 t.Errorf("mismatch (-want +got):\n%s", diff)
1050 }
1051 })
1052 }
1053 }
1054
1055 func TestToBase_Conversion(t *testing.T) {
1056 tests := []struct {
1057 name string
1058 params *CreateMessageWithToolsParams
1059 want *CreateMessageParams
1060 wantErr bool
1061 }{
1062 {
1063 name: "Single content",
1064 params: &CreateMessageWithToolsParams{
1065 MaxTokens: 1000,
1066 Messages: []*SamplingMessageV2{
1067 {Role: "user", Content: []Content{&TextContent{Text: "hello"}}},
1068 },
1069 Tools: []*Tool{{Name: "calc"}},
1070 ToolChoice: &ToolChoice{Mode: "auto"},
1071 },
1072 want: &CreateMessageParams{
1073 MaxTokens: 1000,
1074 Messages: []*SamplingMessage{
1075 {Role: "user", Content: &TextContent{Text: "hello"}},
1076 },
1077 },
1078 },
1079 {
1080 name: "Multi content",
1081 params: &CreateMessageWithToolsParams{
1082 MaxTokens: 1000,
1083 Messages: []*SamplingMessageV2{
1084 {Role: "assistant", Content: []Content{
1085 &ToolUseContent{ID: "c1", Name: "calc", Input: map[string]any{}},
1086 &ToolUseContent{ID: "c2", Name: "search", Input: map[string]any{}},
1087 }},
1088 },
1089 },
1090 wantErr: true,
1091 },
1092 }
1093
1094 for _, tt := range tests {
1095 t.Run(tt.name, func(t *testing.T) {
1096 got, err := tt.params.toBase()
1097 if (err != nil) != tt.wantErr {
1098 t.Fatalf("toBase() error = %v, wantErr %v", err, tt.wantErr)
1099 }
1100 if tt.wantErr {
1101 return
1102 }
1103 if diff := cmp.Diff(tt.want, got); diff != "" {
1104 t.Errorf("mismatch (-want +got):\n%s", diff)
1105 }
1106 })
1107 }
1108 }
1109
1110 func TestToWithTools_Conversion(t *testing.T) {
1111 tests := []struct {
1112 name string
1113 result *CreateMessageResult
1114 want *CreateMessageWithToolsResult
1115 }{
1116 {
1117 name: "with content",
1118 result: &CreateMessageResult{
1119 Model: "test",
1120 Role: "assistant",
1121 Content: &TextContent{Text: "hello"},
1122 StopReason: "endTurn",
1123 },
1124 want: &CreateMessageWithToolsResult{
1125 Model: "test",
1126 Role: "assistant",
1127 Content: []Content{&TextContent{Text: "hello"}},
1128 StopReason: "endTurn",
1129 },
1130 },
1131 {
1132 name: "nil content",
1133 result: &CreateMessageResult{
1134 Model: "test",
1135 Role: "assistant",
1136 },
1137 want: &CreateMessageWithToolsResult{
1138 Model: "test",
1139 Role: "assistant",
1140 },
1141 },
1142 }
1143
1144 for _, tt := range tests {
1145 t.Run(tt.name, func(t *testing.T) {
1146 wt := tt.result.toWithTools()
1147 if diff := cmp.Diff(tt.want, wt); diff != "" {
1148 t.Errorf("mismatch (-want +got):\n%s", diff)
1149 }
1150 })
1151 }
1152 }
1153
1154 func TestContentUnmarshal(t *testing.T) {
1155 // Verify that types with a Content field round-trip properly.
1156 roundtrip := func(in, out any) {
1157 t.Helper()
1158 data, err := json.Marshal(in)
1159 if err != nil {
1160 t.Fatal(err)
1161 }
1162 if err := json.Unmarshal(data, out); err != nil {
1163 t.Fatal(err)
1164 }
1165 if diff := cmp.Diff(in, out, ctrCmpOpts...); diff != "" {
1166 t.Errorf("mismatch (-want, +got):\n%s", diff)
1167 }
1168 }
1169
1170 content := []Content{&TextContent{Text: "t"}}
1171
1172 ctr := &CallToolResult{
1173 Meta: Meta{"m": true},
1174 Content: content,
1175 IsError: true,
1176 StructuredContent: map[string]any{"s": "x"},
1177 }
1178 var got CallToolResult
1179 roundtrip(ctr, &got)
1180
1181 ctrf := &CallToolResult{
1182 Meta: Meta{"m": true},
1183 Content: content,
1184 IsError: true,
1185 StructuredContent: 3.0,
1186 }
1187 var gotf CallToolResult
1188 roundtrip(ctrf, &gotf)
1189
1190 pm := &PromptMessage{
1191 Content: content[0],
1192 Role: "",
1193 }
1194 var gotpm PromptMessage
1195 roundtrip(pm, &gotpm)
1196 }