Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/conformance_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 "flag"
13 "fmt"
14 "io"
15 "io/fs"
16 "os"
17 "path/filepath"
18 "strings"
19 "testing"
20 "testing/synctest"
21 "time"
22
23 "github.com/google/go-cmp/cmp"
24 "github.com/google/go-cmp/cmp/cmpopts"
25 "github.com/google/jsonschema-go/jsonschema"
26 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
27 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
28 "golang.org/x/tools/txtar"
29 )
30
31 var update = flag.Bool("update", false, "if set, update conformance test data")
32
33 // A conformance test checks JSON-level conformance of a test server or client.
34 // This allows us to confirm that we can handle the input or output of other
35 // SDKs, even if they behave differently at the JSON level (for example, have
36 // different behavior with respect to optional fields).
37 //
38 // The client and server fields hold an encoded sequence of JSON-RPC messages.
39 //
40 // For server tests, the client messages are a sequence of messages to be sent
41 // from the (synthetic) client and the server messages are the expected
42 // messages to be received from the real server.
43 //
44 // For client tests, it's the other way around: server messages are synthetic,
45 // and client messages are expected from the real client.
46 //
47 // Conformance tests are loaded from txtar-encoded testdata files. Run the test
48 // with -update to have the test runner update the expected output, which may
49 // be client or server depending on the perspective of the test.
50 type conformanceTest struct {
51 name string // test name
52 path string // path to test file
53 archive *txtar.Archive // raw archive, for updating
54 tools, prompts, resources []string // named features to include
55 client []jsonrpc.Message // client messages
56 server []jsonrpc.Message // server messages
57 }
58
59 // TODO(rfindley): add client conformance tests.
60
61 func TestServerConformance(t *testing.T) {
62 var tests []*conformanceTest
63 dir := filepath.Join("testdata", "conformance", "server")
64 if err := filepath.WalkDir(dir, func(path string, _ fs.DirEntry, err error) error {
65 if err != nil {
66 return err
67 }
68 if strings.HasSuffix(path, ".txtar") {
69 test, err := loadConformanceTest(dir, path)
70 if err != nil {
71 return fmt.Errorf("%s: %v", path, err)
72 }
73 tests = append(tests, test)
74 }
75 return nil
76 }); err != nil {
77 t.Fatal(err)
78 }
79
80 for _, test := range tests {
81 t.Run(test.name, func(t *testing.T) {
82 // We use synctest here because in general, there is no way to know when the
83 // server is done processing any notifications. As long as our server doesn't
84 // do background work, synctest provides an easy way for us to detect when the
85 // server is done processing.
86 //
87 // By comparison, gopls has a complicated framework based on progress
88 // reporting and careful accounting to detect when all 'expected' work
89 // on the server is complete.
90 synctest.Test(t, func(t *testing.T) {
91 runServerTest(t, test)
92 })
93 })
94 }
95 }
96
97 type structuredInput struct {
98 In string `jsonschema:"the input"`
99 }
100
101 type structuredOutput struct {
102 Out string `jsonschema:"the output"`
103 }
104
105 func structuredTool(ctx context.Context, req *CallToolRequest, args *structuredInput) (*CallToolResult, *structuredOutput, error) {
106 return nil, &structuredOutput{"Ack " + args.In}, nil
107 }
108
109 func contentTool(ctx context.Context, req *CallToolRequest, args *structuredInput) (*CallToolResult, any, error) {
110 return &CallToolResult{
111 Content: []Content{
112 &ResourceLink{
113 Name: "Example Resource Link with Icons",
114 MIMEType: "text/plain",
115 URI: "https://example.com/resource/" + args.In,
116 Icons: []Icon{iconObj},
117 },
118 },
119 }, nil, nil
120 }
121
122 type tomorrowInput struct {
123 Now time.Time
124 }
125
126 type tomorrowOutput struct {
127 Tomorrow time.Time
128 }
129
130 func tomorrowTool(ctx context.Context, req *CallToolRequest, args tomorrowInput) (*CallToolResult, tomorrowOutput, error) {
131 return nil, tomorrowOutput{args.Now.Add(24 * time.Hour)}, nil
132 }
133
134 type incInput struct {
135 X int `json:"x,omitempty"`
136 }
137
138 type incOutput struct {
139 Y int `json:"y"`
140 }
141
142 func incTool(_ context.Context, _ *CallToolRequest, args incInput) (*CallToolResult, incOutput, error) {
143 return nil, incOutput{args.X + 1}, nil
144 }
145
146 var iconObj = Icon{
147 Source: "foobar",
148 MIMEType: "image/png",
149 Sizes: []string{"48x48", "96x96"},
150 Theme: IconThemeLight,
151 }
152
153 // runServerTest runs the server conformance test.
154 // It must be executed in a synctest bubble.
155 func runServerTest(t *testing.T, test *conformanceTest) {
156 ctx := t.Context()
157 // Construct the server based on features listed in the test.
158 impl := &Implementation{Name: "testServer", Version: "v1.0.0"}
159
160 if test.name == "spec-sep-973-additional-metadata.txtar" {
161 impl.Icons = []Icon{iconObj}
162 impl.WebsiteURL = "https://github.com/modelcontextprotocol/go-sdk"
163 }
164
165 s := NewServer(impl, nil)
166 for _, tn := range test.tools {
167 switch tn {
168 case "greet":
169 AddTool(s, &Tool{
170 Name: "greet",
171 Description: "say hi",
172 }, sayHi)
173 case "greetWithIcon":
174 AddTool(s, &Tool{
175 Name: "greetWithIcon",
176 Description: "say hi",
177 Icons: []Icon{iconObj},
178 }, sayHi)
179 case "structured":
180 AddTool(s, &Tool{Name: "structured"}, structuredTool)
181 case "tomorrow":
182 AddTool(s, &Tool{Name: "tomorrow"}, tomorrowTool)
183 case "inc":
184 inSchema, err := jsonschema.For[incInput](nil)
185 if err != nil {
186 t.Fatal(err)
187 }
188 inSchema.Properties["x"].Default = json.RawMessage(`6`)
189 AddTool(s, &Tool{Name: "inc", InputSchema: inSchema}, incTool)
190 case "contentTool":
191 AddTool(s, &Tool{
192 Name: "contentTool",
193 Title: "contentTool",
194 Description: "return resourceLink content with Icon",
195 }, contentTool)
196 default:
197 t.Fatalf("unknown tool %q", tn)
198 }
199 }
200 for _, pn := range test.prompts {
201 switch pn {
202 case "code_review":
203 s.AddPrompt(codeReviewPrompt, codReviewPromptHandler)
204 case "code_reviewWithIcon":
205 s.AddPrompt(&Prompt{
206 Name: "code_review",
207 Description: "do a code review",
208 Arguments: []*PromptArgument{{Name: "Code", Required: true}},
209 Icons: []Icon{iconObj},
210 }, codReviewPromptHandler)
211 default:
212 t.Fatalf("unknown prompt %q", pn)
213 }
214 }
215 for _, rn := range test.resources {
216 switch rn {
217 case "info.txt":
218 s.AddResource(resource1, readHandler)
219 case "info":
220 s.AddResource(resource3, handleEmbeddedResource)
221 case "infoWithIcon":
222 s.AddResource(&Resource{
223 Name: "info",
224 MIMEType: "text/plain",
225 URI: "embedded:info",
226 Icons: []Icon{iconObj},
227 }, handleEmbeddedResource)
228 default:
229 t.Fatalf("unknown resource %q", rn)
230 }
231 }
232
233 // Connect the server, and connect the client stream,
234 // but don't connect an actual client.
235 cTransport, sTransport := NewInMemoryTransports()
236 ss, err := s.Connect(ctx, sTransport, nil)
237 if err != nil {
238 t.Fatal(err)
239 }
240 cStream, err := cTransport.Connect(ctx)
241 if err != nil {
242 t.Fatal(err)
243 }
244
245 writeMsg := func(msg jsonrpc.Message) {
246 if err := cStream.Write(ctx, msg); err != nil {
247 t.Fatalf("Write failed: %v", err)
248 }
249 }
250
251 var (
252 serverMessages []jsonrpc.Message
253 outRequests []*jsonrpc.Request
254 outResponses []*jsonrpc.Response
255 )
256
257 // Separate client requests and responses; we use them differently.
258 for _, msg := range test.client {
259 switch msg := msg.(type) {
260 case *jsonrpc.Request:
261 outRequests = append(outRequests, msg)
262 case *jsonrpc.Response:
263 outResponses = append(outResponses, msg)
264 default:
265 t.Fatalf("bad message type %T", msg)
266 }
267 }
268
269 // nextResponse handles incoming requests and notifications, and returns the
270 // next incoming response.
271 nextResponse := func() (*jsonrpc.Response, error, bool) {
272 for {
273 msg, err := cStream.Read(ctx)
274 if err != nil {
275 // TODO(rfindley): we don't document (or want to document) that the in
276 // memory transports use a net.Pipe. How can users detect this failure?
277 // Should we promote it to EOF?
278 if errors.Is(err, io.ErrClosedPipe) {
279 err = nil
280 }
281 return nil, err, false
282 }
283 serverMessages = append(serverMessages, msg)
284 if req, ok := msg.(*jsonrpc.Request); ok && req.IsCall() {
285 // Pair up the next outgoing response with this request.
286 // We assume requests arrive in the same order every time.
287 if len(outResponses) == 0 {
288 t.Fatalf("no outgoing response for request %v", req)
289 }
290 outResponses[0].ID = req.ID
291 writeMsg(outResponses[0])
292 outResponses = outResponses[1:]
293 continue
294 }
295 return msg.(*jsonrpc.Response), nil, true
296 }
297 }
298
299 // Synthetic peer interacts with real peer.
300 for _, req := range outRequests {
301 writeMsg(req)
302 if req.IsCall() {
303 // A call (as opposed to a notification). Wait for the response.
304 res, err, ok := nextResponse()
305 if err != nil {
306 t.Fatalf("reading server messages failed: %v", err)
307 }
308 if !ok {
309 t.Fatalf("missing response for request %v", req)
310 }
311 if res.ID != req.ID {
312 t.Fatalf("out-of-order response %v to request %v", req, res)
313 }
314 }
315 }
316 // There might be more notifications or requests, but there shouldn't be more
317 // responses.
318 // Run this in a goroutine so the current thread can wait for it.
319 var extra *jsonrpc.Response
320 go func() {
321 extra, err, _ = nextResponse()
322 }()
323 // Before closing the stream, wait for all messages to be processed.
324 synctest.Wait()
325 if err != nil {
326 t.Fatalf("reading server messages failed: %v", err)
327 }
328 if extra != nil {
329 t.Fatalf("got extra response: %v", extra)
330 }
331 if err := cStream.Close(); err != nil {
332 t.Fatalf("Stream.Close failed: %v", err)
333 }
334 ss.Wait()
335
336 // Handle server output. If -update is set, write the 'server' file.
337 // Otherwise, compare with expected.
338 if *update {
339 arch := &txtar.Archive{
340 Comment: test.archive.Comment,
341 }
342 var buf bytes.Buffer
343 for _, msg := range serverMessages {
344 data, err := jsonrpc2.EncodeIndent(msg, "", "\t")
345 if err != nil {
346 t.Fatalf("jsonrpc2.EncodeIndent failed: %v", err)
347 }
348 buf.Write(data)
349 buf.WriteByte('\n')
350 }
351 serverFile := txtar.File{Name: "server", Data: buf.Bytes()}
352 seenServer := false // replace or append the 'server' file
353 for _, f := range test.archive.Files {
354 if f.Name == "server" {
355 seenServer = true
356 arch.Files = append(arch.Files, serverFile)
357 } else {
358 arch.Files = append(arch.Files, f)
359 }
360 }
361 if !seenServer {
362 arch.Files = append(arch.Files, serverFile)
363 }
364 if err := os.WriteFile(test.path, txtar.Format(arch), 0o666); err != nil {
365 t.Fatalf("os.WriteFile(%q) failed: %v", test.path, err)
366 }
367 } else {
368 // jsonrpc.Messages are not comparable, so we instead compare lines of JSON.
369 transform := cmpopts.AcyclicTransformer("toJSON", func(msg jsonrpc.Message) []string {
370 encoded, err := jsonrpc2.EncodeIndent(msg, "", "\t")
371 if err != nil {
372 t.Fatal(err)
373 }
374 return strings.Split(string(encoded), "\n")
375 })
376 if diff := cmp.Diff(test.server, serverMessages, transform); diff != "" {
377 t.Errorf("Mismatching server messages (-want +got):\n%s", diff)
378 }
379 }
380 }
381
382 // loadConformanceTest loads one conformance test from the given path contained
383 // in the root dir.
384 func loadConformanceTest(dir, path string) (*conformanceTest, error) {
385 content, err := os.ReadFile(path)
386 if err != nil {
387 return nil, err
388 }
389 test := &conformanceTest{
390 name: strings.TrimPrefix(path, dir+string(filepath.Separator)),
391 path: path,
392 archive: txtar.Parse(content),
393 }
394 if len(test.archive.Files) == 0 {
395 return nil, fmt.Errorf("txtar archive %q has no '-- filename --' sections", path)
396 }
397
398 // decodeMessages loads JSON-RPC messages from the archive file.
399 decodeMessages := func(data []byte) ([]jsonrpc.Message, error) {
400 dec := json.NewDecoder(bytes.NewReader(data))
401 var res []jsonrpc.Message
402 for dec.More() {
403 var raw json.RawMessage
404 if err := dec.Decode(&raw); err != nil {
405 return nil, err
406 }
407 m, err := jsonrpc2.DecodeMessage(raw)
408 if err != nil {
409 return nil, err
410 }
411 res = append(res, m)
412 }
413 return res, nil
414 }
415 // loadFeatures loads lists of named features from the archive file.
416 loadFeatures := func(data []byte) []string {
417 var feats []string
418 for line := range strings.Lines(string(data)) {
419 if f := strings.TrimSpace(line); f != "" {
420 feats = append(feats, f)
421 }
422 }
423 return feats
424 }
425
426 seen := make(map[string]bool) // catch accidentally duplicate files
427 for _, f := range test.archive.Files {
428 if seen[f.Name] {
429 return nil, fmt.Errorf("duplicate file name %q", f.Name)
430 }
431 seen[f.Name] = true
432 switch f.Name {
433 case "tools":
434 test.tools = loadFeatures(f.Data)
435 case "prompts":
436 test.prompts = loadFeatures(f.Data)
437 case "resources":
438 test.resources = loadFeatures(f.Data)
439 case "client":
440 test.client, err = decodeMessages(f.Data)
441 if err != nil {
442 return nil, fmt.Errorf("txtar archive %q contains bad -- client -- section: %v", path, err)
443 }
444 case "server":
445 test.server, err = decodeMessages(f.Data)
446 if err != nil {
447 return nil, fmt.Errorf("txtar archive %q contains bad -- server -- section: %v", path, err)
448 }
449 default:
450 return nil, fmt.Errorf("txtar archive %q contains unexpected file %q", path, f.Name)
451 }
452 }
453
454 return test, nil
455 }