| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
type conformanceTest struct { |
| 51 |
name string |
| 52 |
path string |
| 53 |
archive *txtar.Archive |
| 54 |
tools, prompts, resources []string |
| 55 |
client []jsonrpc.Message |
| 56 |
server []jsonrpc.Message |
| 57 |
} |
| 58 |
|
| 59 |
|
| 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 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 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 |
|
| 154 |
|
| 155 |
func runServerTest(t *testing.T, test *conformanceTest) { |
| 156 |
ctx := t.Context() |
| 157 |
|
| 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 |
|
| 234 |
|
| 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 |
|
| 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 |
|
| 270 |
|
| 271 |
nextResponse := func() (*jsonrpc.Response, error, bool) { |
| 272 |
for { |
| 273 |
msg, err := cStream.Read(ctx) |
| 274 |
if err != nil { |
| 275 |
|
| 276 |
|
| 277 |
|
| 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 |
|
| 286 |
|
| 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 |
|
| 300 |
for _, req := range outRequests { |
| 301 |
writeMsg(req) |
| 302 |
if req.IsCall() { |
| 303 |
|
| 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 |
|
| 317 |
|
| 318 |
|
| 319 |
var extra *jsonrpc.Response |
| 320 |
go func() { |
| 321 |
extra, err, _ = nextResponse() |
| 322 |
}() |
| 323 |
|
| 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 |
|
| 337 |
|
| 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 |
| 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 |
|
| 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 |
|
| 383 |
|
| 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 |
|
| 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 |
|
| 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) |
| 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 |
} |