diff --git a/CHANGELOG.md b/CHANGELOG.md index 5172745..59528f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -157,6 +157,10 @@ support, dependency and breaking-change policy. ### Fixed +- A Streamable HTTP request that timed out while its response headers were arriving left the response + undisposed, so its connection stayed open and the server never noticed that the client had given up; the + handler ran to completion. The client now disposes such a late response. The race was mostly hit on + Windows, where the HTTP cancellation test failed intermittently (#7). - A request id can be reused as soon as its response was sent; before, a request that arrived while the previous request with the same id was still winding down in its worker was rejected with `-32600`. - `Connect-McpServer -Server` fails at once for a server object that is already running, instead of waiting diff --git a/docs/concepts/transports.md b/docs/concepts/transports.md index d465d9c..f972496 100644 --- a/docs/concepts/transports.md +++ b/docs/concepts/transports.md @@ -66,7 +66,9 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan `X-Accel-Buffering: no`); the response is the last event and closes the stream. A request that outlives `-KeepAliveSeconds` (default 5) also switches to SSE and receives keep-alive comments: a failed keep-alive write means the client closed the connection, which cancels the handler (token and pipeline stop). The - same happens when the final write fails. + same happens when the final write fails. On Windows, http.sys still accepts one write after the client + closed the connection and fails the next, so a closed connection is noticed one keep-alive interval later + than with the managed listener on Linux and macOS. - Shutdown (`Stop-McpServer`): the listener stops accepting, running handlers get the grace period, open channels receive an error response (`-32603`, "shutting down") and are closed. @@ -82,6 +84,8 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan by event (`data:` lines joined, comments ignored, `id`/`retry` kept for the resumption of legacy sessions) with notifications dispatched to the progress and log callbacks until the response with the request id arrives. A deadline cancels the request and disposes the response, which closes the stream: the cancellation signal of this transport. + This includes a response whose headers arrive while the send is being cancelled (the send then completes + anyway): an undisposed response would keep the connection open, so the server's writes would never fail. - `Get-McpTool` validates the `x-mcp-header` annotations of every tool (`Get-McpToolHeaderParameter`) and excludes invalid tools with a warning; `Invoke-McpTool` derives the `Mcp-Param-*` headers from the cached annotations and, after a `-32020` from the server, refreshes the list and retries once. diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index b75d40a..2549936 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -93,6 +93,37 @@ function Wait-McpTask { $true } +function Stop-McpHttpSendTask { + <# + .SYNOPSIS + Cancels a send that missed its deadline and disposes its response should the send complete anyway. + .DESCRIPTION + Cancelling cannot undo a send whose response headers arrived just before the cancellation: the task then + completes with a response, and its connection stays open until that response is disposed. The server + detects a client that gave up only through a failing write, which an open connection never produces. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task, + + [Parameter(Mandatory)] + [System.Threading.CancellationTokenSource] $Cts, + + # How long a cancelled send may take to settle; it ends at once unless the connection is stuck. + [int] $SettleMs = 1000 + ) + + try { $Cts.Cancel() } catch { Write-Debug 'Cancelling the send failed.' } + if (-not $Task.IsCompleted) { + try { $null = $Task.Wait($SettleMs) } catch [System.AggregateException] { Write-Debug 'The cancelled send ended with an error.' } + } + if ($Task.Status -eq [System.Threading.Tasks.TaskStatus]::RanToCompletion -and $null -ne $Task.Result) { + try { $Task.Result.Dispose() } catch { Write-Debug 'Disposing the late response failed.' } + } +} + function Get-McpTaskFailure { [CmdletBinding()] [OutputType([System.Exception], [System.OperationCanceledException])] @@ -449,7 +480,7 @@ function Open-McpHttpResumedStream { Write-Debug "-> GET $($Session.Transport.Url) Last-Event-ID $LastEventId (resuming '$Method' id=$Id)" $task = $Session.Transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $Cts.Token) if (-not (Wait-McpTask -Task $task -Deadline $Deadline)) { - $Cts.Cancel() + Stop-McpHttpSendTask -Task $task -Cts $Cts throw [System.TimeoutException]::new("Resuming the response stream of '$Method' (id $Id) timed out.") } $failure = Get-McpTaskFailure -Task $task @@ -569,7 +600,7 @@ function Invoke-McpHttpClientRequest { $tick = if ($Session.Era -eq 'Legacy') { { Invoke-McpLegacyInbox -Session $Session } } else { $null } $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token) if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline -OnTick $tick)) { - $cts.Cancel() + Stop-McpHttpSendTask -Task $sendTask -Cts $cts throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask @@ -666,7 +697,7 @@ function Send-McpHttpClientMessage { try { $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseContentRead, $cts.Token) if (-not (Wait-McpTask -Task $sendTask -Deadline ([datetime]::UtcNow.AddMilliseconds($TimeoutMs)))) { - $cts.Cancel() + Stop-McpHttpSendTask -Task $sendTask -Cts $cts throw [System.TimeoutException]::new("Posting the notification '$Method' timed out after $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask diff --git a/tests/Unit/HttpClient.Tests.ps1 b/tests/Unit/HttpClient.Tests.ps1 new file mode 100644 index 0000000..1a6528f --- /dev/null +++ b/tests/Unit/HttpClient.Tests.ps1 @@ -0,0 +1,45 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseCorrectCasing', '', Justification = 'PSScriptAnalyzer attributes -ScriptBlock of commands nested in BeforeAll to BeforeAll itself.')] +param() + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force +} + +Describe 'Stop-McpHttpSendTask' { + It 'disposes the response of a send that completed although it was cancelled' { + # The response headers arrived between the deadline and the cancellation: the task completed anyway. + $body = [System.IO.MemoryStream]::new([byte[]] @(1, 2, 3)) + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::OK) + $response.Content = [System.Net.Http.StreamContent]::new($body) + $task = [System.Threading.Tasks.Task]::FromResult($response) + $cts = [System.Threading.CancellationTokenSource]::new() + Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c } -Parameters @{ t = $task; c = $cts } + $cts.IsCancellationRequested | Should -BeTrue + $body.CanRead | Should -BeFalse + } + + It 'cancels a pending send and returns once it settled' { + $source = [System.Threading.Tasks.TaskCompletionSource[System.Net.Http.HttpResponseMessage]]::new() + $cts = [System.Threading.CancellationTokenSource]::new() + $null = $cts.Token.Register([System.Action] { $null = $source.TrySetCanceled() }.GetNewClosure()) + { Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c } -Parameters @{ t = $source.Task; c = $cts } } | Should -Not -Throw + $source.Task.IsCanceled | Should -BeTrue + } + + It 'tolerates a failed send and a disposed token source' { + $failed = [System.Threading.Tasks.Task]::FromException([System.Net.Http.HttpRequestException]::new('refused')) + $cts = [System.Threading.CancellationTokenSource]::new() + $cts.Dispose() + { Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c } -Parameters @{ t = $failed; c = $cts } } | Should -Not -Throw + } + + It 'returns after the settle time when a send never ends' { + $source = [System.Threading.Tasks.TaskCompletionSource[System.Net.Http.HttpResponseMessage]]::new() + $cts = [System.Threading.CancellationTokenSource]::new() + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c -SettleMs 100 } -Parameters @{ t = $source.Task; c = $cts } + $stopwatch.ElapsedMilliseconds | Should -BeLessThan 2000 + $source.Task.IsCompleted | Should -BeFalse + } +}