@@ -6,6 +6,7 @@ package mcp
66
77import (
88 "context"
9+ "encoding/json"
910 "log"
1011 "slices"
1112 "testing"
@@ -487,3 +488,59 @@ func TestAddTool(t *testing.T) {
487488 t .Error ("bad Out: expected panic" )
488489 }
489490}
491+
492+ type schema = jsonschema.Schema
493+
494+ func testToolForSchema [In , Out any ](t * testing.T , tool * Tool , in string , out Out , wantIn , wantOut * schema , wantErr bool ) {
495+ t .Helper ()
496+ th := func (context.Context , * CallToolRequest , In ) (* CallToolResult , Out , error ) {
497+ return nil , out , nil
498+ }
499+ gott , goth , err := toolForErr (tool , th )
500+ if err != nil {
501+ t .Fatal (err )
502+ }
503+ if diff := cmp .Diff (wantIn , gott .InputSchema ); diff != "" {
504+ t .Errorf ("input: mismatch (-want, +got):\n %s" , diff )
505+ }
506+ if diff := cmp .Diff (wantOut , gott .OutputSchema ); diff != "" {
507+ t .Errorf ("output: mismatch (-want, +got):\n %s" , diff )
508+ }
509+ ctr := & CallToolRequest {
510+ Params : & CallToolParamsRaw {
511+ Arguments : json .RawMessage (in ),
512+ },
513+ }
514+ _ , err = goth (context .Background (), ctr )
515+
516+ if gotErr := err != nil ; gotErr != wantErr {
517+ t .Errorf ("got error: %t, want error: %t" , gotErr , wantErr )
518+ }
519+ }
520+
521+ func TestToolForSchemas (t * testing.T ) {
522+ // Validate that ToolFor handles schemas properly.
523+
524+ // Infer both schemas.
525+ testToolForSchema [int ](t , & Tool {}, "3" , true ,
526+ & schema {Type : "integer" }, & schema {Type : "boolean" }, false )
527+ // Validate the input schema: expect an error if it's wrong.
528+ // We can't test that the output schema is validated, because it's typed.
529+ testToolForSchema [int ](t , & Tool {}, `"x"` , true ,
530+ & schema {Type : "integer" }, & schema {Type : "boolean" }, true )
531+
532+ // Ignore type any for output.
533+ testToolForSchema [int , any ](t , & Tool {}, "3" , 0 ,
534+ & schema {Type : "integer" }, nil , false )
535+ // Input is still validated.
536+ testToolForSchema [int , any ](t , & Tool {}, `"x"` , 0 ,
537+ & schema {Type : "integer" }, nil , true )
538+
539+ // Tool sets input schema: that is what's used.
540+ testToolForSchema [int , any ](t , & Tool {InputSchema : & schema {Type : "string" }}, "3" , 0 ,
541+ & schema {Type : "string" }, nil , true ) // error: 3 is not a string
542+
543+ // Tool sets output schema: that is what's used, and validation happens.
544+ testToolForSchema [string , any ](t , & Tool {OutputSchema : & schema {Type : "integer" }}, "3" , "x" ,
545+ & schema {Type : "string" }, & schema {Type : "integer" }, true ) // error: "x" is not an integer
546+ }
0 commit comments