MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / TestServerTransportCleanup

Function TestServerTransportCleanup

mcp/streamable_test.go:630–706  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

628}
629
630func TestServerTransportCleanup(t *testing.T) {
631 nClient := 3
632
633 var mu sync.Mutex
634 var id int = -1 // session id starting from "0", "1", "2"...
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 // Spin up clients connect to the same server but refuse to ping request.
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

Callers

nothing calls this directly

Calls 9

ConnectMethod · 0.95
NewServerFunction · 0.85
NewStreamableHTTPHandlerFunction · 0.85
mustNotPanicFunction · 0.85
NewClientFunction · 0.85
LogMethod · 0.80
CloseMethod · 0.65
DoneMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…