| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package mcp |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"context" |
| 10 |
"encoding/json" |
| 11 |
"errors" |
| 12 |
"fmt" |
| 13 |
"io" |
| 14 |
"maps" |
| 15 |
"net" |
| 16 |
"net/http" |
| 17 |
"net/http/cookiejar" |
| 18 |
"net/http/httptest" |
| 19 |
"net/http/httputil" |
| 20 |
"net/url" |
| 21 |
"os" |
| 22 |
"runtime" |
| 23 |
"slices" |
| 24 |
"sort" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"sync/atomic" |
| 28 |
"testing" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/google/go-cmp/cmp" |
| 32 |
"github.com/google/go-cmp/cmp/cmpopts" |
| 33 |
"github.com/google/jsonschema-go/jsonschema" |
| 34 |
"github.com/modelcontextprotocol/go-sdk/auth" |
| 35 |
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2" |
| 36 |
"github.com/modelcontextprotocol/go-sdk/jsonrpc" |
| 37 |
) |
| 38 |
|
| 39 |
func TestStreamableTransports(t *testing.T) { |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
ctx := context.Background() |
| 44 |
|
| 45 |
tests := []struct { |
| 46 |
useJSON bool |
| 47 |
replay bool |
| 48 |
}{ |
| 49 |
{false, false}, |
| 50 |
{false, true}, |
| 51 |
{true, false}, |
| 52 |
{true, true}, |
| 53 |
} |
| 54 |
|
| 55 |
for _, test := range tests { |
| 56 |
t.Run(fmt.Sprintf("JSONResponse=%v;replay=%v", test.useJSON, test.replay), func(t *testing.T) { |
| 57 |
|
| 58 |
server := NewServer(testImpl, nil) |
| 59 |
AddTool(server, &Tool{Name: "greet", Description: "say hi"}, sayHi) |
| 60 |
|
| 61 |
|
| 62 |
var ( |
| 63 |
start = make(chan struct{}) |
| 64 |
cancelled = make(chan struct{}, 1) |
| 65 |
) |
| 66 |
hang := func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) { |
| 67 |
start <- struct{}{} |
| 68 |
select { |
| 69 |
case <-ctx.Done(): |
| 70 |
cancelled <- struct{}{} |
| 71 |
case <-time.After(5 * time.Second): |
| 72 |
return nil, nil, nil |
| 73 |
} |
| 74 |
return nil, nil, nil |
| 75 |
} |
| 76 |
AddTool(server, &Tool{Name: "hang"}, hang) |
| 77 |
|
| 78 |
|
| 79 |
sampleDone := make(chan struct{}) |
| 80 |
var sampleWG sync.WaitGroup |
| 81 |
AddTool(server, &Tool{Name: "sample"}, func(ctx context.Context, req *CallToolRequest, args any) (*CallToolResult, any, error) { |
| 82 |
type testCase struct { |
| 83 |
label string |
| 84 |
ctx context.Context |
| 85 |
wantSuccess bool |
| 86 |
} |
| 87 |
testSample := func(tc testCase) { |
| 88 |
res, err := req.Session.CreateMessage(tc.ctx, &CreateMessageParams{}) |
| 89 |
if gotSuccess := err == nil; gotSuccess != tc.wantSuccess { |
| 90 |
t.Errorf("%s: CreateMessage success=%v, want %v", tc.label, gotSuccess, tc.wantSuccess) |
| 91 |
} |
| 92 |
if err != nil { |
| 93 |
return |
| 94 |
} |
| 95 |
if g, w := res.Model, "aModel"; g != w { |
| 96 |
t.Errorf("%s: got model %q, want %q", tc.label, g, w) |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
for _, test := range []testCase{ |
| 104 |
{"request context", ctx, true}, |
| 105 |
{"background context", context.Background(), true}, |
| 106 |
} { |
| 107 |
testSample(test) |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
sampleWG.Go(func() { |
| 112 |
<-sampleDone |
| 113 |
|
| 114 |
|
| 115 |
for _, test := range []testCase{ |
| 116 |
{"request context", ctx, false}, |
| 117 |
{"background context", context.Background(), true}, |
| 118 |
} { |
| 119 |
testSample(test) |
| 120 |
} |
| 121 |
}) |
| 122 |
return &CallToolResult{}, nil, nil |
| 123 |
}) |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
opts := &StreamableHTTPOptions{ |
| 128 |
JSONResponse: test.useJSON, |
| 129 |
} |
| 130 |
if test.replay { |
| 131 |
opts.EventStore = NewMemoryEventStore(nil) |
| 132 |
} |
| 133 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, opts) |
| 134 |
|
| 135 |
var ( |
| 136 |
headerMu sync.Mutex |
| 137 |
lastHeader http.Header |
| 138 |
) |
| 139 |
httpServer := httptest.NewServer(mustNotPanic(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 140 |
headerMu.Lock() |
| 141 |
lastHeader = r.Header |
| 142 |
headerMu.Unlock() |
| 143 |
cookie, err := r.Cookie("test-cookie") |
| 144 |
if err != nil { |
| 145 |
t.Errorf("missing cookie: %v", err) |
| 146 |
} else if cookie.Value != "test-value" { |
| 147 |
t.Errorf("got cookie %q, want %q", cookie.Value, "test-value") |
| 148 |
} |
| 149 |
handler.ServeHTTP(w, r) |
| 150 |
}))) |
| 151 |
defer httpServer.Close() |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
jar, err := cookiejar.New(nil) |
| 156 |
if err != nil { |
| 157 |
t.Fatal(err) |
| 158 |
} |
| 159 |
u, err := url.Parse(httpServer.URL) |
| 160 |
if err != nil { |
| 161 |
t.Fatal(err) |
| 162 |
} |
| 163 |
jar.SetCookies(u, []*http.Cookie{{Name: "test-cookie", Value: "test-value"}}) |
| 164 |
httpClient := &http.Client{Jar: jar} |
| 165 |
transport := &StreamableClientTransport{ |
| 166 |
Endpoint: httpServer.URL, |
| 167 |
HTTPClient: httpClient, |
| 168 |
} |
| 169 |
client := NewClient(testImpl, &ClientOptions{ |
| 170 |
CreateMessageHandler: func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error) { |
| 171 |
return &CreateMessageResult{Model: "aModel", Content: &TextContent{}}, nil |
| 172 |
}, |
| 173 |
}) |
| 174 |
session, err := client.Connect(ctx, transport, nil) |
| 175 |
if err != nil { |
| 176 |
t.Fatalf("client.Connect() failed: %v", err) |
| 177 |
} |
| 178 |
defer session.Close() |
| 179 |
sid := session.ID() |
| 180 |
if sid == "" { |
| 181 |
t.Fatalf("empty session ID") |
| 182 |
} |
| 183 |
if g, w := session.mcpConn.(*streamableClientConn).initializedResult.ProtocolVersion, latestProtocolVersion; g != w { |
| 184 |
t.Fatalf("got protocol version %q, want %q", g, w) |
| 185 |
} |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
params := &CallToolParams{ |
| 191 |
Name: "greet", |
| 192 |
Arguments: map[string]any{"Name": "foo"}, |
| 193 |
} |
| 194 |
got, err := session.CallTool(ctx, params) |
| 195 |
if err != nil { |
| 196 |
t.Fatalf("CallTool() failed: %v", err) |
| 197 |
} |
| 198 |
if g := session.ID(); g != sid { |
| 199 |
t.Errorf("session ID: got %q, want %q", g, sid) |
| 200 |
} |
| 201 |
if g, w := lastHeader.Get(protocolVersionHeader), latestProtocolVersion; g != w { |
| 202 |
t.Errorf("got protocol version header %q, want %q", g, w) |
| 203 |
} |
| 204 |
want := &CallToolResult{ |
| 205 |
Content: []Content{&TextContent{Text: "hi foo"}}, |
| 206 |
} |
| 207 |
if diff := cmp.Diff(want, got, ctrCmpOpts...); diff != "" { |
| 208 |
t.Errorf("CallTool() returned unexpected content (-want +got):\n%s", diff) |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
ctx2, cancel := context.WithCancel(context.Background()) |
| 213 |
go session.CallTool(ctx2, &CallToolParams{Name: "hang"}) |
| 214 |
<-start |
| 215 |
cancel() |
| 216 |
select { |
| 217 |
case <-cancelled: |
| 218 |
case <-time.After(5 * time.Second): |
| 219 |
t.Fatal("timeout waiting for cancellation") |
| 220 |
} |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
result, err := session.CallTool(ctx, &CallToolParams{ |
| 225 |
Name: "sample", |
| 226 |
Arguments: map[string]any{}, |
| 227 |
}) |
| 228 |
if err != nil { |
| 229 |
t.Fatal(err) |
| 230 |
} |
| 231 |
|
| 232 |
close(sampleDone) |
| 233 |
sampleWG.Wait() |
| 234 |
|
| 235 |
if result.IsError { |
| 236 |
t.Fatalf("tool failed: %s", result.Content[0].(*TextContent).Text) |
| 237 |
} |
| 238 |
}) |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
func TestStreamableConcurrentHandling(t *testing.T) { |
| 243 |
|
| 244 |
|
| 245 |
type count struct { |
| 246 |
Count int |
| 247 |
} |
| 248 |
|
| 249 |
var mu sync.Mutex |
| 250 |
counts := make(map[string]int) |
| 251 |
|
| 252 |
server := NewServer(testImpl, nil) |
| 253 |
AddTool(server, &Tool{Name: "inc"}, func(ctx context.Context, req *CallToolRequest, _ any) (*CallToolResult, count, error) { |
| 254 |
id := req.Session.ID() |
| 255 |
mu.Lock() |
| 256 |
defer mu.Unlock() |
| 257 |
c := counts[id] |
| 258 |
counts[id] = c + 1 |
| 259 |
return nil, count{c}, nil |
| 260 |
}) |
| 261 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 262 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 263 |
defer httpServer.Close() |
| 264 |
|
| 265 |
ctx := context.Background() |
| 266 |
client := NewClient(testImpl, nil) |
| 267 |
var wg sync.WaitGroup |
| 268 |
for range 100 { |
| 269 |
wg.Go(func() { |
| 270 |
clientSession, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, nil) |
| 271 |
if err != nil { |
| 272 |
t.Errorf("Connect failed: %v", err) |
| 273 |
return |
| 274 |
} |
| 275 |
defer clientSession.Close() |
| 276 |
for i := range 10 { |
| 277 |
res, err := clientSession.CallTool(ctx, &CallToolParams{Name: "inc"}) |
| 278 |
if err != nil { |
| 279 |
t.Errorf("CallTool failed: %v", err) |
| 280 |
return |
| 281 |
} |
| 282 |
if got := int(res.StructuredContent.(map[string]any)["Count"].(float64)); got != i { |
| 283 |
t.Errorf("got count %d, want %d", got, i) |
| 284 |
} |
| 285 |
} |
| 286 |
}) |
| 287 |
} |
| 288 |
wg.Wait() |
| 289 |
} |
| 290 |
|
| 291 |
func TestStreamableServerShutdown(t *testing.T) { |
| 292 |
ctx := context.Background() |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
tests := []struct { |
| 299 |
name string |
| 300 |
stateless, keepalive bool |
| 301 |
}{ |
| 302 |
{"stateful", false, false}, |
| 303 |
{"stateless with keepalive", true, true}, |
| 304 |
} |
| 305 |
|
| 306 |
for _, test := range tests { |
| 307 |
t.Run(test.name, func(t *testing.T) { |
| 308 |
server := NewServer(testImpl, nil) |
| 309 |
|
| 310 |
AddTool(server, &Tool{Name: "greet"}, sayHi) |
| 311 |
|
| 312 |
handler := NewStreamableHTTPHandler( |
| 313 |
func(req *http.Request) *Server { return server }, |
| 314 |
&StreamableHTTPOptions{Stateless: test.stateless}) |
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
httpServer := httptest.NewUnstartedServer(handler) |
| 319 |
httpServer.Config.RegisterOnShutdown(func() { |
| 320 |
for session := range server.Sessions() { |
| 321 |
session.Close() |
| 322 |
} |
| 323 |
}) |
| 324 |
httpServer.Start() |
| 325 |
defer httpServer.Close() |
| 326 |
|
| 327 |
|
| 328 |
var opts ClientOptions |
| 329 |
if test.keepalive { |
| 330 |
opts.KeepAlive = 50 * time.Millisecond |
| 331 |
} |
| 332 |
client := NewClient(testImpl, &opts) |
| 333 |
clientSession, err := client.Connect(ctx, &StreamableClientTransport{ |
| 334 |
Endpoint: httpServer.URL, |
| 335 |
MaxRetries: -1, |
| 336 |
}, nil) |
| 337 |
if err != nil { |
| 338 |
t.Fatal(err) |
| 339 |
} |
| 340 |
defer clientSession.Close() |
| 341 |
|
| 342 |
params := &CallToolParams{ |
| 343 |
Name: "greet", |
| 344 |
Arguments: map[string]any{"Name": "foo"}, |
| 345 |
} |
| 346 |
|
| 347 |
if _, err := clientSession.CallTool(ctx, params); err != nil { |
| 348 |
t.Fatalf("CallTool() failed: %v", err) |
| 349 |
} |
| 350 |
|
| 351 |
|
| 352 |
go func() { |
| 353 |
if err := httpServer.Config.Shutdown(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 354 |
t.Errorf("closing http server: %v", err) |
| 355 |
} |
| 356 |
}() |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
t.Log("Client waiting") |
| 361 |
_ = clientSession.Wait() |
| 362 |
}) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
func TestStreamableStatelessKeepaliveRace(t *testing.T) { |
| 369 |
ctx := context.Background() |
| 370 |
server := NewServer(testImpl, &ServerOptions{KeepAlive: time.Hour}) |
| 371 |
AddTool(server, &Tool{Name: "greet"}, sayHi) |
| 372 |
handler := NewStreamableHTTPHandler( |
| 373 |
func(*http.Request) *Server { return server }, |
| 374 |
&StreamableHTTPOptions{Stateless: true}, |
| 375 |
) |
| 376 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 377 |
defer httpServer.Close() |
| 378 |
|
| 379 |
for range 50 { |
| 380 |
cs, err := NewClient(testImpl, nil).Connect(ctx, &StreamableClientTransport{ |
| 381 |
Endpoint: httpServer.URL, |
| 382 |
}, nil) |
| 383 |
if err != nil { |
| 384 |
t.Fatalf("NewClient() failed: %v", err) |
| 385 |
} |
| 386 |
_, _ = cs.CallTool(ctx, &CallToolParams{ |
| 387 |
Name: "greet", |
| 388 |
Arguments: map[string]any{"Name": "world"}, |
| 389 |
}) |
| 390 |
_ = cs.Close() |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
func TestClientReplay(t *testing.T) { |
| 401 |
for _, test := range []clientReplayTest{ |
| 402 |
{"default", 0, true}, |
| 403 |
{"no retries", -1, false}, |
| 404 |
} { |
| 405 |
t.Run(test.name, func(t *testing.T) { |
| 406 |
testClientReplay(t, test) |
| 407 |
}) |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
type clientReplayTest struct { |
| 412 |
name string |
| 413 |
maxRetries int |
| 414 |
wantRecovered bool |
| 415 |
} |
| 416 |
|
| 417 |
func testClientReplay(t *testing.T, test clientReplayTest) { |
| 418 |
notifications := make(chan string) |
| 419 |
|
| 420 |
server := NewServer(testImpl, nil) |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
serverReadyToKillProxy := make(chan struct{}) |
| 425 |
serverClosed := make(chan struct{}) |
| 426 |
AddTool(server, &Tool{Name: "multiMessageTool", InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 427 |
func(ctx context.Context, req *CallToolRequest, args map[string]any) (*CallToolResult, any, error) { |
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
bgCtx := context.Background() |
| 432 |
req.Session.NotifyProgress(ctx, &ProgressNotificationParams{Message: "msg1"}) |
| 433 |
req.Session.NotifyProgress(bgCtx, &ProgressNotificationParams{Message: "msg2"}) |
| 434 |
|
| 435 |
|
| 436 |
close(serverReadyToKillProxy) |
| 437 |
<-serverClosed |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
req.Session.NotifyProgress(ctx, &ProgressNotificationParams{Message: "msg3"}) |
| 442 |
req.Session.NotifyProgress(bgCtx, &ProgressNotificationParams{Message: "msg4"}) |
| 443 |
return new(CallToolResult), nil, nil |
| 444 |
}) |
| 445 |
|
| 446 |
realServer := httptest.NewServer(mustNotPanic(t, NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, &StreamableHTTPOptions{ |
| 447 |
EventStore: NewMemoryEventStore(nil), |
| 448 |
}))) |
| 449 |
t.Cleanup(func() { |
| 450 |
t.Log("Closing real HTTP server") |
| 451 |
realServer.Close() |
| 452 |
}) |
| 453 |
realServerURL, err := url.Parse(realServer.URL) |
| 454 |
if err != nil { |
| 455 |
t.Fatalf("Failed to parse real server URL: %v", err) |
| 456 |
} |
| 457 |
|
| 458 |
|
| 459 |
proxyHandler := httputil.NewSingleHostReverseProxy(realServerURL) |
| 460 |
|
| 461 |
proxy := httptest.NewServer(proxyHandler) |
| 462 |
proxyAddr := proxy.Listener.Addr().String() |
| 463 |
|
| 464 |
|
| 465 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 466 |
defer cancel() |
| 467 |
client := NewClient(testImpl, &ClientOptions{ |
| 468 |
ProgressNotificationHandler: func(ctx context.Context, req *ProgressNotificationClientRequest) { |
| 469 |
notifications <- req.Params.Message |
| 470 |
}, |
| 471 |
}) |
| 472 |
clientSession, err := client.Connect(ctx, &StreamableClientTransport{ |
| 473 |
Endpoint: proxy.URL, |
| 474 |
MaxRetries: test.maxRetries, |
| 475 |
}, nil) |
| 476 |
if err != nil { |
| 477 |
t.Fatalf("client.Connect() failed: %v", err) |
| 478 |
} |
| 479 |
t.Cleanup(func() { |
| 480 |
t.Log("Closing clientSession") |
| 481 |
clientSession.Close() |
| 482 |
}) |
| 483 |
|
| 484 |
toolCallResult := make(chan error, 1) |
| 485 |
go func() { |
| 486 |
_, callErr := clientSession.CallTool(ctx, &CallToolParams{Name: "multiMessageTool"}) |
| 487 |
toolCallResult <- callErr |
| 488 |
}() |
| 489 |
|
| 490 |
select { |
| 491 |
case <-serverReadyToKillProxy: |
| 492 |
t.Log("Server has sent the first two messages and is paused.") |
| 493 |
case <-ctx.Done(): |
| 494 |
t.Fatalf("Context timed out before server was ready to kill proxy") |
| 495 |
} |
| 496 |
|
| 497 |
|
| 498 |
msgs := readNotifications(t, ctx, notifications, 2) |
| 499 |
sort.Strings(msgs) |
| 500 |
want := []string{"msg1", "msg2"} |
| 501 |
if diff := cmp.Diff(want, msgs); diff != "" { |
| 502 |
t.Errorf("Recovered notifications mismatch (-want +got):\n%s", diff) |
| 503 |
} |
| 504 |
|
| 505 |
|
| 506 |
t.Log("--- Killing proxy to simulate network failure ---") |
| 507 |
proxy.CloseClientConnections() |
| 508 |
proxy.Close() |
| 509 |
close(serverClosed) |
| 510 |
|
| 511 |
|
| 512 |
t.Logf("--- Restarting proxy on %s ---", proxyAddr) |
| 513 |
listener, err := net.Listen("tcp", proxyAddr) |
| 514 |
if err != nil { |
| 515 |
t.Fatalf("Failed to listen on proxy address: %v", err) |
| 516 |
} |
| 517 |
|
| 518 |
restartedProxy := &http.Server{Handler: proxyHandler} |
| 519 |
go restartedProxy.Serve(listener) |
| 520 |
t.Cleanup(func() { restartedProxy.Close() }) |
| 521 |
|
| 522 |
callErr := <-toolCallResult |
| 523 |
|
| 524 |
if test.wantRecovered { |
| 525 |
|
| 526 |
|
| 527 |
msgs := readNotifications(t, ctx, notifications, 2) |
| 528 |
sort.Strings(msgs) |
| 529 |
want := []string{"msg3", "msg4"} |
| 530 |
if diff := cmp.Diff(want, msgs); diff != "" { |
| 531 |
t.Errorf("Recovered notifications mismatch (-want +got):\n%s", diff) |
| 532 |
} |
| 533 |
if callErr != nil { |
| 534 |
t.Errorf("CallTool failed unexpectedly: %v", err) |
| 535 |
} |
| 536 |
} else { |
| 537 |
|
| 538 |
if callErr == nil { |
| 539 |
t.Errorf("CallTool succeeded unexpectedly") |
| 540 |
} |
| 541 |
} |
| 542 |
} |
| 543 |
|
| 544 |
func TestStreamableServerDisconnect(t *testing.T) { |
| 545 |
server := NewServer(testImpl, nil) |
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
testStream := func(ctx context.Context, session *ServerSession, extra *RequestExtra) { |
| 553 |
|
| 554 |
|
| 555 |
extra.CloseSSEStream(CloseSSEStreamArgs{RetryAfter: 10 * time.Millisecond}) |
| 556 |
session.NotifyProgress(ctx, &ProgressNotificationParams{Message: "msg1"}) |
| 557 |
time.Sleep(20 * time.Millisecond) |
| 558 |
extra.CloseSSEStream(CloseSSEStreamArgs{RetryAfter: 10 * time.Millisecond}) |
| 559 |
session.NotifyProgress(ctx, &ProgressNotificationParams{Message: "msg2"}) |
| 560 |
} |
| 561 |
|
| 562 |
AddTool(server, &Tool{Name: "disconnect"}, |
| 563 |
func(ctx context.Context, req *CallToolRequest, args map[string]any) (*CallToolResult, map[string]any, error) { |
| 564 |
testStream(ctx, req.Session, req.Extra) |
| 565 |
return new(CallToolResult), nil, nil |
| 566 |
}) |
| 567 |
|
| 568 |
server.AddPrompt(&Prompt{Name: "disconnect"}, func(ctx context.Context, req *GetPromptRequest) (*GetPromptResult, error) { |
| 569 |
testStream(ctx, req.Session, req.Extra) |
| 570 |
return nil, nil |
| 571 |
}) |
| 572 |
|
| 573 |
tests := []struct { |
| 574 |
name string |
| 575 |
doCall func(context.Context, *ClientSession) error |
| 576 |
}{ |
| 577 |
{ |
| 578 |
"tool", |
| 579 |
func(ctx context.Context, cs *ClientSession) error { |
| 580 |
_, err := cs.CallTool(ctx, &CallToolParams{Name: "disconnect"}) |
| 581 |
return err |
| 582 |
}, |
| 583 |
}, |
| 584 |
{ |
| 585 |
"prompt", |
| 586 |
func(ctx context.Context, cs *ClientSession) error { |
| 587 |
_, err := cs.GetPrompt(ctx, &GetPromptParams{Name: "disconnect"}) |
| 588 |
return err |
| 589 |
}, |
| 590 |
}, |
| 591 |
} |
| 592 |
|
| 593 |
for _, test := range tests { |
| 594 |
t.Run(test.name, func(t *testing.T) { |
| 595 |
notifications := make(chan string, 2) |
| 596 |
handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, &StreamableHTTPOptions{ |
| 597 |
EventStore: NewMemoryEventStore(nil), |
| 598 |
}) |
| 599 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 600 |
defer httpServer.Close() |
| 601 |
|
| 602 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 603 |
defer cancel() |
| 604 |
client := NewClient(testImpl, &ClientOptions{ |
| 605 |
ProgressNotificationHandler: func(ctx context.Context, req *ProgressNotificationClientRequest) { |
| 606 |
notifications <- req.Params.Message |
| 607 |
}, |
| 608 |
}) |
| 609 |
clientSession, err := client.Connect(ctx, &StreamableClientTransport{ |
| 610 |
Endpoint: httpServer.URL, |
| 611 |
}, &ClientSessionOptions{protocolVersion: protocolVersion20251125}) |
| 612 |
if err != nil { |
| 613 |
t.Fatalf("client.Connect() failed: %v", err) |
| 614 |
} |
| 615 |
defer clientSession.Close() |
| 616 |
|
| 617 |
if err = test.doCall(ctx, clientSession); err != nil { |
| 618 |
t.Fatalf("CallTool failed: %v", err) |
| 619 |
} |
| 620 |
|
| 621 |
got := readNotifications(t, ctx, notifications, 2) |
| 622 |
want := []string{"msg1", "msg2"} |
| 623 |
if diff := cmp.Diff(want, got); diff != "" { |
| 624 |
t.Errorf("got unexpected notifications (-want +got):\n%s", diff) |
| 625 |
} |
| 626 |
}) |
| 627 |
} |
| 628 |
} |
| 629 |
|
| 630 |
func TestServerTransportCleanup(t *testing.T) { |
| 631 |
nClient := 3 |
| 632 |
|
| 633 |
var mu sync.Mutex |
| 634 |
var id int = -1 |
| 635 |
chans := make(map[string]chan struct{}, nClient) |
| 636 |
|
| 637 |
server := NewServer(testImpl, &ServerOptions{ |
| 638 |
KeepAlive: 10 * time.Millisecond, |
| 639 |
GetSessionID: func() string { |
| 640 |
mu.Lock() |
| 641 |
defer mu.Unlock() |
| 642 |
id++ |
| 643 |
if id == nClient { |
| 644 |
t.Errorf("creating more than %v session", nClient) |
| 645 |
} |
| 646 |
chans[fmt.Sprint(id)] = make(chan struct{}, 1) |
| 647 |
return fmt.Sprint(id) |
| 648 |
}, |
| 649 |
}) |
| 650 |
|
| 651 |
handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil) |
| 652 |
handler.onTransportDeletion = func(sessionID string) { |
| 653 |
mu.Lock() |
| 654 |
ch := chans[sessionID] |
| 655 |
mu.Unlock() |
| 656 |
ch <- struct{}{} |
| 657 |
} |
| 658 |
|
| 659 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 660 |
defer httpServer.Close() |
| 661 |
|
| 662 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 663 |
defer cancel() |
| 664 |
|
| 665 |
|
| 666 |
for range nClient { |
| 667 |
client := NewClient(testImpl, nil) |
| 668 |
pingMiddleware := func(next MethodHandler) MethodHandler { |
| 669 |
return func( |
| 670 |
ctx context.Context, |
| 671 |
method string, |
| 672 |
req Request, |
| 673 |
) (Result, error) { |
| 674 |
if method == "ping" { |
| 675 |
return &emptyResult{}, errors.New("ping error") |
| 676 |
} |
| 677 |
return next(ctx, method, req) |
| 678 |
} |
| 679 |
} |
| 680 |
client.AddReceivingMiddleware(pingMiddleware) |
| 681 |
clientSession, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, nil) |
| 682 |
if err != nil { |
| 683 |
t.Fatalf("client.Connect() failed: %v", err) |
| 684 |
} |
| 685 |
t.Cleanup(func() { _ = clientSession.Close() }) |
| 686 |
} |
| 687 |
|
| 688 |
mu.Lock() |
| 689 |
channels := slices.Collect(maps.Values(chans)) |
| 690 |
mu.Unlock() |
| 691 |
|
| 692 |
for _, ch := range channels { |
| 693 |
select { |
| 694 |
case <-ctx.Done(): |
| 695 |
t.Errorf("did not capture transport deletion event from all session in 10 seconds") |
| 696 |
case <-ch: |
| 697 |
t.Log("Received session transport deletion signal") |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
handler.mu.Lock() |
| 702 |
if len(handler.sessions) != 0 { |
| 703 |
t.Errorf("want empty transports map, find %v entries from handler's transports map", len(handler.sessions)) |
| 704 |
} |
| 705 |
handler.mu.Unlock() |
| 706 |
} |
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
func TestServerInitiatedSSE(t *testing.T) { |
| 711 |
notifications := make(chan string) |
| 712 |
server := NewServer(testImpl, nil) |
| 713 |
|
| 714 |
httpServer := httptest.NewServer(mustNotPanic(t, NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil))) |
| 715 |
defer httpServer.Close() |
| 716 |
|
| 717 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 718 |
defer cancel() |
| 719 |
client := NewClient(testImpl, &ClientOptions{ |
| 720 |
ToolListChangedHandler: func(context.Context, *ToolListChangedRequest) { |
| 721 |
notifications <- "toolListChanged" |
| 722 |
}, |
| 723 |
}) |
| 724 |
clientSession, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, nil) |
| 725 |
if err != nil { |
| 726 |
t.Fatalf("client.Connect() failed: %v", err) |
| 727 |
} |
| 728 |
defer clientSession.Close() |
| 729 |
AddTool(server, &Tool{Name: "testTool", InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 730 |
func(context.Context, *CallToolRequest, map[string]any) (*CallToolResult, any, error) { |
| 731 |
return &CallToolResult{}, nil, nil |
| 732 |
}) |
| 733 |
receivedNotifications := readNotifications(t, ctx, notifications, 1) |
| 734 |
wantReceived := []string{"toolListChanged"} |
| 735 |
if diff := cmp.Diff(wantReceived, receivedNotifications); diff != "" { |
| 736 |
t.Errorf("Received notifications mismatch (-want +got):\n%s", diff) |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
|
| 741 |
func readNotifications(t *testing.T, ctx context.Context, notifications chan string, count int) []string { |
| 742 |
t.Helper() |
| 743 |
var collectedNotifications []string |
| 744 |
for { |
| 745 |
select { |
| 746 |
case n := <-notifications: |
| 747 |
collectedNotifications = append(collectedNotifications, n) |
| 748 |
if len(collectedNotifications) == count { |
| 749 |
return collectedNotifications |
| 750 |
} |
| 751 |
case <-ctx.Done(): |
| 752 |
if len(collectedNotifications) != count { |
| 753 |
t.Fatalf("readProgressNotifications(): did not receive expected notifications, got %d, want %d", len(collectedNotifications), count) |
| 754 |
} |
| 755 |
return collectedNotifications |
| 756 |
} |
| 757 |
} |
| 758 |
} |
| 759 |
|
| 760 |
|
| 761 |
func req(id int64, method string, params any) *jsonrpc.Request { |
| 762 |
r := &jsonrpc.Request{ |
| 763 |
Method: method, |
| 764 |
Params: mustMarshal(params), |
| 765 |
} |
| 766 |
if id > 0 { |
| 767 |
r.ID = jsonrpc2.Int64ID(id) |
| 768 |
} |
| 769 |
return r |
| 770 |
} |
| 771 |
|
| 772 |
func resp(id int64, result any, err error) *jsonrpc.Response { |
| 773 |
return &jsonrpc.Response{ |
| 774 |
ID: jsonrpc2.Int64ID(id), |
| 775 |
Result: mustMarshal(result), |
| 776 |
Error: err, |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
func TestStreamableServerTransport(t *testing.T) { |
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
initReq := req(1, methodInitialize, &InitializeParams{ProtocolVersion: protocolVersion20250618}) |
| 787 |
initResp := resp(1, &InitializeResult{ |
| 788 |
Capabilities: &ServerCapabilities{ |
| 789 |
Logging: &LoggingCapabilities{}, |
| 790 |
Tools: &ToolCapabilities{ListChanged: true}, |
| 791 |
}, |
| 792 |
ProtocolVersion: protocolVersion20250618, |
| 793 |
ServerInfo: &Implementation{Name: "testServer", Version: "v1.0.0"}, |
| 794 |
}, nil) |
| 795 |
initializedMsg := req(0, notificationInitialized, &InitializedParams{}) |
| 796 |
initialize := streamableRequest{ |
| 797 |
method: "POST", |
| 798 |
messages: []jsonrpc.Message{initReq}, |
| 799 |
wantStatusCode: http.StatusOK, |
| 800 |
wantMessages: []jsonrpc.Message{initResp}, |
| 801 |
wantSessionID: true, |
| 802 |
} |
| 803 |
initialized := streamableRequest{ |
| 804 |
method: "POST", |
| 805 |
messages: []jsonrpc.Message{initializedMsg}, |
| 806 |
wantStatusCode: http.StatusAccepted, |
| 807 |
} |
| 808 |
|
| 809 |
|
| 810 |
initReq20251125 := req(1, methodInitialize, &InitializeParams{ProtocolVersion: protocolVersion20251125}) |
| 811 |
initResp20251125 := resp(1, &InitializeResult{ |
| 812 |
Capabilities: &ServerCapabilities{ |
| 813 |
Logging: &LoggingCapabilities{}, |
| 814 |
Tools: &ToolCapabilities{ListChanged: true}, |
| 815 |
}, |
| 816 |
ProtocolVersion: protocolVersion20251125, |
| 817 |
ServerInfo: &Implementation{Name: "testServer", Version: "v1.0.0"}, |
| 818 |
}, nil) |
| 819 |
initialize20251125 := streamableRequest{ |
| 820 |
method: "POST", |
| 821 |
messages: []jsonrpc.Message{initReq20251125}, |
| 822 |
wantStatusCode: http.StatusOK, |
| 823 |
wantMessages: []jsonrpc.Message{initResp20251125}, |
| 824 |
wantSessionID: true, |
| 825 |
} |
| 826 |
initialized20251125 := streamableRequest{ |
| 827 |
method: "POST", |
| 828 |
headers: http.Header{protocolVersionHeader: {protocolVersion20251125}}, |
| 829 |
messages: []jsonrpc.Message{initializedMsg}, |
| 830 |
wantStatusCode: http.StatusAccepted, |
| 831 |
} |
| 832 |
|
| 833 |
tests := []struct { |
| 834 |
name string |
| 835 |
replay bool |
| 836 |
tool func(*testing.T, context.Context, *CallToolRequest) |
| 837 |
requests []streamableRequest |
| 838 |
wantSessions int |
| 839 |
}{ |
| 840 |
{ |
| 841 |
name: "basic", |
| 842 |
requests: []streamableRequest{ |
| 843 |
initialize, |
| 844 |
initialized, |
| 845 |
{ |
| 846 |
method: "POST", |
| 847 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 848 |
wantStatusCode: http.StatusOK, |
| 849 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 850 |
}, |
| 851 |
}, |
| 852 |
wantSessions: 1, |
| 853 |
}, |
| 854 |
{ |
| 855 |
name: "uninitialized", |
| 856 |
requests: []streamableRequest{ |
| 857 |
{ |
| 858 |
method: "POST", |
| 859 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 860 |
wantStatusCode: http.StatusOK, |
| 861 |
wantBodyContaining: "invalid during session initialization", |
| 862 |
}, |
| 863 |
}, |
| 864 |
wantSessions: 0, |
| 865 |
}, |
| 866 |
{ |
| 867 |
name: "content type headers", |
| 868 |
requests: []streamableRequest{ |
| 869 |
initialize, |
| 870 |
initialized, |
| 871 |
{ |
| 872 |
|
| 873 |
method: "POST", |
| 874 |
headers: http.Header{"Content-Type": {"text/plain"}}, |
| 875 |
messages: []jsonrpc.Message{req(3, "tools/call", &CallToolParams{Name: "tool"})}, |
| 876 |
wantStatusCode: http.StatusUnsupportedMediaType, |
| 877 |
}, |
| 878 |
{ |
| 879 |
|
| 880 |
method: "POST", |
| 881 |
headers: http.Header{"Content-Type": {""}}, |
| 882 |
messages: []jsonrpc.Message{req(4, "tools/call", &CallToolParams{Name: "tool"})}, |
| 883 |
wantStatusCode: http.StatusUnsupportedMediaType, |
| 884 |
}, |
| 885 |
{ |
| 886 |
|
| 887 |
method: "POST", |
| 888 |
headers: http.Header{"Content-Type": {"application/json"}}, |
| 889 |
messages: []jsonrpc.Message{req(5, "tools/call", &CallToolParams{Name: "tool"})}, |
| 890 |
wantStatusCode: http.StatusOK, |
| 891 |
wantMessages: []jsonrpc.Message{resp(5, &CallToolResult{Content: []Content{}}, nil)}, |
| 892 |
}, |
| 893 |
{ |
| 894 |
|
| 895 |
method: "POST", |
| 896 |
headers: http.Header{"Content-Type": {"application/json; charset=utf-8"}}, |
| 897 |
messages: []jsonrpc.Message{req(5, "tools/call", &CallToolParams{Name: "tool"})}, |
| 898 |
wantStatusCode: http.StatusOK, |
| 899 |
wantMessages: []jsonrpc.Message{resp(5, &CallToolResult{Content: []Content{}}, nil)}, |
| 900 |
}, |
| 901 |
}, |
| 902 |
wantSessions: 1, |
| 903 |
}, |
| 904 |
{ |
| 905 |
name: "accept headers", |
| 906 |
requests: []streamableRequest{ |
| 907 |
initialize, |
| 908 |
initialized, |
| 909 |
|
| 910 |
{ |
| 911 |
method: "POST", |
| 912 |
headers: http.Header{"Accept": {"text/plain", "application/*"}}, |
| 913 |
messages: []jsonrpc.Message{req(3, "tools/call", &CallToolParams{Name: "tool"})}, |
| 914 |
wantStatusCode: http.StatusBadRequest, |
| 915 |
}, |
| 916 |
{ |
| 917 |
method: "POST", |
| 918 |
headers: http.Header{"Accept": {"text/event-stream"}}, |
| 919 |
messages: []jsonrpc.Message{req(3, "tools/call", &CallToolParams{Name: "tool"})}, |
| 920 |
wantStatusCode: http.StatusBadRequest, |
| 921 |
}, |
| 922 |
{ |
| 923 |
method: "POST", |
| 924 |
headers: http.Header{"Accept": {"text/plain", "*/*"}}, |
| 925 |
messages: []jsonrpc.Message{req(4, "tools/call", &CallToolParams{Name: "tool"})}, |
| 926 |
wantStatusCode: http.StatusOK, |
| 927 |
wantMessages: []jsonrpc.Message{resp(4, &CallToolResult{Content: []Content{}}, nil)}, |
| 928 |
}, |
| 929 |
{ |
| 930 |
method: "POST", |
| 931 |
headers: http.Header{"Accept": {"application/json;charset=utf-8, text/event-stream"}}, |
| 932 |
messages: []jsonrpc.Message{req(5, "tools/call", &CallToolParams{Name: "tool"})}, |
| 933 |
wantStatusCode: http.StatusOK, |
| 934 |
wantMessages: []jsonrpc.Message{resp(5, &CallToolResult{Content: []Content{}}, nil)}, |
| 935 |
}, |
| 936 |
{ |
| 937 |
method: "POST", |
| 938 |
headers: http.Header{"Accept": {"application/json;charset=utf-8", "text/event-stream"}}, |
| 939 |
messages: []jsonrpc.Message{req(6, "tools/call", &CallToolParams{Name: "tool"})}, |
| 940 |
wantStatusCode: http.StatusOK, |
| 941 |
wantMessages: []jsonrpc.Message{resp(6, &CallToolResult{Content: []Content{}}, nil)}, |
| 942 |
}, |
| 943 |
{ |
| 944 |
method: "POST", |
| 945 |
headers: http.Header{"Accept": {"text/*, application/*"}}, |
| 946 |
messages: []jsonrpc.Message{req(7, "tools/call", &CallToolParams{Name: "tool"})}, |
| 947 |
wantStatusCode: http.StatusOK, |
| 948 |
wantMessages: []jsonrpc.Message{resp(7, &CallToolResult{Content: []Content{}}, nil)}, |
| 949 |
}, |
| 950 |
}, |
| 951 |
wantSessions: 1, |
| 952 |
}, |
| 953 |
{ |
| 954 |
name: "protocol version headers", |
| 955 |
requests: []streamableRequest{ |
| 956 |
initialize, |
| 957 |
initialized, |
| 958 |
{ |
| 959 |
method: "POST", |
| 960 |
headers: http.Header{"mcp-protocol-version": {"2025-01-01"}}, |
| 961 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 962 |
wantStatusCode: http.StatusBadRequest, |
| 963 |
wantBodyContaining: "2025-03-26", |
| 964 |
wantSessionID: false, |
| 965 |
}, |
| 966 |
}, |
| 967 |
wantSessions: 1, |
| 968 |
}, |
| 969 |
{ |
| 970 |
name: "batch rejected on 2025-06-18", |
| 971 |
requests: []streamableRequest{ |
| 972 |
initialize, |
| 973 |
initialized, |
| 974 |
{ |
| 975 |
method: "POST", |
| 976 |
|
| 977 |
headers: http.Header{"MCP-Protocol-Version": {"2025-06-18"}}, |
| 978 |
|
| 979 |
messages: []jsonrpc.Message{ |
| 980 |
req(101, "tools/call", &CallToolParams{Name: "tool"}), |
| 981 |
req(102, "tools/call", &CallToolParams{Name: "tool"}), |
| 982 |
}, |
| 983 |
wantStatusCode: http.StatusBadRequest, |
| 984 |
wantBodyContaining: "batch", |
| 985 |
}, |
| 986 |
}, |
| 987 |
wantSessions: 1, |
| 988 |
}, |
| 989 |
{ |
| 990 |
name: "batch accepted on 2025-03-26", |
| 991 |
requests: []streamableRequest{ |
| 992 |
initialize, |
| 993 |
initialized, |
| 994 |
{ |
| 995 |
method: "POST", |
| 996 |
headers: http.Header{"MCP-Protocol-Version": {"2025-03-26"}}, |
| 997 |
|
| 998 |
messages: []jsonrpc.Message{ |
| 999 |
|
| 1000 |
|
| 1001 |
req(201, "tools/call", &CallToolParams{Name: "tool"}), |
| 1002 |
req(0, "notifications/roots/list_changed", &RootsListChangedParams{}), |
| 1003 |
}, |
| 1004 |
wantStatusCode: http.StatusOK, |
| 1005 |
wantMessages: []jsonrpc.Message{ |
| 1006 |
resp(201, &CallToolResult{Content: []Content{}}, nil), |
| 1007 |
}, |
| 1008 |
}, |
| 1009 |
}, |
| 1010 |
wantSessions: 1, |
| 1011 |
}, |
| 1012 |
{ |
| 1013 |
name: "tool notification", |
| 1014 |
tool: func(t *testing.T, ctx context.Context, req *CallToolRequest) { |
| 1015 |
|
| 1016 |
if err := req.Session.NotifyProgress(ctx, &ProgressNotificationParams{}); err != nil { |
| 1017 |
t.Errorf("Notify failed: %v", err) |
| 1018 |
} |
| 1019 |
}, |
| 1020 |
requests: []streamableRequest{ |
| 1021 |
initialize, |
| 1022 |
initialized, |
| 1023 |
{ |
| 1024 |
method: "POST", |
| 1025 |
messages: []jsonrpc.Message{ |
| 1026 |
req(2, "tools/call", &CallToolParams{Name: "tool"}), |
| 1027 |
}, |
| 1028 |
wantStatusCode: http.StatusOK, |
| 1029 |
wantMessages: []jsonrpc.Message{ |
| 1030 |
req(0, "notifications/progress", &ProgressNotificationParams{}), |
| 1031 |
resp(2, &CallToolResult{Content: []Content{}}, nil), |
| 1032 |
}, |
| 1033 |
}, |
| 1034 |
}, |
| 1035 |
wantSessions: 1, |
| 1036 |
}, |
| 1037 |
{ |
| 1038 |
name: "tool upcall", |
| 1039 |
tool: func(t *testing.T, ctx context.Context, req *CallToolRequest) { |
| 1040 |
|
| 1041 |
if _, err := req.Session.ListRoots(ctx, &ListRootsParams{}); err != nil { |
| 1042 |
t.Errorf("Call failed: %v", err) |
| 1043 |
} |
| 1044 |
}, |
| 1045 |
requests: []streamableRequest{ |
| 1046 |
initialize, |
| 1047 |
initialized, |
| 1048 |
{ |
| 1049 |
method: "POST", |
| 1050 |
onRequest: 1, |
| 1051 |
messages: []jsonrpc.Message{ |
| 1052 |
resp(1, &ListRootsResult{}, nil), |
| 1053 |
}, |
| 1054 |
wantStatusCode: http.StatusAccepted, |
| 1055 |
}, |
| 1056 |
{ |
| 1057 |
method: "POST", |
| 1058 |
messages: []jsonrpc.Message{ |
| 1059 |
req(2, "tools/call", &CallToolParams{Name: "tool"}), |
| 1060 |
}, |
| 1061 |
wantStatusCode: http.StatusOK, |
| 1062 |
wantMessages: []jsonrpc.Message{ |
| 1063 |
req(1, "roots/list", &ListRootsParams{}), |
| 1064 |
resp(2, &CallToolResult{Content: []Content{}}, nil), |
| 1065 |
}, |
| 1066 |
}, |
| 1067 |
}, |
| 1068 |
wantSessions: 1, |
| 1069 |
}, |
| 1070 |
{ |
| 1071 |
name: "background", |
| 1072 |
|
| 1073 |
|
| 1074 |
|
| 1075 |
|
| 1076 |
replay: true, |
| 1077 |
tool: func(t *testing.T, _ context.Context, req *CallToolRequest) { |
| 1078 |
|
| 1079 |
|
| 1080 |
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) |
| 1081 |
defer cancel() |
| 1082 |
|
| 1083 |
if err := req.Session.NotifyProgress(ctx, &ProgressNotificationParams{}); err != nil { |
| 1084 |
t.Errorf("Notify failed: %v", err) |
| 1085 |
} |
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
|
| 1090 |
if _, err := req.Session.ListRoots(ctx, &ListRootsParams{}); err != nil { |
| 1091 |
t.Errorf("ListRoots failed: %v", err) |
| 1092 |
} |
| 1093 |
}, |
| 1094 |
requests: []streamableRequest{ |
| 1095 |
initialize, |
| 1096 |
initialized, |
| 1097 |
{ |
| 1098 |
method: "POST", |
| 1099 |
onRequest: 1, |
| 1100 |
messages: []jsonrpc.Message{ |
| 1101 |
resp(1, &ListRootsResult{}, nil), |
| 1102 |
}, |
| 1103 |
wantStatusCode: http.StatusAccepted, |
| 1104 |
}, |
| 1105 |
{ |
| 1106 |
method: "GET", |
| 1107 |
async: true, |
| 1108 |
wantStatusCode: http.StatusOK, |
| 1109 |
closeAfter: 2, |
| 1110 |
wantMessages: []jsonrpc.Message{ |
| 1111 |
req(0, "notifications/progress", &ProgressNotificationParams{}), |
| 1112 |
req(1, "roots/list", &ListRootsParams{}), |
| 1113 |
}, |
| 1114 |
}, |
| 1115 |
{ |
| 1116 |
method: "POST", |
| 1117 |
messages: []jsonrpc.Message{ |
| 1118 |
req(2, "tools/call", &CallToolParams{Name: "tool"}), |
| 1119 |
}, |
| 1120 |
wantStatusCode: http.StatusOK, |
| 1121 |
wantMessages: []jsonrpc.Message{ |
| 1122 |
resp(2, &CallToolResult{Content: []Content{}}, nil), |
| 1123 |
}, |
| 1124 |
}, |
| 1125 |
{ |
| 1126 |
method: "DELETE", |
| 1127 |
wantStatusCode: http.StatusNoContent, |
| 1128 |
|
| 1129 |
|
| 1130 |
headers: map[string][]string{"Accept": nil}, |
| 1131 |
}, |
| 1132 |
}, |
| 1133 |
wantSessions: 0, |
| 1134 |
}, |
| 1135 |
{ |
| 1136 |
name: "no priming message on old protocol", |
| 1137 |
replay: true, |
| 1138 |
requests: []streamableRequest{ |
| 1139 |
initialize, |
| 1140 |
initialized, |
| 1141 |
{ |
| 1142 |
method: "POST", |
| 1143 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1144 |
wantStatusCode: http.StatusOK, |
| 1145 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 1146 |
wantBodyNotContaining: "prime", |
| 1147 |
}, |
| 1148 |
}, |
| 1149 |
wantSessions: 1, |
| 1150 |
}, |
| 1151 |
{ |
| 1152 |
name: "no close message on old protocol", |
| 1153 |
replay: true, |
| 1154 |
tool: func(t *testing.T, _ context.Context, req *CallToolRequest) { |
| 1155 |
req.Extra.CloseSSEStream(CloseSSEStreamArgs{RetryAfter: time.Millisecond}) |
| 1156 |
}, |
| 1157 |
requests: []streamableRequest{ |
| 1158 |
initialize, |
| 1159 |
initialized, |
| 1160 |
{ |
| 1161 |
method: "POST", |
| 1162 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1163 |
wantStatusCode: http.StatusOK, |
| 1164 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 1165 |
wantBodyNotContaining: "close", |
| 1166 |
}, |
| 1167 |
}, |
| 1168 |
wantSessions: 1, |
| 1169 |
}, |
| 1170 |
{ |
| 1171 |
name: "priming message on 2025-11-25", |
| 1172 |
replay: true, |
| 1173 |
requests: []streamableRequest{ |
| 1174 |
initialize20251125, |
| 1175 |
initialized20251125, |
| 1176 |
{ |
| 1177 |
method: "POST", |
| 1178 |
headers: http.Header{protocolVersionHeader: {protocolVersion20251125}}, |
| 1179 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1180 |
wantStatusCode: http.StatusOK, |
| 1181 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 1182 |
wantBodyContaining: "prime", |
| 1183 |
}, |
| 1184 |
}, |
| 1185 |
wantSessions: 1, |
| 1186 |
}, |
| 1187 |
{ |
| 1188 |
name: "close message on 2025-11-25", |
| 1189 |
replay: true, |
| 1190 |
tool: func(t *testing.T, _ context.Context, req *CallToolRequest) { |
| 1191 |
req.Extra.CloseSSEStream(CloseSSEStreamArgs{RetryAfter: time.Millisecond}) |
| 1192 |
}, |
| 1193 |
requests: []streamableRequest{ |
| 1194 |
initialize20251125, |
| 1195 |
initialized20251125, |
| 1196 |
{ |
| 1197 |
method: "POST", |
| 1198 |
headers: http.Header{protocolVersionHeader: {protocolVersion20251125}}, |
| 1199 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1200 |
wantStatusCode: http.StatusOK, |
| 1201 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 1202 |
wantBodyContaining: "close", |
| 1203 |
wantBodyNotContaining: "result", |
| 1204 |
}, |
| 1205 |
}, |
| 1206 |
wantSessions: 1, |
| 1207 |
}, |
| 1208 |
{ |
| 1209 |
name: "no close message", |
| 1210 |
replay: true, |
| 1211 |
tool: func(t *testing.T, _ context.Context, req *CallToolRequest) { |
| 1212 |
req.Extra.CloseSSEStream(CloseSSEStreamArgs{}) |
| 1213 |
}, |
| 1214 |
requests: []streamableRequest{ |
| 1215 |
initialize, |
| 1216 |
initialized, |
| 1217 |
{ |
| 1218 |
method: "POST", |
| 1219 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1220 |
wantStatusCode: http.StatusOK, |
| 1221 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 1222 |
wantBodyNotContaining: "close", |
| 1223 |
}, |
| 1224 |
}, |
| 1225 |
wantSessions: 1, |
| 1226 |
}, |
| 1227 |
{ |
| 1228 |
name: "errors", |
| 1229 |
requests: []streamableRequest{ |
| 1230 |
{ |
| 1231 |
method: "PUT", |
| 1232 |
wantStatusCode: http.StatusMethodNotAllowed, |
| 1233 |
}, |
| 1234 |
{ |
| 1235 |
method: "DELETE", |
| 1236 |
wantStatusCode: http.StatusBadRequest, |
| 1237 |
}, |
| 1238 |
{ |
| 1239 |
method: "POST", |
| 1240 |
messages: []jsonrpc.Message{req(1, "notamethod", nil)}, |
| 1241 |
wantStatusCode: http.StatusBadRequest, |
| 1242 |
}, |
| 1243 |
{ |
| 1244 |
method: "POST", |
| 1245 |
messages: []jsonrpc.Message{req(0, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1246 |
wantStatusCode: http.StatusBadRequest, |
| 1247 |
}, |
| 1248 |
{ |
| 1249 |
method: "POST", |
| 1250 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "tool"})}, |
| 1251 |
wantStatusCode: http.StatusOK, |
| 1252 |
wantMessages: []jsonrpc.Message{resp(2, nil, &jsonrpc.Error{ |
| 1253 |
Message: `method "tools/call" is invalid during session initialization`, |
| 1254 |
})}, |
| 1255 |
}, |
| 1256 |
}, |
| 1257 |
wantSessions: 0, |
| 1258 |
}, |
| 1259 |
} |
| 1260 |
|
| 1261 |
for _, test := range tests { |
| 1262 |
t.Run(test.name, func(t *testing.T) { |
| 1263 |
|
| 1264 |
|
| 1265 |
server := NewServer(&Implementation{Name: "testServer", Version: "v1.0.0"}, nil) |
| 1266 |
server.AddTool( |
| 1267 |
&Tool{Name: "tool", InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 1268 |
func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) { |
| 1269 |
if test.tool != nil { |
| 1270 |
test.tool(t, ctx, req) |
| 1271 |
} |
| 1272 |
return &CallToolResult{}, nil |
| 1273 |
}) |
| 1274 |
|
| 1275 |
opts := &StreamableHTTPOptions{} |
| 1276 |
if test.replay { |
| 1277 |
opts.EventStore = NewMemoryEventStore(nil) |
| 1278 |
} |
| 1279 |
|
| 1280 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, opts) |
| 1281 |
defer handler.closeAll() |
| 1282 |
|
| 1283 |
testStreamableHandler(t, handler, test.requests) |
| 1284 |
if got := len(slices.Collect(server.Sessions())); got != test.wantSessions { |
| 1285 |
t.Errorf("after test, got %d sessions, want %d", got, test.wantSessions) |
| 1286 |
} |
| 1287 |
}) |
| 1288 |
} |
| 1289 |
} |
| 1290 |
|
| 1291 |
func testStreamableHandler(t *testing.T, handler http.Handler, requests []streamableRequest) { |
| 1292 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 1293 |
defer httpServer.Close() |
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
var mu sync.Mutex |
| 1300 |
blocks := make(map[int64]chan struct{}) |
| 1301 |
for _, req := range requests { |
| 1302 |
if req.onRequest > 0 { |
| 1303 |
blocks[req.onRequest] = make(chan struct{}) |
| 1304 |
} |
| 1305 |
} |
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
syncRequestsDone := make(chan struct{}) |
| 1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
var sessionID atomic.Value |
| 1314 |
sessionID.Store("") |
| 1315 |
|
| 1316 |
|
| 1317 |
doStep := func(t *testing.T, i int, request streamableRequest) { |
| 1318 |
if request.onRequest > 0 { |
| 1319 |
|
| 1320 |
mu.Lock() |
| 1321 |
block := blocks[request.onRequest] |
| 1322 |
mu.Unlock() |
| 1323 |
select { |
| 1324 |
case <-block: |
| 1325 |
case <-syncRequestsDone: |
| 1326 |
t.Errorf("after all sync requests are complete, request still blocked on %d", request.onRequest) |
| 1327 |
return |
| 1328 |
} |
| 1329 |
} |
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
var got []jsonrpc.Message |
| 1334 |
out := make(chan jsonrpc.Message) |
| 1335 |
|
| 1336 |
|
| 1337 |
|
| 1338 |
|
| 1339 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 1340 |
|
| 1341 |
var wg sync.WaitGroup |
| 1342 |
wg.Go(func() { |
| 1343 |
|
| 1344 |
for m := range out { |
| 1345 |
if req, ok := m.(*jsonrpc.Request); ok && req.IsCall() { |
| 1346 |
|
| 1347 |
|
| 1348 |
mu.Lock() |
| 1349 |
if block, ok := blocks[req.ID.Raw().(int64)]; ok { |
| 1350 |
close(block) |
| 1351 |
} else { |
| 1352 |
t.Errorf("no queued response for %v", req.ID) |
| 1353 |
cancel() |
| 1354 |
} |
| 1355 |
mu.Unlock() |
| 1356 |
} |
| 1357 |
got = append(got, m) |
| 1358 |
if request.closeAfter > 0 && len(got) == request.closeAfter { |
| 1359 |
cancel() |
| 1360 |
} |
| 1361 |
} |
| 1362 |
}) |
| 1363 |
|
| 1364 |
gotSessionID, gotStatusCode, gotBody, err := request.do(ctx, httpServer.URL, sessionID.Load().(string), out) |
| 1365 |
|
| 1366 |
|
| 1367 |
|
| 1368 |
if err != nil && ctx.Err() == nil { |
| 1369 |
t.Fatal(err) |
| 1370 |
} |
| 1371 |
|
| 1372 |
if gotStatusCode != request.wantStatusCode { |
| 1373 |
t.Errorf("request #%d: got status %d, want %d", i, gotStatusCode, request.wantStatusCode) |
| 1374 |
} |
| 1375 |
if got := gotSessionID != ""; got != request.wantSessionID { |
| 1376 |
t.Errorf("request #%d: got session id: %t, want %t", i, got, request.wantSessionID) |
| 1377 |
} |
| 1378 |
wg.Wait() |
| 1379 |
|
| 1380 |
if request.wantBodyContaining != "" || request.wantBodyNotContaining != "" { |
| 1381 |
body := string(gotBody) |
| 1382 |
if request.wantBodyContaining != "" && !strings.Contains(body, request.wantBodyContaining) { |
| 1383 |
t.Errorf("body does not contain %q:\n%s", request.wantBodyContaining, body) |
| 1384 |
} |
| 1385 |
if request.wantBodyNotContaining != "" && strings.Contains(body, request.wantBodyNotContaining) { |
| 1386 |
t.Errorf("body contains %q:\n%s", request.wantBodyNotContaining, body) |
| 1387 |
} |
| 1388 |
} else { |
| 1389 |
transform := cmpopts.AcyclicTransformer("jsonrpcid", func(id jsonrpc.ID) any { return id.Raw() }) |
| 1390 |
if diff := cmp.Diff(request.wantMessages, got, transform); diff != "" { |
| 1391 |
t.Errorf("request #%d: received unexpected messages (-want +got):\n%s", i, diff) |
| 1392 |
} |
| 1393 |
} |
| 1394 |
sessionID.CompareAndSwap("", gotSessionID) |
| 1395 |
} |
| 1396 |
|
| 1397 |
var wg sync.WaitGroup |
| 1398 |
for i, request := range requests { |
| 1399 |
if request.async || request.onRequest > 0 { |
| 1400 |
wg.Go(func() { |
| 1401 |
doStep(t, i, request) |
| 1402 |
}) |
| 1403 |
} else { |
| 1404 |
doStep(t, i, request) |
| 1405 |
} |
| 1406 |
} |
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
close(syncRequestsDone) |
| 1411 |
|
| 1412 |
wg.Wait() |
| 1413 |
} |
| 1414 |
|
| 1415 |
|
| 1416 |
|
| 1417 |
type streamableRequest struct { |
| 1418 |
|
| 1419 |
|
| 1420 |
|
| 1421 |
|
| 1422 |
|
| 1423 |
|
| 1424 |
|
| 1425 |
|
| 1426 |
|
| 1427 |
onRequest int64 |
| 1428 |
|
| 1429 |
|
| 1430 |
async bool |
| 1431 |
|
| 1432 |
|
| 1433 |
method string |
| 1434 |
headers http.Header |
| 1435 |
messages []jsonrpc.Message |
| 1436 |
|
| 1437 |
closeAfter int |
| 1438 |
wantStatusCode int |
| 1439 |
wantBodyContaining string |
| 1440 |
wantBodyNotContaining string |
| 1441 |
wantMessages []jsonrpc.Message |
| 1442 |
wantSessionID bool |
| 1443 |
} |
| 1444 |
|
| 1445 |
|
| 1446 |
|
| 1447 |
|
| 1448 |
|
| 1449 |
|
| 1450 |
|
| 1451 |
|
| 1452 |
|
| 1453 |
|
| 1454 |
|
| 1455 |
|
| 1456 |
|
| 1457 |
|
| 1458 |
func (s streamableRequest) do(ctx context.Context, serverURL, sessionID string, out chan<- jsonrpc.Message) (string, int, []byte, error) { |
| 1459 |
defer close(out) |
| 1460 |
|
| 1461 |
var body []byte |
| 1462 |
if len(s.messages) == 1 { |
| 1463 |
data, err := jsonrpc2.EncodeMessage(s.messages[0]) |
| 1464 |
if err != nil { |
| 1465 |
return "", 0, nil, fmt.Errorf("encoding message: %w", err) |
| 1466 |
} |
| 1467 |
body = data |
| 1468 |
} else { |
| 1469 |
var rawMsgs []json.RawMessage |
| 1470 |
for _, msg := range s.messages { |
| 1471 |
data, err := jsonrpc2.EncodeMessage(msg) |
| 1472 |
if err != nil { |
| 1473 |
return "", 0, nil, fmt.Errorf("encoding message: %w", err) |
| 1474 |
} |
| 1475 |
rawMsgs = append(rawMsgs, data) |
| 1476 |
} |
| 1477 |
data, err := json.Marshal(rawMsgs) |
| 1478 |
if err != nil { |
| 1479 |
return "", 0, nil, fmt.Errorf("marshaling batch: %w", err) |
| 1480 |
} |
| 1481 |
body = data |
| 1482 |
} |
| 1483 |
|
| 1484 |
req, err := http.NewRequestWithContext(ctx, s.method, serverURL, bytes.NewReader(body)) |
| 1485 |
if err != nil { |
| 1486 |
return "", 0, nil, fmt.Errorf("creating request: %w", err) |
| 1487 |
} |
| 1488 |
if sessionID != "" { |
| 1489 |
req.Header.Set(sessionIDHeader, sessionID) |
| 1490 |
} |
| 1491 |
if s.method == http.MethodPost { |
| 1492 |
req.Header.Set("Content-Type", "application/json") |
| 1493 |
} |
| 1494 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 1495 |
maps.Copy(req.Header, s.headers) |
| 1496 |
|
| 1497 |
if req.Header.Get("Content-Type") == "" { |
| 1498 |
req.Header.Del("Content-Type") |
| 1499 |
} |
| 1500 |
|
| 1501 |
resp, err := http.DefaultClient.Do(req) |
| 1502 |
if err != nil { |
| 1503 |
return "", 0, nil, fmt.Errorf("request failed: %v", err) |
| 1504 |
} |
| 1505 |
defer resp.Body.Close() |
| 1506 |
|
| 1507 |
newSessionID := resp.Header.Get(sessionIDHeader) |
| 1508 |
|
| 1509 |
contentType := baseMediaType(resp.Header.Get("Content-Type")) |
| 1510 |
var respBody []byte |
| 1511 |
if contentType == "text/event-stream" { |
| 1512 |
r := readerInto{resp.Body, new(bytes.Buffer)} |
| 1513 |
for evt, err := range scanEvents(r) { |
| 1514 |
if err != nil { |
| 1515 |
return newSessionID, resp.StatusCode, nil, fmt.Errorf("reading events: %v", err) |
| 1516 |
} |
| 1517 |
if evt.Name == "" || evt.Name == "message" { |
| 1518 |
|
| 1519 |
|
| 1520 |
msg, err := jsonrpc2.DecodeMessage(evt.Data) |
| 1521 |
if err != nil { |
| 1522 |
return newSessionID, resp.StatusCode, nil, fmt.Errorf("decoding message: %w", err) |
| 1523 |
} |
| 1524 |
out <- msg |
| 1525 |
} |
| 1526 |
} |
| 1527 |
respBody = r.w.Bytes() |
| 1528 |
} else if contentType == "application/json" { |
| 1529 |
data, err := io.ReadAll(resp.Body) |
| 1530 |
if err != nil { |
| 1531 |
return newSessionID, resp.StatusCode, nil, fmt.Errorf("reading json body: %w", err) |
| 1532 |
} |
| 1533 |
respBody = data |
| 1534 |
msg, err := jsonrpc2.DecodeMessage(data) |
| 1535 |
if err != nil { |
| 1536 |
return newSessionID, resp.StatusCode, nil, fmt.Errorf("decoding message: %w", err) |
| 1537 |
} |
| 1538 |
out <- msg |
| 1539 |
} else { |
| 1540 |
respBody, err = io.ReadAll(resp.Body) |
| 1541 |
if err != nil { |
| 1542 |
return newSessionID, resp.StatusCode, nil, fmt.Errorf("reading response: %v", err) |
| 1543 |
} |
| 1544 |
} |
| 1545 |
|
| 1546 |
return newSessionID, resp.StatusCode, respBody, nil |
| 1547 |
} |
| 1548 |
|
| 1549 |
|
| 1550 |
type readerInto struct { |
| 1551 |
r io.Reader |
| 1552 |
w *bytes.Buffer |
| 1553 |
} |
| 1554 |
|
| 1555 |
|
| 1556 |
func (r readerInto) Read(p []byte) (n int, err error) { |
| 1557 |
n, err = r.r.Read(p) |
| 1558 |
if err == nil || err == io.EOF { |
| 1559 |
n2, err2 := r.w.Write(p[:n]) |
| 1560 |
if err2 != nil { |
| 1561 |
return n, fmt.Errorf("failed to write: %v", err) |
| 1562 |
} |
| 1563 |
if n2 != n { |
| 1564 |
return n, fmt.Errorf("short write: %d != %d", n2, n) |
| 1565 |
} |
| 1566 |
} |
| 1567 |
return n, err |
| 1568 |
} |
| 1569 |
|
| 1570 |
func mustMarshal(v any) json.RawMessage { |
| 1571 |
if v == nil { |
| 1572 |
return nil |
| 1573 |
} |
| 1574 |
data, err := json.Marshal(v) |
| 1575 |
if err != nil { |
| 1576 |
panic(err) |
| 1577 |
} |
| 1578 |
return data |
| 1579 |
} |
| 1580 |
|
| 1581 |
func TestEventID(t *testing.T) { |
| 1582 |
tests := []struct { |
| 1583 |
sid string |
| 1584 |
idx int |
| 1585 |
}{ |
| 1586 |
{"0", 0}, |
| 1587 |
{"0", 1}, |
| 1588 |
{"1", 0}, |
| 1589 |
{"1", 1}, |
| 1590 |
{"", 1}, |
| 1591 |
{"1234", 5678}, |
| 1592 |
} |
| 1593 |
|
| 1594 |
for _, test := range tests { |
| 1595 |
t.Run(fmt.Sprintf("%s_%d", test.sid, test.idx), func(t *testing.T) { |
| 1596 |
eventID := formatEventID(test.sid, test.idx) |
| 1597 |
gotSID, gotIdx, ok := parseEventID(eventID) |
| 1598 |
if !ok { |
| 1599 |
t.Fatalf("parseEventID(%q) failed, want ok", eventID) |
| 1600 |
} |
| 1601 |
if gotSID != test.sid || gotIdx != test.idx { |
| 1602 |
t.Errorf("parseEventID(%q) = %s, %d, want %s, %d", eventID, gotSID, gotIdx, test.sid, test.idx) |
| 1603 |
} |
| 1604 |
}) |
| 1605 |
} |
| 1606 |
|
| 1607 |
invalid := []string{ |
| 1608 |
"", |
| 1609 |
"_", |
| 1610 |
"1_", |
| 1611 |
"1_a", |
| 1612 |
"1_-1", |
| 1613 |
} |
| 1614 |
|
| 1615 |
for _, eventID := range invalid { |
| 1616 |
t.Run(fmt.Sprintf("invalid_%q", eventID), func(t *testing.T) { |
| 1617 |
if _, _, ok := parseEventID(eventID); ok { |
| 1618 |
t.Errorf("parseEventID(%q) succeeded, want failure", eventID) |
| 1619 |
} |
| 1620 |
}) |
| 1621 |
} |
| 1622 |
} |
| 1623 |
|
| 1624 |
func TestStreamableStateless(t *testing.T) { |
| 1625 |
initReq := req(1, methodInitialize, &InitializeParams{}) |
| 1626 |
initResp := resp(1, &InitializeResult{ |
| 1627 |
Capabilities: &ServerCapabilities{ |
| 1628 |
Logging: &LoggingCapabilities{}, |
| 1629 |
Tools: &ToolCapabilities{ListChanged: true}, |
| 1630 |
}, |
| 1631 |
ProtocolVersion: latestProtocolVersion, |
| 1632 |
ServerInfo: &Implementation{Name: "test", Version: "v1.0.0"}, |
| 1633 |
}, nil) |
| 1634 |
|
| 1635 |
|
| 1636 |
sayHi := func(ctx context.Context, req *CallToolRequest, args hiParams) (*CallToolResult, any, error) { |
| 1637 |
if err := req.Session.Ping(ctx, nil); err == nil { |
| 1638 |
|
| 1639 |
t.Errorf("ping succeeded unexpectedly") |
| 1640 |
} |
| 1641 |
return &CallToolResult{Content: []Content{&TextContent{Text: "hi " + args.Name}}}, nil, nil |
| 1642 |
} |
| 1643 |
|
| 1644 |
requests := []streamableRequest{ |
| 1645 |
{ |
| 1646 |
method: "POST", |
| 1647 |
messages: []jsonrpc.Message{initReq}, |
| 1648 |
wantStatusCode: http.StatusOK, |
| 1649 |
wantMessages: []jsonrpc.Message{initResp}, |
| 1650 |
wantSessionID: false, |
| 1651 |
}, |
| 1652 |
{ |
| 1653 |
method: "POST", |
| 1654 |
wantStatusCode: http.StatusOK, |
| 1655 |
messages: []jsonrpc.Message{req(1, "tools/list", struct{}{})}, |
| 1656 |
wantBodyContaining: "greet", |
| 1657 |
}, |
| 1658 |
{ |
| 1659 |
method: "GET", |
| 1660 |
wantStatusCode: http.StatusMethodNotAllowed, |
| 1661 |
}, |
| 1662 |
{ |
| 1663 |
method: "POST", |
| 1664 |
wantStatusCode: http.StatusOK, |
| 1665 |
messages: []jsonrpc.Message{ |
| 1666 |
req(2, "tools/call", &CallToolParams{Name: "greet", Arguments: hiParams{Name: "World"}}), |
| 1667 |
}, |
| 1668 |
wantMessages: []jsonrpc.Message{ |
| 1669 |
resp(2, &CallToolResult{ |
| 1670 |
Content: []Content{&TextContent{Text: "hi World"}}, |
| 1671 |
}, nil), |
| 1672 |
}, |
| 1673 |
}, |
| 1674 |
{ |
| 1675 |
method: "POST", |
| 1676 |
wantStatusCode: http.StatusOK, |
| 1677 |
messages: []jsonrpc.Message{ |
| 1678 |
req(2, "tools/call", &CallToolParams{Name: "greet", Arguments: hiParams{Name: "foo"}}), |
| 1679 |
}, |
| 1680 |
wantMessages: []jsonrpc.Message{ |
| 1681 |
resp(2, &CallToolResult{ |
| 1682 |
Content: []Content{&TextContent{Text: "hi foo"}}, |
| 1683 |
}, nil), |
| 1684 |
}, |
| 1685 |
}, |
| 1686 |
} |
| 1687 |
|
| 1688 |
testClientCompatibility := func(t *testing.T, handler http.Handler) { |
| 1689 |
ctx := context.Background() |
| 1690 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 1691 |
defer httpServer.Close() |
| 1692 |
cs, err := NewClient(testImpl, nil).Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, nil) |
| 1693 |
if err != nil { |
| 1694 |
t.Fatal(err) |
| 1695 |
} |
| 1696 |
t.Cleanup(func() { cs.Close() }) |
| 1697 |
res, err := cs.CallTool(ctx, &CallToolParams{Name: "greet", Arguments: hiParams{Name: "bar"}}) |
| 1698 |
if err != nil { |
| 1699 |
t.Fatal(err) |
| 1700 |
} |
| 1701 |
if got, want := textContent(t, res), "hi bar"; got != want { |
| 1702 |
t.Errorf("Result = %q, want %q", got, want) |
| 1703 |
} |
| 1704 |
} |
| 1705 |
|
| 1706 |
sessionlessHandler := NewStreamableHTTPHandler(func(*http.Request) *Server { |
| 1707 |
|
| 1708 |
server := NewServer(testImpl, &ServerOptions{ |
| 1709 |
GetSessionID: func() string { return "" }, |
| 1710 |
}) |
| 1711 |
AddTool(server, &Tool{Name: "greet", Description: "say hi"}, sayHi) |
| 1712 |
return server |
| 1713 |
}, &StreamableHTTPOptions{ |
| 1714 |
Stateless: true, |
| 1715 |
}) |
| 1716 |
|
| 1717 |
|
| 1718 |
t.Run("sessionless", func(t *testing.T) { |
| 1719 |
testStreamableHandler(t, sessionlessHandler, requests) |
| 1720 |
testClientCompatibility(t, sessionlessHandler) |
| 1721 |
}) |
| 1722 |
|
| 1723 |
|
| 1724 |
|
| 1725 |
|
| 1726 |
|
| 1727 |
requests[0].wantSessionID = true |
| 1728 |
statelessHandler := NewStreamableHTTPHandler(func(*http.Request) *Server { |
| 1729 |
|
| 1730 |
server := NewServer(testImpl, nil) |
| 1731 |
AddTool(server, &Tool{Name: "greet", Description: "say hi"}, sayHi) |
| 1732 |
return server |
| 1733 |
}, &StreamableHTTPOptions{ |
| 1734 |
Stateless: true, |
| 1735 |
}) |
| 1736 |
t.Run("stateless", func(t *testing.T) { |
| 1737 |
testStreamableHandler(t, statelessHandler, requests) |
| 1738 |
testClientCompatibility(t, sessionlessHandler) |
| 1739 |
}) |
| 1740 |
} |
| 1741 |
|
| 1742 |
func textContent(t *testing.T, res *CallToolResult) string { |
| 1743 |
t.Helper() |
| 1744 |
if len(res.Content) != 1 { |
| 1745 |
t.Fatalf("len(Content) = %d, want 1", len(res.Content)) |
| 1746 |
} |
| 1747 |
text, ok := res.Content[0].(*TextContent) |
| 1748 |
if !ok { |
| 1749 |
t.Fatalf("Content[0] is %T, want *TextContent", res.Content[0]) |
| 1750 |
} |
| 1751 |
return text.Text |
| 1752 |
} |
| 1753 |
|
| 1754 |
func TestSessionHijackingPrevention(t *testing.T) { |
| 1755 |
|
| 1756 |
|
| 1757 |
ctx := context.Background() |
| 1758 |
|
| 1759 |
server := NewServer(testImpl, nil) |
| 1760 |
streamHandler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 1761 |
|
| 1762 |
|
| 1763 |
|
| 1764 |
verifier := func(_ context.Context, token string, _ *http.Request) (*auth.TokenInfo, error) { |
| 1765 |
return &auth.TokenInfo{ |
| 1766 |
Scopes: []string{"scope"}, |
| 1767 |
UserID: token, |
| 1768 |
Expiration: time.Date(5000, 1, 2, 3, 4, 5, 0, time.UTC), |
| 1769 |
}, nil |
| 1770 |
} |
| 1771 |
handler := auth.RequireBearerToken(verifier, nil)(streamHandler) |
| 1772 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 1773 |
defer httpServer.Close() |
| 1774 |
|
| 1775 |
|
| 1776 |
doRequest := func(msg jsonrpc.Message, sessionID, userID string) *http.Response { |
| 1777 |
t.Helper() |
| 1778 |
data, _ := jsonrpc2.EncodeMessage(msg) |
| 1779 |
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, httpServer.URL, bytes.NewReader(data)) |
| 1780 |
req.Header.Set("Content-Type", "application/json") |
| 1781 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 1782 |
req.Header.Set("Authorization", "Bearer "+userID) |
| 1783 |
if sessionID != "" { |
| 1784 |
req.Header.Set(sessionIDHeader, sessionID) |
| 1785 |
} |
| 1786 |
resp, err := http.DefaultClient.Do(req) |
| 1787 |
if err != nil { |
| 1788 |
t.Fatalf("request failed: %v", err) |
| 1789 |
} |
| 1790 |
return resp |
| 1791 |
} |
| 1792 |
|
| 1793 |
|
| 1794 |
initReq := &jsonrpc.Request{Method: "initialize", ID: jsonrpc2.Int64ID(1)} |
| 1795 |
initReq.Params, _ = json.Marshal(&InitializeParams{ |
| 1796 |
ProtocolVersion: protocolVersion20250618, |
| 1797 |
ClientInfo: &Implementation{Name: "test", Version: "1.0"}, |
| 1798 |
}) |
| 1799 |
resp := doRequest(initReq, "", "user1") |
| 1800 |
defer resp.Body.Close() |
| 1801 |
if resp.StatusCode != http.StatusOK { |
| 1802 |
body, _ := io.ReadAll(resp.Body) |
| 1803 |
t.Fatalf("initialize failed with status %d: %s", resp.StatusCode, body) |
| 1804 |
} |
| 1805 |
sessionID := resp.Header.Get(sessionIDHeader) |
| 1806 |
if sessionID == "" { |
| 1807 |
t.Fatal("no session ID in response") |
| 1808 |
} |
| 1809 |
|
| 1810 |
pingReq := &jsonrpc.Request{Method: "ping", ID: jsonrpc2.Int64ID(2)} |
| 1811 |
pingReq.Params, _ = json.Marshal(&PingParams{}) |
| 1812 |
|
| 1813 |
|
| 1814 |
resp2 := doRequest(pingReq, sessionID, "user2") |
| 1815 |
defer resp2.Body.Close() |
| 1816 |
if resp2.StatusCode != http.StatusForbidden { |
| 1817 |
body, _ := io.ReadAll(resp2.Body) |
| 1818 |
t.Errorf("expected status %d for user mismatch, got %d: %s", http.StatusForbidden, resp2.StatusCode, body) |
| 1819 |
} |
| 1820 |
|
| 1821 |
|
| 1822 |
resp3 := doRequest(pingReq, sessionID, "user1") |
| 1823 |
defer resp3.Body.Close() |
| 1824 |
if resp3.StatusCode != http.StatusOK { |
| 1825 |
body, _ := io.ReadAll(resp3.Body) |
| 1826 |
t.Errorf("expected status %d for matching user, got %d: %s", http.StatusOK, resp3.StatusCode, body) |
| 1827 |
} |
| 1828 |
} |
| 1829 |
|
| 1830 |
func TestStreamableGET(t *testing.T) { |
| 1831 |
|
| 1832 |
|
| 1833 |
|
| 1834 |
server := NewServer(testImpl, nil) |
| 1835 |
|
| 1836 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 1837 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 1838 |
defer httpServer.Close() |
| 1839 |
|
| 1840 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 1841 |
defer cancel() |
| 1842 |
|
| 1843 |
newReq := func(method string, msg jsonrpc.Message) *http.Request { |
| 1844 |
var body io.Reader |
| 1845 |
if msg != nil { |
| 1846 |
data, err := jsonrpc2.EncodeMessage(msg) |
| 1847 |
if err != nil { |
| 1848 |
t.Fatal(err) |
| 1849 |
} |
| 1850 |
body = bytes.NewReader(data) |
| 1851 |
} |
| 1852 |
req, err := http.NewRequestWithContext(ctx, method, httpServer.URL, body) |
| 1853 |
if err != nil { |
| 1854 |
t.Fatal(err) |
| 1855 |
} |
| 1856 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 1857 |
if msg != nil { |
| 1858 |
req.Header.Set("Content-Type", "application/json") |
| 1859 |
} |
| 1860 |
return req |
| 1861 |
} |
| 1862 |
|
| 1863 |
get1 := newReq(http.MethodGet, nil) |
| 1864 |
resp, err := http.DefaultClient.Do(get1) |
| 1865 |
if err != nil { |
| 1866 |
t.Fatal(err) |
| 1867 |
} |
| 1868 |
|
| 1869 |
|
| 1870 |
if got, want := resp.StatusCode, http.StatusBadRequest; got != want { |
| 1871 |
t.Errorf("initial GET: got status %d, want %d", got, want) |
| 1872 |
} |
| 1873 |
defer resp.Body.Close() |
| 1874 |
|
| 1875 |
post1 := newReq(http.MethodPost, req(1, methodInitialize, &InitializeParams{})) |
| 1876 |
resp, err = http.DefaultClient.Do(post1) |
| 1877 |
if err != nil { |
| 1878 |
t.Fatal(err) |
| 1879 |
} |
| 1880 |
defer resp.Body.Close() |
| 1881 |
if got, want := resp.StatusCode, http.StatusOK; got != want { |
| 1882 |
body, err := io.ReadAll(resp.Body) |
| 1883 |
if err != nil { |
| 1884 |
t.Fatal(err) |
| 1885 |
} |
| 1886 |
t.Errorf("initialize POST: got status %d, want %d; body:\n%s", got, want, string(body)) |
| 1887 |
} |
| 1888 |
|
| 1889 |
sessionID := resp.Header.Get(sessionIDHeader) |
| 1890 |
if sessionID == "" { |
| 1891 |
t.Fatalf("initialized missing session ID") |
| 1892 |
} |
| 1893 |
|
| 1894 |
get2 := newReq("GET", nil) |
| 1895 |
get2.Header.Set(sessionIDHeader, sessionID) |
| 1896 |
resp, err = http.DefaultClient.Do(get2) |
| 1897 |
if err != nil { |
| 1898 |
t.Fatal(err) |
| 1899 |
} |
| 1900 |
defer resp.Body.Close() |
| 1901 |
if got, want := resp.StatusCode, http.StatusOK; got != want { |
| 1902 |
t.Errorf("GET with session ID: got status %d, want %d", got, want) |
| 1903 |
} |
| 1904 |
|
| 1905 |
t.Log("Sending final DELETE request to close session and release resources") |
| 1906 |
del := newReq("DELETE", nil) |
| 1907 |
del.Header.Set(sessionIDHeader, sessionID) |
| 1908 |
resp, err = http.DefaultClient.Do(del) |
| 1909 |
if err != nil { |
| 1910 |
t.Fatal(err) |
| 1911 |
} |
| 1912 |
defer resp.Body.Close() |
| 1913 |
if got, want := resp.StatusCode, http.StatusNoContent; got != want { |
| 1914 |
t.Errorf("DELETE with session ID: got status %d, want %d", got, want) |
| 1915 |
} |
| 1916 |
} |
| 1917 |
|
| 1918 |
|
| 1919 |
|
| 1920 |
|
| 1921 |
func TestStreamableMcpHeaderValidation(t *testing.T) { |
| 1922 |
|
| 1923 |
orig := supportedProtocolVersions |
| 1924 |
supportedProtocolVersions = append(slices.Clone(orig), minVersionForStandardHeaders) |
| 1925 |
t.Cleanup(func() { supportedProtocolVersions = orig }) |
| 1926 |
|
| 1927 |
server := NewServer(&Implementation{Name: "testServer", Version: "v1.0.0"}, nil) |
| 1928 |
server.AddTool( |
| 1929 |
&Tool{Name: "my-tool", InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 1930 |
func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) { |
| 1931 |
return &CallToolResult{}, nil |
| 1932 |
}) |
| 1933 |
|
| 1934 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 1935 |
defer handler.closeAll() |
| 1936 |
|
| 1937 |
initReq := req(1, methodInitialize, &InitializeParams{ProtocolVersion: minVersionForStandardHeaders}) |
| 1938 |
initResp := resp(1, &InitializeResult{ |
| 1939 |
Capabilities: &ServerCapabilities{ |
| 1940 |
Logging: &LoggingCapabilities{}, |
| 1941 |
Tools: &ToolCapabilities{ListChanged: true}, |
| 1942 |
}, |
| 1943 |
ProtocolVersion: minVersionForStandardHeaders, |
| 1944 |
ServerInfo: &Implementation{Name: "testServer", Version: "v1.0.0"}, |
| 1945 |
}, nil) |
| 1946 |
|
| 1947 |
initialize := streamableRequest{ |
| 1948 |
method: "POST", |
| 1949 |
messages: []jsonrpc.Message{initReq}, |
| 1950 |
wantStatusCode: http.StatusOK, |
| 1951 |
wantMessages: []jsonrpc.Message{initResp}, |
| 1952 |
wantSessionID: true, |
| 1953 |
} |
| 1954 |
initialized := streamableRequest{ |
| 1955 |
method: "POST", |
| 1956 |
headers: http.Header{ |
| 1957 |
protocolVersionHeader: {minVersionForStandardHeaders}, |
| 1958 |
methodHeader: {notificationInitialized}, |
| 1959 |
}, |
| 1960 |
messages: []jsonrpc.Message{req(0, notificationInitialized, &InitializedParams{})}, |
| 1961 |
wantStatusCode: http.StatusAccepted, |
| 1962 |
} |
| 1963 |
|
| 1964 |
testStreamableHandler(t, handler, []streamableRequest{ |
| 1965 |
initialize, |
| 1966 |
initialized, |
| 1967 |
{ |
| 1968 |
method: "POST", |
| 1969 |
headers: http.Header{ |
| 1970 |
protocolVersionHeader: {minVersionForStandardHeaders}, |
| 1971 |
methodHeader: {"tools/call"}, |
| 1972 |
nameHeader: {"my-tool"}, |
| 1973 |
}, |
| 1974 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "my-tool"})}, |
| 1975 |
wantStatusCode: http.StatusOK, |
| 1976 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 1977 |
}, |
| 1978 |
{ |
| 1979 |
method: "POST", |
| 1980 |
headers: http.Header{ |
| 1981 |
protocolVersionHeader: {minVersionForStandardHeaders}, |
| 1982 |
methodHeader: {"prompts/get"}, |
| 1983 |
nameHeader: {"my-tool"}, |
| 1984 |
}, |
| 1985 |
messages: []jsonrpc.Message{req(3, "tools/call", &CallToolParams{Name: "my-tool"})}, |
| 1986 |
wantStatusCode: http.StatusBadRequest, |
| 1987 |
wantBodyContaining: "Mcp-Method header value", |
| 1988 |
}, |
| 1989 |
{ |
| 1990 |
method: "POST", |
| 1991 |
headers: http.Header{ |
| 1992 |
protocolVersionHeader: {minVersionForStandardHeaders}, |
| 1993 |
methodHeader: {"tools/call"}, |
| 1994 |
nameHeader: {"wrong-tool"}, |
| 1995 |
}, |
| 1996 |
messages: []jsonrpc.Message{req(4, "tools/call", &CallToolParams{Name: "my-tool"})}, |
| 1997 |
wantStatusCode: http.StatusBadRequest, |
| 1998 |
wantBodyContaining: "Mcp-Name header value", |
| 1999 |
}, |
| 2000 |
{ |
| 2001 |
method: "POST", |
| 2002 |
headers: http.Header{ |
| 2003 |
protocolVersionHeader: {minVersionForStandardHeaders}, |
| 2004 |
methodHeader: {"TOOLS/CALL"}, |
| 2005 |
nameHeader: {"my-tool"}, |
| 2006 |
}, |
| 2007 |
messages: []jsonrpc.Message{req(5, "tools/call", &CallToolParams{Name: "my-tool"})}, |
| 2008 |
wantStatusCode: http.StatusBadRequest, |
| 2009 |
wantBodyContaining: "Mcp-Method header value", |
| 2010 |
}, |
| 2011 |
{ |
| 2012 |
method: "POST", |
| 2013 |
headers: http.Header{ |
| 2014 |
protocolVersionHeader: {minVersionForStandardHeaders}, |
| 2015 |
methodHeader: {"tools/call"}, |
| 2016 |
nameHeader: {"my-tool"}, |
| 2017 |
}, |
| 2018 |
messages: []jsonrpc.Message{req(6, "tools/call", &CallToolParams{Name: "my-tool"})}, |
| 2019 |
wantStatusCode: http.StatusOK, |
| 2020 |
wantMessages: []jsonrpc.Message{resp(6, &CallToolResult{Content: []Content{}}, nil)}, |
| 2021 |
}, |
| 2022 |
}) |
| 2023 |
} |
| 2024 |
|
| 2025 |
|
| 2026 |
|
| 2027 |
|
| 2028 |
func TestStreamableMcpHeaderValidationErrorFormat(t *testing.T) { |
| 2029 |
orig := supportedProtocolVersions |
| 2030 |
supportedProtocolVersions = append(slices.Clone(orig), minVersionForStandardHeaders) |
| 2031 |
t.Cleanup(func() { supportedProtocolVersions = orig }) |
| 2032 |
|
| 2033 |
server := NewServer(&Implementation{Name: "testServer", Version: "v1.0.0"}, nil) |
| 2034 |
server.AddTool( |
| 2035 |
&Tool{Name: "my-tool", InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 2036 |
func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) { |
| 2037 |
return &CallToolResult{}, nil |
| 2038 |
}) |
| 2039 |
|
| 2040 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 2041 |
defer handler.closeAll() |
| 2042 |
|
| 2043 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 2044 |
defer httpServer.Close() |
| 2045 |
|
| 2046 |
|
| 2047 |
var toolCallResp *http.Response |
| 2048 |
var toolCallRespBody []byte |
| 2049 |
|
| 2050 |
customClient := &http.Client{ |
| 2051 |
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { |
| 2052 |
var originalMethodHeader string |
| 2053 |
if req.Header.Get(methodHeader) == "tools/call" { |
| 2054 |
originalMethodHeader = req.Header.Get(methodHeader) |
| 2055 |
req.Header.Set(methodHeader, "wrong-method") |
| 2056 |
} |
| 2057 |
resp, err := http.DefaultTransport.RoundTrip(req) |
| 2058 |
if err == nil && originalMethodHeader == "tools/call" { |
| 2059 |
toolCallResp = resp |
| 2060 |
toolCallRespBody, _ = io.ReadAll(resp.Body) |
| 2061 |
} |
| 2062 |
return resp, err |
| 2063 |
}), |
| 2064 |
} |
| 2065 |
|
| 2066 |
clientTransport := &StreamableClientTransport{ |
| 2067 |
Endpoint: httpServer.URL, |
| 2068 |
HTTPClient: customClient, |
| 2069 |
} |
| 2070 |
|
| 2071 |
client := NewClient(&Implementation{Name: "testClient", Version: "v1.0.0"}, nil) |
| 2072 |
ctx := context.Background() |
| 2073 |
session, err := client.Connect(ctx, clientTransport, &ClientSessionOptions{protocolVersion: minVersionForStandardHeaders}) |
| 2074 |
if err != nil { |
| 2075 |
t.Fatal(err) |
| 2076 |
} |
| 2077 |
defer session.Close() |
| 2078 |
|
| 2079 |
_, err = session.CallTool(ctx, &CallToolParams{Name: "my-tool"}) |
| 2080 |
|
| 2081 |
if err == nil { |
| 2082 |
t.Error("CallTool succeeded unexpectedly") |
| 2083 |
} |
| 2084 |
|
| 2085 |
if toolCallResp == nil { |
| 2086 |
t.Fatal("no response captured") |
| 2087 |
} |
| 2088 |
|
| 2089 |
|
| 2090 |
if toolCallResp.StatusCode != http.StatusBadRequest { |
| 2091 |
t.Errorf("status code = %d, want %d", toolCallResp.StatusCode, http.StatusBadRequest) |
| 2092 |
} |
| 2093 |
|
| 2094 |
|
| 2095 |
if baseMediaType(toolCallResp.Header.Get("Content-Type")) != "application/json" { |
| 2096 |
t.Errorf("Content-Type = %q, want %q", baseMediaType(toolCallResp.Header.Get("Content-Type")), "application/json") |
| 2097 |
} |
| 2098 |
|
| 2099 |
|
| 2100 |
msg, err := jsonrpc2.DecodeMessage(toolCallRespBody) |
| 2101 |
if err != nil { |
| 2102 |
t.Fatalf("failed to decode message: %v", err) |
| 2103 |
} |
| 2104 |
resp, ok := msg.(*jsonrpc2.Response) |
| 2105 |
if !ok { |
| 2106 |
t.Fatalf("expected *jsonrpc2.Response, got %T", msg) |
| 2107 |
} |
| 2108 |
var wireErr *jsonrpc2.WireError |
| 2109 |
if !errors.As(resp.Error, &wireErr) { |
| 2110 |
t.Fatalf("expected *jsonrpc2.WireError, got %T", resp.Error) |
| 2111 |
} |
| 2112 |
if wireErr.Code != -32001 { |
| 2113 |
t.Errorf("wireErr.Code = %d, want -32001", wireErr.Code) |
| 2114 |
} |
| 2115 |
if !strings.Contains(wireErr.Message, "Mcp-Method header value") { |
| 2116 |
t.Errorf("wireErr.Message = %q, want it to contain %q", wireErr.Message, "Mcp-Method header value") |
| 2117 |
} |
| 2118 |
} |
| 2119 |
|
| 2120 |
|
| 2121 |
|
| 2122 |
func TestStreamableMcpHeaderVersionGating(t *testing.T) { |
| 2123 |
server := NewServer(&Implementation{Name: "testServer", Version: "v1.0.0"}, nil) |
| 2124 |
server.AddTool( |
| 2125 |
&Tool{Name: "my-tool", InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 2126 |
func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) { |
| 2127 |
return &CallToolResult{}, nil |
| 2128 |
}) |
| 2129 |
|
| 2130 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 2131 |
defer handler.closeAll() |
| 2132 |
|
| 2133 |
initReq := req(1, methodInitialize, &InitializeParams{ProtocolVersion: protocolVersion20251125}) |
| 2134 |
initResp := resp(1, &InitializeResult{ |
| 2135 |
Capabilities: &ServerCapabilities{ |
| 2136 |
Logging: &LoggingCapabilities{}, |
| 2137 |
Tools: &ToolCapabilities{ListChanged: true}, |
| 2138 |
}, |
| 2139 |
ProtocolVersion: protocolVersion20251125, |
| 2140 |
ServerInfo: &Implementation{Name: "testServer", Version: "v1.0.0"}, |
| 2141 |
}, nil) |
| 2142 |
|
| 2143 |
testStreamableHandler(t, handler, []streamableRequest{ |
| 2144 |
{ |
| 2145 |
method: "POST", |
| 2146 |
messages: []jsonrpc.Message{initReq}, |
| 2147 |
wantStatusCode: http.StatusOK, |
| 2148 |
wantMessages: []jsonrpc.Message{initResp}, |
| 2149 |
wantSessionID: true, |
| 2150 |
}, |
| 2151 |
{ |
| 2152 |
method: "POST", |
| 2153 |
headers: http.Header{protocolVersionHeader: {protocolVersion20251125}}, |
| 2154 |
messages: []jsonrpc.Message{req(0, notificationInitialized, &InitializedParams{})}, |
| 2155 |
wantStatusCode: http.StatusAccepted, |
| 2156 |
}, |
| 2157 |
|
| 2158 |
|
| 2159 |
{ |
| 2160 |
method: "POST", |
| 2161 |
headers: http.Header{ |
| 2162 |
protocolVersionHeader: {protocolVersion20251125}, |
| 2163 |
methodHeader: {"wrong-method"}, |
| 2164 |
nameHeader: {"wrong-name"}, |
| 2165 |
}, |
| 2166 |
messages: []jsonrpc.Message{req(2, "tools/call", &CallToolParams{Name: "my-tool"})}, |
| 2167 |
wantStatusCode: http.StatusOK, |
| 2168 |
wantMessages: []jsonrpc.Message{resp(2, &CallToolResult{Content: []Content{}}, nil)}, |
| 2169 |
}, |
| 2170 |
}) |
| 2171 |
} |
| 2172 |
|
| 2173 |
: |
| 2174 |
|
| 2175 |
func TestStreamable405AllowHeader(t *testing.T) { |
| 2176 |
server := NewServer(testImpl, nil) |
| 2177 |
|
| 2178 |
tests := []struct { |
| 2179 |
name string |
| 2180 |
stateless bool |
| 2181 |
method string |
| 2182 |
wantStatus int |
| 2183 |
wantAllow string |
| 2184 |
}{ |
| 2185 |
{ |
| 2186 |
name: "unsupported method stateful", |
| 2187 |
stateless: false, |
| 2188 |
method: "PUT", |
| 2189 |
wantStatus: http.StatusMethodNotAllowed, |
| 2190 |
wantAllow: "GET, POST, DELETE", |
| 2191 |
}, |
| 2192 |
{ |
| 2193 |
name: "GET in stateless mode", |
| 2194 |
stateless: true, |
| 2195 |
method: "GET", |
| 2196 |
wantStatus: http.StatusMethodNotAllowed, |
| 2197 |
wantAllow: "POST", |
| 2198 |
}, |
| 2199 |
{ |
| 2200 |
|
| 2201 |
|
| 2202 |
name: "DELETE without session stateless", |
| 2203 |
stateless: true, |
| 2204 |
method: "DELETE", |
| 2205 |
wantStatus: http.StatusBadRequest, |
| 2206 |
wantAllow: "", |
| 2207 |
}, |
| 2208 |
} |
| 2209 |
|
| 2210 |
for _, tt := range tests { |
| 2211 |
t.Run(tt.name, func(t *testing.T) { |
| 2212 |
opts := &StreamableHTTPOptions{Stateless: tt.stateless} |
| 2213 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, opts) |
| 2214 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 2215 |
defer httpServer.Close() |
| 2216 |
|
| 2217 |
req, err := http.NewRequest(tt.method, httpServer.URL, nil) |
| 2218 |
if err != nil { |
| 2219 |
t.Fatal(err) |
| 2220 |
} |
| 2221 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 2222 |
|
| 2223 |
resp, err := http.DefaultClient.Do(req) |
| 2224 |
if err != nil { |
| 2225 |
t.Fatal(err) |
| 2226 |
} |
| 2227 |
defer resp.Body.Close() |
| 2228 |
|
| 2229 |
if got := resp.StatusCode; got != tt.wantStatus { |
| 2230 |
t.Errorf("status code: got %d, want %d", got, tt.wantStatus) |
| 2231 |
} |
| 2232 |
|
| 2233 |
allow := resp.Header.Get("Allow") |
| 2234 |
if allow != tt.wantAllow { |
| 2235 |
t.Errorf("Allow header: got %q, want %q", allow, tt.wantAllow) |
| 2236 |
} |
| 2237 |
}) |
| 2238 |
} |
| 2239 |
} |
| 2240 |
|
| 2241 |
|
| 2242 |
|
| 2243 |
func TestStreamableGETWithoutSession(t *testing.T) { |
| 2244 |
server := NewServer(testImpl, nil) |
| 2245 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 2246 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 2247 |
defer httpServer.Close() |
| 2248 |
|
| 2249 |
req, err := http.NewRequest("GET", httpServer.URL, nil) |
| 2250 |
if err != nil { |
| 2251 |
t.Fatal(err) |
| 2252 |
} |
| 2253 |
req.Header.Set("Accept", "text/event-stream") |
| 2254 |
|
| 2255 |
resp, err := http.DefaultClient.Do(req) |
| 2256 |
if err != nil { |
| 2257 |
t.Fatal(err) |
| 2258 |
} |
| 2259 |
defer resp.Body.Close() |
| 2260 |
body, err := io.ReadAll(resp.Body) |
| 2261 |
if err != nil { |
| 2262 |
t.Fatal(err) |
| 2263 |
} |
| 2264 |
|
| 2265 |
|
| 2266 |
|
| 2267 |
if got, want := resp.StatusCode, http.StatusBadRequest; got != want { |
| 2268 |
t.Errorf("status code: got %d, want %d", got, want) |
| 2269 |
} |
| 2270 |
if got, want := strings.TrimSpace(string(body)), "Bad Request: GET requires an Mcp-Session-Id header"; got != want { |
| 2271 |
t.Errorf("body: got %q, want %q", got, want) |
| 2272 |
} |
| 2273 |
} |
| 2274 |
|
| 2275 |
func TestStreamableGETWithoutEventStreamAccept(t *testing.T) { |
| 2276 |
server := NewServer(testImpl, nil) |
| 2277 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil) |
| 2278 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 2279 |
defer httpServer.Close() |
| 2280 |
|
| 2281 |
req, err := http.NewRequest("GET", httpServer.URL, nil) |
| 2282 |
if err != nil { |
| 2283 |
t.Fatal(err) |
| 2284 |
} |
| 2285 |
req.Header.Set("Accept", "application/json") |
| 2286 |
|
| 2287 |
resp, err := http.DefaultClient.Do(req) |
| 2288 |
if err != nil { |
| 2289 |
t.Fatal(err) |
| 2290 |
} |
| 2291 |
defer resp.Body.Close() |
| 2292 |
body, err := io.ReadAll(resp.Body) |
| 2293 |
if err != nil { |
| 2294 |
t.Fatal(err) |
| 2295 |
} |
| 2296 |
|
| 2297 |
if got, want := resp.StatusCode, http.StatusBadRequest; got != want { |
| 2298 |
t.Errorf("status code: got %d, want %d", got, want) |
| 2299 |
} |
| 2300 |
if got, want := strings.TrimSpace(string(body)), "Accept must contain 'text/event-stream' for GET requests"; got != want { |
| 2301 |
t.Errorf("body: got %q, want %q", got, want) |
| 2302 |
} |
| 2303 |
} |
| 2304 |
|
| 2305 |
func TestBaseMediaType(t *testing.T) { |
| 2306 |
tests := []struct { |
| 2307 |
name string |
| 2308 |
value string |
| 2309 |
want string |
| 2310 |
}{ |
| 2311 |
{name: "empty", want: ""}, |
| 2312 |
{name: "json", value: "application/json", want: "application/json"}, |
| 2313 |
{name: "json with params", value: "Application/JSON; charset=utf-8", want: "application/json"}, |
| 2314 |
{name: "event stream with params", value: "Text/Event-Stream; charset=utf-8", want: "text/event-stream"}, |
| 2315 |
{name: "invalid", value: "application/json; charset", want: ""}, |
| 2316 |
} |
| 2317 |
|
| 2318 |
for _, test := range tests { |
| 2319 |
t.Run(test.name, func(t *testing.T) { |
| 2320 |
if got := baseMediaType(test.value); got != test.want { |
| 2321 |
t.Errorf("baseMediaType(%q) = %q, want %q", test.value, got, test.want) |
| 2322 |
} |
| 2323 |
}) |
| 2324 |
} |
| 2325 |
} |
| 2326 |
|
| 2327 |
func TestStreamableClientContextPropagation(t *testing.T) { |
| 2328 |
type contextKey string |
| 2329 |
const testKey = contextKey("test-key") |
| 2330 |
const testValue = "test-value" |
| 2331 |
|
| 2332 |
ctx, cancel := context.WithCancel(context.Background()) |
| 2333 |
defer cancel() |
| 2334 |
ctx2 := context.WithValue(ctx, testKey, testValue) |
| 2335 |
|
| 2336 |
server := httptest.NewServer(mustNotPanic(t, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 2337 |
switch req.Method { |
| 2338 |
case "POST": |
| 2339 |
w.Header().Set("Content-Type", "application/json") |
| 2340 |
w.Header().Set(sessionIDHeader, "test-session") |
| 2341 |
w.WriteHeader(http.StatusOK) |
| 2342 |
w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-03-26","capabilities":{},"serverInfo":{"name":"test","version":"1.0"}}}`)) |
| 2343 |
case "GET": |
| 2344 |
w.Header().Set("Content-Type", "text/event-stream") |
| 2345 |
w.WriteHeader(http.StatusOK) |
| 2346 |
case "DELETE": |
| 2347 |
w.WriteHeader(http.StatusNoContent) |
| 2348 |
} |
| 2349 |
}))) |
| 2350 |
defer server.Close() |
| 2351 |
|
| 2352 |
transport := &StreamableClientTransport{Endpoint: server.URL} |
| 2353 |
conn, err := transport.Connect(ctx2) |
| 2354 |
if err != nil { |
| 2355 |
t.Fatalf("Connect failed: %v", err) |
| 2356 |
} |
| 2357 |
defer conn.Close() |
| 2358 |
|
| 2359 |
streamableConn, ok := conn.(*streamableClientConn) |
| 2360 |
if !ok { |
| 2361 |
t.Fatalf("Expected *streamableClientConn, got %T", conn) |
| 2362 |
} |
| 2363 |
|
| 2364 |
if got := streamableConn.ctx.Value(testKey); got != testValue { |
| 2365 |
t.Errorf("Context value not propagated: got %v, want %v", got, testValue) |
| 2366 |
} |
| 2367 |
|
| 2368 |
if streamableConn.ctx.Done() == nil { |
| 2369 |
t.Error("Connection context is not cancellable") |
| 2370 |
} |
| 2371 |
|
| 2372 |
cancel() |
| 2373 |
select { |
| 2374 |
case <-streamableConn.ctx.Done(): |
| 2375 |
t.Errorf("cancelling the connection context after successful connection broke the connection") |
| 2376 |
default: |
| 2377 |
} |
| 2378 |
} |
| 2379 |
|
| 2380 |
func TestStreamableSessionTimeout(t *testing.T) { |
| 2381 |
|
| 2382 |
|
| 2383 |
|
| 2384 |
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 2385 |
defer cancel() |
| 2386 |
|
| 2387 |
server := NewServer(testImpl, nil) |
| 2388 |
|
| 2389 |
deleted := make(chan string, 1) |
| 2390 |
handler := NewStreamableHTTPHandler( |
| 2391 |
func(req *http.Request) *Server { return server }, |
| 2392 |
&StreamableHTTPOptions{ |
| 2393 |
SessionTimeout: 50 * time.Millisecond, |
| 2394 |
}, |
| 2395 |
) |
| 2396 |
handler.onTransportDeletion = func(sessionID string) { |
| 2397 |
deleted <- sessionID |
| 2398 |
} |
| 2399 |
|
| 2400 |
httpServer := httptest.NewServer(mustNotPanic(t, handler)) |
| 2401 |
defer httpServer.Close() |
| 2402 |
|
| 2403 |
|
| 2404 |
client := NewClient(testImpl, nil) |
| 2405 |
session, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, nil) |
| 2406 |
if err != nil { |
| 2407 |
t.Fatalf("client.Connect() failed: %v", err) |
| 2408 |
} |
| 2409 |
defer session.Close() |
| 2410 |
|
| 2411 |
sessionID := session.ID() |
| 2412 |
if sessionID == "" { |
| 2413 |
t.Fatal("client session has empty ID") |
| 2414 |
} |
| 2415 |
|
| 2416 |
|
| 2417 |
serverSessions := slices.Collect(server.Sessions()) |
| 2418 |
if len(serverSessions) != 1 { |
| 2419 |
t.Fatalf("got %d sessions, want 1", len(serverSessions)) |
| 2420 |
} |
| 2421 |
if got := serverSessions[0].ID(); got != sessionID { |
| 2422 |
t.Fatalf("server session is %q, want %q", got, sessionID) |
| 2423 |
} |
| 2424 |
|
| 2425 |
|
| 2426 |
|
| 2427 |
|
| 2428 |
|
| 2429 |
var wg sync.WaitGroup |
| 2430 |
for range 2 { |
| 2431 |
wg.Go(func() { |
| 2432 |
for range 20 { |
| 2433 |
if _, err := session.ListTools(ctx, nil); err != nil { |
| 2434 |
t.Errorf("ListTools failed: %v", err) |
| 2435 |
} |
| 2436 |
time.Sleep(10 * time.Millisecond) |
| 2437 |
} |
| 2438 |
}) |
| 2439 |
} |
| 2440 |
|
| 2441 |
wg.Wait() |
| 2442 |
|
| 2443 |
|
| 2444 |
select { |
| 2445 |
case deletedID := <-deleted: |
| 2446 |
if deletedID != sessionID { |
| 2447 |
t.Errorf("deleted session ID = %q, want %q", deletedID, sessionID) |
| 2448 |
} |
| 2449 |
case <-ctx.Done(): |
| 2450 |
t.Fatal("timed out waiting for session cleanup") |
| 2451 |
} |
| 2452 |
|
| 2453 |
|
| 2454 |
handler.mu.Lock() |
| 2455 |
if len(handler.sessions) != 0 { |
| 2456 |
t.Errorf("handler.sessions is not empty; length %d", len(handler.sessions)) |
| 2457 |
} |
| 2458 |
if ss := slices.Collect(server.Sessions()); len(ss) != 0 { |
| 2459 |
t.Errorf("server.Sessions() is not empty; length %d", len(ss)) |
| 2460 |
} |
| 2461 |
handler.mu.Unlock() |
| 2462 |
} |
| 2463 |
|
| 2464 |
|
| 2465 |
|
| 2466 |
func mustNotPanic(t *testing.T, h http.Handler) http.Handler { |
| 2467 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 2468 |
defer func() { |
| 2469 |
if r := recover(); r != nil { |
| 2470 |
buf := make([]byte, 1<<20) |
| 2471 |
n := runtime.Stack(buf, false) |
| 2472 |
fmt.Fprintf(os.Stderr, "handler panic: %v\n\n%s", r, buf[:n]) |
| 2473 |
t.Errorf("handler panicked: %v", r) |
| 2474 |
} |
| 2475 |
}() |
| 2476 |
h.ServeHTTP(w, req) |
| 2477 |
}) |
| 2478 |
} |
| 2479 |
|
| 2480 |
|
| 2481 |
|
| 2482 |
|
| 2483 |
|
| 2484 |
|
| 2485 |
|
| 2486 |
|
| 2487 |
func TestPingEventFiltering(t *testing.T) { |
| 2488 |
|
| 2489 |
|
| 2490 |
|
| 2491 |
sseData := `event: ping |
| 2492 |
data: ping |
| 2493 |
|
| 2494 |
event: message |
| 2495 |
id: 1 |
| 2496 |
data: {"jsonrpc":"2.0","id":1,"result":{}} |
| 2497 |
|
| 2498 |
event: ping |
| 2499 |
data: keepalive |
| 2500 |
|
| 2501 |
` |
| 2502 |
|
| 2503 |
resp := &http.Response{ |
| 2504 |
StatusCode: http.StatusOK, |
| 2505 |
Header: http.Header{"Content-Type": []string{"text/event-stream"}}, |
| 2506 |
Body: io.NopCloser(bytes.NewReader([]byte(sseData))), |
| 2507 |
} |
| 2508 |
|
| 2509 |
|
| 2510 |
ctx := t.Context() |
| 2511 |
|
| 2512 |
incoming := make(chan jsonrpc.Message, 10) |
| 2513 |
done := make(chan struct{}) |
| 2514 |
|
| 2515 |
conn := &streamableClientConn{ |
| 2516 |
ctx: ctx, |
| 2517 |
done: done, |
| 2518 |
incoming: incoming, |
| 2519 |
} |
| 2520 |
|
| 2521 |
|
| 2522 |
testReq := &jsonrpc.Request{ |
| 2523 |
ID: jsonrpc2.Int64ID(1), |
| 2524 |
Method: "test", |
| 2525 |
} |
| 2526 |
|
| 2527 |
|
| 2528 |
go conn.processStream(ctx, "test", resp, testReq) |
| 2529 |
|
| 2530 |
|
| 2531 |
var messages []jsonrpc.Message |
| 2532 |
timeout := time.After(1 * time.Second) |
| 2533 |
|
| 2534 |
collectLoop: |
| 2535 |
for { |
| 2536 |
select { |
| 2537 |
case msg := <-incoming: |
| 2538 |
messages = append(messages, msg) |
| 2539 |
|
| 2540 |
if len(messages) >= 1 { |
| 2541 |
break collectLoop |
| 2542 |
} |
| 2543 |
case <-timeout: |
| 2544 |
break collectLoop |
| 2545 |
} |
| 2546 |
} |
| 2547 |
|
| 2548 |
|
| 2549 |
if len(messages) != 1 { |
| 2550 |
t.Errorf("got %d messages, want 1 (ping events should be filtered)", len(messages)) |
| 2551 |
for i, msg := range messages { |
| 2552 |
t.Logf("message %d: %T", i, msg) |
| 2553 |
} |
| 2554 |
} |
| 2555 |
|
| 2556 |
|
| 2557 |
if len(messages) > 0 { |
| 2558 |
resp, ok := messages[0].(*jsonrpc.Response) |
| 2559 |
if !ok { |
| 2560 |
t.Errorf("first message is %T, want *jsonrpc.Response", messages[0]) |
| 2561 |
} else if resp.ID.Raw() != int64(1) { |
| 2562 |
t.Errorf("response ID is %v, want 1", resp.ID.Raw()) |
| 2563 |
} |
| 2564 |
} |
| 2565 |
} |
| 2566 |
|
| 2567 |
|
| 2568 |
|
| 2569 |
func TestProcessStreamPrimingEvent(t *testing.T) { |
| 2570 |
|
| 2571 |
|
| 2572 |
sseData := `id: 123 |
| 2573 |
|
| 2574 |
id: 124 |
| 2575 |
data: {"jsonrpc":"2.0","id":1,"result":{}} |
| 2576 |
|
| 2577 |
` |
| 2578 |
|
| 2579 |
ctx := t.Context() |
| 2580 |
resp := &http.Response{ |
| 2581 |
StatusCode: http.StatusOK, |
| 2582 |
Header: http.Header{"Content-Type": []string{"text/event-stream"}}, |
| 2583 |
Body: io.NopCloser(strings.NewReader(sseData)), |
| 2584 |
} |
| 2585 |
|
| 2586 |
incoming := make(chan jsonrpc.Message, 10) |
| 2587 |
done := make(chan struct{}) |
| 2588 |
|
| 2589 |
conn := &streamableClientConn{ |
| 2590 |
ctx: ctx, |
| 2591 |
done: done, |
| 2592 |
incoming: incoming, |
| 2593 |
failed: make(chan struct{}), |
| 2594 |
logger: ensureLogger(nil), |
| 2595 |
} |
| 2596 |
|
| 2597 |
lastID, _, clientClosed := conn.processStream(ctx, "test", resp, nil) |
| 2598 |
|
| 2599 |
if clientClosed { |
| 2600 |
t.Fatalf("processStream was unexpectedly closed by client") |
| 2601 |
} |
| 2602 |
|
| 2603 |
if lastID != "124" { |
| 2604 |
t.Errorf("lastEventID = %q, want %q", lastID, "124") |
| 2605 |
} |
| 2606 |
|
| 2607 |
select { |
| 2608 |
case msg := <-incoming: |
| 2609 |
if res, ok := msg.(*jsonrpc.Response); !(ok && res.ID == jsonrpc2.Int64ID(1)) { |
| 2610 |
t.Errorf("got unexpected message: %v", msg) |
| 2611 |
} |
| 2612 |
default: |
| 2613 |
t.Errorf("expected a JSON-RPC message to be produced") |
| 2614 |
} |
| 2615 |
} |
| 2616 |
|
| 2617 |
|
| 2618 |
|
| 2619 |
func TestScanEventsPingFiltering(t *testing.T) { |
| 2620 |
|
| 2621 |
sseData := `event: ping |
| 2622 |
data: ping |
| 2623 |
|
| 2624 |
event: message |
| 2625 |
data: {"jsonrpc":"2.0","method":"test","params":{}} |
| 2626 |
|
| 2627 |
event: ping |
| 2628 |
data: keepalive |
| 2629 |
|
| 2630 |
event: message |
| 2631 |
data: {"jsonrpc":"2.0","method":"test2","params":{}} |
| 2632 |
|
| 2633 |
` |
| 2634 |
|
| 2635 |
reader := strings.NewReader(sseData) |
| 2636 |
var events []Event |
| 2637 |
|
| 2638 |
|
| 2639 |
for evt, err := range scanEvents(reader) { |
| 2640 |
if err != nil { |
| 2641 |
if err != io.EOF { |
| 2642 |
t.Fatalf("scanEvents error: %v", err) |
| 2643 |
} |
| 2644 |
break |
| 2645 |
} |
| 2646 |
events = append(events, evt) |
| 2647 |
} |
| 2648 |
|
| 2649 |
|
| 2650 |
if len(events) != 4 { |
| 2651 |
t.Fatalf("got %d events, want 4", len(events)) |
| 2652 |
} |
| 2653 |
|
| 2654 |
|
| 2655 |
expectedNames := []string{"ping", "message", "ping", "message"} |
| 2656 |
for i, evt := range events { |
| 2657 |
if evt.Name != expectedNames[i] { |
| 2658 |
t.Errorf("event %d: got name %q, want %q", i, evt.Name, expectedNames[i]) |
| 2659 |
} |
| 2660 |
} |
| 2661 |
|
| 2662 |
|
| 2663 |
for i, evt := range events { |
| 2664 |
switch evt.Name { |
| 2665 |
case "message": |
| 2666 |
_, err := jsonrpc.DecodeMessage(evt.Data) |
| 2667 |
if err != nil { |
| 2668 |
t.Errorf("event %d: failed to decode message event: %v", i, err) |
| 2669 |
} |
| 2670 |
case "ping": |
| 2671 |
|
| 2672 |
_, err := jsonrpc.DecodeMessage(evt.Data) |
| 2673 |
if err == nil { |
| 2674 |
t.Errorf("event %d: ping event unexpectedly decoded as valid JSON-RPC", i) |
| 2675 |
} |
| 2676 |
} |
| 2677 |
} |
| 2678 |
} |
| 2679 |
|
| 2680 |
func Test_ExportErrSessionMissing(t *testing.T) { |
| 2681 |
ctx := context.Background() |
| 2682 |
|
| 2683 |
|
| 2684 |
impl := &Implementation{Name: "test", Version: "1.0.0"} |
| 2685 |
server := NewServer(impl, nil) |
| 2686 |
handler := NewStreamableHTTPHandler(func(r *http.Request) *Server { return server }, nil) |
| 2687 |
ts := httptest.NewServer(handler) |
| 2688 |
defer ts.Close() |
| 2689 |
|
| 2690 |
|
| 2691 |
clientTransport := &StreamableClientTransport{ |
| 2692 |
Endpoint: ts.URL, |
| 2693 |
} |
| 2694 |
client := NewClient(impl, nil) |
| 2695 |
session, err := client.Connect(ctx, clientTransport, nil) |
| 2696 |
if err != nil { |
| 2697 |
t.Fatalf("Connect failed: %v", err) |
| 2698 |
} |
| 2699 |
defer session.Close() |
| 2700 |
|
| 2701 |
|
| 2702 |
handler.mu.Lock() |
| 2703 |
if len(handler.sessions) != 1 { |
| 2704 |
handler.mu.Unlock() |
| 2705 |
t.Fatalf("expected 1 session, got %d", len(handler.sessions)) |
| 2706 |
} |
| 2707 |
for id := range handler.sessions { |
| 2708 |
delete(handler.sessions, id) |
| 2709 |
} |
| 2710 |
handler.mu.Unlock() |
| 2711 |
|
| 2712 |
|
| 2713 |
_, err = session.ListTools(ctx, nil) |
| 2714 |
if err == nil { |
| 2715 |
t.Fatal("expected error, got nil") |
| 2716 |
} |
| 2717 |
|
| 2718 |
|
| 2719 |
if !errors.Is(err, ErrSessionMissing) { |
| 2720 |
t.Errorf("expected error to wrap ErrSessionMissing, got: %v", err) |
| 2721 |
} |
| 2722 |
} |
| 2723 |
|
| 2724 |
|
| 2725 |
|
| 2726 |
func TestStreamableLocalhostProtection(t *testing.T) { |
| 2727 |
server := NewServer(testImpl, nil) |
| 2728 |
|
| 2729 |
tests := []struct { |
| 2730 |
name string |
| 2731 |
listenAddr string |
| 2732 |
hostHeader string |
| 2733 |
disableProtection bool |
| 2734 |
wantStatus int |
| 2735 |
}{ |
| 2736 |
|
| 2737 |
{ |
| 2738 |
name: "127.0.0.1 accepts 127.0.0.1", |
| 2739 |
listenAddr: "127.0.0.1:0", |
| 2740 |
hostHeader: "127.0.0.1:1234", |
| 2741 |
disableProtection: false, |
| 2742 |
wantStatus: http.StatusOK, |
| 2743 |
}, |
| 2744 |
{ |
| 2745 |
name: "127.0.0.1 accepts localhost", |
| 2746 |
listenAddr: "127.0.0.1:0", |
| 2747 |
hostHeader: "localhost:1234", |
| 2748 |
disableProtection: false, |
| 2749 |
wantStatus: http.StatusOK, |
| 2750 |
}, |
| 2751 |
{ |
| 2752 |
name: "127.0.0.1 rejects evil.com", |
| 2753 |
listenAddr: "127.0.0.1:0", |
| 2754 |
hostHeader: "evil.com", |
| 2755 |
disableProtection: false, |
| 2756 |
wantStatus: http.StatusForbidden, |
| 2757 |
}, |
| 2758 |
{ |
| 2759 |
name: "127.0.0.1 rejects evil.com:80", |
| 2760 |
listenAddr: "127.0.0.1:0", |
| 2761 |
hostHeader: "evil.com:80", |
| 2762 |
disableProtection: false, |
| 2763 |
wantStatus: http.StatusForbidden, |
| 2764 |
}, |
| 2765 |
{ |
| 2766 |
name: "127.0.0.1 rejects localhost.evil.com", |
| 2767 |
listenAddr: "127.0.0.1:0", |
| 2768 |
hostHeader: "localhost.evil.com", |
| 2769 |
disableProtection: false, |
| 2770 |
wantStatus: http.StatusForbidden, |
| 2771 |
}, |
| 2772 |
|
| 2773 |
|
| 2774 |
|
| 2775 |
|
| 2776 |
|
| 2777 |
{ |
| 2778 |
name: "0.0.0.0 via localhost rejects evil.com", |
| 2779 |
listenAddr: "0.0.0.0:0", |
| 2780 |
hostHeader: "evil.com", |
| 2781 |
disableProtection: false, |
| 2782 |
wantStatus: http.StatusForbidden, |
| 2783 |
}, |
| 2784 |
|
| 2785 |
|
| 2786 |
{ |
| 2787 |
name: "disabled accepts evil.com", |
| 2788 |
listenAddr: "127.0.0.1:0", |
| 2789 |
hostHeader: "evil.com", |
| 2790 |
disableProtection: true, |
| 2791 |
wantStatus: http.StatusOK, |
| 2792 |
}, |
| 2793 |
} |
| 2794 |
|
| 2795 |
for _, tt := range tests { |
| 2796 |
t.Run(tt.name, func(t *testing.T) { |
| 2797 |
opts := &StreamableHTTPOptions{ |
| 2798 |
Stateless: true, |
| 2799 |
DisableLocalhostProtection: tt.disableProtection, |
| 2800 |
} |
| 2801 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, opts) |
| 2802 |
|
| 2803 |
listener, err := net.Listen("tcp", tt.listenAddr) |
| 2804 |
if err != nil { |
| 2805 |
t.Fatalf("Failed to listen on %s: %v", tt.listenAddr, err) |
| 2806 |
} |
| 2807 |
defer listener.Close() |
| 2808 |
|
| 2809 |
srv := &http.Server{Handler: handler} |
| 2810 |
go srv.Serve(listener) |
| 2811 |
defer srv.Close() |
| 2812 |
|
| 2813 |
reqReader := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}`) |
| 2814 |
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s", listener.Addr().String()), reqReader) |
| 2815 |
if err != nil { |
| 2816 |
t.Fatal(err) |
| 2817 |
} |
| 2818 |
req.Host = tt.hostHeader |
| 2819 |
req.Header.Set("Content-Type", "application/json") |
| 2820 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 2821 |
|
| 2822 |
resp, err := http.DefaultClient.Do(req) |
| 2823 |
if err != nil { |
| 2824 |
t.Fatal(err) |
| 2825 |
} |
| 2826 |
defer resp.Body.Close() |
| 2827 |
|
| 2828 |
if got := resp.StatusCode; got != tt.wantStatus { |
| 2829 |
t.Errorf("Status code: got %d, want %d", got, tt.wantStatus) |
| 2830 |
} |
| 2831 |
}) |
| 2832 |
} |
| 2833 |
} |
| 2834 |
|
| 2835 |
func TestStreamableOriginProtection(t *testing.T) { |
| 2836 |
server := NewServer(testImpl, nil) |
| 2837 |
|
| 2838 |
tests := []struct { |
| 2839 |
name string |
| 2840 |
protection *http.CrossOriginProtection |
| 2841 |
requestOrigin string |
| 2842 |
wantStatusCode int |
| 2843 |
}{ |
| 2844 |
{ |
| 2845 |
name: "no protection with Origin header", |
| 2846 |
protection: nil, |
| 2847 |
requestOrigin: "https://example.com", |
| 2848 |
wantStatusCode: http.StatusOK, |
| 2849 |
}, |
| 2850 |
{ |
| 2851 |
name: "custom protection with trusted origin and same Origin", |
| 2852 |
protection: func() *http.CrossOriginProtection { |
| 2853 |
p := http.NewCrossOriginProtection() |
| 2854 |
if err := p.AddTrustedOrigin("https://example.com"); err != nil { |
| 2855 |
t.Fatal(err) |
| 2856 |
} |
| 2857 |
return p |
| 2858 |
}(), |
| 2859 |
requestOrigin: "https://example.com", |
| 2860 |
wantStatusCode: http.StatusOK, |
| 2861 |
}, |
| 2862 |
{ |
| 2863 |
name: "custom protection with trusted origin and different Origin", |
| 2864 |
protection: func() *http.CrossOriginProtection { |
| 2865 |
p := http.NewCrossOriginProtection() |
| 2866 |
if err := p.AddTrustedOrigin("https://example.com"); err != nil { |
| 2867 |
t.Fatal(err) |
| 2868 |
} |
| 2869 |
return p |
| 2870 |
}(), |
| 2871 |
requestOrigin: "https://malicious.com", |
| 2872 |
wantStatusCode: http.StatusForbidden, |
| 2873 |
}, |
| 2874 |
} |
| 2875 |
|
| 2876 |
for _, tt := range tests { |
| 2877 |
t.Run(tt.name, func(t *testing.T) { |
| 2878 |
opts := &StreamableHTTPOptions{ |
| 2879 |
Stateless: true, |
| 2880 |
CrossOriginProtection: tt.protection, |
| 2881 |
} |
| 2882 |
handler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, opts) |
| 2883 |
httpServer := httptest.NewServer(handler) |
| 2884 |
defer httpServer.Close() |
| 2885 |
|
| 2886 |
reqReader := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}`) |
| 2887 |
req, err := http.NewRequest(http.MethodPost, httpServer.URL, reqReader) |
| 2888 |
if err != nil { |
| 2889 |
t.Fatal(err) |
| 2890 |
} |
| 2891 |
req.Header.Set("Content-Type", "application/json") |
| 2892 |
req.Header.Set("Origin", tt.requestOrigin) |
| 2893 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 2894 |
|
| 2895 |
resp, err := http.DefaultClient.Do(req) |
| 2896 |
if err != nil { |
| 2897 |
t.Fatal(err) |
| 2898 |
} |
| 2899 |
defer resp.Body.Close() |
| 2900 |
|
| 2901 |
if got := resp.StatusCode; got != tt.wantStatusCode { |
| 2902 |
t.Errorf("Status code: got %d, want %d", got, tt.wantStatusCode) |
| 2903 |
} |
| 2904 |
}) |
| 2905 |
} |
| 2906 |
} |