Skip to content

Commit 2f7a923

Browse files
committed
Acquire lock before writing to parent transport
1 parent 7262e5d commit 2f7a923

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,23 +51,21 @@ public async ValueTask<bool> HandlePostAsync(JsonRpcMessage message, Cancellatio
5151
message.Context.ExecutionContext = ExecutionContext.Capture();
5252
}
5353

54-
// When applicable, we start the write task as soon as possible so that:
55-
// 1. We don't risk processing the final response message and closing the _sseWriter channel before starting to write to the response stream.
56-
// 2. We don't risk deadlocking by filling up the _sseWriter channel with messages before they start being consumed.
57-
var shouldWriteToResponseStream = _pendingRequest.Id is not null;
58-
var writeTask = shouldWriteToResponseStream
59-
? _sseWriter.WriteAllAsync(responseStream, cancellationToken)
60-
: Task.CompletedTask;
61-
62-
await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);
63-
64-
if (!shouldWriteToResponseStream)
54+
if (_pendingRequest.Id is null)
6555
{
56+
await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);
6657
return false;
6758
}
6859

60+
// We start the write task as soon as possible so that:
61+
// 1. We don't risk processing the final response message and closing the _sseWriter channel before starting to write to the response stream.
62+
// 2. We don't risk deadlocking by filling up the _sseWriter channel with messages before they start being consumed.
63+
var writeTask = _sseWriter.WriteAllAsync(responseStream, cancellationToken);
64+
6965
using (await _sendLock.LockAsync(cancellationToken).ConfigureAwait(false))
7066
{
67+
await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);
68+
7169
var eventStreamWriter = await GetOrCreateEventStreamAsync(cancellationToken).ConfigureAwait(false);
7270
if (eventStreamWriter is not null)
7371
{

0 commit comments

Comments
 (0)