Skip to content

Commit fbf0638

Browse files
Copilotstephentoub
andcommitted
Cancel SendToRelatedTransportAsync when response arrives via concurrent channel
Use a linked CancellationTokenSource so the foreground transport send (e.g., retry GET loop) is cancelled when the response TCS completes first via a concurrent background stream. Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
1 parent 3686f6f commit fbf0638

1 file changed

Lines changed: 4 additions & 2 deletions

File tree

src/ModelContextProtocol.Core/McpSessionHandler.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -540,11 +540,13 @@ public async Task<JsonRpcResponse> SendRequestAsync(JsonRpcRequest request, Canc
540540
// concurrent channel (e.g. the background GET SSE stream in Streamable HTTP). Without
541541
// this, the foreground transport send could block indefinitely waiting for a response
542542
// that was already delivered via a different stream.
543-
Task sendTask = SendToRelatedTransportAsync(request, cancellationToken);
543+
using var sendCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
544+
Task sendTask = SendToRelatedTransportAsync(request, sendCts.Token);
544545
if (sendTask != await Task.WhenAny(sendTask, tcs.Task).ConfigureAwait(false))
545546
{
546547
// The response arrived via a concurrent channel before the transport send completed.
547-
// Observe any exception from the still-running send to prevent unobserved task exceptions.
548+
// Cancel the still-running send and observe any exception to prevent unobserved task exceptions.
549+
sendCts.Cancel();
548550
_ = sendTask.ContinueWith(
549551
static (t, _) => _ = t.Exception,
550552
null,

0 commit comments

Comments
 (0)