Skip to content

Commit 7e13da4

Browse files
committed
mcp: fix context propagation in StreamableClientTransport
Context propagation was broken in StreamableClientTransport because: 1. Connect() used context.Background() instead of the parent context 2. Close() created a race condition where DELETE requests were cancelled This change fixes both issues by: - Using the parent context when creating the connection context - Reordering Close() to perform cleanup DELETE before cancelling context This ensures request-scoped values (auth tokens, trace IDs) propagate correctly to background HTTP operations. Fixes #513
1 parent ef2fc60 commit 7e13da4

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

mcp/streamable.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1018,7 +1018,7 @@ func (t *StreamableClientTransport) Connect(ctx context.Context) (Connection, er
10181018
// Create a new cancellable context that will manage the connection's lifecycle.
10191019
// This is crucial for cleanly shutting down the background SSE listener by
10201020
// cancelling its blocking network operations, which prevents hangs on exit.
1021-
connCtx, cancel := context.WithCancel(context.Background())
1021+
connCtx, cancel := context.WithCancel(ctx)
10221022
conn := &streamableClientConn{
10231023
url: t.Endpoint,
10241024
client: client,
@@ -1394,14 +1394,10 @@ func (c *streamableClientConn) reconnect(lastEventID string) (*http.Response, er
13941394
// Close implements the [Connection] interface.
13951395
func (c *streamableClientConn) Close() error {
13961396
c.closeOnce.Do(func() {
1397-
// Cancel any hanging network requests.
1398-
c.cancel()
1399-
close(c.done)
1400-
14011397
if errors.Is(c.failure(), errSessionMissing) {
14021398
// If the session is missing, no need to delete it.
14031399
} else {
1404-
req, err := http.NewRequest(http.MethodDelete, c.url, nil)
1400+
req, err := http.NewRequestWithContext(c.ctx, http.MethodDelete, c.url, nil)
14051401
if err != nil {
14061402
c.closeErr = err
14071403
} else {
@@ -1411,6 +1407,10 @@ func (c *streamableClientConn) Close() error {
14111407
}
14121408
}
14131409
}
1410+
1411+
// Cancel any hanging network requests after cleanup.
1412+
c.cancel()
1413+
close(c.done)
14141414
})
14151415
return c.closeErr
14161416
}

0 commit comments

Comments
 (0)