From ff961f8ee50ec525a6b8ae63cb5a0371bd0221f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:29:15 +0000 Subject: [PATCH 1/4] M5 server core: legacy sessions next to the stateless core A dual-era server serves the initialize handshake of 2025-11-25 and 2025-06-18 (2025-03-26 accepted as a version string) next to the 2026-07-28 core on the same process. New-McpServer defaults to all three revisions; the era of every request is chosen in one place (Get-McpMessageEra) and legacy results and errors are converted in one place (Era.ps1): no resultType, ttlMs, cacheScope or io.modelcontextprotocol/ _meta keys, -32002 for unknown resources. LegacySession.ps1 implements the session (version and capability negotiation, ping, logging/setLevel, resources/subscribe and unsubscribe), unsolicited list-changed and resource-updated notifications, and server-initiated elicitation, sampling and roots requests: the MRTR cmdlets stay era-agnostic, in a legacy session the worker sends the request and blocks until the dispatcher correlates the client's response, the request is cancelled or it times out. Requests of a session are keyed with the session's prefix. A modern-only server answers initialize with -32022 and its versions; a legacy-only server answers requests before initialize with -32600. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rvihdz4S9tqxJNrZGrX3qD --- src/Classes/010-McpProtocolException.ps1 | 8 + src/Private/Dispatcher.ps1 | 197 +++++++-- src/Private/Era.ps1 | 148 +++++++ src/Private/HttpServer.ps1 | 3 +- src/Private/InputRequest.ps1 | 7 + src/Private/JsonRpc.ps1 | 17 +- src/Private/LegacySession.ps1 | 488 +++++++++++++++++++++ src/Private/Resources.ps1 | 4 +- src/Private/Server.ps1 | 5 +- src/Private/Worker.ps1 | 10 +- src/Public/New-McpServer.ps1 | 16 +- tests/Integration/HttpServer.Tests.ps1 | 6 +- tests/Integration/InMemoryClient.Tests.ps1 | 7 +- tests/Integration/LegacyServer.Tests.ps1 | 273 ++++++++++++ tests/Support/McpTestSupport.psm1 | 4 +- tests/Unit/Era.Tests.ps1 | 114 +++++ tests/Unit/Server.Tests.ps1 | 12 +- 17 files changed, 1265 insertions(+), 54 deletions(-) create mode 100644 src/Private/Era.ps1 create mode 100644 src/Private/LegacySession.ps1 create mode 100644 tests/Integration/LegacyServer.Tests.ps1 create mode 100644 tests/Unit/Era.Tests.ps1 diff --git a/src/Classes/010-McpProtocolException.ps1 b/src/Classes/010-McpProtocolException.ps1 index 5706c02..342a91c 100644 --- a/src/Classes/010-McpProtocolException.ps1 +++ b/src/Classes/010-McpProtocolException.ps1 @@ -27,3 +27,11 @@ class McpInputRequiredException : McpProtocolException { $this.InputRequests = $inputRequests } } + +# A URI that names no resource. Revision 2026-07-28 answers it with -32602 and data.uri (SEP-2164); the legacy +# revisions use -32002. The subclass marks the error so that the era-aware serialization can pick the code. +[NoRunspaceAffinity()] +class McpResourceNotFoundException : McpProtocolException { + McpResourceNotFoundException([string] $uri) : base(-32602, 'Resource not found', [ordered]@{ uri = $uri }) { + } +} diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1 index 20fa8f4..94bbb07 100644 --- a/src/Private/Dispatcher.ps1 +++ b/src/Private/Dispatcher.ps1 @@ -6,6 +6,10 @@ # Over stdio and in memory all messages share one line writer. Over Streamable HTTP every request owns a # channel (its HTTP response, sent as one JSON object or as a request-scoped SSE stream); accepting # connections, header validation and SSE writing live in HttpServer.ps1. +# +# A dual-era server also serves legacy sessions (initialize handshake, LegacySession.ps1): every request is +# routed by its era (Get-McpMessageEra), legacy responses are converted in Send-McpDispatcherMessage and in the +# worker, and the requests of a legacy session are keyed with the session's prefix. function Get-McpRequestKey { [CmdletBinding()] @@ -88,6 +92,9 @@ function Invoke-McpDispatcher { Pool = $null EofReceived = $false Stopping = $false + # Legacy sessions: the process-wide one of a line transport, and those of Streamable HTTP by Mcp-Session-Id. + LineSession = $null + Sessions = @{} ServerInfo = Get-McpServerInfoObject -Server $Server LogLevel = $Server.Options.LogLevel } @@ -112,6 +119,7 @@ function Invoke-McpDispatcher { } } finally { Close-McpAllListener -State $state + foreach ($session in @(Get-McpLegacySession -State $state)) { Close-McpLegacySession -State $state -Session $session -Reason 'ended: the server stopped' } Stop-McpAllInFlightRequest -State $state Send-McpOutboundQueue -State $state if ($null -ne $state.Pool) { @@ -182,9 +190,14 @@ function Send-McpDispatcherMessage { [System.Collections.IDictionary] $Message, [AllowNull()] - [hashtable] $Channel + [hashtable] $Channel, + + # The era of the request being answered: legacy results and errors are converted (Era.ps1). + [ValidateSet('Modern', 'Legacy')] + [string] $Era = 'Modern' ) + $Message = ConvertTo-McpEraMessage -Message $Message -Era $Era if ($null -ne $Channel -and $Channel.Kind -eq 'Http') { $errorCode = $null if ($Message.Contains('error') -and $Message['error'] -is [System.Collections.IDictionary] -and $Message['error'].Contains('code')) { $errorCode = $Message['error']['code'] } @@ -216,13 +229,20 @@ function Send-McpOutboundQueue { $params = if ($item.ParamsJson) { ConvertFrom-McpJson -Json $item.ParamsJson } else { $null } Send-McpListenerNotification -State $State -Method $item.Method -Params $params if ($State.Stopping) { return } + Send-McpLegacyNotification -State $State -Method $item.Method -Params $params + if ($State.Stopping) { return } continue } $entry = $null if ($null -ne $item.RequestId) { - $key = Get-McpRequestKey -Id $item.RequestId + $key = [string] $item.KeyPrefix + (Get-McpRequestKey -Id $item.RequestId) if ($State.InFlight.ContainsKey($key)) { $entry = $State.InFlight[$key] } } + if ($item.Kind -eq 'ServerRequest') { + Send-McpServerRequest -State $State -Item $item -Entry $entry + if ($State.Stopping) { return } + continue + } if ($null -ne $entry -and ($entry.Cancelled -or $entry.Responded)) { continue } if ($item.Kind -eq 'Response' -and $null -ne $entry) { $entry.Responded = $true } Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("-> {0} id={1} ({2} bytes)" -f $item.Kind, $item.RequestId, $item.Json.Length) @@ -277,8 +297,12 @@ function Invoke-McpInboundLine { switch ($kind) { 'Request' { Invoke-McpInboundRequest -State $State -Message $message } 'Notification' { Invoke-McpInboundNotification -State $State -Message $message } - 'Response' { Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message 'Ignoring a JSON-RPC response: clients do not send responses in revision 2026-07-28.' } - 'ErrorResponse' { Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message 'Ignoring a JSON-RPC error response.' } + { $_ -in @('Response', 'ErrorResponse') } { + # Answers to server-initiated requests of the legacy session; modern clients send no responses. + if ($null -eq $State.LineSession -or -not (Complete-McpLegacyServerRequest -Session $State.LineSession -Message $message)) { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message 'Ignoring a JSON-RPC response that answers no open server request.' + } + } default { $id = $null if ($message -is [System.Collections.IDictionary] -and $message.Contains('id') -and (Test-McpRequestId -Id $message['id'])) { $id = $message['id'] } @@ -294,10 +318,19 @@ function Invoke-McpInboundNotification { [hashtable] $State, [Parameter(Mandatory)] - [System.Collections.IDictionary] $Message + [System.Collections.IDictionary] $Message, + + # The legacy session of a Streamable HTTP request (Mcp-Session-Id); line transports use the process-wide one. + [AllowNull()] + [hashtable] $Session ) $method = [string] $Message['method'] + if ($null -eq $Session -and $State.Transport.Kind -ne 'Http') { $Session = $State.LineSession } + if ($method -eq 'notifications/initialized' -and $null -ne $Session) { + $Session.Initialized = $true + return + } if ($method -ne 'notifications/cancelled') { Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Ignoring notification '$method'." return @@ -305,6 +338,7 @@ function Invoke-McpInboundNotification { $params = if ($Message.Contains('params')) { $Message['params'] } else { $null } if ($params -isnot [System.Collections.IDictionary] -or -not $params.Contains('requestId') -or -not (Test-McpRequestId -Id $params['requestId'])) { return } $key = Get-McpRequestKey -Id $params['requestId'] + if ($null -ne $Session -and $State.InFlight.ContainsKey($Session.KeyPrefix + $key)) { $key = $Session.KeyPrefix + $key } if ($State.Listeners.ContainsKey($key)) { Remove-McpListener -State $State -Key $key -Reason 'cancelled by the client' return @@ -397,7 +431,7 @@ function Update-McpInFlightRequest { Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)) timed out after $timeout s." Stop-McpInFlightRequest -Entry $entry $entry.Responded = $true - Send-McpDispatcherMessage -State $State -Channel $entry.Channel -Message (New-McpErrorResponse -Id $entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message "The request timed out after $timeout seconds.")) + Send-McpDispatcherMessage -State $State -Channel $entry.Channel -Era $entry.Era -Message (New-McpErrorResponse -Id $entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message "The request timed out after $timeout seconds.")) } continue } @@ -408,7 +442,7 @@ function Update-McpInFlightRequest { $text = if ($reason) { $reason.Message } else { 'The worker failed.' } Write-McpStderr -Level Error -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)) failed in the worker: $text" $entry.Responded = $true - Send-McpDispatcherMessage -State $State -Channel $entry.Channel -Message (New-McpErrorResponse -Id $entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $text)) + Send-McpDispatcherMessage -State $State -Channel $entry.Channel -Era $entry.Era -Message (New-McpErrorResponse -Id $entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $text)) } Close-McpRequestChannel -State $State -Entry $entry try { $entry.PowerShell.Dispose() } catch { Write-Debug 'Disposing a worker failed.' } @@ -417,6 +451,42 @@ function Update-McpInFlightRequest { } } +function Send-McpServerRequest { + <# + .SYNOPSIS + Delivers a server-initiated request of a legacy session: on the line transport, on the SSE stream of the request that asked, or on the session's GET stream. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Item, + + [AllowNull()] + [hashtable] $Entry + ) + + if ($null -ne $Entry -and ($Entry.Cancelled -or $Entry.Responded)) { return } + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("-> ServerRequest {0} for request {1}" -f $Item.ServerRequestId, $Item.RequestId) + if ($State.Transport.Kind -ne 'Http') { + try { + Send-McpTransportLine -Transport $State.Transport -Line $Item.Json + } catch [System.IO.IOException] { + Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing to the transport failed: $($_.Exception.Message)" + $State.Stopping = $true + } + return + } + $session = if ($null -ne $Entry) { $Entry.Session } else { $null } + if ($null -ne $Entry -and $null -ne $Entry.Channel -and -not $Entry.Channel.Closed -and (Send-McpHttpNotification -State $State -Channel $Entry.Channel -Json $Item.Json)) { return } + if ($null -ne $session -and $null -ne $session.GetChannel -and (Write-McpSseChunk -State $State -Channel $session.GetChannel -Text "event: message`ndata: $($Item.Json)`n`n")) { return } + if ($null -ne $session) { + Stop-McpLegacyServerRequest -Session $session -Id $Item.ServerRequestId -Reason 'The request could not be delivered to the client: no open stream.' + } +} + function Invoke-McpInboundRequest { [CmdletBinding()] param( @@ -427,14 +497,27 @@ function Invoke-McpInboundRequest { [System.Collections.IDictionary] $Message, [AllowNull()] - [hashtable] $Channel + [hashtable] $Channel, + + # The legacy session of a Streamable HTTP request, resolved from its Mcp-Session-Id header. + [AllowNull()] + [hashtable] $Session ) $server = $State.Server $id = $Message['id'] $method = [string] $Message['method'] $params = if ($Message.Contains('params')) { $Message['params'] } else { $null } + $isHttp = $null -ne $Channel -and $Channel.Kind -eq 'Http' + $era = Get-McpMessageEra -State $State -Method $method -Params $params -Session $Session -Http:$isHttp + # A modern-only server answers initialize with -32022 in the modern shape (the versions it supports). + if ($method -ceq 'initialize' -and @(Get-McpServerVersion -Server $server -Era Legacy).Count -eq 0) { $era = 'Modern' } + if ($era -eq 'Legacy' -and $null -eq $Session -and -not $isHttp) { $Session = $State.LineSession } + if ($isHttp) { $Channel.Era = $era } + $reply = @{ State = $State; Channel = $Channel; Era = $era } $key = Get-McpRequestKey -Id $id + if ($null -ne $Session) { $key = $Session.KeyPrefix + $key } + if ($isHttp) { $Channel.RequestKey = $key } if ($State.InFlight.ContainsKey($key) -and ($State.InFlight[$key].Responded -or $State.InFlight[$key].Cancelled)) { # Answered or cancelled, only its worker is still winding down: the client may reuse the id. The entry # stays under a private key until Update-McpInFlightRequest disposes the worker. @@ -442,20 +525,57 @@ function Invoke-McpInboundRequest { $State.InFlight.Remove($key) } if ($State.InFlight.ContainsKey($key) -or $State.Listeners.ContainsKey($key)) { - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InvalidRequest -Message "A request with id '$id' is already in flight.")) + Send-McpDispatcherMessage @reply -Message (New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InvalidRequest -Message "A request with id '$id' is already in flight.")) return } try { - if ($method -eq 'initialize') { - throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "This server speaks the stateless lifecycle of protocol version(s) $($server.SupportedVersions -join ', '); the initialize handshake of earlier revisions is not supported.") + if ($method -ceq 'initialize') { + if ($null -ne $Session -or (-not $isHttp -and $null -ne $State.LineSession)) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidRequest, 'The session is already initialized.') + } + $sessionId = if ($isHttp) { [guid]::NewGuid().ToString() } else { $null } + $opened = Invoke-McpLegacyInitialize -Server $server -Params $params -SessionId $sessionId + if ($isHttp) { + $State.Sessions[$sessionId] = $opened + $Channel.Headers = @{ 'Mcp-Session-Id' = $sessionId } + } else { + $State.LineSession = $opened + } + $client = $opened.ClientInfo + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $server.Name -Message ("Legacy session {0}opened: protocol version {1}, client {2} {3}." -f $(if ($sessionId) { "$sessionId " } else { '' }), $opened.ProtocolVersion, $client['name'], $client['version']) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Get-McpLegacyInitializeResult -Server $server -Session $opened)) + return } - $meta = Get-McpRequestMeta -Params $params -SupportedVersions $server.SupportedVersions + if ($era -eq 'Legacy') { + $Session.LastSeen = [datetime]::UtcNow + $legacyResult = Invoke-McpLegacyMethod -Server $server -Session $Session -Method $method -Params $params + if ($null -ne $legacyResult) { + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result $legacyResult) + return + } + if ($method -in @('server/discover', 'subscriptions/listen')) { + throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "Method not found: $method (revision $($Session.ProtocolVersion) of this session does not have it).") + } + $meta = Get-McpLegacyRequestMeta -Session $Session -Params $params + } else { + $modernVersions = @(Get-McpServerVersion -Server $server -Era Modern) + if ($modernVersions.Count -eq 0) { + # A legacy-only server answers like the servers of those revisions before initialize. + throw [McpProtocolException]::new($script:McpErrorCode.InvalidRequest, "The server is not initialized: send initialize first (protocol versions $((Get-McpServerVersion -Server $server -Era Legacy) -join ', ')).") + } + if ($method -in $script:McpLegacyOnlyMethods) { + throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "Method not found: $method (removed in revision 2026-07-28; available in a legacy session after initialize).") + } + $meta = Get-McpRequestMeta -Params $params -SupportedVersions $modernVersions + } + if ($null -eq $params) { $params = [ordered]@{} } + $worker = @{ State = $State; Id = $id; Key = $key; Meta = $meta; Channel = $Channel; Era = $era; Session = $Session } switch ($method) { 'server/discover' { - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpDiscoverResult -Server $server)) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Get-McpDiscoverResult -Server $server)) } 'tools/list' { - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpToolListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Get-McpToolListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) } 'tools/call' { if (-not $params.Contains('name') -or $params['name'] -isnot [string]) { @@ -469,23 +589,23 @@ function Invoke-McpInboundRequest { } } $registration = Get-McpToolRegistration -Server $server -Name $params['name'] - if ($null -ne $Channel -and $Channel.Kind -eq 'Http') { + if ($isHttp -and $era -eq 'Modern') { Test-McpToolParameterHeader -HeaderParameters $registration.HeaderParameters -Arguments $arguments -Headers $Channel.Context.Request.Headers } $payload = New-McpInputPayload -Server $server -Method $method -Name $registration.Name -Params $params $payload['Arguments'] = $arguments - Start-McpWorkerRequest -State $State -Id $id -Kind Tool -Method $method -Name $registration.Name -Registration $registration -Payload $payload -Meta $meta -Channel $Channel + Start-McpWorkerRequest @worker -Kind Tool -Method $method -Name $registration.Name -Registration $registration -Payload $payload } 'subscriptions/listen' { Start-McpListener -State $State -Id $id -Params $params -Channel $Channel } 'resources/list' { Assert-McpServerCapability -Server $server -Capability resources -Method $method - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpResourceListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Get-McpResourceListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) } 'resources/templates/list' { Assert-McpServerCapability -Server $server -Capability resources -Method $method - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpResourceTemplateListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Get-McpResourceTemplateListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) } 'resources/read' { Assert-McpServerCapability -Server $server -Capability resources -Method $method @@ -499,31 +619,31 @@ function Invoke-McpInboundRequest { $cacheHint = Get-McpResourceCacheHint -Server $server -Registration $registration if ($registration.Source -eq 'Content') { $result = Invoke-McpResourceHandler -Registration $registration -Uri $uri -CacheHint $cacheHint - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result $result -Server $server)) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result $result -Server $server)) } else { $payload['Variables'] = $resolved.Variables $payload['CacheHint'] = $cacheHint - Start-McpWorkerRequest -State $State -Id $id -Kind Resource -Method $method -Name $uri -Registration $registration -Payload $payload -Meta $meta -Channel $Channel + Start-McpWorkerRequest @worker -Kind Resource -Method $method -Name $uri -Registration $registration -Payload $payload } } 'prompts/list' { Assert-McpServerCapability -Server $server -Capability prompts -Method $method - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpPromptListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Get-McpPromptListResult -Server $server -Cursor (Get-McpCursorParam -Params $params))) } 'prompts/get' { Assert-McpServerCapability -Server $server -Capability prompts -Method $method $registration = Get-McpPromptRegistration -Server $server -Name $params['name'] $payload = New-McpInputPayload -Server $server -Method $method -Name $registration.Name -Params $params $payload['Arguments'] = Test-McpPromptArgument -Registration $registration -Arguments $(if ($params.Contains('arguments')) { $params['arguments'] } else { $null }) - Start-McpWorkerRequest -State $State -Id $id -Kind Prompt -Method $method -Name $registration.Name -Registration $registration -Payload $payload -Meta $meta -Channel $Channel + Start-McpWorkerRequest @worker -Kind Prompt -Method $method -Name $registration.Name -Registration $registration -Payload $payload } 'completion/complete' { Assert-McpServerCapability -Server $server -Capability completions -Method $method $request = Resolve-McpCompletionRequest -Server $server -Params $params if ($null -eq $request.Source -or $null -eq $request.Source.Handler) { - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result (Invoke-McpCompletionHandler -Request $request) -Server $server)) + Send-McpDispatcherMessage @reply -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result (Invoke-McpCompletionHandler -Request $request) -Server $server)) } else { - Start-McpWorkerRequest -State $State -Id $id -Kind Completion -Method $method -Name $request.Label -Registration $null -Payload @{ Completion = $request } -Meta $meta -Channel $Channel + Start-McpWorkerRequest @worker -Kind Completion -Method $method -Name $request.Label -Registration $null -Payload @{ Completion = $request } } } default { @@ -531,15 +651,15 @@ function Invoke-McpInboundRequest { } } } catch [McpProtocolException] { - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $id -ErrorObject (ConvertTo-McpErrorObject -Exception $_.Exception)) + Send-McpDispatcherMessage @reply -Message (New-McpErrorResponse -Id $id -ErrorObject (ConvertTo-McpErrorObject -Exception $_.Exception -Era $era)) } catch { $exception = $_.Exception if ($exception -is [System.Management.Automation.RuntimeException] -and $exception.InnerException -is [McpProtocolException]) { - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $id -ErrorObject (ConvertTo-McpErrorObject -Exception $exception.InnerException)) + Send-McpDispatcherMessage @reply -Message (New-McpErrorResponse -Id $id -ErrorObject (ConvertTo-McpErrorObject -Exception $exception.InnerException -Era $era)) return } Write-McpStderr -Level Error -Threshold $State.LogLevel -Logger $server.Name -Message "Request $id ($method) failed: $($exception.Message)" - Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $exception.Message)) + Send-McpDispatcherMessage @reply -Message (New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $exception.Message)) } } @@ -646,11 +766,22 @@ function Start-McpWorkerRequest { [hashtable] $Meta, [AllowNull()] - [hashtable] $Channel + [hashtable] $Channel, + + # The in-flight key (the request id, prefixed with the session's prefix in a legacy session). + [Parameter(Mandatory)] + [string] $Key, + + [ValidateSet('Modern', 'Legacy')] + [string] $Era = 'Modern', + + [AllowNull()] + [hashtable] $Session ) $server = $State.Server $cts = [System.Threading.CancellationTokenSource]::new() + $keyPrefix = if ($null -ne $Session) { $Session.KeyPrefix } else { '' } $envelope = @{ RequestId = $Id Kind = $Kind @@ -658,19 +789,21 @@ function Start-McpWorkerRequest { Name = $Name Registration = $Registration Meta = $Meta - Sink = @{ Queue = $State.Outbound; Signal = $State.Signal } + Era = $Era + Legacy = if ($null -ne $Session) { @{ Pending = $Session.Pending; TimeoutSeconds = [int] $server.Options.RequestTimeoutSeconds } } else { $null } + Sink = @{ Queue = $State.Outbound; Signal = $State.Signal; KeyPrefix = $keyPrefix } CancellationToken = $cts.Token ServerName = $server.Name ServerLogLevel = $server.Options.LogLevel ServerInfo = $State.ServerInfo IncludeServerInfo = [bool] $server.Options.IncludeServerInfo } - foreach ($key in $Payload.Keys) { $envelope[$key] = $Payload[$key] } + foreach ($member in $Payload.Keys) { $envelope[$member] = $Payload[$member] } $worker = [powershell]::Create() $worker.RunspacePool = $State.Pool $null = $worker.AddScript($script:McpWorkerScript).AddArgument($envelope) $handle = $worker.BeginInvoke() - $State.InFlight[(Get-McpRequestKey -Id $Id)] = @{ + $State.InFlight[$Key] = @{ Id = $Id Label = "$Method $Name" PowerShell = $worker @@ -680,5 +813,7 @@ function Start-McpWorkerRequest { Cancelled = $false Responded = $false Channel = $Channel + Era = $Era + Session = $Session } } diff --git a/src/Private/Era.ps1 b/src/Private/Era.ps1 new file mode 100644 index 0000000..b71d25d --- /dev/null +++ b/src/Private/Era.ps1 @@ -0,0 +1,148 @@ +# Dual era: the choice between the stateless lifecycle of revision 2026-07-28 (modern) and the initialize +# handshake of the earlier revisions (legacy) for every inbound request, and the era-aware serialization of +# results and errors. Handlers and the result builders produce modern shapes; legacy responses are derived from +# them here, in one place. + +function Get-McpServerVersion { + <# + .SYNOPSIS + The protocol versions a server speaks in one era: the modern versions of SupportedVersions, or its legacy versions. + .DESCRIPTION + A server that lists any legacy revision also accepts 2025-03-26 in initialize (as a version string + without features of its own), so that clients of that revision are answered with a revision they know. + #> + [CmdletBinding()] + [OutputType([string[]])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [Parameter(Mandatory)] + [ValidateSet('Modern', 'Legacy')] + [string] $Era, + + # Legacy: also the versions accepted without being listed (2025-03-26). + [switch] $Accepted + ) + + if ($Era -eq 'Modern') { + return [string[]] @($Server.SupportedVersions | Where-Object { $_ -in $script:McpModernProtocolVersions }) + } + $legacy = [System.Collections.Generic.List[string]]::new() + foreach ($version in $Server.SupportedVersions) { + if ($version -in $script:McpLegacyProtocolVersions -and -not $legacy.Contains($version)) { $legacy.Add($version) } + } + if ($Accepted -and $legacy.Count -gt 0) { + foreach ($version in $script:McpLegacyProtocolVersions) { + if (-not $legacy.Contains($version)) { $legacy.Add($version) } + } + } + [string[]] $legacy.ToArray() +} + +function Get-McpMessageEra { + <# + .SYNOPSIS + The era of an inbound request: Legacy for initialize and for requests of an initialized legacy session, Modern otherwise. + .DESCRIPTION + Over Streamable HTTP the session is resolved from the Mcp-Session-Id header before (HttpServer.ps1) and + passed in. Over the line transports (stdio, in memory) a request whose _meta carries the modern protocol + version is modern; any other request belongs to the process-wide legacy session once one was opened. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [string] $Method, + + [AllowNull()] + [object] $Params, + + [AllowNull()] + [hashtable] $Session, + + [switch] $Http + ) + + if ($Method -ceq 'initialize') { return 'Legacy' } + if ($null -ne $Session) { return 'Legacy' } + if ($Http) { return 'Modern' } + if ($Params -is [System.Collections.IDictionary] -and $Params['_meta'] -is [System.Collections.IDictionary] -and $Params['_meta'].Contains($script:McpMetaKey.ProtocolVersion)) { + return 'Modern' + } + if ($null -ne $State.LineSession) { return 'Legacy' } + 'Modern' +} + +function ConvertTo-McpLegacyResult { + <# + .SYNOPSIS + The legacy shape of a result: without resultType, ttlMs, cacheScope and the io.modelcontextprotocol/ keys of _meta. + #> + [CmdletBinding()] + [OutputType([System.Collections.IDictionary])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Result + ) + + foreach ($name in 'resultType', 'ttlMs', 'cacheScope') { + if ($Result.Contains($name)) { $Result.Remove($name) } + } + if ($Result.Contains('_meta')) { + $meta = $Result['_meta'] + if ($meta -is [System.Collections.IDictionary]) { + foreach ($key in @($meta.Keys)) { + if (([string] $key).StartsWith('io.modelcontextprotocol/', [System.StringComparison]::Ordinal)) { $meta.Remove($key) } + } + if ($meta.Count -eq 0) { $Result.Remove('_meta') } + } + } + $Result +} + +function ConvertTo-McpLegacyErrorObject { + <# + .SYNOPSIS + The legacy form of an error object: the codes of revision 2026-07-28 (-32020, -32021, -32022) do not exist before it and become -32600. + #> + [CmdletBinding()] + [OutputType([System.Collections.IDictionary])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $ErrorObject + ) + + $modernOnly = @($script:McpErrorCode.HeaderMismatch, $script:McpErrorCode.MissingRequiredClientCapability, $script:McpErrorCode.UnsupportedProtocolVersion) + if ($ErrorObject.Contains('code') -and [int] $ErrorObject['code'] -in $modernOnly) { + $ErrorObject['code'] = $script:McpErrorCode.InvalidRequest + } + $ErrorObject +} + +function ConvertTo-McpEraMessage { + <# + .SYNOPSIS + A response in the shape of an era: modern responses pass unchanged, legacy results and errors are converted. + #> + [CmdletBinding()] + [OutputType([System.Collections.IDictionary])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message, + + [ValidateSet('Modern', 'Legacy')] + [string] $Era = 'Modern' + ) + + if ($Era -ne 'Legacy') { return $Message } + if ($Message.Contains('result') -and $Message['result'] -is [System.Collections.IDictionary]) { + $null = ConvertTo-McpLegacyResult -Result $Message['result'] + } elseif ($Message.Contains('error') -and $Message['error'] -is [System.Collections.IDictionary]) { + $null = ConvertTo-McpLegacyErrorObject -ErrorObject $Message['error'] + } + $Message +} diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 index 360a937..b7479a6 100644 --- a/src/Private/HttpServer.ps1 +++ b/src/Private/HttpServer.ps1 @@ -476,7 +476,8 @@ function Stop-McpHttpChannelRequest { [hashtable] $Channel ) - $key = Get-McpRequestKey -Id $Channel.RequestId + if ($null -eq $Channel.RequestId -and $null -eq $Channel.RequestKey) { return } + $key = if ($Channel.RequestKey) { $Channel.RequestKey } else { Get-McpRequestKey -Id $Channel.RequestId } if ($State.Listeners.ContainsKey($key) -and $State.Listeners[$key].Channel -eq $Channel) { Remove-McpListener -State $State -Key $key -Reason 'ended: the client closed the stream' return diff --git a/src/Private/InputRequest.ps1 b/src/Private/InputRequest.ps1 index 50103c0..6f17cda 100644 --- a/src/Private/InputRequest.ps1 +++ b/src/Private/InputRequest.ps1 @@ -178,6 +178,9 @@ function Invoke-McpInputRequest { <# .SYNOPSIS The answer to an input request when the client sent it; otherwise records the request and, unless deferred, throws McpInputRequiredException. + .DESCRIPTION + In a legacy session the request is sent to the client as a server-initiated request and the answer + returned at once, also with -Defer (Wait-McpInput then has nothing left to wait for). #> [CmdletBinding()] [OutputType([System.Collections.IDictionary])] @@ -204,6 +207,10 @@ function Invoke-McpInputRequest { return $response } foreach ($required in $Capability) { Assert-McpInputCapability -Context $Context -Capability $required } + if ($Context.Era -eq 'Legacy') { + # A legacy session has no input rounds: the request goes to the client now and the handler waits. + return Invoke-McpLegacyInputRequest -Context $Context -Key $Key -Request $Request + } $Context.PendingInput[$Key] = $Request if (-not $Defer) { throw [McpInputRequiredException]::new($Context.PendingInput) diff --git a/src/Private/JsonRpc.ps1 b/src/Private/JsonRpc.ps1 index 3c1f8bc..71d3c3b 100644 --- a/src/Private/JsonRpc.ps1 +++ b/src/Private/JsonRpc.ps1 @@ -15,6 +15,11 @@ $script:McpErrorCode = @{ UnsupportedProtocolVersion = -32022 } +# Codes of the legacy revisions (2025-11-25 and earlier) that revision 2026-07-28 retired: never sent to modern clients. +$script:McpLegacyErrorCode = @{ + ResourceNotFound = -32002 +} + function Get-McpErrorCode { [CmdletBinding()] [OutputType([int])] @@ -201,9 +206,19 @@ function ConvertTo-McpErrorObject { [OutputType([System.Collections.Specialized.OrderedDictionary])] param( [Parameter(Mandatory)] - [System.Exception] $Exception + [System.Exception] $Exception, + + # Legacy: an unknown resource is -32002, and the codes of revision 2026-07-28 become -32600. + [ValidateSet('Modern', 'Legacy')] + [string] $Era = 'Modern' ) + if ($Era -eq 'Legacy') { + if ($Exception -is [McpResourceNotFoundException]) { + return New-McpError -Code $script:McpLegacyErrorCode.ResourceNotFound -Message $Exception.Message -Data $Exception.Data + } + return ConvertTo-McpLegacyErrorObject -ErrorObject (ConvertTo-McpErrorObject -Exception $Exception) + } if ($Exception -is [McpProtocolException]) { if ($null -ne $Exception.Data -and $Exception.Data -isnot [System.Collections.IDictionary] -and $Exception.Data -isnot [string] -and $Exception.Data -isnot [System.Collections.IList]) { return New-McpError -Code $Exception.Code -Message $Exception.Message diff --git a/src/Private/LegacySession.ps1 b/src/Private/LegacySession.ps1 new file mode 100644 index 0000000..be6807e --- /dev/null +++ b/src/Private/LegacySession.ps1 @@ -0,0 +1,488 @@ +# Legacy sessions (revisions 2025-11-25, 2025-06-18 and 2025-03-26 as a version string) of a dual-era server: +# the initialize handshake with version and capability negotiation, the methods only these revisions have +# (ping, logging/setLevel, resources/subscribe and resources/unsubscribe), server-initiated requests (a worker +# blocks until the dispatcher correlates the client's response), and the unsolicited list-changed and +# resource-updated notifications. The stateless 2026-07-28 core does not depend on anything here. +# +# A session is a hashtable owned by the dispatcher; the members workers touch (Pending, a concurrent table of +# the open server-initiated requests) are thread-safe. Over stdio and in memory there is one process-wide +# session ($State.LineSession); over Streamable HTTP one per Mcp-Session-Id ($State.Sessions). + +$script:McpLegacyOnlyMethods = @('ping', 'logging/setLevel', 'resources/subscribe', 'resources/unsubscribe') + +function New-McpLegacySession { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + # The Mcp-Session-Id over Streamable HTTP; none over the line transports. + [AllowNull()] + [string] $Id, + + [Parameter(Mandatory)] + [string] $ProtocolVersion, + + [AllowNull()] + [System.Collections.IDictionary] $ClientCapabilities, + + [AllowNull()] + [System.Collections.IDictionary] $ClientInfo + ) + + $now = [datetime]::UtcNow + @{ + Id = $Id + # Prefix of the in-flight keys of the session's requests: request ids are unique per session only. + KeyPrefix = if ($Id) { "legacy:$Id|" } else { 'legacy|' } + ProtocolVersion = $ProtocolVersion + ClientCapabilities = if ($null -ne $ClientCapabilities) { $ClientCapabilities } else { [ordered]@{} } + ClientInfo = $ClientInfo + Initialized = $false + LogLevel = $null + ResourceSubscriptions = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + Pending = [System.Collections.Concurrent.ConcurrentDictionary[string, hashtable]]::new([System.StringComparer]::Ordinal) + GetChannel = $null + Created = $now + LastSeen = $now + Closed = $false + } +} + +function Get-McpLegacySession { + <# + .SYNOPSIS + The open legacy sessions of a dispatcher: the process-wide one of a line transport, or the HTTP sessions. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + if ($null -ne $State.LineSession) { $State.LineSession } + if ($null -ne $State.Sessions) { + foreach ($session in @($State.Sessions.Values)) { $session } + } +} + +function Get-McpLegacyServerCapability { + <# + .SYNOPSIS + The capabilities of an InitializeResult: those of server/discover plus logging (logging/setLevel). + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server + ) + + $capabilities = Get-McpServerCapability -Server $Server + $capabilities['logging'] = [ordered]@{} + $capabilities +} + +function Get-McpLegacyServerInfo { + <# + .SYNOPSIS + serverInfo of an InitializeResult: 2025-06-18 and earlier know name, version and title only. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [Parameter(Mandatory)] + [string] $ProtocolVersion + ) + + $info = Get-McpServerInfoObject -Server $Server + if ($ProtocolVersion -ne '2025-11-25') { + foreach ($name in 'description', 'websiteUrl', 'icons') { + if ($info.Contains($name)) { $info.Remove($name) } + } + } + $info +} + +function Invoke-McpLegacyInitialize { + <# + .SYNOPSIS + Answers initialize: negotiates the version, opens the legacy session and returns it (the caller registers it). + .DESCRIPTION + A requested version the server speaks is echoed; otherwise the server answers with its newest legacy + version and the client decides whether it can speak it. A server without legacy revisions answers + -32022 with the versions it supports, as the specification recommends for modern-only servers. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [AllowNull()] + [object] $Params, + + # The Mcp-Session-Id to assign over Streamable HTTP. + [AllowNull()] + [string] $SessionId + ) + + $requested = if ($Params -is [System.Collections.IDictionary] -and $Params['protocolVersion'] -is [string]) { [string] $Params['protocolVersion'] } else { $null } + $legacy = @(Get-McpServerVersion -Server $Server -Era Legacy -Accepted) + if ($legacy.Count -eq 0) { + $modern = @(Get-McpServerVersion -Server $Server -Era Modern) + $data = [ordered]@{ supported = $modern; requested = if ($null -ne $requested) { $requested } else { '' } } + throw [McpProtocolException]::new($script:McpErrorCode.UnsupportedProtocolVersion, "This server speaks the stateless lifecycle of protocol version(s) $($modern -join ', ') without the initialize handshake; send server/discover and per-request _meta instead.", $data) + } + $invalidParams = $script:McpErrorCode.InvalidParams + if ($null -eq $requested) { + throw [McpProtocolException]::new($invalidParams, "initialize requires a string parameter 'protocolVersion'.") + } + $capabilities = $Params['capabilities'] + if ($capabilities -isnot [System.Collections.IDictionary]) { + throw [McpProtocolException]::new($invalidParams, "initialize requires an object parameter 'capabilities'.") + } + $clientInfo = $Params['clientInfo'] + if ($clientInfo -isnot [System.Collections.IDictionary] -or $clientInfo['name'] -isnot [string] -or $clientInfo['version'] -isnot [string]) { + throw [McpProtocolException]::new($invalidParams, "initialize requires a parameter 'clientInfo' with string members 'name' and 'version'.") + } + $version = if ($requested -in $legacy) { $requested } else { $legacy[0] } + New-McpLegacySession -Id $SessionId -ProtocolVersion $version -ClientCapabilities $capabilities -ClientInfo $clientInfo +} + +function Get-McpLegacyInitializeResult { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [Parameter(Mandatory)] + [hashtable] $Session + ) + + $result = [ordered]@{ + protocolVersion = $Session.ProtocolVersion + capabilities = Get-McpLegacyServerCapability -Server $Server + serverInfo = Get-McpLegacyServerInfo -Server $Server -ProtocolVersion $Session.ProtocolVersion + } + if ($Server.Instructions) { $result['instructions'] = $Server.Instructions } + $result +} + +function Invoke-McpLegacyMethod { + <# + .SYNOPSIS + Answers the methods only the legacy revisions have; returns the result, or $null when the method is not one of them. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [Parameter(Mandatory)] + [hashtable] $Session, + + [Parameter(Mandatory)] + [string] $Method, + + [AllowNull()] + [object] $Params + ) + + $invalidParams = $script:McpErrorCode.InvalidParams + switch ($Method) { + 'ping' { + return [ordered]@{} + } + 'logging/setLevel' { + $level = if ($Params -is [System.Collections.IDictionary]) { $Params['level'] } else { $null } + if ($level -isnot [string] -or $level -cnotin $script:McpLoggingLevelNames) { + throw [McpProtocolException]::new($invalidParams, "logging/setLevel requires 'level', one of: $($script:McpLoggingLevelNames -join ', ').") + } + $Session.LogLevel = $level + return [ordered]@{} + } + { $_ -in @('resources/subscribe', 'resources/unsubscribe') } { + Assert-McpServerCapability -Server $Server -Capability resources -Method $Method + $uri = if ($Params -is [System.Collections.IDictionary]) { $Params['uri'] } else { $null } + if (-not (Test-McpResourceUri -Uri $uri)) { + throw [McpProtocolException]::new($invalidParams, "$Method requires a parameter 'uri' with an absolute URI.") + } + if ($Method -eq 'resources/subscribe') { + $null = $Session.ResourceSubscriptions.Add([string] $uri) + } else { + $null = $Session.ResourceSubscriptions.Remove([string] $uri) + } + return [ordered]@{} + } + } + $null +} + +function Get-McpLegacyRequestMeta { + <# + .SYNOPSIS + The request metadata of a legacy request, in the shape of Get-McpRequestMeta: version, capabilities and client info from the session, the log level of logging/setLevel, the progress token from _meta. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [hashtable] $Session, + + [AllowNull()] + [object] $Params + ) + + $progressToken = $null + if ($Params -is [System.Collections.IDictionary] -and $Params['_meta'] -is [System.Collections.IDictionary]) { + $meta = $Params['_meta'] + $tokenKey = $script:McpMetaKey.ProgressToken + if ($meta.Contains($tokenKey) -and $null -ne $meta[$tokenKey]) { + $progressToken = $meta[$tokenKey] + if (-not (Test-McpRequestId -Id $progressToken)) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "_meta field '$tokenKey' must be a string or an integer.") + } + } + } + @{ + ProtocolVersion = $Session.ProtocolVersion + ClientCapabilities = $Session.ClientCapabilities + ClientInfo = $Session.ClientInfo + LogLevel = $Session.LogLevel + ProgressToken = $progressToken + } +} + +function Complete-McpLegacyServerRequest { + <# + .SYNOPSIS + Hands the client's response to a server-initiated request to the worker waiting for it; $false when no request of the session has that id. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $Session, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message + ) + + if (-not $Message.Contains('id') -or $null -eq $Message['id']) { return $false } + $slot = $null + if (-not $Session.Pending.TryGetValue([string] $Message['id'], [ref] $slot)) { return $false } + $slot.Json = ConvertTo-McpJson -InputObject $Message + $slot.Event.Set() + $true +} + +function Stop-McpLegacyServerRequest { + <# + .SYNOPSIS + Fails an open server-initiated request (it could not be delivered, or the session ended). + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Session, + + [Parameter(Mandatory)] + [string] $Id, + + [Parameter(Mandatory)] + [string] $Reason + ) + + $slot = $null + if (-not $Session.Pending.TryGetValue($Id, [ref] $slot)) { return } + $slot.Json = ConvertTo-McpJson -InputObject (New-McpErrorResponse -Id $Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $Reason)) + $slot.Event.Set() +} + +function Close-McpLegacySession { + <# + .SYNOPSIS + Ends a legacy session: cancels its requests, fails its open server-initiated requests and closes its GET stream. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal session bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Session, + + [string] $Reason = 'closed' + ) + + if ($Session.Closed) { return } + $Session.Closed = $true + foreach ($key in @($State.InFlight.Keys)) { + if (-not ([string] $key).StartsWith($Session.KeyPrefix, [System.StringComparison]::Ordinal)) { continue } + $entry = $State.InFlight[$key] + if (-not $entry.Cancelled -and -not $entry.Responded) { + Stop-McpInFlightRequest -Entry $entry + $entry.Responded = $true + } + } + foreach ($id in @($Session.Pending.Keys)) { Stop-McpLegacyServerRequest -Session $Session -Id $id -Reason "The session ended ($Reason)." } + if ($null -ne $Session.GetChannel) { + Close-McpHttpChannel -State $State -Channel $Session.GetChannel + $Session.GetChannel = $null + } + if ($Session.Id -and $null -ne $State.Sessions) { $State.Sessions.Remove($Session.Id) } + if ($State.LineSession -eq $Session) { $State.LineSession = $null } + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("Legacy session {0}{1}." -f $(if ($Session.Id) { "$($Session.Id) " } else { '' }), $Reason) +} + +function Test-McpLegacyNotificationMatch { + <# + .SYNOPSIS + Whether a session receives an unsolicited notification: list changes always, resource updates for subscribed URIs and their sub-resources. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $Session, + + [Parameter(Mandatory)] + [string] $Method, + + [AllowNull()] + [System.Collections.IDictionary] $Params + ) + + if (-not $Session.Initialized -or $Session.Closed) { return $false } + if ($Method -ceq 'notifications/resources/updated') { + if ($null -eq $Params -or $Session.ResourceSubscriptions.Count -eq 0) { return $false } + $honoured = @{ resourceSubscriptions = [string[]] @($Session.ResourceSubscriptions) } + return Test-McpListenerMatch -Honoured $honoured -Method $Method -Params $Params + } + $Method -in @($script:McpListenFilterFlags.Values) +} + +function Send-McpLegacyNotification { + <# + .SYNOPSIS + Delivers a list-changed or resource-updated notification to the legacy sessions: on the line transport, or on a session's GET stream. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [string] $Method, + + [AllowNull()] + [System.Collections.IDictionary] $Params + ) + + $json = $null + foreach ($session in @(Get-McpLegacySession -State $State)) { + if (-not (Test-McpLegacyNotificationMatch -Session $session -Method $Method -Params $Params)) { continue } + if ($null -eq $json) { + $plain = $null + if ($null -ne $Params) { + $plain = [ordered]@{} + foreach ($key in $Params.Keys) { if ([string] $key -ne '_meta') { $plain[$key] = $Params[$key] } } + } + $json = ConvertTo-McpJson -InputObject (New-McpNotification -Method $Method -Params $plain) + } + if ($session.Id) { + $channel = $session.GetChannel + if ($null -eq $channel -or $channel.Closed) { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Dropping $Method for session $($session.Id): no GET stream open." + continue + } + if (-not (Write-McpSseChunk -State $State -Channel $channel -Text "event: message`ndata: $json`n`n")) { $session.GetChannel = $null } + continue + } + try { + Send-McpTransportLine -Transport $State.Transport -Line $json + } catch [System.IO.IOException] { + Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing to the transport failed: $($_.Exception.Message)" + $State.Stopping = $true + return + } + } +} + +function Invoke-McpLegacyInputRequest { + <# + .SYNOPSIS + Worker side of an input request in a legacy session: sends it as a server-initiated request and waits for the client's answer. + .DESCRIPTION + The request goes to the dispatcher (Kind ServerRequest), which writes it to the line transport or to the + request's SSE stream. The worker waits for the response, the cancellation of its request or the request + timeout; a cancelled wait ends the handler. The answer is validated like an answer to an input request + and cached under its key, so that asking again with the same key does not ask the client twice. + #> + [CmdletBinding()] + [OutputType([System.Collections.IDictionary])] + param( + [Parameter(Mandatory)] + [object] $Context, + + [Parameter(Mandatory)] + [string] $Key, + + [Parameter(Mandatory)] + [System.Collections.Specialized.OrderedDictionary] $Request + ) + + $legacy = $Context.Legacy + $params = [ordered]@{} + foreach ($name in $Request['params'].Keys) { $params[$name] = $Request['params'][$name] } + if ($Request['method'] -eq 'elicitation/create') { + if ($params['mode'] -eq 'url') { + if ($Context.ProtocolVersion -ne '2025-11-25') { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidRequest, "URL mode elicitation needs protocol version 2025-11-25; the session speaks $($Context.ProtocolVersion).") + } + if (-not $params.Contains('elicitationId')) { $params['elicitationId'] = [guid]::NewGuid().ToString() } + } elseif ($Context.ProtocolVersion -ne '2025-11-25' -and $params.Contains('mode')) { + $params.Remove('mode') + } + } + $id = 'srv-' + [guid]::NewGuid().ToString('n') + $slot = @{ Event = [System.Threading.ManualResetEventSlim]::new($false); Json = $null } + $null = $legacy.Pending.TryAdd($id, $slot) + try { + $json = ConvertTo-McpJson -InputObject (New-McpRequest -Id $id -Method $Request['method'] -Params $params) + $Context.Sink.Queue.Enqueue(@{ Kind = 'ServerRequest'; RequestId = $Context.RequestId; KeyPrefix = $Context.Sink.KeyPrefix; ServerRequestId = $id; Json = $json }) + $null = $Context.Sink.Signal.Set() + $timeoutMs = if ($legacy.TimeoutSeconds -gt 0) { [int] $legacy.TimeoutSeconds * 1000 } else { -1 } + $handles = [System.Threading.WaitHandle[]] @($slot.Event.WaitHandle, $Context.CancellationToken.WaitHandle) + $index = [System.Threading.WaitHandle]::WaitAny($handles, $timeoutMs) + if ($index -eq 1 -or $Context.CancellationToken.IsCancellationRequested) { + throw [System.OperationCanceledException]::new('The request was cancelled while it waited for the client.') + } + if ($index -eq [System.Threading.WaitHandle]::WaitTimeout) { + throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "The client did not answer $($Request['method']) within $($legacy.TimeoutSeconds) seconds.") + } + } finally { + $removed = $null + $null = $legacy.Pending.TryRemove($id, [ref] $removed) + $slot.Event.Dispose() + } + $answer = ConvertFrom-McpJson -Json $slot.Json + if ($answer.Contains('error')) { + $errorObject = $answer['error'] + throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "The client answered $($Request['method']) with error $($errorObject['code']): $($errorObject['message'])") + } + $result = $answer['result'] + if ($result -is [System.Collections.IDictionary] -and $result.Contains('_meta')) { $result.Remove('_meta') } + $response = Test-McpInputResponse -Key $Key -Request ([ordered]@{ method = $Request['method']; params = $params }) -Response $result + $Context.InputResponses[$Key] = $response + $Context.ConsumedInput[$Key] = $response + $response +} diff --git a/src/Private/Resources.ps1 b/src/Private/Resources.ps1 index 2f4e16a..d18f939 100644 --- a/src/Private/Resources.ps1 +++ b/src/Private/Resources.ps1 @@ -175,7 +175,7 @@ function Get-McpResourceTemplateListResult { function New-McpResourceNotFoundException { <# .SYNOPSIS - The error for a URI that names no resource: -32602 with the URI in data (SEP-2164). + The error for a URI that names no resource: -32602 with the URI in data (SEP-2164); -32002 in the legacy revisions. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an exception object.')] [CmdletBinding()] @@ -186,7 +186,7 @@ function New-McpResourceNotFoundException { [string] $Uri ) - [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Resource not found', [ordered]@{ uri = $Uri }) + [McpResourceNotFoundException]::new($Uri) } function Resolve-McpResourceRequest { diff --git a/src/Private/Server.ps1 b/src/Private/Server.ps1 index e8d1396..d28ac01 100644 --- a/src/Private/Server.ps1 +++ b/src/Private/Server.ps1 @@ -3,6 +3,9 @@ $script:McpLatestProtocolVersion = '2026-07-28' $script:McpModernProtocolVersions = @('2026-07-28') +# The revisions with the initialize handshake, newest first. 2025-03-26 is accepted as a version string without +# features of its own (dual era, see Era.ps1). +$script:McpLegacyProtocolVersions = @('2025-11-25', '2025-06-18', '2025-03-26') $script:McpDefaultServer = $null function Test-McpServerObject { @@ -112,7 +115,7 @@ function Get-McpDiscoverResult { $result = [ordered]@{ resultType = 'complete' - supportedVersions = @($Server.SupportedVersions) + supportedVersions = @(Get-McpServerVersion -Server $Server -Era Modern) capabilities = Get-McpServerCapability -Server $Server } if ($Server.Instructions) { $result['instructions'] = $Server.Instructions } diff --git a/src/Private/Worker.ps1 b/src/Private/Worker.ps1 index 7409753..6c073bd 100644 --- a/src/Private/Worker.ps1 +++ b/src/Private/Worker.ps1 @@ -29,7 +29,7 @@ function New-McpRequestContext { Method = $Envelope.Method Name = $Envelope.Name ToolName = if ($Envelope.Kind -eq 'Tool') { $Envelope.Name } else { $null } - Era = 'Modern' + Era = if ($Envelope.Era) { $Envelope.Era } else { 'Modern' } ProtocolVersion = $meta.ProtocolVersion ClientInfo = $meta.ClientInfo ClientCapabilities = $meta.ClientCapabilities @@ -39,6 +39,8 @@ function New-McpRequestContext { Sink = $Envelope.Sink ServerName = $Envelope.ServerName ServerLogLevel = $Envelope.ServerLogLevel + # Legacy sessions: the table of open server-initiated requests and their timeout. + Legacy = $Envelope.Legacy ProgressState = @{ Last = $null } # Multi-round-trip requests: the answers of this and earlier rounds, the requests of this round, the # answers the handler accepted, and handler state that survives the rounds (in the signed requestState). @@ -78,7 +80,8 @@ function Send-McpSinkMessage { [object] $ErrorCode ) - $Sink.Queue.Enqueue(@{ Kind = $Kind; RequestId = $RequestId; Json = $Json; ErrorCode = $ErrorCode }) + # KeyPrefix: requests of a legacy session are keyed per session (request ids are unique per session only). + $Sink.Queue.Enqueue(@{ Kind = $Kind; RequestId = $RequestId; KeyPrefix = $Sink.KeyPrefix; Json = $Json; ErrorCode = $ErrorCode }) $null = $Sink.Signal.Set() } @@ -147,6 +150,7 @@ function Invoke-McpWorkerRequest { $meta[$script:McpMetaKey.ServerInfo] = $Envelope.ServerInfo $result['_meta'] = $meta } + if ($context.Era -eq 'Legacy') { $result = ConvertTo-McpLegacyResult -Result $result } $response = New-McpResultResponse -Id $Envelope.RequestId -Result $result } catch [System.Management.Automation.PipelineStoppedException] { throw @@ -163,7 +167,7 @@ function Invoke-McpWorkerRequest { Send-McpSinkMessage -Sink $Envelope.Sink -Kind Response -RequestId $Envelope.RequestId -Json (ConvertTo-McpJson -InputObject (New-McpResultResponse -Id $Envelope.RequestId -Result $result)) return } - $errorObject = ConvertTo-McpErrorObject -Exception $exception + $errorObject = ConvertTo-McpErrorObject -Exception $exception -Era $context.Era $errorCode = $errorObject['code'] $response = New-McpErrorResponse -Id $Envelope.RequestId -ErrorObject $errorObject } diff --git a/src/Public/New-McpServer.ps1 b/src/Public/New-McpServer.ps1 index 8770ea4..5baa013 100644 --- a/src/Public/New-McpServer.ps1 +++ b/src/Public/New-McpServer.ps1 @@ -23,7 +23,12 @@ function New-McpServer { .PARAMETER Instructions Natural-language guidance for clients and their models, returned by server/discover. .PARAMETER SupportedVersions - The protocol revisions the server speaks. This milestone supports 2026-07-28 only. + The protocol revisions the server speaks (default: 2026-07-28, 2025-11-25 and 2025-06-18). With both + 2026-07-28 and a legacy revision the server is dual-era: requests with the per-request _meta of + 2026-07-28 are served statelessly, an initialize request opens a legacy session (process-wide over stdio, + one per Mcp-Session-Id over Streamable HTTP). Only 2026-07-28 makes it modern-only (initialize is + answered with -32022 and the supported versions), only legacy revisions make it legacy-only. A server + with any legacy revision also accepts 2025-03-26 in initialize. .PARAMETER MaxConcurrency The maximum number of handlers running at the same time (the size of the worker runspace pool). .PARAMETER RequestTimeoutSeconds @@ -76,7 +81,7 @@ function New-McpServer { [string] $Instructions, [ValidateNotNullOrEmpty()] - [string[]] $SupportedVersions = @('2026-07-28'), + [string[]] $SupportedVersions = @('2026-07-28', '2025-11-25', '2025-06-18'), [ValidateRange(1, 64)] [int] $MaxConcurrency = [System.Math]::Max(1, [System.Environment]::ProcessorCount), @@ -105,9 +110,10 @@ function New-McpServer { [switch] $SetDefault ) + $known = @($script:McpModernProtocolVersions) + @($script:McpLegacyProtocolVersions) foreach ($candidate in $SupportedVersions) { - if ($candidate -notin $script:McpModernProtocolVersions) { - throw [System.ArgumentException]::new("Protocol version '$candidate' is not supported by this milestone; supported: $($script:McpModernProtocolVersions -join ', ').") + if ($candidate -notin $known) { + throw [System.ArgumentException]::new("Protocol version '$candidate' is not supported; supported: $($known -join ', ').") } } @@ -120,7 +126,7 @@ function New-McpServer { WebsiteUrl = $WebsiteUrl Icons = ConvertTo-McpIconList -Icons $Icons Instructions = $Instructions - SupportedVersions = [string[]] $SupportedVersions + SupportedVersions = [string[]] @($SupportedVersions | Select-Object -Unique) Tools = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) Resources = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) ResourceTemplates = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1 index de98648..c3eef2c 100644 --- a/tests/Integration/HttpServer.Tests.ps1 +++ b/tests/Integration/HttpServer.Tests.ps1 @@ -211,15 +211,13 @@ Describe 'Raw Streamable HTTP behaviour' -Tag 'Integration' { $noMeta.Status | Should -Be 400 $noMeta.Json['error']['code'] | Should -Be -32602 $noMeta.Json['id'] | Should -Be 3 - foreach ($method in 'initialize', 'ping', 'logging/setLevel', 'resources/subscribe', 'nothing/here') { + # Methods of the legacy revisions exist only in a legacy session (after initialize). + foreach ($method in 'ping', 'logging/setLevel', 'resources/subscribe', 'nothing/here') { $response = Send-Raw -Body "{`"jsonrpc`":`"2.0`",`"id`":4,`"method`":`"$method`",`"params`":{$($script:meta)}}" -Headers @{ 'Mcp-Method' = $method } $response.Status | Should -Be 404 $response.Json['error']['code'] | Should -Be -32601 $response.Json['id'] | Should -Be 4 } - $legacy = Send-Raw -Body '{"jsonrpc":"2.0","id":5,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"old","version":"1"}}}' -NoVersion - $legacy.Status | Should -Be 404 - $legacy.Json['error']['message'] | Should -Match '2026-07-28' } It 'validates Mcp-Name for tools/call including whitespace and the Base64 sentinel' { diff --git a/tests/Integration/InMemoryClient.Tests.ps1 b/tests/Integration/InMemoryClient.Tests.ps1 index 821dd92..a768883 100644 --- a/tests/Integration/InMemoryClient.Tests.ps1 +++ b/tests/Integration/InMemoryClient.Tests.ps1 @@ -173,7 +173,7 @@ Describe 'Connect-McpServer over the in-memory transport' { } It 'answers raw protocol violations like the specification requires' { - $raw = New-McpServer -Name 'raw' -Version '1' + $raw = New-McpServer -Name 'raw' -Version '1' -SupportedVersions '2026-07-28' Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $raw $pair = Invoke-McpInModule { New-McpInMemoryTransportPair } $background = Invoke-McpInModule { param($s, $e) Start-McpBackgroundServer -Server $s -Endpoint $e } $raw $pair.Server @@ -197,8 +197,11 @@ Describe 'Connect-McpServer over the in-memory transport' { $version['error']['code'] | Should -Be -32022 $version['error']['data']['supported'] | Should -Be @('2026-07-28') & $send '{"jsonrpc":"2.0","id":3,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"legacy","version":"1"}}}' + # A modern-only server names the versions it supports in its answer to initialize. $legacy = & $receive - $legacy['error']['code'] | Should -Be -32601 + $legacy['error']['code'] | Should -Be -32022 + $legacy['error']['data']['supported'] | Should -Be @('2026-07-28') + $legacy['error']['data']['requested'] | Should -Be '2025-11-25' $legacy['error']['message'] | Should -Match '2026-07-28' & $send '{"jsonrpc":"2.0","id":4,"method":"nothing/here","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}' (& $receive)['error']['code'] | Should -Be -32601 diff --git a/tests/Integration/LegacyServer.Tests.ps1 b/tests/Integration/LegacyServer.Tests.ps1 new file mode 100644 index 0000000..eeb4a7f --- /dev/null +++ b/tests/Integration/LegacyServer.Tests.ps1 @@ -0,0 +1,273 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseCorrectCasing', '', Justification = 'PSScriptAnalyzer attributes -ScriptBlock of commands nested in BeforeAll to BeforeAll itself.')] +param() + +# The legacy session of a dual-era server on the wire, over the in-memory transport (the same dispatcher path as +# stdio): the initialize handshake, the legacy-only methods, the legacy result shapes, server-initiated requests, +# session-wide logging and the unsolicited notifications. + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force + + function Connect-LegacyWire { + param([pscustomobject] $Server) + $pair = Invoke-McpInModule { New-McpInMemoryTransportPair } + $background = Invoke-McpInModule { param($s, $e) Start-McpBackgroundServer -Server $s -Endpoint $e } $Server $pair.Server + @{ Pair = $pair; Background = $background } + } + + function Disconnect-LegacyWire { + param([hashtable] $Wire) + Invoke-McpInModule { param($t) Close-McpTransport -Transport $t } $Wire.Pair.Client + Invoke-McpInModule { param($b) Stop-McpBackgroundServer -Background $b } $Wire.Background + } + + function Send-Line { + param([hashtable] $Wire, [string] $Line) + Invoke-McpInModule { param($t, $l) Send-McpTransportLine -Transport $t -Line $l } $Wire.Pair.Client $Line + } + + function Receive-Message { + param([hashtable] $Wire) + $received = Invoke-McpInModule { param($t) Receive-McpTransportLine -Transport $t -TimeoutMs 10000 } $Wire.Pair.Client + $received.Status | Should -Be 'Line' + Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } $received.Line + } + + function Send-Json { + param([hashtable] $Wire, [object] $Message) + Send-Line -Wire $Wire -Line (Invoke-McpInModule { param($m) ConvertTo-McpJson -InputObject $m } -Parameters @{ m = $Message }) + } + + function Initialize-Legacy { + param([hashtable] $Wire, [string] $Version = '2025-11-25', [hashtable] $Capabilities = @{}) + Send-Json -Wire $Wire -Message ([ordered]@{ jsonrpc = '2.0'; id = 0; method = 'initialize'; params = [ordered]@{ protocolVersion = $Version; capabilities = $Capabilities; clientInfo = [ordered]@{ name = 'legacy-test'; version = '1.0' } } }) + $answer = Receive-Message -Wire $Wire + Send-Line -Wire $Wire -Line '{"jsonrpc":"2.0","method":"notifications/initialized"}' + $answer + } + + $script:server = New-McpServer -Name 'legacy' -Version '1.0.0' -Title 'Legacy test' -Description 'Only 2025-11-25 knows descriptions.' -Instructions 'Legacy instructions.' -RequestTimeoutSeconds 30 + Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $script:server + Register-McpTool -Name 'ask' -ScriptBlock { + param($Context) + $answer = Request-McpElicitation -Context $Context -Key 'name' -Message 'Your name?' -Schema @{ name = @{ type = 'string' } } -Required name + if ($answer.Accepted) { "Hello, $($answer.Content.name)!" } else { "no: $($answer.Action)" } + } -Server $script:server + Register-McpTool -Name 'sample' -ScriptBlock { + param($Context) + $reply = Request-McpSampling -Context $Context -Key 'llm' -Messages 'Say hi' -MaxTokens 10 + "model said: $($reply.Text)" + } -Server $script:server + Register-McpTool -Name 'roots' -ScriptBlock { + param($Context) + $roots = Request-McpRoot -Context $Context -Key 'roots' + @($roots | ForEach-Object Uri) -join ',' + } -Server $script:server + Register-McpTool -Name 'chatty' -ScriptBlock { + param($Context) + Write-McpLog -Context $Context -Level debug -Message 'one' + Write-McpLog -Context $Context -Level info -Message 'two' + Write-McpLog -Context $Context -Level error -Message 'three' + 'logged' + } -Server $script:server + Register-McpTool -Name 'touch' -ScriptBlock { param([string] $Uri, $Context) Send-McpResourceUpdated -Context $Context -Uri $Uri; 'touched' } -Server $script:server + Register-McpResource -Uri 'test://doc' -Name 'doc' -Content 'document' -Server $script:server +} + +Describe 'Legacy session over the line transports' -Tag 'Integration' { + It 'negotiates the version and answers initialize with an InitializeResult of the requested revision' { + foreach ($case in @(@{ Requested = '2025-11-25'; Expected = '2025-11-25' }, @{ Requested = '2025-06-18'; Expected = '2025-06-18' }, @{ Requested = '2025-03-26'; Expected = '2025-03-26' }, @{ Requested = '2099-01-01'; Expected = '2025-11-25' })) { + $wire = Connect-LegacyWire -Server $script:server + try { + $answer = Initialize-Legacy -Wire $wire -Version $case.Requested + $answer['id'] | Should -Be 0 + $result = $answer['result'] + $result['protocolVersion'] | Should -Be $case.Expected + $result['serverInfo']['name'] | Should -Be 'legacy' + $result['instructions'] | Should -Be 'Legacy instructions.' + $result['capabilities']['tools']['listChanged'] | Should -BeTrue + $result['capabilities']['resources']['subscribe'] | Should -BeTrue + $result['capabilities'].Contains('logging') | Should -BeTrue + $result.Contains('resultType') | Should -BeFalse + if ($case.Expected -eq '2025-11-25') { + $result['serverInfo']['description'] | Should -Be 'Only 2025-11-25 knows descriptions.' + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'InitializeResult' -Instance $result).IsValid | Should -BeTrue + } else { + $result['serverInfo'].Contains('description') | Should -BeFalse + } + if ($case.Expected -eq '2025-06-18') { + (Test-McpSpecShape -Revision '2025-06-18' -Definition 'InitializeResult' -Instance $result).IsValid | Should -BeTrue + } + } finally { + Disconnect-LegacyWire -Wire $wire + } + } + } + + It 'serves ping, logging/setLevel, lists, calls and reads in the legacy shapes' { + $wire = Connect-LegacyWire -Server $script:server + try { + $null = Initialize-Legacy -Wire $wire + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":1,"method":"ping"}' + $ping = Receive-Message -Wire $wire + $ping['id'] | Should -Be 1 + $ping['result'].Count | Should -Be 0 + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' + $list = (Receive-Message -Wire $wire)['result'] + @($list['tools'] | ForEach-Object { $_['name'] }) | Should -Contain 'echo' + foreach ($name in 'resultType', 'ttlMs', 'cacheScope', '_meta') { $list.Contains($name) | Should -BeFalse } + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'ListToolsResult' -Instance $list).IsValid | Should -BeTrue + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":"c","method":"tools/call","params":{"name":"echo","arguments":{"Text":"legacy"}}}' + $call = Receive-Message -Wire $wire + $call['id'] | Should -Be 'c' + $call['result']['content'][0]['text'] | Should -Be 'legacy' + $call['result'].Contains('resultType') | Should -BeFalse + $call['result'].Contains('_meta') | Should -BeFalse + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'CallToolResult' -Instance $call['result']).IsValid | Should -BeTrue + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"test://doc"}}' + $read = (Receive-Message -Wire $wire)['result'] + $read['contents'][0]['text'] | Should -Be 'document' + $read.Contains('ttlMs') | Should -BeFalse + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"test://missing"}}' + $missing = Receive-Message -Wire $wire + $missing['error']['code'] | Should -Be -32002 + $missing['error']['data']['uri'] | Should -Be 'test://missing' + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":5,"method":"server/discover"}' + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32601 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":6,"method":"logging/setLevel","params":{"level":"loud"}}' + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32602 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":7,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"again","version":"1"}}}' + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32600 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"nope"}}' + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32602 + + # A modern request on the same line is still served statelessly. + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":9,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}' + $discover = (Receive-Message -Wire $wire)['result'] + $discover['resultType'] | Should -Be 'complete' + $discover['supportedVersions'] | Should -Be @('2026-07-28') + } finally { + Disconnect-LegacyWire -Wire $wire + } + } + + It 'sends elicitation, sampling and roots requests to the client and hands the answers to the handler' { + $wire = Connect-LegacyWire -Server $script:server + try { + $null = Initialize-Legacy -Wire $wire -Capabilities @{ elicitation = @{}; sampling = @{}; roots = @{ listChanged = $true } } + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"ask"}}' + $request = Receive-Message -Wire $wire + $request['method'] | Should -Be 'elicitation/create' + $request['params']['message'] | Should -Be 'Your name?' + $request['params']['requestedSchema']['properties']['name']['type'] | Should -Be 'string' + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'ElicitRequest' -Instance $request).IsValid | Should -BeTrue + Send-Json -Wire $wire -Message ([ordered]@{ jsonrpc = '2.0'; id = $request['id']; result = [ordered]@{ action = 'accept'; content = [ordered]@{ name = 'Ada' } } }) + $call = Receive-Message -Wire $wire + $call['id'] | Should -Be 10 + $call['result']['content'][0]['text'] | Should -Be 'Hello, Ada!' + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"sample"}}' + $request = Receive-Message -Wire $wire + $request['method'] | Should -Be 'sampling/createMessage' + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'CreateMessageRequest' -Instance $request).IsValid | Should -BeTrue + Send-Json -Wire $wire -Message ([ordered]@{ jsonrpc = '2.0'; id = $request['id']; result = [ordered]@{ role = 'assistant'; model = 'm'; content = [ordered]@{ type = 'text'; text = 'hi' } } }) + (Receive-Message -Wire $wire)['result']['content'][0]['text'] | Should -Be 'model said: hi' + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"roots"}}' + $request = Receive-Message -Wire $wire + $request['method'] | Should -Be 'roots/list' + Send-Json -Wire $wire -Message ([ordered]@{ jsonrpc = '2.0'; id = $request['id']; result = [ordered]@{ roots = @([ordered]@{ uri = 'file:///a' }, [ordered]@{ uri = 'file:///b' }) } }) + (Receive-Message -Wire $wire)['result']['content'][0]['text'] | Should -Be 'file:///a,file:///b' + + # An error from the client fails the call; an answer that does not fit the request is rejected. + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"ask"}}' + $request = Receive-Message -Wire $wire + Send-Json -Wire $wire -Message ([ordered]@{ jsonrpc = '2.0'; id = $request['id']; error = [ordered]@{ code = -32601; message = 'no' } }) + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32603 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"ask"}}' + $request = Receive-Message -Wire $wire + Send-Json -Wire $wire -Message ([ordered]@{ jsonrpc = '2.0'; id = $request['id']; result = [ordered]@{ action = 'accept'; content = [ordered]@{ name = 42 } } }) + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32602 + + # Cancelling a call that waits for the client ends it without a response. + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":15,"method":"tools/call","params":{"name":"ask"}}' + $null = Receive-Message -Wire $wire + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":15}}' + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":16,"method":"ping"}' + (Receive-Message -Wire $wire)['id'] | Should -Be 16 + } finally { + Disconnect-LegacyWire -Wire $wire + } + } + + It 'refuses input requests the client did not declare' { + $wire = Connect-LegacyWire -Server $script:server + try { + $null = Initialize-Legacy -Wire $wire -Version '2025-06-18' + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ask"}}' + $answer = Receive-Message -Wire $wire + $answer['error']['code'] | Should -Be -32600 + $answer['error']['message'] | Should -Match 'elicitation' + } finally { + Disconnect-LegacyWire -Wire $wire + } + } + + It 'sends log notifications after logging/setLevel and unsolicited list and resource notifications' { + $wire = Connect-LegacyWire -Server $script:server + try { + $null = Initialize-Legacy -Wire $wire + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"chatty"}}' + (Receive-Message -Wire $wire)['result']['content'][0]['text'] | Should -Be 'logged' + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":2,"method":"logging/setLevel","params":{"level":"info"}}' + (Receive-Message -Wire $wire)['id'] | Should -Be 2 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"chatty"}}' + $messages = @(Receive-Message -Wire $wire; Receive-Message -Wire $wire; Receive-Message -Wire $wire) + @($messages[0..1] | ForEach-Object { $_['params']['data'] }) | Should -Be @('two', 'three') + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'LoggingMessageNotification' -Instance $messages[0]).IsValid | Should -BeTrue + $messages[2]['id'] | Should -Be 3 + + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":4,"method":"resources/subscribe","params":{"uri":"test://doc"}}' + (Receive-Message -Wire $wire)['id'] | Should -Be 4 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"touch","arguments":{"Uri":"test://other"}}}' + (Receive-Message -Wire $wire)['id'] | Should -Be 5 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"touch","arguments":{"Uri":"test://doc/part"}}}' + $both = @(Receive-Message -Wire $wire; Receive-Message -Wire $wire) + $updated = $both | Where-Object { $_['method'] -eq 'notifications/resources/updated' } + $updated['params']['uri'] | Should -Be 'test://doc/part' + $updated['params'].Contains('_meta') | Should -BeFalse + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":7,"method":"resources/unsubscribe","params":{"uri":"test://doc"}}' + (Receive-Message -Wire $wire)['id'] | Should -Be 7 + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"touch","arguments":{"Uri":"test://doc"}}}' + (Receive-Message -Wire $wire)['id'] | Should -Be 8 + + $null = Send-McpToolListChanged -Server $script:server + $changed = Receive-Message -Wire $wire + $changed['method'] | Should -Be 'notifications/tools/list_changed' + $changed.Contains('params') | Should -BeFalse + } finally { + Disconnect-LegacyWire -Wire $wire + } + } + + It 'answers requests before initialize on a legacy-only server with an error that is not a modern one' { + $legacyOnly = New-McpServer -Name 'old' -Version '1' -SupportedVersions '2025-11-25' + Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $legacyOnly + $wire = Connect-LegacyWire -Server $legacyOnly + try { + Send-Line -Wire $wire -Line '{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}' + (Receive-Message -Wire $wire)['error']['code'] | Should -Be -32600 + (Initialize-Legacy -Wire $wire)['result']['protocolVersion'] | Should -Be '2025-11-25' + } finally { + Disconnect-LegacyWire -Wire $wire + } + } +} diff --git a/tests/Support/McpTestSupport.psm1 b/tests/Support/McpTestSupport.psm1 index d39c11e..6a4f1bd 100644 --- a/tests/Support/McpTestSupport.psm1 +++ b/tests/Support/McpTestSupport.psm1 @@ -195,7 +195,9 @@ function Test-McpSpecShape { ) $definitions = Get-McpSpecDefinition -Revision $Revision - $schema = @{ '$ref' = "#/`$defs/$Definition"; '$defs' = $definitions } + # The references inside the definitions point at $defs (2020-12 schemas) or definitions (draft-07 schemas). + $container = if ((Get-McpSpecSchema -Revision $Revision).ContainsKey('$defs')) { '$defs' } else { 'definitions' } + $schema = @{ '$ref' = "#/$container/$Definition"; $container = $definitions } Invoke-McpInModule { param($s, $i) Test-McpJsonSchema -Schema $s -Instance $i } -Parameters @{ s = $schema; i = $Instance } } diff --git a/tests/Unit/Era.Tests.ps1 b/tests/Unit/Era.Tests.ps1 new file mode 100644 index 0000000..3674161 --- /dev/null +++ b/tests/Unit/Era.Tests.ps1 @@ -0,0 +1,114 @@ +[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 'Era selection' { + BeforeAll { + $script:modernMeta = [ordered]@{ _meta = [ordered]@{ 'io.modelcontextprotocol/protocolVersion' = '2026-07-28'; 'io.modelcontextprotocol/clientCapabilities' = [ordered]@{} } } + } + + It 'chooses for (session: , line session: , HTTP: , modern _meta: )' -ForEach @( + @{ Method = 'initialize'; HasSession = $false; HasLineSession = $false; Http = $false; Modern = $false; Expected = 'Legacy' } + @{ Method = 'initialize'; HasSession = $false; HasLineSession = $false; Http = $true; Modern = $true; Expected = 'Legacy' } + @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $false; Http = $false; Modern = $true; Expected = 'Modern' } + @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $false; Http = $false; Modern = $false; Expected = 'Modern' } + @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $true; Http = $false; Modern = $false; Expected = 'Legacy' } + @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $true; Http = $false; Modern = $true; Expected = 'Modern' } + @{ Method = 'tools/list'; HasSession = $true; HasLineSession = $false; Http = $true; Modern = $false; Expected = 'Legacy' } + @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $false; Http = $true; Modern = $false; Expected = 'Modern' } + @{ Method = 'ping'; HasSession = $false; HasLineSession = $false; Http = $true; Modern = $true; Expected = 'Modern' } + ) { + $state = @{ LineSession = if ($HasLineSession) { @{ KeyPrefix = 'legacy|' } } else { $null } } + $parameters = @{ + s = $state + m = $Method + p = if ($Modern) { $script:modernMeta } else { [ordered]@{} } + x = if ($HasSession) { @{ KeyPrefix = 'legacy:1|' } } else { $null } + h = $Http + } + Invoke-McpInModule { param($s, $m, $p, $x, $h) Get-McpMessageEra -State $s -Method $m -Params $p -Session $x -Http:$h } -Parameters $parameters | Should -Be $Expected + } + + It 'splits the supported versions by era and accepts 2025-03-26 with any legacy revision' { + $dual = New-McpServer -Name 'd' -Version '1' + Invoke-McpInModule { param($s) Get-McpServerVersion -Server $s -Era Modern } $dual | Should -Be @('2026-07-28') + Invoke-McpInModule { param($s) Get-McpServerVersion -Server $s -Era Legacy } $dual | Should -Be @('2025-11-25', '2025-06-18') + Invoke-McpInModule { param($s) Get-McpServerVersion -Server $s -Era Legacy -Accepted } $dual | Should -Be @('2025-11-25', '2025-06-18', '2025-03-26') + $modern = New-McpServer -Name 'm' -Version '1' -SupportedVersions '2026-07-28' + @(Invoke-McpInModule { param($s) Get-McpServerVersion -Server $s -Era Legacy -Accepted } $modern).Count | Should -Be 0 + } +} + +Describe 'Era-aware serialization' { + It 'removes the modern-only members from legacy results' { + $result = [ordered]@{ resultType = 'complete'; tools = @(); ttlMs = 0; cacheScope = 'public'; nextCursor = 'x'; _meta = [ordered]@{ 'io.modelcontextprotocol/serverInfo' = @{ name = 's' }; 'example.com/keep' = 1 } } + $converted = Invoke-McpInModule { param($r) ConvertTo-McpLegacyResult -Result $r } -Parameters @{ r = $result } + @($converted.Keys) | Should -Be @('tools', 'nextCursor', '_meta') + @($converted['_meta'].Keys) | Should -Be @('example.com/keep') + $bare = Invoke-McpInModule { param($r) ConvertTo-McpLegacyResult -Result $r } -Parameters @{ r = [ordered]@{ resultType = 'complete'; _meta = [ordered]@{ 'io.modelcontextprotocol/serverInfo' = @{} } } } + $bare.Count | Should -Be 0 + } + + It 'leaves modern messages unchanged' { + $message = [ordered]@{ jsonrpc = '2.0'; id = 1; result = [ordered]@{ resultType = 'complete' } } + (Invoke-McpInModule { param($m) ConvertTo-McpEraMessage -Message $m -Era Modern } -Parameters @{ m = $message })['result']['resultType'] | Should -Be 'complete' + } + + It 'maps errors: unknown resources to -32002 and the modern codes to -32600' { + $notFound = Invoke-McpInModule { ConvertTo-McpErrorObject -Exception (New-McpResourceNotFoundException -Uri 'test://x') -Era Legacy } + $notFound['code'] | Should -Be -32002 + $notFound['data']['uri'] | Should -Be 'test://x' + (Invoke-McpInModule { ConvertTo-McpErrorObject -Exception (New-McpResourceNotFoundException -Uri 'test://x') })['code'] | Should -Be -32602 + foreach ($code in -32020, -32021, -32022) { + (Invoke-McpInModule { param($c) ConvertTo-McpErrorObject -Exception ([McpProtocolException]::new($c, 'm')) -Era Legacy } $code)['code'] | Should -Be -32600 + } + (Invoke-McpInModule { ConvertTo-McpErrorObject -Exception ([McpProtocolException]::new(-32601, 'm')) -Era Legacy })['code'] | Should -Be -32601 + } +} + +Describe 'Legacy sessions' { + BeforeAll { + $script:server = New-McpServer -Name 's' -Version '1' + Register-McpResource -Uri 'test://doc' -Name 'doc' -Content 'x' -Server $script:server + } + + It 'validates initialize and answers a modern-only server with -32022' { + $params = [ordered]@{ protocolVersion = '2025-06-18'; capabilities = [ordered]@{ sampling = [ordered]@{} }; clientInfo = [ordered]@{ name = 'c'; version = '1' } } + $session = Invoke-McpInModule { param($s, $p) Invoke-McpLegacyInitialize -Server $s -Params $p -SessionId 'abc' } -Parameters @{ s = $script:server; p = $params } + $session.ProtocolVersion | Should -Be '2025-06-18' + $session.KeyPrefix | Should -Be 'legacy:abc|' + $session.ClientCapabilities.Contains('sampling') | Should -BeTrue + foreach ($bad in @([ordered]@{ capabilities = @{}; clientInfo = @{ name = 'c'; version = '1' } }, [ordered]@{ protocolVersion = '2025-11-25'; clientInfo = @{ name = 'c'; version = '1' } }, [ordered]@{ protocolVersion = '2025-11-25'; capabilities = @{}; clientInfo = @{ name = 'c' } })) { + { Invoke-McpInModule { param($s, $p) Invoke-McpLegacyInitialize -Server $s -Params $p } -Parameters @{ s = $script:server; p = $bad } } | Should -Throw -ExceptionType ([McpProtocolException]) + } + $modernOnly = New-McpServer -Name 'm' -Version '1' -SupportedVersions '2026-07-28' + try { + Invoke-McpInModule { param($s, $p) Invoke-McpLegacyInitialize -Server $s -Params $p } -Parameters @{ s = $modernOnly; p = $params } + throw 'expected an exception' + } catch [McpProtocolException] { + $_.Exception.Code | Should -Be -32022 + $_.Exception.Data['supported'] | Should -Be @('2026-07-28') + $_.Exception.Data['requested'] | Should -Be '2025-06-18' + } + } + + It 'keeps the log level and the resource subscriptions of a session' { + $session = Invoke-McpInModule { New-McpLegacySession -ProtocolVersion '2025-11-25' } + $session.KeyPrefix | Should -Be 'legacy|' + $null = Invoke-McpInModule { param($s, $x) Invoke-McpLegacyMethod -Server $s -Session $x -Method 'logging/setLevel' -Params ([ordered]@{ level = 'warning' }) } $script:server $session + $session.LogLevel | Should -Be 'warning' + (Invoke-McpInModule { param($x) Get-McpLegacyRequestMeta -Session $x -Params ([ordered]@{ _meta = [ordered]@{ progressToken = 't' } }) } $session).ProgressToken | Should -Be 't' + $null = Invoke-McpInModule { param($s, $x) Invoke-McpLegacyMethod -Server $s -Session $x -Method 'resources/subscribe' -Params ([ordered]@{ uri = 'test://doc' }) } $script:server $session + $session.Initialized = $true + Invoke-McpInModule { param($x) Test-McpLegacyNotificationMatch -Session $x -Method 'notifications/resources/updated' -Params ([ordered]@{ uri = 'test://doc/a' }) } $session | Should -BeTrue + Invoke-McpInModule { param($x) Test-McpLegacyNotificationMatch -Session $x -Method 'notifications/resources/updated' -Params ([ordered]@{ uri = 'test://docx' }) } $session | Should -BeFalse + Invoke-McpInModule { param($x) Test-McpLegacyNotificationMatch -Session $x -Method 'notifications/prompts/list_changed' -Params $null } $session | Should -BeTrue + $null = Invoke-McpInModule { param($s, $x) Invoke-McpLegacyMethod -Server $s -Session $x -Method 'resources/unsubscribe' -Params ([ordered]@{ uri = 'test://doc' }) } $script:server $session + Invoke-McpInModule { param($x) Test-McpLegacyNotificationMatch -Session $x -Method 'notifications/resources/updated' -Params ([ordered]@{ uri = 'test://doc' }) } $session | Should -BeFalse + Invoke-McpInModule { param($s, $x) Invoke-McpLegacyMethod -Server $s -Session $x -Method 'tools/list' -Params $null } $script:server $session | Should -BeNullOrEmpty + } +} diff --git a/tests/Unit/Server.Tests.ps1 b/tests/Unit/Server.Tests.ps1 index 532432c..3802fc3 100644 --- a/tests/Unit/Server.Tests.ps1 +++ b/tests/Unit/Server.Tests.ps1 @@ -10,7 +10,7 @@ Describe 'New-McpServer' { It 'creates a server object with defaults' { $server = New-McpServer -Name 'demo' -Version '0.1.0' $server.PSObject.TypeNames | Should -Contain 'Mcp.Server' - $server.SupportedVersions | Should -Be @('2026-07-28') + $server.SupportedVersions | Should -Be @('2026-07-28', '2025-11-25', '2025-06-18') $server.Tools.Count | Should -Be 0 $server.Options.MaxConcurrency | Should -BeGreaterOrEqual 1 $server.Options.PageSize | Should -Be 100 @@ -19,8 +19,14 @@ Describe 'New-McpServer' { $server.Options.LogLevel | Should -Be ([McpLoggingLevel]::Warning) } - It 'rejects protocol versions this milestone does not support' { - { New-McpServer -Name 'demo' -Version '1' -SupportedVersions '2025-11-25' } | Should -Throw -ExpectedMessage '*not supported*' + It 'rejects protocol versions it does not know and accepts the legacy revisions' { + { New-McpServer -Name 'demo' -Version '1' -SupportedVersions '2024-11-05' } | Should -Throw -ExpectedMessage '*not supported*' + (New-McpServer -Name 'demo' -Version '1' -SupportedVersions '2025-11-25', '2025-03-26').SupportedVersions | Should -Be @('2025-11-25', '2025-03-26') + } + + It 'lists only the modern versions in server/discover' { + $server = New-McpServer -Name 'demo' -Version '1' + (Invoke-McpInModule { param($s) Get-McpDiscoverResult -Server $s } $server)['supportedVersions'] | Should -Be @('2026-07-28') } It 'sets the default server with -SetDefault' { From a7b16e262514f0cc6256f667c354ca1d8d9d021c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:38:29 +0000 Subject: [PATCH 2/4] M5 Streamable HTTP: legacy sessions, GET stream and DELETE A server with legacy revisions speaks the Streamable HTTP of 2025-11-25 and 2025-06-18 on the same endpoint: initialize mints an Mcp-Session-Id (a UUID), requests carrying it belong to that session and skip the header validation of 2026-07-28 (MCP-Protocol-Version is optional and must be a legacy version), notifications are dispatched, responses to server-initiated requests are accepted with 202, GET opens the session's stream (one per session, 409 for a second one) for list-changed and resource-updated notifications, DELETE ends the session, unknown or expired sessions answer 404. Errors of a session are JSON-RPC responses with status 200 (404 would end the client's session). Server-initiated requests go out on the SSE stream of the request that asked. Start-McpServer -SessionIdleTimeoutSeconds (default 1800) ends idle sessions without an open GET stream; -MaxSessions (default 100) answers further initialize requests with 503. A modern-only server keeps answering GET and DELETE with 405 and ignores Mcp-Session-Id. initialize with the per-request _meta of 2026-07-28 is a modern request for a removed method (404, -32601), as the 2026-07-28 conformance suite checks on the dual-era fixture. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rvihdz4S9tqxJNrZGrX3qD --- src/Private/Dispatcher.ps1 | 8 +- src/Private/Era.ps1 | 11 +- src/Private/HttpServer.ps1 | 252 +++++++++++++++++++++++-- src/Public/Start-McpServer.ps1 | 21 ++- tests/Integration/HttpServer.Tests.ps1 | 5 +- tests/Integration/LegacyHttp.Tests.ps1 | 250 ++++++++++++++++++++++++ tests/Unit/Era.Tests.ps1 | 3 +- tests/Unit/Header.Tests.ps1 | 12 ++ 8 files changed, 533 insertions(+), 29 deletions(-) create mode 100644 tests/Integration/LegacyHttp.Tests.ps1 diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1 index 94bbb07..65cf4fd 100644 --- a/src/Private/Dispatcher.ps1 +++ b/src/Private/Dispatcher.ps1 @@ -510,8 +510,10 @@ function Invoke-McpInboundRequest { $params = if ($Message.Contains('params')) { $Message['params'] } else { $null } $isHttp = $null -ne $Channel -and $Channel.Kind -eq 'Http' $era = Get-McpMessageEra -State $State -Method $method -Params $params -Session $Session -Http:$isHttp - # A modern-only server answers initialize with -32022 in the modern shape (the versions it supports). - if ($method -ceq 'initialize' -and @(Get-McpServerVersion -Server $server -Era Legacy).Count -eq 0) { $era = 'Modern' } + # A modern-only server answers the initialize of a legacy client with -32022 in the modern shape (the + # versions it supports); initialize with modern _meta is a modern request for a removed method (-32601). + $handshake = $method -ceq 'initialize' -and $era -eq 'Legacy' + if ($handshake -and @(Get-McpServerVersion -Server $server -Era Legacy).Count -eq 0) { $era = 'Modern' } if ($era -eq 'Legacy' -and $null -eq $Session -and -not $isHttp) { $Session = $State.LineSession } if ($isHttp) { $Channel.Era = $era } $reply = @{ State = $State; Channel = $Channel; Era = $era } @@ -529,7 +531,7 @@ function Invoke-McpInboundRequest { return } try { - if ($method -ceq 'initialize') { + if ($handshake) { if ($null -ne $Session -or (-not $isHttp -and $null -ne $State.LineSession)) { throw [McpProtocolException]::new($script:McpErrorCode.InvalidRequest, 'The session is already initialized.') } diff --git a/src/Private/Era.ps1 b/src/Private/Era.ps1 index b71d25d..a2195b4 100644 --- a/src/Private/Era.ps1 +++ b/src/Private/Era.ps1 @@ -46,8 +46,9 @@ function Get-McpMessageEra { The era of an inbound request: Legacy for initialize and for requests of an initialized legacy session, Modern otherwise. .DESCRIPTION Over Streamable HTTP the session is resolved from the Mcp-Session-Id header before (HttpServer.ps1) and - passed in. Over the line transports (stdio, in memory) a request whose _meta carries the modern protocol - version is modern; any other request belongs to the process-wide legacy session once one was opened. + passed in. Otherwise a request whose _meta carries the modern protocol version is modern, initialize + without it opens a legacy session, and over the line transports (stdio, in memory) any other request + belongs to the process-wide legacy session once one was opened. #> [CmdletBinding()] [OutputType([string])] @@ -67,12 +68,14 @@ function Get-McpMessageEra { [switch] $Http ) - if ($Method -ceq 'initialize') { return 'Legacy' } if ($null -ne $Session) { return 'Legacy' } - if ($Http) { return 'Modern' } + # The per-request _meta of revision 2026-07-28 makes a request modern, also initialize (a modern client + # probing for the removed method gets -32601); legacy clients never send it. if ($Params -is [System.Collections.IDictionary] -and $Params['_meta'] -is [System.Collections.IDictionary] -and $Params['_meta'].Contains($script:McpMetaKey.ProtocolVersion)) { return 'Modern' } + if ($Method -ceq 'initialize') { return 'Legacy' } + if ($Http) { return 'Modern' } if ($null -ne $State.LineSession) { return 'Legacy' } 'Modern' } diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 index b7479a6..9af5f47 100644 --- a/src/Private/HttpServer.ps1 +++ b/src/Private/HttpServer.ps1 @@ -2,6 +2,11 @@ # loop in Dispatcher.ps1 calls Invoke-McpHttpDispatcherLoop; every accepted POST becomes a channel (the HTTP # response) that receives either one JSON object or a request-scoped SSE stream of notifications followed by # the final response. Nothing here touches the console: diagnostics go through Write-McpStderr. +# +# A server with legacy revisions also speaks the Streamable HTTP of 2025-11-25 and 2025-06-18: initialize +# mints an Mcp-Session-Id, requests carrying it belong to that legacy session, GET opens the session's stream +# for unsolicited notifications and server-initiated requests, DELETE ends the session, and responses to +# server-initiated requests are POSTed back. Sessions expire after an idle timeout; their number is capped. # Built on first use: the error code table (JsonRpc.ps1) is assembled after this file. $script:McpHttpStatusByErrorCode = $null @@ -10,15 +15,25 @@ function Get-McpHttpStatusCode { <# .SYNOPSIS The HTTP status of a JSON-RPC response: 400 for malformed requests, headers and versions, 404 for unknown methods, 200 otherwise. + .DESCRIPTION + In a legacy session only malformed messages are 400; every other error is a JSON-RPC response with + status 200, because 404 tells a client of those revisions that its session is gone. #> [CmdletBinding()] [OutputType([int])] param( [AllowNull()] - [object] $ErrorCode + [object] $ErrorCode, + + [ValidateSet('Modern', 'Legacy')] + [string] $Era = 'Modern' ) if ($null -eq $ErrorCode) { return 200 } + if ($Era -eq 'Legacy') { + if ([int] $ErrorCode -in @($script:McpErrorCode.ParseError, $script:McpErrorCode.InvalidRequest)) { return 400 } + return 200 + } if ($null -eq $script:McpHttpStatusByErrorCode) { $table = @{} foreach ($name in 'ParseError', 'InvalidRequest', 'InvalidParams', 'HeaderMismatch', 'MissingRequiredClientCapability', 'UnsupportedProtocolVersion') { @@ -52,7 +67,13 @@ function New-McpHttpServerTransport { [int] $KeepAliveSeconds = 5, - [int] $BodyTimeoutSeconds = 30 + [int] $BodyTimeoutSeconds = 30, + + # Legacy sessions: seconds without a request after which a session without an open GET stream ends. + [int] $SessionIdleTimeoutSeconds = 1800, + + # Legacy sessions: the maximum number of open sessions; initialize beyond it is answered with 503. + [int] $MaxSessions = 100 ) if (-not $Url.IsAbsoluteUri -or $Url.Scheme -notin @('http', 'https')) { @@ -80,6 +101,8 @@ function New-McpHttpServerTransport { MaxBodyBytes = $MaxBodyBytes KeepAliveSeconds = $KeepAliveSeconds BodyTimeoutSeconds = $BodyTimeoutSeconds + SessionIdleTimeout = $SessionIdleTimeoutSeconds + MaxSessions = $MaxSessions PendingBodies = [System.Collections.Generic.List[hashtable]]::new() OpenChannels = [System.Collections.Generic.List[hashtable]]::new() Stopped = $false @@ -206,14 +229,20 @@ function New-McpHttpChannel { ) @{ - Kind = 'Http' - Context = $Context - Response = $Context.Response - Mode = $null - Stream = $null - Closed = $false - LastWrite = [datetime]::UtcNow - RequestId = $null + Kind = 'Http' + Context = $Context + Response = $Context.Response + Mode = $null + Stream = $null + Closed = $false + LastWrite = [datetime]::UtcNow + RequestId = $null + # Set by the router: the in-flight key and the era of the request, headers of the response + # (Mcp-Session-Id of initialize), and the legacy session of a GET stream. + RequestKey = $null + Era = 'Modern' + Headers = $null + Session = $null } } @@ -288,8 +317,10 @@ function Send-McpHttpStatus { try { $response = $Channel.Response $response.StatusCode = $StatusCode - if ($Headers) { - foreach ($name in $Headers.Keys) { $response.AddHeader([string] $name, [string] $Headers[$name]) } + foreach ($table in @($Channel.Headers, $Headers)) { + if ($table) { + foreach ($name in $table.Keys) { $response.AddHeader([string] $name, [string] $table[$name]) } + } } if ($Json) { $bytes = [System.Text.Encoding]::UTF8.GetBytes($Json) @@ -332,6 +363,9 @@ function Start-McpHttpSse { $response.SendChunked = $true $response.AddHeader('Cache-Control', 'no-cache') $response.AddHeader('X-Accel-Buffering', 'no') + if ($Channel.Headers) { + foreach ($name in $Channel.Headers.Keys) { $response.AddHeader([string] $name, [string] $Channel.Headers[$name]) } + } $Channel.Stream = $response.OutputStream $Channel.Mode = 'Sse' $Channel.LastWrite = [datetime]::UtcNow @@ -422,7 +456,7 @@ function Send-McpHttpResponse { Close-McpHttpChannel -State $State -Channel $Channel return $written } - Send-McpHttpStatus -State $State -Channel $Channel -StatusCode (Get-McpHttpStatusCode -ErrorCode $ErrorCode) -Json $Json + Send-McpHttpStatus -State $State -Channel $Channel -StatusCode (Get-McpHttpStatusCode -ErrorCode $ErrorCode -Era $Channel.Era) -Json $Json } function Update-McpHttpChannel { @@ -476,6 +510,11 @@ function Stop-McpHttpChannelRequest { [hashtable] $Channel ) + if ($null -ne $Channel.Session -and $Channel.Session.GetChannel -eq $Channel) { + # The GET stream of a legacy session: the session stays, only its stream is gone. + $Channel.Session.GetChannel = $null + return + } if ($null -eq $Channel.RequestId -and $null -eq $Channel.RequestKey) { return } $key = if ($Channel.RequestKey) { $Channel.RequestKey } else { Get-McpRequestKey -Id $Channel.RequestId } if ($State.Listeners.ContainsKey($key) -and $State.Listeners[$key].Channel -eq $Channel) { @@ -540,10 +579,91 @@ function Test-McpHttpRequestHeader { } } +function Test-McpHttpLegacy { + <# + .SYNOPSIS + Whether the server speaks a legacy revision, and with it sessions, GET streams and DELETE. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + @(Get-McpServerVersion -Server $State.Server -Era Legacy).Count -gt 0 +} + +function Resolve-McpHttpSession { + <# + .SYNOPSIS + The legacy session named by the Mcp-Session-Id header of a request; answers 404 and returns $null when there is no such session. + .OUTPUTS + The session, or $null when the request carries no session id (or the server has no legacy revisions). + Found is $false when the response was already sent. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [AllowNull()] + [object] $Id + ) + + $sessionId = $Channel.Context.Request.Headers['Mcp-Session-Id'] + # A modern-only server ignores the header: it never mints or echoes session ids. + if ([string]::IsNullOrWhiteSpace($sessionId) -or -not (Test-McpHttpLegacy -State $State)) { return @{ Found = $true; Session = $null } } + $sessionId = $sessionId.Trim() + $session = if ($State.Sessions.ContainsKey($sessionId)) { $State.Sessions[$sessionId] } else { $null } + if ($null -eq $session -or $session.Closed -or $session.Id -cne $sessionId) { + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 404 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InvalidRequest -Message "Session '$sessionId' not found or expired; send initialize to start a new session." -Id $Id) + return @{ Found = $false; Session = $null } + } + $session.LastSeen = [datetime]::UtcNow + $Channel.Era = 'Legacy' + @{ Found = $true; Session = $session } +} + +function Test-McpHttpLegacyVersionHeader { + <# + .SYNOPSIS + Validates MCP-Protocol-Version on a request of a legacy session (optional; absent means 2025-03-26); answers 400 and returns $false for an unsupported version. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [AllowNull()] + [object] $Id + ) + + $version = $Channel.Context.Request.Headers['MCP-Protocol-Version'] + if ($null -eq $version) { return $true } + $version = $version.Trim() + $accepted = @(Get-McpServerVersion -Server $State.Server -Era Legacy -Accepted) + if ($version -in $accepted) { return $true } + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 400 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InvalidRequest -Message "Unsupported MCP-Protocol-Version '$version' for a session; supported: $($accepted -join ', ')." -Id $Id) + $false +} + function Invoke-McpInboundHttpMessage { <# .SYNOPSIS Handles the body of an accepted POST: parse errors and invalid messages answer 400, notifications 202, requests go to the dispatcher. + .DESCRIPTION + A POST with Mcp-Session-Id belongs to a legacy session: its requests skip the header validation of + revision 2026-07-28, its notifications are dispatched, and responses to server-initiated requests are + accepted with 202. #> [CmdletBinding()] param( @@ -568,10 +688,23 @@ function Invoke-McpInboundHttpMessage { } $kind = Get-McpMessageKind -Message $message Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $logger -Message ("<- {0} {1} {2}" -f $kind, $(if ($message -is [System.Collections.IDictionary] -and $message.Contains('method')) { $message['method'] } else { '' }), $(if ($message -is [System.Collections.IDictionary] -and $message.Contains('id')) { "id=$($message['id'])" } else { '' })) + $messageId = if ($kind -eq 'Request') { $message['id'] } else { $null } + $resolved = Resolve-McpHttpSession -State $State -Channel $Channel -Id $messageId + if (-not $resolved.Found) { return } + $session = $resolved.Session switch ($kind) { 'Request' { $Channel.RequestId = $message['id'] - if ([string] $message['method'] -ne 'initialize') { + $method = [string] $message['method'] + if ($null -ne $session) { + if (-not (Test-McpHttpLegacyVersionHeader -State $State -Channel $Channel -Id $message['id'])) { return } + } elseif ($method -ceq 'initialize') { + if ((Test-McpHttpLegacy -State $State) -and $State.Sessions.Count -ge $State.Transport.MaxSessions) { + Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $logger -Message "Refused initialize: $($State.Sessions.Count) legacy sessions are open (the limit)." + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 503 -Headers @{ 'Retry-After' = '30' } -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InternalError -Message 'Too many open sessions; try again later.' -Id $message['id']) + return + } + } else { try { Test-McpHttpRequestHeader -Request $Channel.Context.Request -Message $message } catch [McpProtocolException] { @@ -579,13 +712,24 @@ function Invoke-McpInboundHttpMessage { return } } - Invoke-McpInboundRequest -State $State -Message $message -Channel $Channel + Invoke-McpInboundRequest -State $State -Message $message -Channel $Channel -Session $session } 'Notification' { - Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $logger -Message "Accepted notification '$($message['method'])' (revision 2026-07-28 defines no client notifications over Streamable HTTP)." + if ($null -ne $session) { + Invoke-McpInboundNotification -State $State -Message $message -Session $session + } else { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $logger -Message "Accepted notification '$($message['method'])' (revision 2026-07-28 defines no client notifications over Streamable HTTP)." + } $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 202 } { $_ -in @('Response', 'ErrorResponse') } { + if ($null -ne $session) { + if (-not (Complete-McpLegacyServerRequest -Session $session -Message $message)) { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $logger -Message "Ignoring a response that answers no open request of session $($session.Id)." + } + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 202 + return + } $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 400 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InvalidRequest -Message 'Clients do not send JSON-RPC responses in revision 2026-07-28; server-to-client interactions are input requests inside results.') } default { @@ -596,6 +740,75 @@ function Invoke-McpInboundHttpMessage { } } +function Invoke-McpHttpSessionRequest { + <# + .SYNOPSIS + GET and DELETE on the endpoint of a legacy session: GET opens the session's stream, DELETE ends the session. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel + ) + + $resolved = Resolve-McpHttpSession -State $State -Channel $Channel -Id $null + if (-not $resolved.Found) { return } + $session = $resolved.Session + $invalidRequest = $script:McpErrorCode.InvalidRequest + if ($Channel.Context.Request.HttpMethod -ceq 'DELETE') { + Close-McpLegacySession -State $State -Session $session -Reason 'ended by the client' + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 200 + return + } + if (-not (Test-McpHttpLegacyVersionHeader -State $State -Channel $Channel -Id $null)) { return } + $accept = $Channel.Context.Request.Headers['Accept'] + if (-not [string]::IsNullOrWhiteSpace($accept) -and $accept -notmatch 'text/event-stream|\*/\*') { + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 406 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message 'The GET stream is text/event-stream; the Accept header must allow it.') + return + } + if ($null -ne $session.GetChannel -and -not $session.GetChannel.Closed) { + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 409 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message "Session $($session.Id) already has an open GET stream.") + return + } + $Channel.Session = $session + $Channel.Era = 'Legacy' + if (-not (Start-McpHttpSse -State $State -Channel $Channel)) { return } + # A comment flushes the headers, so that the client sees the stream open at once. + if (-not (Write-McpSseChunk -State $State -Channel $Channel -Text ": stream open`n`n")) { return } + $session.GetChannel = $Channel + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Session $($session.Id): GET stream open." +} + +function Update-McpHttpSession { + <# + .SYNOPSIS + Ends legacy sessions that were idle longer than the idle timeout (no request, no open GET stream, nothing in flight). + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal housekeeping of the dispatcher loop.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + $timeout = [int] $State.Transport.SessionIdleTimeout + if ($timeout -le 0 -or $State.Sessions.Count -eq 0) { return } + $now = [datetime]::UtcNow + foreach ($session in @($State.Sessions.Values)) { + if (($now - $session.LastSeen).TotalSeconds -lt $timeout) { continue } + if ($null -ne $session.GetChannel -and -not $session.GetChannel.Closed) { continue } + $busy = $false + foreach ($key in $State.InFlight.Keys) { + if (([string] $key).StartsWith($session.KeyPrefix, [System.StringComparison]::Ordinal) -and -not $State.InFlight[$key].Responded) { $busy = $true; break } + } + if ($busy) { continue } + Close-McpLegacySession -State $State -Session $session -Reason "expired after $timeout s without requests" + } +} + function Invoke-McpHttpAccept { <# .SYNOPSIS @@ -633,7 +846,11 @@ function Invoke-McpHttpAccept { return } if ($request.HttpMethod -cne 'POST') { - $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 405 -Headers @{ Allow = 'POST' } -Json (New-McpHttpErrorJson -Code $invalidRequest -Message 'The MCP endpoint accepts POST only: revision 2026-07-28 has neither a GET stream nor sessions.') + if ($request.HttpMethod -cin @('GET', 'DELETE') -and -not [string]::IsNullOrWhiteSpace($request.Headers['Mcp-Session-Id']) -and (Test-McpHttpLegacy -State $State)) { + Invoke-McpHttpSessionRequest -State $State -Channel $channel + return + } + $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 405 -Headers @{ Allow = 'POST' } -Json (New-McpHttpErrorJson -Code $invalidRequest -Message 'The MCP endpoint accepts POST only: revision 2026-07-28 has neither a GET stream nor sessions (a legacy session opens its GET stream with its Mcp-Session-Id).') return } $contentType = $request.ContentType @@ -738,6 +955,7 @@ function Invoke-McpHttpDispatcherLoop { Send-McpOutboundQueue -State $State Update-McpInFlightRequest -State $State Update-McpHttpChannel -State $State + Update-McpHttpSession -State $State if ($State.Stopping) { break } if ($server.State.StopRequested) { if ($State.Listeners.Count -gt 0) { Close-McpAllListener -State $State } diff --git a/src/Public/Start-McpServer.ps1 b/src/Public/Start-McpServer.ps1 index 2ea9dad..f80cb54 100644 --- a/src/Public/Start-McpServer.ps1 +++ b/src/Public/Start-McpServer.ps1 @@ -11,7 +11,13 @@ function Start-McpServer { POST carries one JSON-RPC request or notification with the request metadata headers of revision 2026-07-28; the response is a single JSON object, or a request-scoped SSE stream when the request asks for progress or log notifications. GET and DELETE answer 405, unknown methods 404, header, version - and capability violations 400 with the JSON-RPC error codes of the specification. The Origin header + and capability violations 400 with the JSON-RPC error codes of the specification. + + A server with legacy revisions (the default, see New-McpServer -SupportedVersions) also speaks the + Streamable HTTP of 2025-11-25 and 2025-06-18: initialize returns an Mcp-Session-Id, requests with that + header belong to the session, GET with it opens the session's stream (list-changed and resource-updated + notifications, server-initiated requests), DELETE ends the session, unknown or expired sessions answer + 404. Over stdio an initialize request opens one process-wide legacy session. The Origin header is validated (403): by default only loopback origins and the server's own origin are accepted. Bind to 127.0.0.1 unless the server is meant to be reachable from other machines, and put TLS and authentication in front of it (a reverse proxy, or on Windows an http.sys certificate binding). @@ -34,6 +40,11 @@ function Start-McpServer { .PARAMETER KeepAliveSeconds Seconds between SSE keep-alive comments on open response streams; a failed keep-alive means the client closed the stream, which cancels the request (default: 5; 0 disables keep-alives). + .PARAMETER SessionIdleTimeoutSeconds + Legacy sessions over HTTP: seconds without a request after which a session without an open GET stream + ends (default: 1800; 0 keeps sessions until DELETE or shutdown). + .PARAMETER MaxSessions + Legacy sessions over HTTP: the maximum number of open sessions; initialize beyond it answers 503 (default: 100). .PARAMETER Endpoint The server end of an in-memory transport pair (internal use by Connect-McpServer). .PARAMETER ShutdownGraceSeconds @@ -63,6 +74,12 @@ function Start-McpServer { [ValidateRange(0, 3600)] [int] $KeepAliveSeconds = 5, + [ValidateRange(0, 604800)] + [int] $SessionIdleTimeoutSeconds = 1800, + + [ValidateRange(1, 100000)] + [int] $MaxSessions = 100, + [hashtable] $Endpoint, [ValidateRange(0, 3600)] @@ -80,7 +97,7 @@ function Start-McpServer { if (-not $PSCmdlet.ShouldProcess("server '$($target.Name)' on $where", 'Start')) { return } $transportObject = switch ($Transport) { 'Stdio' { New-McpStdioServerTransport } - 'Http' { New-McpHttpServerTransport -Url $Url -AllowedOrigins $AllowedOrigins -MaxBodyBytes $MaxBodyBytes -KeepAliveSeconds $KeepAliveSeconds } + 'Http' { New-McpHttpServerTransport -Url $Url -AllowedOrigins $AllowedOrigins -MaxBodyBytes $MaxBodyBytes -KeepAliveSeconds $KeepAliveSeconds -SessionIdleTimeoutSeconds $SessionIdleTimeoutSeconds -MaxSessions $MaxSessions } default { $Endpoint } } Invoke-McpDispatcher -Server $target -Transport $transportObject -ShutdownGraceSeconds $ShutdownGraceSeconds diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1 index c3eef2c..c0ad26b 100644 --- a/tests/Integration/HttpServer.Tests.ps1 +++ b/tests/Integration/HttpServer.Tests.ps1 @@ -211,8 +211,9 @@ Describe 'Raw Streamable HTTP behaviour' -Tag 'Integration' { $noMeta.Status | Should -Be 400 $noMeta.Json['error']['code'] | Should -Be -32602 $noMeta.Json['id'] | Should -Be 3 - # Methods of the legacy revisions exist only in a legacy session (after initialize). - foreach ($method in 'ping', 'logging/setLevel', 'resources/subscribe', 'nothing/here') { + # Methods of the legacy revisions exist only in a legacy session: a modern request (with _meta) for them, + # initialize included, is a request for a removed method. + foreach ($method in 'initialize', 'ping', 'logging/setLevel', 'resources/subscribe', 'nothing/here') { $response = Send-Raw -Body "{`"jsonrpc`":`"2.0`",`"id`":4,`"method`":`"$method`",`"params`":{$($script:meta)}}" -Headers @{ 'Mcp-Method' = $method } $response.Status | Should -Be 404 $response.Json['error']['code'] | Should -Be -32601 diff --git a/tests/Integration/LegacyHttp.Tests.ps1 b/tests/Integration/LegacyHttp.Tests.ps1 new file mode 100644 index 0000000..4ae722d --- /dev/null +++ b/tests/Integration/LegacyHttp.Tests.ps1 @@ -0,0 +1,250 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseCorrectCasing', '', Justification = 'PSScriptAnalyzer attributes -ScriptBlock of commands nested in BeforeAll to BeforeAll itself.')] +param() + +# Legacy sessions of a dual-era server over Streamable HTTP, on the wire: Mcp-Session-Id, the GET stream, DELETE, +# server-initiated requests on the POST stream, era-aware status codes, session limits and expiry, and modern +# requests next to legacy sessions on the same endpoint. + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force + + $script:server = New-McpServer -Name 'legacy-http' -Version '1.0.0' -RequestTimeoutSeconds 30 + Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $script:server + Register-McpTool -Name 'slow' -ScriptBlock { param([string] $Text) Start-Sleep -Milliseconds 700; $Text } -Server $script:server + Register-McpTool -Name 'ask' -ScriptBlock { + param($Context) + $answer = Request-McpElicitation -Context $Context -Key 'name' -Message 'Your name?' -Schema @{ name = @{ type = 'string' } } + "Hello, $($answer.Content.name)!" + } -Server $script:server + Register-McpTool -Name 'chatty' -ScriptBlock { + param($Context) + Write-McpLog -Context $Context -Level info -Message 'one' + Write-McpLog -Context $Context -Level warning -Message 'two' + 'logged' + } -Server $script:server + Register-McpResource -Uri 'test://watched' -Name 'watched' -Content 'w' -Server $script:server + $script:handle = Start-McpTestHttpServer -Server $script:server -Parameters @{ KeepAliveSeconds = 1 } + $script:url = $script:handle.Url + + function script:Send-Legacy { + param([string] $Body, [string] $SessionId, [hashtable] $Headers = @{}, [string] $Method = 'POST', [string] $Url = $script:url) + $all = @{ 'Accept' = 'application/json, text/event-stream' } + if ($SessionId) { $all['Mcp-Session-Id'] = $SessionId; $all['MCP-Protocol-Version'] = '2025-11-25' } + foreach ($key in $Headers.Keys) { + if ($null -eq $Headers[$key]) { $all.Remove($key) } else { $all[$key] = $Headers[$key] } + } + Invoke-McpRawHttp -Url $Url -Body $Body -Headers $all -Method $Method + } + + function script:Open-Legacy { + param([string] $Url = $script:url, [string] $Version = '2025-11-25', [string] $Capabilities = '{}') + $answer = Send-Legacy -Url $Url -Body "{`"jsonrpc`":`"2.0`",`"id`":0,`"method`":`"initialize`",`"params`":{`"protocolVersion`":`"$Version`",`"capabilities`":$Capabilities,`"clientInfo`":{`"name`":`"raw`",`"version`":`"1`"}}}" + $answer.Status | Should -Be 200 + $sessionId = $answer.Headers['Mcp-Session-Id'] + $sessionId | Should -Not -BeNullOrEmpty + (Send-Legacy -Url $Url -SessionId $sessionId -Body '{"jsonrpc":"2.0","method":"notifications/initialized"}').Status | Should -Be 202 + @{ Id = $sessionId; Result = $answer.Json['result'] } + } + + function script:Open-Stream { + param([string] $Method, [string] $SessionId, [string] $Body, [string] $Url = $script:url) + $handler = [System.Net.Http.SocketsHttpHandler]::new() + $handler.UseProxy = $false + $client = [System.Net.Http.HttpClient]::new($handler) + $request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::new($Method), $Url) + if ($Body) { $request.Content = [System.Net.Http.StringContent]::new($Body, [System.Text.Encoding]::UTF8, 'application/json') } + $null = $request.Headers.TryAddWithoutValidation('Accept', $(if ($Method -eq 'GET') { 'text/event-stream' } else { 'application/json, text/event-stream' })) + $null = $request.Headers.TryAddWithoutValidation('Mcp-Session-Id', $SessionId) + $null = $request.Headers.TryAddWithoutValidation('MCP-Protocol-Version', '2025-11-25') + $response = $client.SendAsync($request, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult() + $sse = $null + if ($response.Content.Headers.ContentType -and $response.Content.Headers.ContentType.MediaType -eq 'text/event-stream') { + $sse = Invoke-McpInModule { param($s) New-McpSseReader -Stream $s } -Parameters @{ s = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult() } + } + @{ Client = $client; Response = $response; Sse = $sse; Status = [int] $response.StatusCode } + } + + function script:Receive-StreamMessage { + param([hashtable] $Stream, [int] $TimeoutMs = 10000) + $deadline = [datetime]::UtcNow.AddMilliseconds($TimeoutMs) + while ([datetime]::UtcNow -lt $deadline) { + $received = Invoke-McpInModule { param($s) Receive-McpSseEvent -Sse $s -TimeoutMs 250 } -Parameters @{ s = $Stream.Sse } + if ($received.Status -eq 'Eof') { return $null } + if ($received.Status -eq 'Event' -and $received.Data) { return Invoke-McpInModule { param($d) ConvertFrom-McpJson $d } -Parameters @{ d = $received.Data } } + } + $null + } + + function script:Close-Stream { + param([hashtable] $Stream) + $Stream.Response.Dispose() + $Stream.Client.Dispose() + } +} + +AfterAll { + if ($script:handle) { Stop-McpTestHttpServer -Handle $script:handle } +} + +Describe 'Legacy sessions over Streamable HTTP' -Tag 'Integration' { + It 'mints a session id on initialize and serves the session in the legacy shapes' { + $session = Open-Legacy + $session.Id | Should -Match '^[\x21-\x7E]+$' + $session.Result['protocolVersion'] | Should -Be '2025-11-25' + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'InitializeResult' -Instance $session.Result).IsValid | Should -BeTrue + + $list = Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' + $list.Status | Should -Be 200 + $list.Json['result'].Contains('resultType') | Should -BeFalse + @($list.Json['result']['tools'] | ForEach-Object { $_['name'] }) | Should -Contain 'echo' + + $call = Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"Text":"hi"}}}' + $call.Json['result']['content'][0]['text'] | Should -Be 'hi' + $call.Json['result'].Contains('resultType') | Should -BeFalse + + # Errors of a session are JSON-RPC responses with status 200: 404 would tell the client its session is gone. + $unknown = Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":3,"method":"nothing/here"}' + $unknown.Status | Should -Be 200 + $unknown.Json['error']['code'] | Should -Be -32601 + $missing = Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"test://nope"}}' + $missing.Status | Should -Be 200 + $missing.Json['error']['code'] | Should -Be -32002 + + $ping = Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":5,"method":"ping"}' -Headers @{ 'MCP-Protocol-Version' = $null } + $ping.Json['result'].Count | Should -Be 0 + (Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":6,"method":"ping"}' -Headers @{ 'MCP-Protocol-Version' = '1999-01-01' }).Status | Should -Be 400 + $unknownSession = Send-Legacy -SessionId 'no-such-session' -Body '{"jsonrpc":"2.0","id":7,"method":"ping"}' + $unknownSession.Status | Should -Be 404 + $unknownSession.Json['id'] | Should -Be 7 + # Without the session id the request is a modern one and fails the header validation of 2026-07-28. + (Send-Legacy -Body '{"jsonrpc":"2.0","id":8,"method":"tools/list"}').Status | Should -Be 400 + } + + It 'opens the GET stream of a session and delivers list changes and resource updates on it' { + $session = Open-Legacy + $stream = Open-Stream -Method GET -SessionId $session.Id + try { + $stream.Status | Should -Be 200 + $second = Open-Stream -Method GET -SessionId $session.Id + $second.Status | Should -Be 409 + Close-Stream -Stream $second + + $null = Send-McpToolListChanged -Server $script:server + $changed = Receive-StreamMessage -Stream $stream + $changed['method'] | Should -Be 'notifications/tools/list_changed' + + (Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":1,"method":"resources/subscribe","params":{"uri":"test://watched"}}').Json['result'].Count | Should -Be 0 + $null = Send-McpResourceUpdated -Server $script:server -Uri 'test://watched' + $updated = Receive-StreamMessage -Stream $stream + $updated['method'] | Should -Be 'notifications/resources/updated' + $updated['params']['uri'] | Should -Be 'test://watched' + (Test-McpSpecShape -Revision '2025-11-25' -Definition 'ResourceUpdatedNotification' -Instance $updated).IsValid | Should -BeTrue + } finally { + Close-Stream -Stream $stream + } + (Send-Legacy -SessionId $session.Id -Method DELETE -Body $null).Status | Should -Be 200 + } + + It 'sends server-initiated requests and log notifications on the POST stream and accepts the response with 202' { + $session = Open-Legacy -Capabilities '{"elicitation":{}}' + $stream = Open-Stream -Method POST -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"ask"}}' + try { + $stream.Status | Should -Be 200 + $request = Receive-StreamMessage -Stream $stream + $request['method'] | Should -Be 'elicitation/create' + $answer = Invoke-McpInModule { param($m) ConvertTo-McpJson -InputObject $m } -Parameters @{ m = [ordered]@{ jsonrpc = '2.0'; id = $request['id']; result = [ordered]@{ action = 'accept'; content = [ordered]@{ name = 'Grace' } } } } + (Send-Legacy -SessionId $session.Id -Body $answer).Status | Should -Be 202 + $final = Receive-StreamMessage -Stream $stream + $final['id'] | Should -Be 'a' + $final['result']['content'][0]['text'] | Should -Be 'Hello, Grace!' + } finally { + Close-Stream -Stream $stream + } + + (Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":1,"method":"logging/setLevel","params":{"level":"info"}}').Status | Should -Be 200 + $stream = Open-Stream -Method POST -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"chatty"}}' + try { + $messages = @(Receive-StreamMessage -Stream $stream; Receive-StreamMessage -Stream $stream; Receive-StreamMessage -Stream $stream) + @($messages[0..1] | ForEach-Object { $_['params']['data'] }) | Should -Be @('one', 'two') + $messages[2]['result']['content'][0]['text'] | Should -Be 'logged' + } finally { + Close-Stream -Stream $stream + } + } + + It 'ends a session on DELETE and answers its requests with 404 afterwards' { + $session = Open-Legacy + $stream = Open-Stream -Method GET -SessionId $session.Id + try { + (Send-Legacy -SessionId $session.Id -Method DELETE -Body $null).Status | Should -Be 200 + Receive-StreamMessage -Stream $stream -TimeoutMs 3000 | Should -BeNullOrEmpty + } finally { + Close-Stream -Stream $stream + } + (Send-Legacy -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":1,"method":"ping"}').Status | Should -Be 404 + (Send-Legacy -SessionId $session.Id -Method GET -Body $null).Status | Should -Be 404 + (Send-Legacy -SessionId $session.Id -Method DELETE -Body $null).Status | Should -Be 404 + # Without a session id GET and DELETE stay 405. + (Invoke-McpRawHttp -Url $script:url -Method GET -Body $null -Headers @{ Accept = 'text/event-stream' }).Status | Should -Be 405 + } + + It 'keeps request ids apart between sessions and the stateless core' { + $first = Open-Legacy + $second = Open-Legacy + $jobs = foreach ($target in @($first.Id, $second.Id, $null)) { + $body = if ($target) { '{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"slow","arguments":{"Text":"' + $target + '"}}}' } else { '{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"slow","arguments":{"Text":"modern"}}}' } + $headers = if ($target) { @{ Accept = 'application/json, text/event-stream'; 'Mcp-Session-Id' = $target } } else { @{ Accept = 'application/json, text/event-stream'; 'MCP-Protocol-Version' = '2026-07-28'; 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'slow' } } + $support = Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1' + $manifest = Get-McpBuiltModuleManifest + $url = $script:url + Start-ThreadJob -ScriptBlock { + Import-Module $using:support + Import-Module $using:manifest + Invoke-McpRawHttp -Url $using:url -Body $using:body -Headers $using:headers + } + } + $answers = @($jobs | Wait-Job -Timeout 30 | Receive-Job) + $jobs | Remove-Job -Force + $answers.Count | Should -Be 3 + @($answers | ForEach-Object { $_.Status }) | Should -Be @(200, 200, 200) + $texts = @($answers | ForEach-Object { $_.Json['result']['content'][0]['text'] }) + $texts | Should -Contain $first.Id + $texts | Should -Contain $second.Id + $texts | Should -Contain 'modern' + } +} + +Describe 'Session limits' -Tag 'Integration' { + It 'refuses sessions beyond -MaxSessions and ends idle sessions after -SessionIdleTimeoutSeconds' { + $server = New-McpServer -Name 'limits' -Version '1' + Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $server + $handle = Start-McpTestHttpServer -Server $server -Parameters @{ MaxSessions = 1; SessionIdleTimeoutSeconds = 1 } + try { + $session = Open-Legacy -Url $handle.Url + $refused = Send-Legacy -Url $handle.Url -Body '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"raw","version":"1"}}}' + $refused.Status | Should -Be 503 + Start-Sleep -Seconds 3 + (Send-Legacy -Url $handle.Url -SessionId $session.Id -Body '{"jsonrpc":"2.0","id":1,"method":"ping"}').Status | Should -Be 404 + $null = Open-Legacy -Url $handle.Url + } finally { + Stop-McpTestHttpServer -Handle $handle + } + } + + It 'keeps a modern-only server free of sessions' { + $server = New-McpServer -Name 'modern' -Version '1' -SupportedVersions '2026-07-28' + $handle = Start-McpTestHttpServer -Server $server + try { + $answer = Send-Legacy -Url $handle.Url -Body '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"raw","version":"1"}}}' + $answer.Status | Should -Be 400 + $answer.Json['error']['code'] | Should -Be -32022 + $answer.Json['error']['data']['supported'] | Should -Be @('2026-07-28') + $answer.Headers.ContainsKey('Mcp-Session-Id') | Should -BeFalse + (Invoke-McpRawHttp -Url $handle.Url -Method GET -Body $null -Headers @{ Accept = 'text/event-stream'; 'Mcp-Session-Id' = 'x' }).Status | Should -Be 405 + (Invoke-McpRawHttp -Url $handle.Url -Method DELETE -Body $null -Headers @{ 'Mcp-Session-Id' = 'x' }).Status | Should -Be 405 + } finally { + Stop-McpTestHttpServer -Handle $handle + } + } +} diff --git a/tests/Unit/Era.Tests.ps1 b/tests/Unit/Era.Tests.ps1 index 3674161..2d5e942 100644 --- a/tests/Unit/Era.Tests.ps1 +++ b/tests/Unit/Era.Tests.ps1 @@ -13,7 +13,8 @@ Describe 'Era selection' { It 'chooses for (session: , line session: , HTTP: , modern _meta: )' -ForEach @( @{ Method = 'initialize'; HasSession = $false; HasLineSession = $false; Http = $false; Modern = $false; Expected = 'Legacy' } - @{ Method = 'initialize'; HasSession = $false; HasLineSession = $false; Http = $true; Modern = $true; Expected = 'Legacy' } + @{ Method = 'initialize'; HasSession = $false; HasLineSession = $false; Http = $true; Modern = $true; Expected = 'Modern' } + @{ Method = 'initialize'; HasSession = $false; HasLineSession = $false; Http = $true; Modern = $false; Expected = 'Legacy' } @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $false; Http = $false; Modern = $true; Expected = 'Modern' } @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $false; Http = $false; Modern = $false; Expected = 'Modern' } @{ Method = 'tools/list'; HasSession = $false; HasLineSession = $true; Http = $false; Modern = $false; Expected = 'Legacy' } diff --git a/tests/Unit/Header.Tests.ps1 b/tests/Unit/Header.Tests.ps1 index 319089a..8234516 100644 --- a/tests/Unit/Header.Tests.ps1 +++ b/tests/Unit/Header.Tests.ps1 @@ -198,6 +198,18 @@ Describe 'HTTP status codes and Origin validation' { Invoke-McpInModule { param($c) Get-McpHttpStatusCode -ErrorCode $c } -Parameters @{ c = $Code } | Should -Be $Expected } + It 'maps the errors of a legacy session to 200 except malformed messages' -TestCases @( + @{ Code = $null; Expected = 200 } + @{ Code = -32700; Expected = 400 } + @{ Code = -32600; Expected = 400 } + @{ Code = -32602; Expected = 200 } + @{ Code = -32601; Expected = 200 } + @{ Code = -32002; Expected = 200 } + @{ Code = -32603; Expected = 200 } + ) { + Invoke-McpInModule { param($c) Get-McpHttpStatusCode -ErrorCode $c -Era Legacy } -Parameters @{ c = $Code } | Should -Be $Expected + } + It 'accepts only Host headers that name the endpoint host and port' { $test = { param($u, $h) Invoke-McpInModule { param($u, $h) Test-McpHttpHost -Transport @{ Url = [uri] $u } -HostHeader $h } -Parameters @{ u = $u; h = $h } } & $test 'http://127.0.0.1:8080/mcp/' '127.0.0.1:8080' | Should -BeTrue From 474fe5a1e64897752d597304023eec4a6dd76a40 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:53:24 +0000 Subject: [PATCH 3/4] M5 client: era detection, legacy lifecycle and SSE resumption Connect-McpServer -Era Auto (default) probes with server/discover and falls back to the initialize handshake when the answer is neither a DiscoverResult nor an error only revision 2026-07-28 has (-32020, -32021, -32022), or when no answer arrives within five seconds; -Era Modern and -Era Legacy skip the detection. The era of an HTTP endpoint is remembered for later connections of the process. A legacy version given with -ProtocolVersion is requested in initialize. A legacy session sends no per-request _meta or headers of 2026-07-28 but the Mcp-Session-Id and the negotiated MCP-Protocol-Version, answers the server's elicitation, sampling, roots and ping requests with the existing callbacks (on stdio, on response streams and on the GET stream), sets the log level with logging/setLevel (new Set-McpLogLevel for both eras), maps subscriptions to unsolicited notifications and resources/subscribe with a GET stream reader over HTTP, initializes a new session after HTTP 404, resumes a response stream that ends before its response with GET and Last-Event-ID after the announced retry time, and sends DELETE on disconnect. 2025-03-26 is accepted from servers. Tests cover the compatibility matrix of client and server eras in memory, the legacy session over stdio, HTTP and in memory, and resumption against a mock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rvihdz4S9tqxJNrZGrX3qD --- src/Private/Client.ps1 | 19 +- src/Private/ClientLegacy.ps1 | 494 +++++++++++++++++++++++ src/Private/ClientSubscriptions.ps1 | 23 +- src/Private/HttpClient.ps1 | 192 ++++++++- src/Public/Connect-McpServer.ps1 | 128 +++--- src/Public/Disconnect-McpServer.ps1 | 3 + src/Public/Get-McpServerInfo.ps1 | 2 + src/Public/Get-McpTool.ps1 | 2 +- src/Public/Invoke-McpTool.ps1 | 2 +- src/Public/Register-McpSubscription.ps1 | 26 ++ src/Public/Set-McpLogLevel.ps1 | 29 ++ tests/Integration/LegacyClient.Tests.ps1 | 329 +++++++++++++++ tests/Unit/Header.Tests.ps1 | 22 +- 13 files changed, 1189 insertions(+), 82 deletions(-) create mode 100644 src/Private/ClientLegacy.ps1 create mode 100644 src/Public/Set-McpLogLevel.ps1 create mode 100644 tests/Integration/LegacyClient.Tests.ps1 diff --git a/src/Private/Client.ps1 b/src/Private/Client.ps1 index 9084fde..549eeba 100644 --- a/src/Private/Client.ps1 +++ b/src/Private/Client.ps1 @@ -69,6 +69,11 @@ function New-McpClientRequestMeta { ) $meta = [ordered]@{} + if ($Session.Era -eq 'Legacy') { + # A legacy session negotiated version and capabilities in initialize; the log level is set with logging/setLevel. + if ($null -ne $ProgressToken) { $meta[$script:McpMetaKey.ProgressToken] = $ProgressToken } + return $meta + } $meta[$script:McpMetaKey.ProtocolVersion] = $Session.ProtocolVersion $meta[$script:McpMetaKey.ClientCapabilities] = $Session.ClientCapabilities if ($null -ne $Session.ClientInfo) { $meta[$script:McpMetaKey.ClientInfo] = $Session.ClientInfo } @@ -129,6 +134,9 @@ function Invoke-McpClientRequest { [hashtable] $Headers ) + if ($Session.Era -eq 'Legacy' -and $null -ne $LogLevel -and $Method -notin @('initialize', 'logging/setLevel')) { + Set-McpLegacyClientLogLevel -Session $Session -Level $LogLevel + } if ($Session.Transport.Kind -eq 'Http') { return Invoke-McpHttpClientRequest -Session $Session -Method $Method -Params $Params -OnProgress $OnProgress -LogLevel $LogLevel -TimeoutMs $TimeoutMs -Headers $Headers } @@ -137,7 +145,8 @@ function Invoke-McpClientRequest { $Session.NextId = $id + 1 $progressToken = if ($OnProgress) { "p-$id" } else { $null } $requestParams = [ordered]@{} - $requestParams['_meta'] = New-McpClientRequestMeta -Session $Session -ProgressToken $progressToken -LogLevel $LogLevel + $meta = New-McpClientRequestMeta -Session $Session -ProgressToken $progressToken -LogLevel $LogLevel + if ($meta.Count -gt 0) { $requestParams['_meta'] = $meta } if ($null -ne $Params) { foreach ($key in $Params.Keys) { if ([string] $key -eq '_meta') { continue } @@ -189,7 +198,7 @@ function Invoke-McpClientRequest { Invoke-McpClientNotificationHandler -Session $Session -Message $message -ProgressToken $progressToken -OnProgress $OnProgress } 'Request' { - Write-Warning "Ignoring a request '$($message['method'])' from the server: servers do not send requests in protocol version $($Session.ProtocolVersion)." + Invoke-McpClientServerRequest -Session $Session -Message $message -RequestMethod $Method } default { Write-Warning 'Ignoring an invalid JSON-RPC message from the server.' @@ -222,6 +231,11 @@ function Invoke-McpClientNotificationHandler { return } } + if ($Session.Era -eq 'Legacy' -and ($method -in @($script:McpListenFilterFlags.Values) -or $method -eq 'notifications/resources/updated')) { + # Legacy servers send list changes and resource updates unsolicited, without a subscription id. + Send-McpLegacyNotificationToSubscription -Session $Session -Message $Message + return + } switch ($method) { 'notifications/cancelled' { # The server ended a subscription (servers do not cancel anything else in this revision). @@ -798,6 +812,7 @@ function ConvertTo-McpInputRequestObject { [System.Collections.IDictionary] $Request, [Parameter(Mandatory)] + [AllowEmptyString()] [string] $RequestMethod ) diff --git a/src/Private/ClientLegacy.ps1 b/src/Private/ClientLegacy.ps1 new file mode 100644 index 0000000..6ade53b --- /dev/null +++ b/src/Private/ClientLegacy.ps1 @@ -0,0 +1,494 @@ +# Client side of the dual era: the detection of the server's era (the server/discover probe over stdio and in +# memory, the modern POST whose answer is inspected over Streamable HTTP), the initialize handshake with the +# servers of 2025-11-25, 2025-06-18 and 2025-03-26, answers to server-initiated requests (elicitation, sampling +# and roots through the session's callbacks, ping), resumption of an interrupted SSE response stream with GET +# and Last-Event-ID, the session's GET stream, and DELETE when the session ends. The request path in +# Client.ps1 and HttpClient.ps1 consults Session.Era for the per-request metadata and headers. + +# The era of HTTP endpoints this process has talked to (keyed by URL), so that a second connection to a legacy +# server skips the probe. A failed handshake removes the entry. +$script:McpClientEraCache = [System.Collections.Concurrent.ConcurrentDictionary[string, string]]::new([System.StringComparer]::Ordinal) + +# The revisions whose initialize handshake the client speaks, newest first; 2025-03-26 is accepted from servers. +$script:McpClientLegacyVersions = @('2025-11-25', '2025-06-18', '2025-03-26') + +# Errors that only a server of revision 2026-07-28 sends: they identify a modern server (no fallback). +$script:McpModernOnlyErrorCodes = @(-32020, -32021, -32022) + +function Get-McpClientEraCacheKey { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session + ) + + if ($Session.Kind -ne 'Http') { return $null } + $Session.Transport.Url.AbsoluteUri +} + +function Test-McpDiscoverResult { + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Result + ) + + $Result -is [System.Collections.IDictionary] -and $Result['supportedVersions'] -is [System.Collections.IList] -and $Result['capabilities'] -is [System.Collections.IDictionary] +} + +function Connect-McpClientModern { + <# + .SYNOPSIS + The modern start of a session: server/discover, with one retry at a mutual version after -32022; returns $null when the answer shows a legacy server (Auto only). + #> + [CmdletBinding()] + [OutputType([System.Collections.IDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [int] $TimeoutMs, + + # Auto: an answer that is not a DiscoverResult or a modern error means a legacy server ($null). + [switch] $Probe + ) + + $discover = $null + try { + $discover = Invoke-McpClientRequest -Session $Session -Method 'server/discover' -TimeoutMs $TimeoutMs + } catch [McpProtocolException] { + $exception = $_.Exception + if ($exception.Code -eq $script:McpErrorCode.UnsupportedProtocolVersion -and $exception.Data -is [System.Collections.IDictionary] -and $exception.Data.Contains('supported')) { + $mutual = @($exception.Data['supported'] | Where-Object { $_ -in $script:McpModernProtocolVersions }) + if ($mutual.Count -eq 0) { + throw [System.InvalidOperationException]::new("The server supports protocol version(s) $(@($exception.Data['supported']) -join ', '), none of which this client speaks ($($script:McpModernProtocolVersions -join ', ')).") + } + $Session.ProtocolVersion = $mutual[0] + $discover = Invoke-McpClientRequest -Session $Session -Method 'server/discover' -TimeoutMs $TimeoutMs + } elseif ($Probe -and $exception.Code -notin $script:McpModernOnlyErrorCodes) { + # Any other error is how a legacy server answers an unknown method before initialize. + Write-Verbose "server/discover failed with $($exception.Code) ($($exception.Message)); falling back to the initialize handshake." + return $null + } else { + throw [System.InvalidOperationException]::new("server/discover failed with $($exception.Code): $($exception.Message)", $exception) + } + } catch [System.TimeoutException] { + if (-not $Probe) { throw } + Write-Verbose 'No answer to server/discover in time; falling back to the initialize handshake.' + return $null + } catch [System.Net.Http.HttpRequestException] { + # A response without a JSON-RPC body (an empty 400, an HTML error page) comes from a legacy server. + if (-not $Probe) { throw } + Write-Verbose "server/discover failed: $($_.Exception.Message); falling back to the initialize handshake." + return $null + } + if (-not (Test-McpDiscoverResult -Result $discover)) { + if ($Probe) { + Write-Verbose 'The answer to server/discover is not a DiscoverResult; falling back to the initialize handshake.' + return $null + } + throw [System.InvalidOperationException]::new('The server/discover result is not a DiscoverResult.') + } + $supported = @($discover['supportedVersions']) + if ($Session.ProtocolVersion -notin $supported) { + $mutual = @($supported | Where-Object { $_ -in $script:McpModernProtocolVersions }) + if ($mutual.Count -eq 0) { + throw [System.InvalidOperationException]::new("The server supports protocol version(s) $($supported -join ', '), none of which this client speaks.") + } + $Session.ProtocolVersion = $mutual[0] + } + $discover +} + +function ConvertTo-McpLegacyClientCapability { + <# + .SYNOPSIS + The client capabilities of an initialize request: those of the session, in the shape of the negotiated revision. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Capabilities, + + [Parameter(Mandatory)] + [string] $ProtocolVersion + ) + + $legacy = [ordered]@{} + foreach ($key in $Capabilities.Keys) { + # Extensions are negotiated in revision 2026-07-28 only. + if ([string] $key -eq 'extensions') { continue } + $legacy[[string] $key] = $Capabilities[$key] + } + if ($legacy.Contains('elicitation') -and $ProtocolVersion -ne '2025-11-25') { + # Before 2025-11-25 elicitation had no modes (form only). + $legacy['elicitation'] = [ordered]@{} + } + if ($legacy.Contains('roots')) { + $legacy['roots'] = [ordered]@{ listChanged = $false } + } + $legacy +} + +function ConvertTo-McpLegacyServerInfoObject { + <# + .SYNOPSIS + The Mcp.ServerInfo of a legacy session, from its InitializeResult. + #> + [CmdletBinding()] + [OutputType('Mcp.ServerInfo')] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $InitializeResult + ) + + $info = Get-McpWireValue -Object $InitializeResult -Key 'serverInfo' + [pscustomobject]@{ + PSTypeName = 'Mcp.ServerInfo' + Name = Get-McpWireValue -Object $info -Key 'name' + Version = Get-McpWireValue -Object $info -Key 'version' + Title = Get-McpWireValue -Object $info -Key 'title' + Description = Get-McpWireValue -Object $info -Key 'description' + WebsiteUrl = Get-McpWireValue -Object $info -Key 'websiteUrl' + Icons = Get-McpWireValue -Object $info -Key 'icons' + ProtocolVersion = [string] $InitializeResult['protocolVersion'] + SupportedVersions = @([string] $InitializeResult['protocolVersion']) + Capabilities = Get-McpWireValue -Object $InitializeResult -Key 'capabilities' + Instructions = Get-McpWireValue -Object $InitializeResult -Key 'instructions' + TtlMs = $null + CacheScope = $null + Raw = $InitializeResult + } +} + +function Initialize-McpLegacyClient { + <# + .SYNOPSIS + The initialize handshake of the legacy revisions: negotiates the version, keeps the server info, sends notifications/initialized and sets the session's log level. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [int] $TimeoutMs + ) + + $requested = if ($Session.PreferredLegacyVersion) { $Session.PreferredLegacyVersion } else { $script:McpClientLegacyVersions[0] } + $Session.Era = 'Legacy' + $Session.SessionId = $null + $Session.InitializeResult = $null + $Session.ProtocolVersion = $requested + $params = [ordered]@{ + protocolVersion = $requested + capabilities = ConvertTo-McpLegacyClientCapability -Capabilities $Session.ClientCapabilities -ProtocolVersion $requested + clientInfo = $Session.ClientInfo + } + $result = Invoke-McpClientRequest -Session $Session -Method 'initialize' -Params $params -TimeoutMs $TimeoutMs + if ($result -isnot [System.Collections.IDictionary] -or $result['protocolVersion'] -isnot [string] -or $result['capabilities'] -isnot [System.Collections.IDictionary]) { + throw [System.InvalidOperationException]::new('The initialize result is not an InitializeResult.') + } + $negotiated = [string] $result['protocolVersion'] + if ($negotiated -notin $script:McpClientLegacyVersions) { + throw [System.InvalidOperationException]::new("The server answered initialize with protocol version '$negotiated', which this client does not speak ($($script:McpClientLegacyVersions -join ', ')).") + } + $Session.ProtocolVersion = $negotiated + $Session.InitializeResult = $result + $Session.ServerInfo = ConvertTo-McpLegacyServerInfoObject -InitializeResult $result + $Session.Name = $Session.ServerInfo.Name + Send-McpClientNotification -Session $Session -Method 'notifications/initialized' + $Session.LegacyLogLevel = $null + if ($null -ne $Session.LogLevel) { Set-McpLegacyClientLogLevel -Session $Session -Level $Session.LogLevel } +} + +function Set-McpLegacyClientLogLevel { + <# + .SYNOPSIS + Sends logging/setLevel when the level differs from the one the session last set and the server declares logging. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller owns the ShouldProcess decision.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [object] $Level + ) + + $name = (ConvertTo-McpLoggingLevel -Level $Level).ToString().ToLowerInvariant() + if ($Session.LegacyLogLevel -ceq $name) { return } + $capabilities = if ($null -ne $Session.InitializeResult) { $Session.InitializeResult['capabilities'] } else { $null } + if (-not (Test-McpCapabilityPath -Capabilities $capabilities -Path 'logging')) { + Write-Verbose "The server does not declare the logging capability; the log level '$name' is not sent." + return + } + $null = Invoke-McpClientRequest -Session $Session -Method 'logging/setLevel' -Params ([ordered]@{ level = $name }) + $Session.LegacyLogLevel = $name +} + +function Initialize-McpClientSession { + <# + .SYNOPSIS + Starts a session in the requested era (Auto detects it): the modern server/discover or the legacy initialize handshake. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [ValidateSet('Auto', 'Modern', 'Legacy')] + [string] $Era, + + [Parameter(Mandatory)] + [int] $ConnectTimeoutMs + ) + + $cacheKey = Get-McpClientEraCacheKey -Session $Session + $cached = $null + if ($Era -eq 'Auto' -and $null -ne $cacheKey) { $null = $script:McpClientEraCache.TryGetValue($cacheKey, [ref] $cached) } + if ($Era -eq 'Legacy' -or $cached -eq 'Legacy') { + try { + Initialize-McpLegacyClient -Session $Session -TimeoutMs $ConnectTimeoutMs + if ($null -ne $cacheKey) { $script:McpClientEraCache[$cacheKey] = 'Legacy' } + return + } catch { + $removed = $null + if ($null -ne $cacheKey) { $null = $script:McpClientEraCache.TryRemove($cacheKey, [ref] $removed) } + # A cached assumption that no longer holds is probed again; an explicit -Era Legacy fails. + if ($Era -eq 'Legacy') { throw } + $Session.Era = 'Modern' + $Session.ProtocolVersion = $Session.PreferredModernVersion + } + } + $probeTimeout = if ($Era -eq 'Auto') { [math]::Min($ConnectTimeoutMs, 5000) } else { $ConnectTimeoutMs } + $discover = Connect-McpClientModern -Session $Session -TimeoutMs $probeTimeout -Probe:($Era -eq 'Auto') + if ($null -eq $discover) { + Initialize-McpLegacyClient -Session $Session -TimeoutMs $ConnectTimeoutMs + if ($null -ne $cacheKey) { $script:McpClientEraCache[$cacheKey] = 'Legacy' } + return + } + $Session.Era = 'Modern' + $Session.ServerInfo = ConvertTo-McpServerInfoObject -DiscoverResult $discover -ProtocolVersion $Session.ProtocolVersion + $Session.Name = $Session.ServerInfo.Name + Set-McpClientCacheEntry -Session $Session -Key 'server/discover' -Value $Session.ServerInfo -CacheHint (Get-McpResultCacheHint -Result $discover) + if ($null -ne $cacheKey) { $script:McpClientEraCache[$cacheKey] = 'Modern' } +} + +function Invoke-McpClientServerRequest { + <# + .SYNOPSIS + Answers a request of a legacy server: ping, and elicitation, sampling and roots through the session's callbacks; sends the response back. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message, + + # The client request during which the server asked (empty on the GET stream). + [AllowEmptyString()] + [string] $RequestMethod = '' + ) + + $id = $Message['id'] + $method = [string] $Message['method'] + $response = $null + if ($Session.Era -ne 'Legacy') { + Write-Warning "Ignoring a request '$method' from the server: servers do not send requests in protocol version $($Session.ProtocolVersion)." + return + } + try { + $result = switch ($method) { + 'ping' { [ordered]@{} } + { $_ -in @('elicitation/create', 'sampling/createMessage', 'roots/list') } { + $request = ConvertTo-McpInputRequestObject -Key ([string] $id) -Request $Message -RequestMethod $RequestMethod + Invoke-McpClientInputCallback -Session $Session -Request $request + } + default { throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "Method not found: $method") } + } + $response = New-McpResultResponse -Id $id -Result $result + } catch [McpProtocolException] { + $response = New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $_.Exception.Code -Message $_.Exception.Message) + } catch [System.InvalidOperationException] { + # No callback for this kind of request: the client does not offer it. + $response = New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.MethodNotFound -Message $_.Exception.Message) + } catch { + $response = New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message "The client failed to answer $method : $($_.Exception.Message)") + } + $json = ConvertTo-McpJson -InputObject $response + try { + if ($Session.Transport.Kind -eq 'Http') { + Send-McpHttpClientMessage -Session $Session -Json $json -Method $method + } else { + Send-McpTransportLine -Transport $Session.Transport -Line $json + } + } catch { + Write-Warning "Sending the answer to the server's $method request failed: $($_.Exception.Message)" + } +} + +function Send-McpLegacyNotificationToSubscription { + <# + .SYNOPSIS + Hands an unsolicited notification of a legacy server to the session's subscriptions that asked for it; invalidates the cache in any case. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message + ) + + $method = [string] $Message['method'] + $params = if ($Message['params'] -is [System.Collections.IDictionary]) { $Message['params'] } else { $null } + $delivered = $false + foreach ($subscription in @($Session.Subscriptions.Values)) { + if ($subscription.State -ne 'Open' -or $null -eq $subscription.Honoured) { continue } + if (-not (Test-McpListenerMatch -Honoured $subscription.Honoured -Method $method -Params $params)) { continue } + Receive-McpSubscriptionNotification -Session $Session -Subscription $subscription -Message $Message + $delivered = $true + } + if (-not $delivered) { + # Invalidate the cache like a subscription would, and keep the notification on the session. + $scratch = [pscustomobject]@{ Id = $null; Action = $null; Notifications = [System.Collections.Generic.Queue[object]]::new(); State = 'Open'; Honoured = $null } + Receive-McpSubscriptionNotification -Session $Session -Subscription $scratch -Message $Message + $Session.Notifications.Enqueue($Message) + } +} + +function Invoke-McpHttpLegacyStreamLoop { + <# + .SYNOPSIS + Background loop of the GET stream of a legacy session: reads its events into the session inbox, reconnecting with Last-Event-ID; ends when the server refuses the stream (405). + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [hashtable] $Stream + ) + + $inbox = $Session.Inbox + $attempt = 0 + $lastEventId = $null + while (-not $Stream.StopRequested) { + $message = New-McpHttpGetMessage -Session $Session -LastEventId $lastEventId + $response = $null + try { + $sendTask = $Session.Transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $Stream.Cts.Token) + while (-not $sendTask.IsCompleted -and -not $Stream.StopRequested) { $null = $sendTask.Wait(250) } + if ($Stream.StopRequested) { break } + $failure = Get-McpTaskFailure -Task $sendTask + if ($null -ne $failure) { throw $failure } + $response = $sendTask.Result + $mediaType = if ($null -ne $response.Content.Headers.ContentType) { $response.Content.Headers.ContentType.MediaType } else { $null } + if (-not $response.IsSuccessStatusCode -or $mediaType -ne 'text/event-stream') { + $Stream.Status = "HTTP $([int] $response.StatusCode)" + break + } + $Stream.Status = 'Open' + $sse = New-McpSseReader -Stream ($response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) + try { + while (-not $Stream.StopRequested) { + $received = Receive-McpSseEvent -Sse $sse -TimeoutMs 250 + if ($received.Status -eq 'Timeout') { continue } + if ($received.Status -eq 'Eof') { break } + if ($null -ne $received.Id) { $lastEventId = $received.Id } + if ([string]::IsNullOrWhiteSpace($received.Data) -or ($null -ne $received.Event -and $received.Event -ne 'message')) { continue } + $attempt = 0 + $inbox.Enqueue(@{ Kind = 'Legacy'; Json = $received.Data }) + } + } finally { + try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } + } + } catch { + $Stream.Status = "failed: $($_.Exception.Message)" + } finally { + if ($null -ne $response) { try { $response.Dispose() } catch { Write-Debug 'Disposing the GET response failed.' } } + $message.Dispose() + } + if ($Stream.StopRequested) { break } + $attempt++ + if ($attempt -gt 5) { break } + $until = [datetime]::UtcNow.AddSeconds([math]::Min(16, [math]::Pow(2, $attempt - 1))) + while ([datetime]::UtcNow -lt $until -and -not $Stream.StopRequested) { Start-Sleep -Milliseconds 100 } + } + if ($Stream.Status -eq 'Open') { $Stream.Status = 'Closed' } +} + +function Start-McpLegacyClientStream { + <# + .SYNOPSIS + Opens the GET stream of a legacy HTTP session in the background (once per session). + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session + ) + + if ($Session.Kind -ne 'Http' -or $null -ne $Session.LegacyStream) { return } + $stream = @{ StopRequested = $false; Cts = [System.Threading.CancellationTokenSource]::new(); Status = 'Opening'; Reader = $null } + $stream.Reader = New-McpClientBackgroundRunspace -FunctionName 'Invoke-McpHttpLegacyStreamLoop' -Parameters @{ Session = $Session; Stream = $stream } + $Session.LegacyStream = $stream +} + +function Stop-McpLegacyClientStream { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session + ) + + $stream = $Session.LegacyStream + if ($null -eq $stream) { return } + $stream.StopRequested = $true + try { $stream.Cts.Cancel() } catch { Write-Debug 'Cancelling the GET stream failed.' } + Stop-McpClientBackgroundRunspace -Background $stream.Reader -TimeoutMs 5000 + try { $stream.Cts.Dispose() } catch { Write-Debug 'Disposing the token source failed.' } + $Session.LegacyStream = $null +} + +function Close-McpLegacyClientSession { + <# + .SYNOPSIS + Ends a legacy HTTP session: stops the GET stream and sends DELETE with the session id (a refusal is fine). + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller (Disconnect-McpServer) owns the ShouldProcess decision.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session + ) + + Stop-McpLegacyClientStream -Session $Session + if ($Session.Kind -ne 'Http' -or -not $Session.SessionId -or $Session.Transport.Closed) { return } + $message = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Delete, $Session.Transport.Url) + Add-McpHttpSessionHeader -Session $Session -Message $message + $cts = [System.Threading.CancellationTokenSource]::new() + try { + $task = $Session.Transport.Client.SendAsync($message, $cts.Token) + if (-not (Wait-McpTask -Task $task -Deadline ([datetime]::UtcNow.AddSeconds(5)))) { $cts.Cancel() } + elseif ($task.IsCompletedSuccessfully) { $task.Result.Dispose() } + } catch { + Write-Debug "DELETE of session $($Session.SessionId) failed: $($_.Exception.Message)" + } finally { + $cts.Dispose() + $message.Dispose() + } +} diff --git a/src/Private/ClientSubscriptions.ps1 b/src/Private/ClientSubscriptions.ps1 index b11e441..e447199 100644 --- a/src/Private/ClientSubscriptions.ps1 +++ b/src/Private/ClientSubscriptions.ps1 @@ -281,6 +281,11 @@ function Invoke-McpClientStrayMessage { Invoke-McpClientNotificationHandler -Session $Session -Message $Message return } + if ($kind -eq 'Request') { + # A request of a legacy server outside of a client request (the GET stream, or read by the pump). + Invoke-McpClientServerRequest -Session $Session -Message $Message + return + } if ($kind -notin @('Response', 'ErrorResponse')) { return } $subscription = Get-McpClientSubscriptionById -Session $Session -Id $(if ($Message.Contains('id')) { $Message['id'] } else { $null }) if ($null -eq $subscription) { @@ -341,6 +346,13 @@ function Invoke-McpClientEventPump { } $item = $null while ($Session.Inbox.TryDequeue([ref] $item)) { + if ($item.Kind -eq 'Legacy') { + # A message of the GET stream of a legacy session. + $message = $null + try { $message = ConvertFrom-McpJson -Json $item.Json } catch { $message = $null } + if ($message -is [System.Collections.IDictionary]) { Invoke-McpClientStrayMessage -Session $Session -Message $message } + continue + } $subscription = $Session.Subscriptions[[string] $item.Subscription] if ($null -eq $subscription) { continue } switch ($item.Kind) { @@ -388,7 +400,16 @@ function Close-McpClientSubscription { ) $Subscription.StopRequested = $true - if ($Session.Kind -eq 'Http') { + if ($Subscription.Legacy) { + # resources/unsubscribe for the URIs no other subscription of the session still needs. + $kept = @($Session.Subscriptions.Values | Where-Object { -not [object]::ReferenceEquals($_, $Subscription) -and $_.Honoured -is [System.Collections.IDictionary] -and $_.Honoured.Contains('resourceSubscriptions') } | ForEach-Object { $_.Honoured['resourceSubscriptions'] }) + if (-not $Session.Closed -and $Subscription.Honoured -is [System.Collections.IDictionary] -and $Subscription.Honoured.Contains('resourceSubscriptions')) { + foreach ($uri in $Subscription.Honoured['resourceSubscriptions']) { + if ($uri -cin $kept) { continue } + try { $null = Invoke-McpClientRequest -Session $Session -Method 'resources/unsubscribe' -Params ([ordered]@{ uri = $uri }) } catch { Write-Debug "resources/unsubscribe of $uri failed: $($_.Exception.Message)" } + } + } + } elseif ($Session.Kind -eq 'Http') { try { $Subscription.Cts.Cancel() } catch { Write-Debug 'Cancelling the listen request failed.' } Stop-McpClientBackgroundRunspace -Background $Subscription.Reader -TimeoutMs 5000 $Subscription.Reader = $null diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index 2d84574..7b2108a 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -3,6 +3,10 @@ # x-mcp-header annotated tool parameters), and responses read either as one JSON object or as a request-scoped # SSE stream whose notifications are dispatched while the final response is awaited. A timeout closes the # response stream, which is the cancellation signal of this transport. +# +# In a legacy session (ClientLegacy.ps1) requests carry Mcp-Session-Id and the negotiated MCP-Protocol-Version +# instead of the per-request headers, requests of the server on a response stream are answered with a POST, and +# a response stream that ends before the response is resumed with GET and Last-Event-ID. function New-McpHttpClientTransport { <# @@ -113,16 +117,21 @@ function New-McpSseReader { PendingRead = $null Data = [System.Collections.Generic.List[string]]::new() EventName = $null + # The last event id and the reconnection time (ms) the server announced, for resumption. + LastEventId = $null + Retry = $null + HasData = $false } } function Receive-McpSseEvent { <# .SYNOPSIS - Reads the next SSE event: a hashtable with Status (Event, Eof or Timeout), Data (the joined data lines) and Event (the event name). + Reads the next SSE event: a hashtable with Status (Event, Eof or Timeout), Data (the joined data lines), Event (the event name) and Id (the last event id). .DESCRIPTION - Comment lines (starting with ':') and the id and retry fields are ignored; an empty line dispatches the - event collected so far. The pending line read survives a timeout so that no bytes are lost. + Comment lines (starting with ':') are ignored; the id and retry fields are kept on the reader + (LastEventId, Retry) for resumption. An empty line dispatches the event collected so far, also an event + with an empty data line (a priming event). The pending line read survives a timeout so that no bytes are lost. #> [CmdletBinding()] [OutputType([hashtable])] @@ -154,14 +163,14 @@ function Receive-McpSseEvent { throw $failure } $line = $task.Result - if ($null -eq $line) { return @{ Status = 'Eof'; Data = $null; Event = $null } } + if ($null -eq $line) { return @{ Status = 'Eof'; Data = $null; Event = $null; Id = $Sse.LastEventId } } if ($line.Length -eq 0) { if ($Sse.Data.Count -eq 0) { $Sse.EventName = $null; continue } $data = $Sse.Data -join "`n" $name = $Sse.EventName $Sse.Data.Clear() $Sse.EventName = $null - return @{ Status = 'Event'; Data = $data; Event = $name } + return @{ Status = 'Event'; Data = $data; Event = $name; Id = $Sse.LastEventId } } if ($line[0] -eq ':') { continue } $colon = $line.IndexOf(':') @@ -174,6 +183,8 @@ function Receive-McpSseEvent { switch ($field) { 'data' { $Sse.Data.Add($value) } 'event' { $Sse.EventName = $value } + 'id' { if ($value.IndexOf([char] 0) -lt 0) { $Sse.LastEventId = $value } } + 'retry' { $retry = 0; if ([int]::TryParse($value, [ref] $retry) -and $retry -ge 0) { $Sse.Retry = $retry } } default { Write-Debug "Ignoring the SSE field '$field'." } } } @@ -271,6 +282,8 @@ function Receive-McpSseResponse { $failure = Get-McpTaskFailure -Task $streamTask if ($null -ne $failure) { throw [System.IO.IOException]::new("Opening the response stream of '$Method' (id $Id) failed: $($failure.Message)", $failure) } $sse = New-McpSseReader -Stream $streamTask.Result + $resumed = $null + $resumptions = 0 try { while ($true) { $remaining = ($Deadline - [datetime]::UtcNow).TotalMilliseconds @@ -281,8 +294,25 @@ function Receive-McpSseResponse { $received = Receive-McpSseEvent -Sse $sse -TimeoutMs ([int] [math]::Min(500, $remaining)) if ($received.Status -eq 'Timeout') { continue } if ($received.Status -eq 'Eof') { + # A legacy server may close the stream after announcing an event id and a retry time: the + # response then arrives on a GET stream opened with Last-Event-ID. + if ($Session.Era -eq 'Legacy' -and $null -ne $sse.LastEventId -and $resumptions -lt 3) { + $resumptions++ + $delay = if ($null -ne $sse.Retry) { [int] $sse.Retry } else { 1000 } + $until = [datetime]::UtcNow.AddMilliseconds($delay) + while ([datetime]::UtcNow -lt $until) { Start-Sleep -Milliseconds ([int] [math]::Max(1, [math]::Min(50, ($until - [datetime]::UtcNow).TotalMilliseconds))) } + try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } + if ($null -ne $resumed) { try { $resumed.Dispose() } catch { Write-Debug 'Disposing the resumed response failed.' } } + $resumed = Open-McpHttpResumedStream -Session $Session -LastEventId $sse.LastEventId -Deadline $Deadline -Cts $Cts -Method $Method -Id $Id + $retry = $sse.Retry + $sse = New-McpSseReader -Stream ($resumed.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) + $sse.Retry = $retry + continue + } throw [System.IO.IOException]::new("The server closed the response stream of '$Method' (id $Id) before the response arrived; the request may be re-issued with a new id.") } + # A priming event (an id with an empty data line) carries no message. + if ([string]::IsNullOrWhiteSpace($received.Data)) { continue } if ($null -ne $received.Event -and $received.Event -ne 'message') { Write-Debug "Ignoring an SSE event named '$($received.Event)'." continue @@ -311,7 +341,7 @@ function Receive-McpSseResponse { Invoke-McpClientNotificationHandler -Session $Session -Message $message -ProgressToken $ProgressToken -OnProgress $OnProgress } 'Request' { - Write-Warning "Ignoring a request '$($message['method'])' from the server: servers do not send requests in protocol version $($Session.ProtocolVersion)." + Invoke-McpClientServerRequest -Session $Session -Message $message -RequestMethod $Method } default { Write-Warning 'Ignoring an invalid JSON-RPC message on the response stream.' @@ -320,6 +350,101 @@ function Receive-McpSseResponse { } } finally { try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } + if ($null -ne $resumed) { try { $resumed.Dispose() } catch { Write-Debug 'Disposing the resumed response failed.' } } + } +} + +function Add-McpHttpSessionHeader { + <# + .SYNOPSIS + Adds the headers of a legacy session to a request: Mcp-Session-Id (when the server assigned one) and the negotiated MCP-Protocol-Version. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [System.Net.Http.HttpRequestMessage] $Message + ) + + if ($Session.SessionId) { $null = $Message.Headers.TryAddWithoutValidation('Mcp-Session-Id', $Session.SessionId) } + if ($null -ne $Session.InitializeResult) { $null = $Message.Headers.TryAddWithoutValidation('MCP-Protocol-Version', $Session.ProtocolVersion) } + foreach ($key in $Session.Transport.Headers.Keys) { + $null = $Message.Headers.TryAddWithoutValidation($key, $Session.Transport.Headers[$key]) + } +} + +function New-McpHttpGetMessage { + <# + .SYNOPSIS + A GET request for the stream of a legacy session, optionally resuming after an event id. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType([System.Net.Http.HttpRequestMessage])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [AllowNull()] + [string] $LastEventId + ) + + $message = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Get, $Session.Transport.Url) + $null = $message.Headers.TryAddWithoutValidation('Accept', 'text/event-stream') + if ($LastEventId) { $null = $message.Headers.TryAddWithoutValidation('Last-Event-ID', $LastEventId) } + Add-McpHttpSessionHeader -Session $Session -Message $message + $message +} + +function Open-McpHttpResumedStream { + <# + .SYNOPSIS + Resumes an interrupted response stream of a legacy session: GET with Last-Event-ID; returns the SSE response. + #> + [CmdletBinding()] + [OutputType([System.Net.Http.HttpResponseMessage])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [string] $LastEventId, + + [Parameter(Mandatory)] + [datetime] $Deadline, + + [Parameter(Mandatory)] + [System.Threading.CancellationTokenSource] $Cts, + + [Parameter(Mandatory)] + [string] $Method, + + [Parameter(Mandatory)] + [object] $Id + ) + + $message = New-McpHttpGetMessage -Session $Session -LastEventId $LastEventId + try { + 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() + throw [System.TimeoutException]::new("Resuming the response stream of '$Method' (id $Id) timed out.") + } + $failure = Get-McpTaskFailure -Task $task + if ($null -ne $failure) { throw [System.IO.IOException]::new("Resuming the response stream of '$Method' (id $Id) failed: $($failure.Message)", $failure) } + $response = $task.Result + $mediaType = if ($null -ne $response.Content.Headers.ContentType) { $response.Content.Headers.ContentType.MediaType } else { $null } + if (-not $response.IsSuccessStatusCode -or $mediaType -ne 'text/event-stream') { + $status = [int] $response.StatusCode + $response.Dispose() + throw [System.IO.IOException]::new("The server refused to resume the response stream of '$Method' (id $Id): HTTP $status.") + } + $response + } finally { + $message.Dispose() } } @@ -348,6 +473,11 @@ function New-McpHttpRequestMessage { $message.Content = [System.Net.Http.ByteArrayContent]::new([System.Text.Encoding]::UTF8.GetBytes($Json)) $message.Content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::new('application/json') $null = $message.Headers.TryAddWithoutValidation('Accept', 'application/json, text/event-stream') + if ($Session.Era -eq 'Legacy') { + # A legacy session: the session id and the negotiated version (after initialize), no per-request headers. + Add-McpHttpSessionHeader -Session $Session -Message $message + return $message + } $null = $message.Headers.TryAddWithoutValidation('MCP-Protocol-Version', $Session.ProtocolVersion) $null = $message.Headers.TryAddWithoutValidation('Mcp-Method', $Method) $bodyName = Get-McpStandardHeaderName -Method $Method -Params $Params @@ -388,7 +518,10 @@ function Invoke-McpHttpClientRequest { [int] $TimeoutMs = 0, - [hashtable] $Headers + [hashtable] $Headers, + + # Internal: the retry after a legacy session expired (no further re-initialization). + [switch] $NoReinitialize ) $transport = $Session.Transport @@ -398,7 +531,8 @@ function Invoke-McpHttpClientRequest { $Session.NextId = $id + 1 $progressToken = if ($OnProgress) { "p-$id" } else { $null } $requestParams = [ordered]@{} - $requestParams['_meta'] = New-McpClientRequestMeta -Session $Session -ProgressToken $progressToken -LogLevel $LogLevel + $meta = New-McpClientRequestMeta -Session $Session -ProgressToken $progressToken -LogLevel $LogLevel + if ($meta.Count -gt 0) { $requestParams['_meta'] = $meta } if ($null -ne $Params) { foreach ($key in $Params.Keys) { if ([string] $key -eq '_meta') { continue } @@ -423,6 +557,19 @@ function Invoke-McpHttpClientRequest { } $response = $sendTask.Result $status = [int] $response.StatusCode + if ($Session.Era -eq 'Legacy') { + if ($Method -eq 'initialize') { + $values = $null + if ($response.Headers.TryGetValues('Mcp-Session-Id', [ref] $values)) { $Session.SessionId = @($values)[0] } + } elseif ($status -eq 404 -and $Session.SessionId -and -not $NoReinitialize) { + # The server ended the session: start a new one and send the request once more. + Write-Verbose "Session $($Session.SessionId) expired (HTTP 404); initializing a new session." + $response.Dispose() + $response = $null + Initialize-McpLegacyClient -Session $Session -TimeoutMs $TimeoutMs + return Invoke-McpHttpClientRequest -Session $Session -Method $Method -Params $Params -OnProgress $OnProgress -LogLevel $LogLevel -TimeoutMs $TimeoutMs -Headers $Headers -NoReinitialize + } + } $mediaType = $null if ($null -ne $response.Content -and $null -ne $response.Content.Headers.ContentType) { $mediaType = $response.Content.Headers.ContentType.MediaType } Write-Debug "<- HTTP $status $mediaType for $Method id=$id" @@ -464,10 +611,35 @@ function Send-McpHttpClientNotification { [int] $TimeoutMs = 10000 ) + $json = ConvertTo-McpJson -InputObject (New-McpNotification -Method $Method -Params $Params) + Send-McpHttpClientMessage -Session $Session -Json $json -Method $Method -Params $Params -TimeoutMs $TimeoutMs +} + +function Send-McpHttpClientMessage { + <# + .SYNOPSIS + Posts a notification or a response (to a request of a legacy server); the server answers 202 without a body. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [string] $Json, + + # The method of the notification, or of the server request being answered (for diagnostics and headers). + [Parameter(Mandatory)] + [string] $Method, + + [System.Collections.IDictionary] $Params, + + [int] $TimeoutMs = 10000 + ) + $transport = $Session.Transport if ($transport.Closed) { throw [System.IO.IOException]::new('The transport is closed.') } - $json = ConvertTo-McpJson -InputObject (New-McpNotification -Method $Method -Params $Params) - $message = New-McpHttpRequestMessage -Session $Session -Method $Method -Params $Params -Json $json + $message = New-McpHttpRequestMessage -Session $Session -Method $Method -Params $Params -Json $Json $cts = [System.Threading.CancellationTokenSource]::new() $response = $null try { diff --git a/src/Public/Connect-McpServer.ps1 b/src/Public/Connect-McpServer.ps1 index 974a063..8173a65 100644 --- a/src/Public/Connect-McpServer.ps1 +++ b/src/Public/Connect-McpServer.ps1 @@ -8,8 +8,16 @@ function Connect-McpServer { with the request metadata headers of revision 2026-07-28 (MCP-Protocol-Version, Mcp-Method, Mcp-Name, Mcp-Param-*); responses arrive as JSON or as a request-scoped SSE stream. The session probes the server with server/discover, selects a protocol version from the server's supported versions and caches the - server info. Servers that only speak the initialize handshake of earlier revisions are not supported by - this milestone. + server info. + + Servers of the earlier revisions (2025-11-25, 2025-06-18, 2025-03-26) are detected by the probe (-Era + Auto): an answer that is neither a DiscoverResult nor one of the errors only revision 2026-07-28 has + (-32020, -32021, -32022), or no answer within five seconds, makes the session speak their initialize + handshake instead. Such a legacy session negotiates version and capabilities once, sends + Mcp-Session-Id over HTTP, answers the server's elicitation, sampling and roots requests with the same + callbacks as input requests, resumes an interrupted response stream with GET and Last-Event-ID, and + sends DELETE on disconnect. The era of an HTTP endpoint is remembered for later connections of this + process; the session's Era property tells which one was chosen. With -Server, the given server object runs in a background runspace of this process over an in-memory transport: the way to test a server without a child process. @@ -53,7 +61,11 @@ function Connect-McpServer { .PARAMETER MaxInputRounds The maximum number of input rounds of one request before it fails (default: 10). .PARAMETER ProtocolVersion - The preferred protocol version (default: 2026-07-28). + The preferred protocol version (default: 2026-07-28). A legacy version (2025-11-25, 2025-06-18) is the + version requested in initialize when the server turns out to be a legacy one. + .PARAMETER Era + Auto (default) detects the server's era; Modern only speaks revision 2026-07-28; Legacy skips the probe + and starts with initialize. .PARAMETER RequestTimeoutSeconds The default timeout for requests (default: 60). .PARAMETER ConnectTimeoutSeconds @@ -123,6 +135,9 @@ function Connect-McpServer { [ValidateNotNullOrEmpty()] [string] $ProtocolVersion = '2026-07-28', + [ValidateSet('Auto', 'Modern', 'Legacy')] + [string] $Era = 'Auto', + [ValidateRange(1, 86400)] [int] $RequestTimeoutSeconds = 60, @@ -171,77 +186,58 @@ function Connect-McpServer { $stderrPath = $transport.StandardErrorPath } + $legacyRequested = $ProtocolVersion -in $script:McpClientLegacyVersions + if ($legacyRequested -and $Era -eq 'Modern') { + throw [System.ArgumentException]::new("-ProtocolVersion $ProtocolVersion is a legacy revision; it cannot be used with -Era Modern.") + } + $modernVersion = if ($legacyRequested) { $script:McpLatestProtocolVersion } else { $ProtocolVersion } $session = [pscustomobject]@{ - PSTypeName = 'Mcp.Session' - Name = $null - Kind = $transport.Kind - Endpoint = $target - Transport = $transport - Background = $background - ClientInfo = $clientInfoObject - ClientCapabilities = $capabilityObject - ProtocolVersion = $ProtocolVersion - Era = 'Modern' - ServerInfo = $null - Tools = $null - ToolHeaders = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) - Cache = [hashtable]::new([System.StringComparer]::Ordinal) - NextId = 1 - RequestTimeoutMs = $RequestTimeoutSeconds * 1000 - LogLevel = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $null } - OnLog = $OnLog - OnElicitation = $OnElicitation - OnSampling = $OnSampling - OnRoots = $OnRoots - MaxInputRounds = $MaxInputRounds - Log = [System.Collections.Generic.List[object]]::new() - Notifications = [System.Collections.Generic.Queue[object]]::new() - Subscriptions = [ordered]@{} - SubscriptionIds = @{} - Inbox = [System.Collections.Concurrent.ConcurrentQueue[hashtable]]::new() - PendingEvents = [System.Collections.Generic.List[object]]::new() - StandardErrorPath = $stderrPath - Closed = $false + PSTypeName = 'Mcp.Session' + Name = $null + Kind = $transport.Kind + Endpoint = $target + Transport = $transport + Background = $background + ClientInfo = $clientInfoObject + ClientCapabilities = $capabilityObject + ProtocolVersion = $modernVersion + Era = if ($Era -eq 'Legacy') { 'Legacy' } else { 'Modern' } + # Legacy sessions: the Mcp-Session-Id of HTTP, the InitializeResult, the log level set with + # logging/setLevel, the background reader of the GET stream, and the versions preferred per era. + SessionId = $null + InitializeResult = $null + LegacyLogLevel = $null + LegacyStream = $null + PreferredLegacyVersion = if ($legacyRequested) { $ProtocolVersion } else { $null } + PreferredModernVersion = $modernVersion + ServerInfo = $null + Tools = $null + ToolHeaders = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + Cache = [hashtable]::new([System.StringComparer]::Ordinal) + NextId = 1 + RequestTimeoutMs = $RequestTimeoutSeconds * 1000 + LogLevel = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $null } + OnLog = $OnLog + OnElicitation = $OnElicitation + OnSampling = $OnSampling + OnRoots = $OnRoots + MaxInputRounds = $MaxInputRounds + Log = [System.Collections.Generic.List[object]]::new() + Notifications = [System.Collections.Generic.Queue[object]]::new() + Subscriptions = [ordered]@{} + SubscriptionIds = @{} + Inbox = [System.Collections.Concurrent.ConcurrentQueue[hashtable]]::new() + PendingEvents = [System.Collections.Generic.List[object]]::new() + StandardErrorPath = $stderrPath + Closed = $false } try { - $discover = $null - try { - $discover = Invoke-McpClientRequest -Session $session -Method 'server/discover' -TimeoutMs ($ConnectTimeoutSeconds * 1000) - } catch [McpProtocolException] { - $exception = $_.Exception - if ($exception.Code -eq $script:McpErrorCode.UnsupportedProtocolVersion -and $exception.Data -is [System.Collections.IDictionary] -and $exception.Data.Contains('supported')) { - $mutual = @($exception.Data['supported'] | Where-Object { $_ -in $script:McpModernProtocolVersions }) - if ($mutual.Count -eq 0) { - throw [System.InvalidOperationException]::new("The server supports protocol version(s) $(@($exception.Data['supported']) -join ', '), none of which this client speaks ($($script:McpModernProtocolVersions -join ', ')).") - } - $session.ProtocolVersion = $mutual[0] - $discover = Invoke-McpClientRequest -Session $session -Method 'server/discover' -TimeoutMs ($ConnectTimeoutSeconds * 1000) - } else { - throw [System.InvalidOperationException]::new("server/discover failed with $($exception.Code): $($exception.Message). Servers that only implement the initialize handshake of revisions before 2026-07-28 are not supported by this milestone.") - } - } catch [System.Net.Http.HttpRequestException] { - throw [System.InvalidOperationException]::new("server/discover at $Url failed: $($_.Exception.Message) A response without a JSON-RPC error body indicates a server of a revision before 2026-07-28; its initialize handshake is not supported by this milestone.", $_.Exception) - } - if ($discover -isnot [System.Collections.IDictionary] -or -not $discover.Contains('supportedVersions')) { - throw [System.InvalidOperationException]::new('The server/discover result is not a DiscoverResult.') - } - $supported = @($discover['supportedVersions']) - if ($session.ProtocolVersion -notin $supported) { - $mutual = @($supported | Where-Object { $_ -in $script:McpModernProtocolVersions }) - if ($mutual.Count -eq 0) { - throw [System.InvalidOperationException]::new("The server supports protocol version(s) $($supported -join ', '), none of which this client speaks.") - } - $session.ProtocolVersion = $mutual[0] - } - $session.ServerInfo = ConvertTo-McpServerInfoObject -DiscoverResult $discover -ProtocolVersion $session.ProtocolVersion - $session.Name = $session.ServerInfo.Name - Set-McpClientCacheEntry -Session $session -Key 'server/discover' -Value $session.ServerInfo -CacheHint (Get-McpResultCacheHint -Result $discover) + Initialize-McpClientSession -Session $session -Era $Era -ConnectTimeoutMs ($ConnectTimeoutSeconds * 1000) } catch { try { Disconnect-McpServer -Session $session -Confirm:$false } catch { Write-Debug 'Cleanup after a failed connection failed.' } throw } - if ($SetDefault -or $null -eq $script:McpDefaultSession -or $script:McpDefaultSession.Closed) { $script:McpDefaultSession = $session } diff --git a/src/Public/Disconnect-McpServer.ps1 b/src/Public/Disconnect-McpServer.ps1 index 5325bf2..5f80781 100644 --- a/src/Public/Disconnect-McpServer.ps1 +++ b/src/Public/Disconnect-McpServer.ps1 @@ -31,6 +31,9 @@ function Disconnect-McpServer { foreach ($subscription in @($target.Subscriptions.Values)) { try { Close-McpClientSubscription -Session $target -Subscription $subscription } catch { Write-Debug "Closing subscription $($subscription.Id) failed." } } + if ($target.Era -eq 'Legacy') { + try { Close-McpLegacyClientSession -Session $target } catch { Write-Debug "Ending the legacy session failed: $($_.Exception.Message)" } + } $target.Closed = $true Stop-McpTransportPump -Transport $target.Transport Close-McpTransport -Transport $target.Transport -ExitTimeoutSeconds $ExitTimeoutSeconds diff --git a/src/Public/Get-McpServerInfo.ps1 b/src/Public/Get-McpServerInfo.ps1 index 6385db9..84c970b 100644 --- a/src/Public/Get-McpServerInfo.ps1 +++ b/src/Public/Get-McpServerInfo.ps1 @@ -23,6 +23,8 @@ function Get-McpServerInfo { ) $target = Resolve-McpSession -Session $Session + # A legacy session learned about the server once, in initialize. + if ($target.Era -eq 'Legacy') { return $target.ServerInfo } if (-not $Refresh) { $entry = Get-McpClientCacheEntry -Session $target -Key 'server/discover' if ($null -ne $entry) { return $entry.Value } diff --git a/src/Public/Get-McpTool.ps1 b/src/Public/Get-McpTool.ps1 index fa6685f..a176fbc 100644 --- a/src/Public/Get-McpTool.ps1 +++ b/src/Public/Get-McpTool.ps1 @@ -38,7 +38,7 @@ function Get-McpTool { $converted = [System.Collections.Generic.List[object]]::new() $headers = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) foreach ($tool in $list.Items) { - if ($target.Kind -eq 'Http') { + if ($target.Kind -eq 'Http' -and $target.Era -ne 'Legacy') { $toolName = if ($tool.Contains('name')) { [string] $tool['name'] } else { '(unnamed)' } $headerParameters = @() try { diff --git a/src/Public/Invoke-McpTool.ps1 b/src/Public/Invoke-McpTool.ps1 index e5049ca..41b7e78 100644 --- a/src/Public/Invoke-McpTool.ps1 +++ b/src/Public/Invoke-McpTool.ps1 @@ -49,7 +49,7 @@ function Invoke-McpTool { $level = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $target.LogLevel } $timeoutMs = $TimeoutSeconds * 1000 $result = $null - if ($target.Kind -ne 'Http') { + if ($target.Kind -ne 'Http' -or $target.Era -eq 'Legacy') { $result = (Invoke-McpClientRequestWithInput -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs).Result } else { # Streamable HTTP mirrors x-mcp-header parameters into Mcp-Param-* headers; the annotations come from the diff --git a/src/Public/Register-McpSubscription.ps1 b/src/Public/Register-McpSubscription.ps1 index 4319a7d..6c52a27 100644 --- a/src/Public/Register-McpSubscription.ps1 +++ b/src/Public/Register-McpSubscription.ps1 @@ -17,6 +17,11 @@ function Register-McpSubscription { The subscription ends with Unregister-McpSubscription, Disconnect-McpServer or when the server closes it (State Closed). + + In a legacy session (a server of revision 2025-11-25 or earlier) there is no listen request: the server + sends list changes unsolicited and resource updates after resources/subscribe, which this command sends + for -ResourceUri (Unregister-McpSubscription sends resources/unsubscribe). Over Streamable HTTP they arrive + on the session's GET stream, which the first subscription opens. .PARAMETER ToolsListChanged Subscribe to notifications/tools/list_changed. .PARAMETER PromptsListChanged @@ -92,6 +97,27 @@ function Register-McpSubscription { Cts = $null Reader = $null Session = $target + Legacy = $target.Era -eq 'Legacy' + } + if ($subscription.Legacy) { + # A legacy server sends list changes unsolicited and resource updates after resources/subscribe; the + # subscription filters what it sees from them. + $capabilities = $target.InitializeResult['capabilities'] + $honoured = [ordered]@{} + foreach ($flag in 'toolsListChanged', 'promptsListChanged', 'resourcesListChanged') { + if ($filter.Contains($flag) -and (Get-McpWireValue -Object (Get-McpWireValue -Object $capabilities -Key $flag.Substring(0, $flag.Length - 'ListChanged'.Length)) -Key 'listChanged')) { $honoured[$flag] = $true } + } + if ($filter.Contains('resourceSubscriptions') -and (Get-McpWireValue -Object (Get-McpWireValue -Object $capabilities -Key 'resources') -Key 'subscribe')) { + foreach ($uri in $filter['resourceSubscriptions']) { + $null = Invoke-McpClientRequest -Session $target -Method 'resources/subscribe' -Params ([ordered]@{ uri = $uri }) + } + $honoured['resourceSubscriptions'] = $filter['resourceSubscriptions'] + } + $subscription.Honoured = $honoured + $subscription.State = 'Open' + $target.Subscriptions[[string] $id] = $subscription + if ($target.Kind -eq 'Http') { Start-McpLegacyClientStream -Session $target } else { Start-McpTransportPump -Transport $target.Transport } + return $subscription } $target.Subscriptions[[string] $id] = $subscription $target.SubscriptionIds[[string] $id] = $subscription diff --git a/src/Public/Set-McpLogLevel.ps1 b/src/Public/Set-McpLogLevel.ps1 new file mode 100644 index 0000000..d1979d3 --- /dev/null +++ b/src/Public/Set-McpLogLevel.ps1 @@ -0,0 +1,29 @@ +function Set-McpLogLevel { + <# + .SYNOPSIS + Sets the level from which the server sends log notifications (notifications/message) to this session. + .DESCRIPTION + In revision 2026-07-28 the level travels with every request (io.modelcontextprotocol/logLevel); this + command sets the session's default, which Invoke-McpTool, Invoke-McpPrompt and Read-McpResource send unless + they are given -LogLevel. In a legacy session (revision 2025-11-25 or earlier) it sends logging/setLevel, + which applies to everything the server logs from then on. Logging is deprecated in revision 2026-07-28. + .PARAMETER Level + The minimum level: debug, info, notice, warning, error, critical, alert or emergency. + .PARAMETER Session + The session; defaults to the default session. + .EXAMPLE + Set-McpLogLevel -Level warning + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory, Position = 0)] + [McpLoggingLevel] $Level, + + [object] $Session + ) + + $target = Resolve-McpSession -Session $Session + if (-not $PSCmdlet.ShouldProcess("session '$($target.Name)'", "Set log level $Level")) { return } + if ($target.Era -eq 'Legacy') { Set-McpLegacyClientLogLevel -Session $target -Level $Level } + $target.LogLevel = $Level +} diff --git a/tests/Integration/LegacyClient.Tests.ps1 b/tests/Integration/LegacyClient.Tests.ps1 new file mode 100644 index 0000000..8d80680 --- /dev/null +++ b/tests/Integration/LegacyClient.Tests.ps1 @@ -0,0 +1,329 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseCorrectCasing', '', Justification = 'PSScriptAnalyzer attributes -ScriptBlock of commands nested in BeforeAll to BeforeAll itself.')] +param() + +# The client against servers of the legacy revisions: era detection, the initialize handshake, answers to +# server-initiated requests through the callbacks, session-wide logging, unsolicited notifications, the session +# lifecycle over Streamable HTTP (session id, re-initialization after expiry, DELETE), resumption of an +# interrupted response stream, and the compatibility matrix of the versioning page. + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force + + function script:New-TestServer { + param([string[]] $SupportedVersions, [string] $Name = 'legacy-target') + $server = New-McpServer -Name $Name -Version '3.1.0' -Instructions 'Legacy target.' -SupportedVersions $SupportedVersions -RequestTimeoutSeconds 30 + Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $server + Register-McpTool -Name 'ask' -ScriptBlock { + param($Context) + $answer = Request-McpElicitation -Context $Context -Key 'name' -Message 'Your name?' -Schema @{ name = @{ type = 'string' } } + if ($answer.Accepted) { "Hello, $($answer.Content.name)!" } else { $answer.Action } + } -Server $server + Register-McpTool -Name 'sample' -ScriptBlock { + param($Context) + "model: $((Request-McpSampling -Context $Context -Key 's' -Messages 'hi' -MaxTokens 5).Text)" + } -Server $server + Register-McpTool -Name 'roots' -ScriptBlock { param($Context) @(Request-McpRoot -Context $Context -Key 'r' | ForEach-Object Uri) -join ',' } -Server $server + Register-McpTool -Name 'chatty' -ScriptBlock { + param($Context) + Write-McpLog -Context $Context -Level debug -Message 'debug line' + Write-McpLog -Context $Context -Level warning -Message 'warning line' + 'done' + } -Server $server + Register-McpTool -Name 'touch' -ScriptBlock { param([string] $Uri, $Context) Send-McpResourceUpdated -Context $Context -Uri $Uri; 'touched' } -Server $server + Register-McpResource -Uri 'test://doc' -Name 'doc' -Content 'document' -Server $server + Register-McpPrompt -Name 'greet' -Description 'Greets.' -ScriptBlock { param([string] $Who = 'you') "Hi $Who" } -Server $server + $server + } + + $script:callbacks = @{ + OnElicitation = { param($Request) @{ name = "legacy-$($Request.Mode)" } } + OnSampling = { 'sampled' } + OnRoots = { @('file:///one', 'file:///two') } + } +} + +Describe 'Legacy sessions of the client in memory' -Tag 'Integration' { + BeforeAll { + $script:legacyServer = New-TestServer -SupportedVersions '2025-11-25', '2025-06-18' + $script:session = Connect-McpServer -Server $script:legacyServer @script:callbacks -ConnectTimeoutSeconds 10 + } + + AfterAll { + if ($script:session) { Disconnect-McpServer -Session $script:session } + } + + It 'detects the legacy server and negotiates with initialize' { + $script:session.Era | Should -Be 'Legacy' + $script:session.ProtocolVersion | Should -Be '2025-11-25' + $info = Get-McpServerInfo -Session $script:session + $info.Name | Should -Be 'legacy-target' + $info.Version | Should -Be '3.1.0' + $info.Instructions | Should -Be 'Legacy target.' + $info.SupportedVersions | Should -Be @('2025-11-25') + $info.Capabilities.Contains('logging') | Should -BeTrue + } + + It 'lists and calls tools, reads resources and renders prompts' { + @(Get-McpTool -Session $script:session | ForEach-Object Name) | Should -Contain 'echo' + $result = Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'legacy wire' } -Session $script:session + $result.Text | Should -Be 'legacy wire' + $result.ResultType | Should -Be 'complete' + (Read-McpResource -Uri 'test://doc' -Session $script:session).Text | Should -Be 'document' + Read-McpResource -Uri 'test://none' -Session $script:session -ErrorAction SilentlyContinue -ErrorVariable missing | Should -BeNullOrEmpty + # -ErrorVariable also collects the errors the module catches internally; the reported one is ObjectNotFound. + $notFound = @($missing | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] -and $_.CategoryInfo.Category -eq 'ObjectNotFound' }) + $notFound.Count | Should -Be 1 + $notFound[0].Exception.InnerException.Code | Should -Be -32002 + (Invoke-McpPrompt -Name 'greet' -Arguments @{ Who = 'Ada' } -Session $script:session).Text | Should -Be 'Hi Ada' + } + + It 'answers the elicitation, sampling and roots requests of the server with the callbacks' { + (Invoke-McpTool -Name 'ask' -Session $script:session).Text | Should -Be 'Hello, legacy-form!' + (Invoke-McpTool -Name 'sample' -Session $script:session).Text | Should -Be 'model: sampled' + (Invoke-McpTool -Name 'roots' -Session $script:session).Text | Should -Be 'file:///one,file:///two' + } + + It 'sets the log level with logging/setLevel and receives the log notifications' { + $script:session.Log.Clear() + $null = Invoke-McpTool -Name 'chatty' -Session $script:session + $script:session.Log.Count | Should -Be 0 + Set-McpLogLevel -Level warning -Session $script:session + $script:session.LegacyLogLevel | Should -Be 'warning' + $null = Invoke-McpTool -Name 'chatty' -Session $script:session + @($script:session.Log | ForEach-Object Data) | Should -Be @('warning line') + $null = Invoke-McpTool -Name 'chatty' -Session $script:session -LogLevel debug + $script:session.LegacyLogLevel | Should -Be 'debug' + @($script:session.Log | ForEach-Object Data) | Should -Contain 'debug line' + } + + It 'delivers list changes and resource updates to subscriptions and invalidates the cache' { + $subscription = Register-McpSubscription -ToolsListChanged -ResourceUri 'test://doc' -Session $script:session + try { + $subscription.State | Should -Be 'Open' + $subscription.Honoured['toolsListChanged'] | Should -BeTrue + $null = Get-McpTool -Session $script:session + $null = Send-McpToolListChanged -Server $script:legacyServer + $changed = Receive-McpNotification -Subscription $subscription -TimeoutSeconds 10 + $changed.Method | Should -Be 'notifications/tools/list_changed' + $script:session.Cache.ContainsKey('tools/list') | Should -BeFalse + $null = Invoke-McpTool -Name 'touch' -Arguments @{ Uri = 'test://doc' } -Session $script:session + $updated = Receive-McpNotification -Subscription $subscription -TimeoutSeconds 10 + $updated.Uri | Should -Be 'test://doc' + } finally { + Unregister-McpSubscription -Subscription $subscription -Confirm:$false + } + } +} + +Describe 'Compatibility matrix' -Tag 'Integration' { + It 'client against a server: ' -ForEach @( + @{ ClientEra = 'Auto'; ServerKind = 'modern-only'; Expected = 'Modern' } + @{ ClientEra = 'Auto'; ServerKind = 'legacy-only'; Expected = 'Legacy' } + @{ ClientEra = 'Auto'; ServerKind = 'dual-era'; Expected = 'Modern' } + @{ ClientEra = 'Modern'; ServerKind = 'modern-only'; Expected = 'Modern' } + @{ ClientEra = 'Modern'; ServerKind = 'legacy-only'; Expected = 'fails' } + @{ ClientEra = 'Modern'; ServerKind = 'dual-era'; Expected = 'Modern' } + @{ ClientEra = 'Legacy'; ServerKind = 'modern-only'; Expected = 'fails' } + @{ ClientEra = 'Legacy'; ServerKind = 'legacy-only'; Expected = 'Legacy' } + @{ ClientEra = 'Legacy'; ServerKind = 'dual-era'; Expected = 'Legacy' } + ) { + $versions = switch ($ServerKind) { + 'modern-only' { @('2026-07-28') } + 'legacy-only' { @('2025-11-25', '2025-06-18') } + default { @('2026-07-28', '2025-11-25', '2025-06-18') } + } + $server = New-TestServer -SupportedVersions $versions -Name "matrix-$ServerKind" + if ($Expected -eq 'fails') { + { Connect-McpServer -Server $server -Era $ClientEra -ConnectTimeoutSeconds 10 } | Should -Throw + return + } + $session = Connect-McpServer -Server $server -Era $ClientEra -ConnectTimeoutSeconds 10 + try { + $session.Era | Should -Be $Expected + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'matrix' } -Session $session).Text | Should -Be 'matrix' + } finally { + Disconnect-McpServer -Session $session + } + } + + It 'names the versions of a modern-only server when a legacy client is refused' { + $server = New-TestServer -SupportedVersions '2026-07-28' -Name 'refusing' + try { + $null = Connect-McpServer -Server $server -Era Legacy -ConnectTimeoutSeconds 10 + throw 'expected a failure' + } catch [McpProtocolException] { + $_.Exception.Code | Should -Be -32022 + $_.Exception.Data['supported'] | Should -Be @('2026-07-28') + } + } + + It 'requests a legacy version given with -ProtocolVersion' { + $server = New-TestServer -SupportedVersions '2026-07-28', '2025-11-25', '2025-06-18' -Name 'versioned' + $session = Connect-McpServer -Server $server -Era Legacy -ProtocolVersion '2025-06-18' -ConnectTimeoutSeconds 10 + try { + $session.ProtocolVersion | Should -Be '2025-06-18' + } finally { + Disconnect-McpServer -Session $session + } + { Connect-McpServer -Server $server -Era Modern -ProtocolVersion '2025-06-18' } | Should -Throw -ExpectedMessage '*legacy revision*' + } +} + +Describe 'Legacy sessions of the client over Streamable HTTP' -Tag 'Integration' { + BeforeAll { + $script:httpServer = New-TestServer -SupportedVersions '2025-11-25' -Name 'legacy-http' + $script:handle = Start-McpTestHttpServer -Server $script:httpServer -Parameters @{ KeepAliveSeconds = 1; SessionIdleTimeoutSeconds = 2 } + } + + AfterAll { + if ($script:handle) { Stop-McpTestHttpServer -Handle $script:handle } + } + + It 'detects the legacy server, keeps the session id and answers requests on the response stream' { + $session = Connect-McpServer -Url $script:handle.Url @script:callbacks -ConnectTimeoutSeconds 10 + try { + $session.Era | Should -Be 'Legacy' + $session.SessionId | Should -Not -BeNullOrEmpty + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'over http' } -Session $session).Text | Should -Be 'over http' + (Invoke-McpTool -Name 'ask' -Session $session).Text | Should -Be 'Hello, legacy-form!' + $null = Invoke-McpTool -Name 'chatty' -Session $session -LogLevel warning + @($session.Log | ForEach-Object Data) | Should -Be @('warning line') + } finally { + Disconnect-McpServer -Session $session + } + # DELETE ended the session on the server. + $gone = Invoke-McpRawHttp -Url $script:handle.Url -Body '{"jsonrpc":"2.0","id":1,"method":"ping"}' -Headers @{ 'Mcp-Session-Id' = $session.SessionId } + $gone.Status | Should -Be 404 + } + + It 'receives notifications on the GET stream of the session' { + $session = Connect-McpServer -Url $script:handle.Url -ConnectTimeoutSeconds 10 + try { + $subscription = Register-McpSubscription -ToolsListChanged -Session $session + $deadline = [datetime]::UtcNow.AddSeconds(10) + while ($session.LegacyStream.Status -ne 'Open' -and [datetime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 50 } + $session.LegacyStream.Status | Should -Be 'Open' + $null = Send-McpToolListChanged -Server $script:httpServer + (Receive-McpNotification -Subscription $subscription -TimeoutSeconds 10).Method | Should -Be 'notifications/tools/list_changed' + } finally { + Disconnect-McpServer -Session $session + } + } + + It 'initializes a new session when the server ended the old one' { + $session = Connect-McpServer -Url $script:handle.Url -ConnectTimeoutSeconds 10 + try { + $first = $session.SessionId + Start-Sleep -Seconds 4 + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'again' } -Session $session).Text | Should -Be 'again' + $session.SessionId | Should -Not -Be $first + } finally { + Disconnect-McpServer -Session $session + } + } + + It 'remembers the era of the endpoint for the next connection' { + $cached = Invoke-McpInModule { param($u) $v = $null; $null = $script:McpClientEraCache.TryGetValue($u, [ref] $v); $v } ([uri] $script:handle.Url).AbsoluteUri + $cached | Should -Be 'Legacy' + } +} + +Describe 'Resumption of an interrupted response stream' -Tag 'Integration' { + It 'reconnects with GET and Last-Event-ID after the announced retry time and reads the response there' { + $port = Get-McpFreeTcpPort + $prefix = "http://127.0.0.1:$port/" + $log = [System.Collections.Concurrent.ConcurrentQueue[string]]::new() + $stop = [System.Collections.Concurrent.ConcurrentDictionary[string, bool]]::new() + $mock = Start-ThreadJob -ScriptBlock { + $listener = [System.Net.HttpListener]::new() + $listener.Prefixes.Add($using:prefix) + $listener.Start() + $log = $using:log + $stop = $using:stop + $pendingId = $null + try { + $task = $null + while (-not $stop.ContainsKey('stop')) { + if ($null -eq $task) { $task = $listener.GetContextAsync() } + if (-not $task.Wait(200)) { continue } + $context = $task.Result + $task = $null + $request = $context.Request + $response = $context.Response + $body = if ($request.HasEntityBody) { [System.IO.StreamReader]::new($request.InputStream).ReadToEnd() } else { '' } + $log.Enqueue("$($request.HttpMethod) $($request.Headers['Last-Event-ID']) $body") + $write = { + param($status, $type, $text, $headers) + $response.StatusCode = $status + if ($headers) { foreach ($key in $headers.Keys) { $response.AddHeader($key, $headers[$key]) } } + if ($type) { $response.ContentType = $type } + $bytes = [System.Text.Encoding]::UTF8.GetBytes($text) + $response.ContentLength64 = $bytes.Length + $response.OutputStream.Write($bytes, 0, $bytes.Length) + $response.Close() + } + if ($request.HttpMethod -eq 'GET') { + if ($request.Headers['Last-Event-ID'] -ne 'ev-1') { & $write 405 $null '' $null; continue } + & $write 200 'text/event-stream' "id: ev-2`ndata: {`"jsonrpc`":`"2.0`",`"id`":$pendingId,`"result`":{`"content`":[{`"type`":`"text`",`"text`":`"resumed`"}]}}`n`n" $null + continue + } + if ($request.HttpMethod -eq 'DELETE') { & $write 405 $null '' $null; continue } + $message = $body | ConvertFrom-Json -AsHashtable + switch ($message['method']) { + 'initialize' { + & $write 200 'application/json' "{`"jsonrpc`":`"2.0`",`"id`":$($message['id']),`"result`":{`"protocolVersion`":`"2025-03-26`",`"capabilities`":{`"tools`":{}},`"serverInfo`":{`"name`":`"mock`",`"version`":`"1`"}}}" @{ 'Mcp-Session-Id' = 'mock-session' } + } + 'tools/call' { + $pendingId = $message['id'] + # A priming event with an id and a retry time, then the stream ends without the response. + & $write 200 'text/event-stream' "id: ev-1`nretry: 300`ndata:`n`n" $null + } + { $null -eq $message['id'] } { & $write 202 $null '' $null } + default { + & $write 400 'application/json' "{`"jsonrpc`":`"2.0`",`"id`":$($message['id']),`"error`":{`"code`":-32600,`"message`":`"not initialized`"}}" $null + } + } + } + } finally { + $listener.Stop() + $listener.Close() + } + } + try { + Start-Sleep -Milliseconds 300 + $session = Connect-McpServer -Url $prefix -ConnectTimeoutSeconds 10 + try { + $session.Era | Should -Be 'Legacy' + $session.ProtocolVersion | Should -Be '2025-03-26' + $session.SessionId | Should -Be 'mock-session' + $watch = [System.Diagnostics.Stopwatch]::StartNew() + (Invoke-McpTool -Name 'anything' -Session $session -TimeoutSeconds 10).Text | Should -Be 'resumed' + $watch.ElapsedMilliseconds | Should -BeGreaterOrEqual 250 + } finally { + Disconnect-McpServer -Session $session + } + $entries = @($log.ToArray()) + @($entries | Where-Object { $_ -like 'GET ev-1*' }).Count | Should -Be 1 + } finally { + $stop['stop'] = $true + $null = Wait-Job -Job $mock -Timeout 10 + Remove-Job -Job $mock -Force + } + } +} + +Describe 'Legacy session over stdio' -Tag 'Integration' { + It 'speaks the initialize handshake with the example server when asked to' { + $script = Join-Path (Get-McpRepositoryRoot) 'examples' 'echo-server.ps1' + $environment = @{ MCP_MODULE_MANIFEST = (Get-McpBuiltModuleManifest) } + $session = Connect-McpServer -Command (Get-McpPowerShellPath) -Arguments '-NoLogo', '-NoProfile', '-NonInteractive', '-File', $script -Environment $environment -Era Legacy -ConnectTimeoutSeconds 30 + try { + $session.Era | Should -Be 'Legacy' + $session.ProtocolVersion | Should -Be '2025-11-25' + @(Get-McpTool -Session $session).Count | Should -BeGreaterThan 0 + } finally { + Disconnect-McpServer -Session $session + } + } +} diff --git a/tests/Unit/Header.Tests.ps1 b/tests/Unit/Header.Tests.ps1 index 8234516..0aedf43 100644 --- a/tests/Unit/Header.Tests.ps1 +++ b/tests/Unit/Header.Tests.ps1 @@ -253,7 +253,7 @@ Describe 'HTTP status codes and Origin validation' { } Describe 'SSE parsing' { - It 'reads events with data lines, ignores comments, ids and unknown fields, and reports end of stream' { + It 'reads events with data lines, ignores comments and unknown fields, and reports end of stream' { $lines = @(': connected', '', 'event: message', 'data: {"a":1}', '', ': keep-alive', '', 'id: 7', 'retry: 100', 'data: first', 'data: second', '', 'event: other', 'data: x', '', 'data:{"b":2}', '') $text = ($lines -join "`n") + "`n" $stream = [System.IO.MemoryStream]::new([System.Text.Encoding]::UTF8.GetBytes($text)) @@ -277,4 +277,24 @@ Describe 'SSE parsing' { $events[3].Data | Should -Be '{"b":2}' $events[4].Status | Should -Be 'Eof' } + + It 'keeps the last event id and the retry time for resumption and dispatches priming events' { + $text = "id: ev-1`nretry: 500`ndata:`n`nretry: soon`ndata: x`n`nid: ev-2`ndata: y`n`n" + $stream = [System.IO.MemoryStream]::new([System.Text.Encoding]::UTF8.GetBytes($text)) + $state = Invoke-McpInModule { + param($s) + $sse = New-McpSseReader -Stream $s + $first = Receive-McpSseEvent -Sse $sse -TimeoutMs 2000 + $second = Receive-McpSseEvent -Sse $sse -TimeoutMs 2000 + $third = Receive-McpSseEvent -Sse $sse -TimeoutMs 2000 + @{ First = $first; Second = $second; Third = $third; Retry = $sse.Retry; LastEventId = $sse.LastEventId } + } -Parameters @{ s = $stream } + $state.First.Status | Should -Be 'Event' + $state.First.Data | Should -Be '' + $state.First.Id | Should -Be 'ev-1' + $state.Second.Id | Should -Be 'ev-1' + $state.Third.Id | Should -Be 'ev-2' + $state.Retry | Should -Be 500 + $state.LastEventId | Should -Be 'ev-2' + } } From 243fd4fcf038ac261ed2386bca50d07218718710 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 20:14:55 +0000 Subject: [PATCH 4/4] M5 conformance fixtures, GET stream of legacy clients, docs The fixture server is one dual-era instance for both requirement sets (-Era Dual|Modern|Legacy) with the tools and the resource of the 2025-11-25 scenarios; the fixture client detects the era and fills forms from schema defaults. The Conformance task and workflow run 2026-07-28 and 2025-11-25: all scored server scenarios of both sets pass; on the client side initialize, tools_call, elicitation-sep1034-client-defaults and sse-retry pass, and the baseline still holds only the authorization scenarios (M6). Legacy HTTP clients open the session's GET stream after initialize, as the TypeScript SDK does, because servers send requests that belong to no client request there; the stream is read without blocking on the caller's thread, also while a request waits for its response, instead of in a background runspace (whose module import competed with the timing of sse-retry). Resumption prepares the GET before the announced retry time and sends it then. GET streams use Connection: close on both sides: the managed HttpListener reset the connection of a stream that ended while the client still read it when the next request reused it. Docs: dual-era concept, transports, conformance state after M5, development, README, about help, ROADMAP (M5 done, exit criterion: server 30/30, client 4/4 outside authorization) and the implementation plan with the corrections and deviations of M5; CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rvihdz4S9tqxJNrZGrX3qD --- .github/workflows/conformance.yml | 4 +- CHANGELOG.md | 35 ++++ ModelContextProtocol.build.ps1 | 5 +- README.md | 12 +- ROADMAP.md | 4 +- build.ps1 | 5 +- conformance-baseline.yml | 5 +- docs/concepts/dual-era.md | 113 +++++++++-- docs/concepts/transports.md | 21 +- docs/conformance.md | 80 ++++---- docs/development.md | 10 +- docs/implementation-plan.md | 13 +- src/Private/ClientLegacy.ps1 | 179 ++++++++++++------ src/Private/ClientSubscriptions.ps1 | 8 +- src/Private/HttpClient.ps1 | 41 +++- src/Private/HttpServer.ps1 | 3 + src/Public/Connect-McpServer.ps1 | 1 + src/Public/Register-McpSubscription.ps1 | 2 +- src/en-US/about_ModelContextProtocol.help.txt | 33 +++- tests/Conformance/everything-client.ps1 | 20 +- tests/Conformance/everything-server.ps1 | 87 ++++++++- tests/Integration/LegacyClient.Tests.ps1 | 11 +- 22 files changed, 519 insertions(+), 173 deletions(-) diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml index affb40b..dabe363 100644 --- a/.github/workflows/conformance.yml +++ b/.github/workflows/conformance.yml @@ -20,7 +20,7 @@ env: jobs: conformance: - name: Conformance (2026-07-28) + name: Conformance (2026-07-28 and 2025-11-25) runs-on: ubuntu-latest steps: - name: Check out @@ -31,7 +31,7 @@ jobs: version: '7.4.20' - name: Node.js version run: node --version && npm --version - - name: Run the conformance suite (server and client legs) + - name: Run the conformance suite (server and client legs of both requirement sets) shell: pwsh run: ./build.ps1 -Bootstrap -Task Conformance - name: Upload conformance results diff --git a/CHANGELOG.md b/CHANGELOG.md index 093d4bd..5172745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,34 @@ support, dependency and breaking-change policy. ### Added +- Milestone M5 (dual era): a server serves the `initialize` handshake of revisions 2025-11-25 and 2025-06-18 + (and 2025-03-26 as a version string) next to the stateless 2026-07-28 core on the same process and endpoint. + `New-McpServer -SupportedVersions` now defaults to `2026-07-28, 2025-11-25, 2025-06-18`; the era of every + request is chosen from its `_meta` and its session. A legacy session negotiates version and capabilities + in `initialize`, answers `ping`, `logging/setLevel` (session-wide log notifications), + `resources/subscribe` and `resources/unsubscribe`, sends list changes and resource updates unsolicited, + and its results carry no `resultType`, `ttlMs` or `cacheScope` (unknown resources are `-32002`). +- In a legacy session `Request-McpElicitation`, `Request-McpSampling` and `Request-McpRoot` send + server-initiated requests and wait for the answer, so handlers are era-agnostic. +- Streamable HTTP legacy sessions: `Mcp-Session-Id` from `initialize`, the GET stream of a session, DELETE, + 404 for unknown or expired sessions, JSON-RPC errors of a session with status 200, responses to + server-initiated requests accepted with 202; `Start-McpServer -SessionIdleTimeoutSeconds` and + `-MaxSessions` bound the sessions. +- Client: `Connect-McpServer -Era Auto|Modern|Legacy` (default Auto) detects the server's era with the + `server/discover` probe and falls back to `initialize`; the era of an HTTP endpoint is remembered. Legacy + sessions send `Mcp-Session-Id` and the negotiated `MCP-Protocol-Version`, answer the server's elicitation, + sampling, roots and ping requests with the `-OnElicitation`, `-OnSampling` and `-OnRoots` callbacks (on + stdio, response streams and the session's GET stream), map `Register-McpSubscription` to unsolicited + notifications and `resources/subscribe`, start a new session after HTTP 404, resume a response stream that + ends before its response with GET and `Last-Event-ID` after the announced retry time, and send DELETE on + disconnect. `Set-McpLogLevel` sets the log level in both eras (`logging/setLevel` in a legacy session). +- Conformance: the fixture server serves both requirement sets as one dual-era instance (new tools + `test_tool_with_logging`, `test_sampling`, `test_elicitation`, `test_elicitation_sep1034_defaults`, + `test_elicitation_sep1330_enums`, `test_reconnection` and the resource `test://watched-resource`); the + fixture client detects the era and fills forms from schema defaults; the `Conformance` task and workflow + run the 2026-07-28 and 2025-11-25 requirement sets. All 30 scored server scenarios of 2025-11-25 pass; the + client baseline still holds only the authorization scenarios. + - Milestone M4 (multi-round-trip requests and subscriptions): handlers ask for input with `Request-McpElicitation` (form mode with the flat primitive schema subset, or URL mode), `Request-McpSampling` and `Request-McpRoot`; the request is answered with an `InputRequiredResult`, and on @@ -120,6 +148,13 @@ support, dependency and breaking-change policy. - Governance: roadmap, dependency and support policy, security policy, contributing guide, code of conduct, conformance baseline file, documentation skeleton. +### Changed + +- A modern-only server answers `initialize` with `-32022` and the versions it supports instead of `-32601`; + `initialize` with the per-request `_meta` of 2026-07-28 is a request for a removed method (404, `-32601`). +- The SSE reader keeps the `id` and `retry` fields of events (for resumption) and passes priming events + with empty data on. + ### Fixed - A request id can be reused as soon as its response was sent; before, a request that arrived while the diff --git a/ModelContextProtocol.build.ps1 b/ModelContextProtocol.build.ps1 index 79f0dc3..ce036eb 100644 --- a/ModelContextProtocol.build.ps1 +++ b/ModelContextProtocol.build.ps1 @@ -14,7 +14,7 @@ param( [string[]] $TestTag, [string[]] $ExcludeTestTag, [string] $OutputDirectory = (Join-Path $PSScriptRoot 'output'), - [string[]] $ConformanceRequirements = @('2026-07-28'), + [string[]] $ConformanceRequirements = @('2026-07-28', '2025-11-25'), [string[]] $ConformanceLeg, [string] $ConformanceScenario ) @@ -371,7 +371,8 @@ function Start-ConformanceServer { $probe.Stop() $pwsh = (Get-Process -Id $PID).Path $script = Join-Path $script:TestsPath 'Conformance' 'everything-server.ps1' - $process = Start-Process -FilePath $pwsh -ArgumentList @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', $script, '-Port', $port) -RedirectStandardError $LogPath -PassThru -NoNewWindow + # The dual-era fixture serves both requirement sets: 2026-07-28 statelessly, 2025-11-25 in legacy sessions. + $process = Start-Process -FilePath $pwsh -ArgumentList @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', $script, '-Era', 'Dual', '-Port', $port) -RedirectStandardError $LogPath -PassThru -NoNewWindow $deadline = [datetime]::UtcNow.AddSeconds(60) while ([datetime]::UtcNow -lt $deadline) { if ($process.HasExited) { throw "The conformance server exited with code $($process.ExitCode); see $LogPath." } diff --git a/README.md b/README.md index e7461f2..1367974 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ PowerShell SDK for building and consuming [Model Context Protocol](https://model and clients, targeting specification revision **2026-07-28** with dual-era support for 2025-11-25 and 2025-06-18. -> **Status: milestone M4 (input requests and subscriptions).** Servers expose PowerShell functions, cmdlets, +> **Status: milestone M5 (dual era).** Servers expose PowerShell functions, cmdlets, > scripts and script blocks as tools, resources (fixed content, files, directories, handlers, RFC 6570 > templates) and prompts, with argument completion and caching hints, over stdio and Streamable HTTP with the > stateless 2026-07-28 lifecycle (`server/discover`, per-request `_meta`, request metadata headers, progress, @@ -12,9 +12,13 @@ and clients, targeting specification revision **2026-07-28** with dual-era suppo > and roots through multi-round-trip requests with a signed `requestState`; clients subscribe to list changes > and resource updates with `subscriptions/listen`, and tools, resources and prompts can be registered while > the server runs. The client side consumes all of it over both transports and caches results for the -> `ttlMs` the server sends. The official conformance suite runs in CI: every 2026-07-28 server scenario -> passes, and on the client side everything but authorization, which is listed in -> [conformance-baseline.yml](conformance-baseline.yml) and follows in M6. The milestones are in +> `ttlMs` the server sends. Both sides also speak the `initialize` handshake of 2025-11-25 and 2025-06-18: +> a server serves both eras on the same process and endpoint (legacy sessions with `Mcp-Session-Id`, GET +> stream, DELETE, server-initiated elicitation, sampling and roots requests), a client detects the era of the +> server and falls back to the handshake. The official conformance suite runs in CI for both requirement +> sets: every server scenario of 2026-07-28 and 2025-11-25 passes, and on the client side everything but +> authorization, which is listed in [conformance-baseline.yml](conformance-baseline.yml) and follows in M6. +> The milestones are in > [ROADMAP.md](ROADMAP.md); the design is in [docs/implementation-plan.md](docs/implementation-plan.md). ## Requirements diff --git a/ROADMAP.md b/ROADMAP.md index 6329a53..5a3315a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,8 +20,8 @@ against the requirement sets `2026-07-28` (37 server + 32 client scenarios) and | **M2 Streamable HTTP (modern)** | HttpListener host, header validation, Origin allowlist, JSON/SSE selection, keep-alive, disconnect → cancel; client HTTP transport with SSE parser; conformance fixtures and workflow | Conformance 2026-07-28: `server-stateless`, `tools-list`, `tools-call-simple-text/-error/-with-progress`, `dns-rebinding-protection`, `http-header-validation`, `http-custom-header-server-validation`; client `tools_call`, `request-metadata`, `http-*`, `json-schema-ref-no-deref`; first `0.1.0-preview` on the PowerShell Gallery | Done (the Gallery preview is published from the release workflow by tagging `v0.1.0-preview1`) | | **M3 Server primitives** | Resources (static, file, templates, blob), prompts, completion, pagination, caching fields, all content types, `structuredContent`/`outputSchema`, icons, annotations, `notifications/message`; client counterparts with TTL cache | `tools-call-image/-audio/-embedded-resource/-mixed-content`, `json-schema-2020-12`, `resources-*`, `sep-2164-resource-not-found`, `prompts-*`, `completion-complete`, `caching`; client `json-schema-2020-12-preservation` | Done | | **M4 MRTR and subscriptions** | Input-required machinery with signed `requestState`, capability gating, elicitation validator, sampling and roots as input requests, client retry loop; `subscriptions/listen` on server and client, list-changed and resource-updated fan-out, dynamic registration | All 14 `input-required-result-*`; the `subscriptions/listen` checks of `server-stateless` (acknowledgement, subscription id, filter, tools and prompts list changes); client `sep-2322-client-request-state` | Done | -| **M5 Dual era** | Legacy session (`initialize`, `ping`, `logging/setLevel`, `resources/subscribe`, server-initiated requests, HTTP sessions, GET SSE, DELETE), era-aware serialization, client legacy lifecycle | `--requirements 2025-11-25`: server 30/30, client 18/18; 2026-07-28 still green on the dual-era instance | Planned | -| **M6 Authorization** | Client OAuth provider (discovery, PKCE, resource indicators, `iss`, CIMD/DCR/pre-registered clients, scope step-up, token store); server bearer middleware and protected-resource metadata; `requestState` encrypted (AES-GCM) and bound to the authenticated principal | All client `auth/*` scenarios of the 2026-07-28 requirement set | Planned | +| **M5 Dual era** | Legacy session (`initialize`, `ping`, `logging/setLevel`, `resources/subscribe`, server-initiated requests, HTTP sessions, GET SSE, DELETE), era-aware serialization, client era detection and legacy lifecycle (including SSE resumption with `Last-Event-ID`) | `--requirements 2025-11-25`: server 30/30, client 4/4 outside authorization (`initialize`, `tools_call`, `elicitation-sep1034-client-defaults`, `sse-retry`; the 14 `auth/*` scenarios of the set follow with M6); 2026-07-28 still green on the dual-era instance; compatibility matrix of the versioning page as Pester tests | Done | +| **M6 Authorization** | Client OAuth provider (discovery, PKCE, resource indicators, `iss`, CIMD/DCR/pre-registered clients, scope step-up, token store); server bearer middleware and protected-resource metadata; `requestState` encrypted (AES-GCM) and bound to the authenticated principal | All client `auth/*` scenarios of the 2026-07-28 and 2025-11-25 requirement sets | Planned | | **M7 Extensions** | Tasks, Skills, Apps (server side), OAuth client credentials, enterprise-managed authorization | `tasks-*` (10), `auth/client-credentials-*`, `auth/enterprise-managed-authorization` | Planned | | **M8 Developer experience and 1.0** | Discovery styles, launcher and client-configuration helpers, scaffolder, examples, PlatyPS help, concept documentation, performance pass | Empty baseline for both requirement sets; PowerShell Gallery release 1.0.0 | Planned | diff --git a/build.ps1 b/build.ps1 index d2b9db1..2211472 100644 --- a/build.ps1 +++ b/build.ps1 @@ -43,7 +43,8 @@ Skip Pester tests with one of these tags. .PARAMETER ConformanceRequirements - Requirement sets of the Conformance task (default: 2026-07-28). Each set runs the server and the client leg. + Requirement sets of the Conformance task (default: 2026-07-28 and 2025-11-25). Each set runs the server and + the client leg; both server legs run against the same dual-era fixture. .PARAMETER ConformanceLeg Restrict the Conformance task to the Server or the Client leg. @@ -78,7 +79,7 @@ param( [string[]] $ExcludeTestTag, - [string[]] $ConformanceRequirements = @('2026-07-28'), + [string[]] $ConformanceRequirements = @('2026-07-28', '2025-11-25'), [ValidateSet('Server', 'Client')] [string[]] $ConformanceLeg, diff --git a/conformance-baseline.yml b/conformance-baseline.yml index bf1ba76..fac14ea 100644 --- a/conformance-baseline.yml +++ b/conformance-baseline.yml @@ -5,8 +5,9 @@ # pass + baselined = 1 (stale entry, remove it), pass + not baselined = 0. # # This file may only shrink. Version 1.0.0 requires empty lists for both requirement sets -# (2026-07-28 and 2025-11-25). The milestone that removes an entry is noted next to it (see ROADMAP.md); -# the 2025-11-25 requirement set is run from milestone M5 (dual era) on. +# (2026-07-28 and 2025-11-25). The milestone that removes an entry is noted next to it (see ROADMAP.md). +# Both requirement sets are run with this one baseline (from milestone M5 on, the server legs against the same +# dual-era fixture); the authorization scenarios below belong to both sets. server: [] client: # M6: authorization diff --git a/docs/concepts/dual-era.md b/docs/concepts/dual-era.md index 5f9a096..0ec5144 100644 --- a/docs/concepts/dual-era.md +++ b/docs/concepts/dual-era.md @@ -2,19 +2,102 @@ Implemented in milestone M5. The 2026-07-28 core is stateless; the legacy revisions need sessions, `initialize`, server-initiated requests and GET-based SSE streams. Both are served by the same process and -endpoint without contaminating the core. +endpoint without contaminating the core, and the client speaks both. -- **Era selection per message.** A message with the mandatory `_meta` fields of 2026-07-28 is handled - statelessly. An `initialize` request opens a legacy session (process-wide on stdio; keyed by - `Mcp-Session-Id` on HTTP). Follow-up requests are associated through the session. -- **Legacy component.** `McpLegacySession` implements `initialize`/`initialized`, capability negotiation, - `ping`, `logging/setLevel`, `resources/subscribe`/`unsubscribe`, server-initiated `elicitation/create`, - `sampling/createMessage` and `roots/list` with a pending-request table, the GET SSE stream, DELETE, and the - era-specific error codes (`-32002`, `-32042`). Resumability (`Last-Event-ID`) is not implemented. -- **Era-aware serialization in one place.** Legacy responses omit `resultType`, `ttlMs` and `cacheScope` - and use the legacy elicitation shapes; not-found is `-32002` instead of `-32602`. -- **Client.** On stdio the client probes with `server/discover`; on HTTP it sends a modern POST and inspects - a 400 body for `-32020`/`-32021`/`-32022` before falling back to `initialize`. The detected era is cached - per server. 2025-03-26 is accepted as a version string without additional features. -- **Handlers stay era-agnostic.** The MRTR cmdlets (`Request-McpElicitation` and friends) run as input - requests in the modern era and as blocking server-initiated requests in a legacy session. +## Server + +- **Which eras.** `New-McpServer -SupportedVersions` decides: the default `2026-07-28, 2025-11-25, + 2025-06-18` is dual-era, `2026-07-28` alone is modern-only, legacy revisions alone are legacy-only. A server + with any legacy revision also accepts `2025-03-26` in `initialize` (as a version string, without features + of its own). `server/discover` and the `data.supported` of `-32022` list the modern versions only. +- **Era selection per message** (`Get-McpMessageEra`, `src/Private/Era.ps1`). Over Streamable HTTP a request + with `Mcp-Session-Id` belongs to that legacy session (404 when there is none). Otherwise a request whose + `_meta` carries `io.modelcontextprotocol/protocolVersion` is modern, also `initialize` (a modern client + asking for a removed method gets 404 and `-32601`); `initialize` without it opens a legacy session; over + stdio and in memory every other request belongs to the process-wide legacy session once one was opened. + The methods only the legacy revisions have (`ping`, `logging/setLevel`, `resources/subscribe`, + `resources/unsubscribe`) are `-32601` for modern requests, `server/discover` and `subscriptions/listen` are + `-32601` in a legacy session. +- **Modern-only and legacy-only servers.** A modern-only server answers `initialize` with `-32022` and the + versions it supports (the SHOULD of the versioning page; HTTP 400), keeps GET and DELETE at 405 and + ignores `Mcp-Session-Id`. A legacy-only server answers requests before `initialize` with `-32600`, an + error that no 2026-07-28 server sends, so that dual-era clients fall back. +- **Legacy session** (`src/Private/LegacySession.ps1`). `initialize` echoes a requested version the server + accepts and answers with its newest legacy version otherwise; the `InitializeResult` has + `protocolVersion`, the capabilities of `server/discover` plus `logging`, `serverInfo` (without + `description`, `websiteUrl` and `icons` before 2025-11-25) and `instructions`. `notifications/initialized` + marks the session initialized, `ping` answers `{}`, `logging/setLevel` sets the level from which the + session's requests send `notifications/message`, `resources/subscribe`/`unsubscribe` maintain the URIs + whose updates (and those of their sub-resources) the session receives. List changes go to every + initialized session, unsolicited: over stdio on the line, over HTTP on the session's GET stream (dropped + while none is open). +- **Server-initiated requests.** Handlers stay era-agnostic: `Request-McpElicitation`, `Request-McpSampling` + and `Request-McpRoot` check the capabilities the client declared in `initialize` and then, in a legacy + session, send the request to the client and wait for the answer instead of ending the round with an + `InputRequiredResult`. The worker enqueues the request for the dispatcher and blocks on the answer, the + cancellation of its request or the request timeout; the dispatcher writes the request on the line, on the + SSE stream of the request that asked (over HTTP) or on the session's GET stream, and hands the client's + response back to the worker. The answer is validated like an input response and cached under its key, so + `-Defer`/`Wait-McpInput` and repeated calls work unchanged. URL mode needs 2025-11-25 and gets an + `elicitationId`; `-32042` is not used (the blocking request replaces it). +- **Era-aware serialization in one place** (`ConvertTo-McpEraMessage`, `ConvertTo-McpLegacyResult`). Legacy + results carry no `resultType`, `ttlMs`, `cacheScope` or `io.modelcontextprotocol/` `_meta` keys; an unknown + resource is `-32002` instead of `-32602` (`McpResourceNotFoundException`); the error codes that only + 2026-07-28 has become `-32600`. The dispatcher converts what it answers itself, the worker what handlers + return. +- **Streamable HTTP.** `initialize` returns a UUID as `Mcp-Session-Id`. Requests of a session skip the + header validation of 2026-07-28; `MCP-Protocol-Version` is optional (absent means 2025-03-26) and must be a + legacy version. Notifications of a session are dispatched, responses to server-initiated requests are + accepted with 202. GET with the session id opens the session's stream (one per session, 409 for a second + one, `Connection: close`), DELETE ends the session (its requests are cancelled, its open server-initiated + requests fail). Errors of a session are JSON-RPC responses with status 200. `Start-McpServer + -SessionIdleTimeoutSeconds` (default 1800) ends sessions without requests and without an open GET stream, + `-MaxSessions` (default 100) answers further `initialize` requests with 503. +- **Request ids** are unique per session only: the requests of a legacy session are keyed with the session's + prefix, so two sessions and the stateless core can use the same ids at the same time. +- **Not implemented:** SSE resumability on the server (event ids, replay after `Last-Event-ID`; a MAY, and the + `server-sse-polling` scenario is pending in the suite). A closed POST stream cancels the handler in both + eras; without resumability its response could not be delivered anyway. + +## Client + +- **Detection** (`Connect-McpServer -Era Auto`, the default; `src/Private/ClientLegacy.ps1`). The client + probes with `server/discover` (at most five seconds). A DiscoverResult means modern; `-32020`, `-32021` + and `-32022` mean modern too (after `-32022` the client retries once with a mutual version). Anything else + means legacy: another error (a legacy server's answer to an unknown method before `initialize`), no answer + in time, an HTTP error without a JSON-RPC body, or a result that is not a DiscoverResult. The fallback is + not keyed to one error code. The era of an HTTP endpoint is cached for the process; a failing cached + assumption is probed again. `-Era Modern` and `-Era Legacy` skip the detection; a legacy + `-ProtocolVersion` is the version requested in `initialize` (default 2025-11-25). +- **Legacy lifecycle.** `initialize` with the client info and the capabilities in the shape of the requested + revision (no `extensions`; elicitation without modes before 2025-11-25), then `notifications/initialized`. + The server's `protocolVersion` must be 2025-11-25, 2025-06-18 or 2025-03-26. Requests carry no + per-request `_meta` fields but the progress token; over HTTP they carry `Mcp-Session-Id` and the negotiated + `MCP-Protocol-Version` instead of `Mcp-Method`, `Mcp-Name` and `Mcp-Param-*`. A 404 on a request of the + session starts a new session and repeats the request once. `Get-McpServerInfo` returns what `initialize` + reported; `Disconnect-McpServer` sends DELETE (a refusal is fine). +- **Requests of the server** (`elicitation/create`, `sampling/createMessage`, `roots/list`, `ping`) are + answered with the same callbacks as input requests (`-OnElicitation`, `-OnSampling`, `-OnRoots`), on stdio, + on a response stream or on the GET stream; a request without a callback is answered with `-32601`. Over + HTTP the session opens its GET stream after `initialize` (tolerating 405) and reads it without blocking + on the caller's thread, also while a request of the session waits for its response, because servers send + requests that belong to no client request there. +- **Logging.** `-LogLevel` of `Connect-McpServer`, `Set-McpLogLevel` and `-LogLevel` of `Invoke-McpTool`, + `Invoke-McpPrompt` and `Read-McpResource` send `logging/setLevel` when the level changes and the server + declares `logging`. +- **Subscriptions.** `Register-McpSubscription` sends `resources/subscribe` for `-ResourceUri` and filters the + unsolicited list changes; `Unregister-McpSubscription` sends `resources/unsubscribe` for URIs no other + subscription needs. List changes and resource updates invalidate the cache in any case. +- **Resumption.** A response stream that ends before the response, after the server announced an event id, + is resumed with GET and `Last-Event-ID` once the announced `retry` time (default one second) has passed; + the response is read from the new stream. Priming events (an id with an empty data line) are skipped. +- **Results** without `resultType` are complete, `-32002` is an unknown resource (`Read-McpResource` reports + `ObjectNotFound`). + +## Compatibility matrix + +`tests/Integration/LegacyClient.Tests.ps1` runs the matrix of the versioning page in memory: a client with +`-Era Auto`, `Modern` or `Legacy` against a modern-only, a legacy-only and a dual-era server. Auto always +connects (modern where the server offers it), Modern fails against a legacy-only server, Legacy fails +against a modern-only server with `-32022` and the supported versions, and every other combination speaks +the era of the client's choice. diff --git a/docs/concepts/transports.md b/docs/concepts/transports.md index 2811daf..d465d9c 100644 --- a/docs/concepts/transports.md +++ b/docs/concepts/transports.md @@ -43,7 +43,9 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan response travel through the outbound queue to the channel, like over stdio. - Screening order per request: path (404), `Origin` (403; absent or loopback origins and the server's own origin are accepted by default, `-AllowedOrigins` overrides), method (GET and DELETE answer 405 with - `Allow: POST`; revision 2026-07-28 has neither a GET stream nor sessions), content type (415), size (413), + `Allow: POST`; revision 2026-07-28 has neither a GET stream nor sessions, and only a request with the + `Mcp-Session-Id` of a legacy session reaches the legacy GET and DELETE handling, see + [dual-era.md](dual-era.md)), content type (415), size (413), JSON (400 with `-32700`), message kind (notifications answer 202 and are not processed further, JSON-RPC responses and invalid messages 400 with `-32600`). - Header validation (`-32020`, HTTP 400): `MCP-Protocol-Version` present and equal to @@ -52,10 +54,13 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan or `params.uri` after decoding the `=?base64?...?=` sentinel, and for `tools/call` every `x-mcp-header` annotated argument that is present in the body must arrive as `Mcp-Param-{Name}` with the same value (integers compare numerically, strings exactly; a header without a body value, a missing header, a - malformed sentinel or invalid characters are mismatches). `initialize` is answered before the header checks - with `-32601` naming the supported versions, so that legacy clients get a diagnostic. + malformed sentinel or invalid characters are mismatches). `initialize` without the modern `_meta` skips + these checks: it opens a legacy session, or a modern-only server answers `-32022` with the supported + versions. Requests of a legacy session (with `Mcp-Session-Id`) skip them too. - HTTP status by JSON-RPC error code: 400 for `-32700`, `-32600`, `-32602`, `-32020`, `-32021` and `-32022`; - 404 for `-32601`; 200 for everything else (including `-32603` and tool errors reported with `isError`). + 404 for `-32601`; 200 for everything else (including `-32603` and tool errors reported with `isError`). In + a legacy session only `-32700` and `-32600` are 400 and every other error is 200: a 404 tells a client of + those revisions that its session is gone. - Response mode: a single JSON object (`application/json`) unless the handler sends a notification (progress, log message), which starts an SSE stream (`text/event-stream`, `event: message` + `data:` lines, `X-Accel-Buffering: no`); the response is the last event and closes the stream. A request that outlives @@ -74,11 +79,13 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan `Mcp-Param-*` headers of the call. - The response is read with `ResponseHeadersRead`: `application/json` bodies are one JSON-RPC message (error responses on any status become `McpProtocolException`), `text/event-stream` bodies are parsed event - by event (`data:` lines joined, comments and `id`/`retry` fields ignored) with notifications dispatched to + 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. - `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. -- Not implemented on purpose: the removed GET stream, `Mcp-Session-Id`, `Last-Event-ID` resumption; the - legacy `initialize` fallback arrives with milestone M5 (dual era). +- In a legacy session (see [dual-era.md](dual-era.md)) requests carry `Mcp-Session-Id` and the negotiated + `MCP-Protocol-Version` instead of the per-request headers; the `id` and `retry` fields of SSE events are + kept, and a response stream that ends before its response is resumed with GET and `Last-Event-ID` after + the announced retry time. Modern sessions use none of this. diff --git a/docs/conformance.md b/docs/conformance.md index 071f428..1e4f2b6 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -2,48 +2,62 @@ The SDK is measured with the official suite `@modelcontextprotocol/conformance`. The npm `latest` dist-tag (0.1.x) does not know revision 2026-07-28; the version pinned in `requirements.psd1` (alpha channel) does. -The fixtures live in `tests/Conformance/` (`everything-server.ps1`, a Streamable HTTP server with every tool, -resource, prompt and completion the server scenarios call; `everything-client.ps1`, a client that discovers, -lists and calls tools, answers input requests with fixed callbacks, and reads resources and renders prompts -when the server declares them, as the client scenarios expect), the build task `Conformance` runs both legs, and `.github/workflows/conformance.yml` -runs them on every push and pull request. +The fixtures live in `tests/Conformance/` (`everything-server.ps1`, a dual-era Streamable HTTP server with +every tool, resource, prompt and completion the server scenarios of both requirement sets call; +`everything-client.ps1`, a client that detects the era of the scenario server, discovers or initializes, +lists and calls tools, answers input requests and the requests of legacy servers with fixed callbacks (form +content from the schema defaults), and reads resources and renders prompts when the server declares them, as +the client scenarios expect), the build task `Conformance` runs both legs of both requirement sets, and +`.github/workflows/conformance.yml` runs them on every push and pull request. ## Running the suite ```powershell -./build.ps1 -Task Conformance # both legs, requirement set 2026-07-28 +./build.ps1 -Task Conformance # both legs, requirement sets 2026-07-28 and 2025-11-25 +./build.ps1 -Task Conformance -ConformanceRequirements 2025-11-25 # one requirement set ./build.ps1 -Task Conformance -ConformanceLeg Server # one leg ./build.ps1 -Task Conformance -ConformanceScenario tools-list # one scenario (both legs try it) ``` Node.js 20 or later is required (`npx` runs the pinned package). The task builds the module, starts the -fixture server on a free loopback port with `MCP_MODULE_MANIFEST` pointing at the build, waits for the port, -runs the server leg, stops the fixture, then runs the client leg with the fixture client. Results +dual-era fixture server (`-Era Dual`) on a free loopback port with `MCP_MODULE_MANIFEST` pointing at the +build, waits for the port, runs the server leg, stops the fixture, then runs the client leg with the fixture +client; this for each requirement set. Results (`checks.json` per scenario, the fixture server log) are written to `output/conformance/`. The task fails when a leg exits with a non-zero code: an unexpected failure or a stale baseline entry. -## State after milestone M4 - -Requirement set `2026-07-28`, server leg: every scenario of the requirement set passes and the server -baseline is empty. That covers `server-stateless` (30 checks, among them the `subscriptions/listen` checks: -acknowledgement first, the subscription id on every notification, a strictly honoured filter, and tools and -prompts list changes triggered by the fixture tools `test_trigger_tool_change` and -`test_trigger_prompt_change`), the fourteen `input-required-result-*` scenarios (elicitation, sampling and -roots input requests, answers accumulated over several rounds in the signed `requestState`, a tampered -state rejected before any other validation, input requests gated by the client capabilities, prompts and -resources as well as tools), `tools-list`, the seven `tools-call-*` scenarios, the `resources-*`, -`prompts-*`, `completion-complete`, `caching`, `sep-2164-resource-not-found`, `dns-rebinding-protection` -and `server-sse-multiple-streams` scenarios, each including the `wire-schema-valid` check of every message -against the 2026-07-28 schema; the not-scored `json-schema-2020-12`, `http-header-validation` and -`http-custom-header-server-validation` pass too. The `tasks-*` scenarios are extensions (milestone M7) and -do not affect the score. - -Client leg: `tools_call`, `request-metadata`, `sep-2322-client-request-state` (the state echoed verbatim, -a new request id per round, no state when the server sent none, no MRTR parameters on unrelated calls, a -missing `resultType` read as `complete`), `auth/resource-mismatch`, `http-standard-headers`, -`http-custom-headers`, `http-invalid-tool-headers`, `json-schema-ref-no-deref` and the not-scored -`json-schema-2020-12-preservation` pass. The remaining entries of `conformance-baseline.yml` are the -authorization scenarios of milestone M6. +## State after milestone M5 + +Requirement set `2026-07-28`, server leg, against the dual-era fixture: every scenario of the requirement set +passes and the server baseline is empty. That covers `server-stateless` (among its checks the +`subscriptions/listen` checks and `initialize` with the per-request `_meta` answered as a removed method, +404 and `-32601`), the fourteen `input-required-result-*` scenarios, `tools-list`, the seven `tools-call-*` +scenarios, the `resources-*`, `prompts-*`, `completion-complete`, `caching`, `sep-2164-resource-not-found`, +`dns-rebinding-protection` and `server-sse-multiple-streams` scenarios, each including the `wire-schema-valid` +check of every message against the 2026-07-28 schema; the not-scored `json-schema-2020-12`, +`http-header-validation` and `http-custom-header-server-validation` pass too. The `tasks-*` scenarios are +extensions (milestone M7) and do not affect the score. + +Requirement set `2025-11-25`, server leg, against the same fixture: all 30 scored scenarios pass +(`server-initialize`, `logging-set-level`, `ping`, `tools-call-with-logging`, `tools-call-sampling`, +`tools-call-elicitation`, `elicitation-sep1034-defaults`, `elicitation-sep1330-enums`, `resources-subscribe`, +`resources-unsubscribe`, `server-sse-multiple-streams` and the scenarios shared with 2026-07-28 at the legacy +wire), and so does the not-scored `server-session-lifecycle` (DELETE ends the session, a later request gets +404). `server-sse-polling` is pending in the suite; it reports that the server answers `test_reconnection` +without closing the stream (the server does not implement SSE resumability). + +Client leg, `2026-07-28`: `tools_call`, `request-metadata`, `sep-2322-client-request-state`, +`auth/resource-mismatch`, `http-standard-headers`, `http-custom-headers`, `http-invalid-tool-headers`, +`json-schema-ref-no-deref` and the not-scored `json-schema-2020-12-preservation` pass. Client leg, +`2025-11-25`: `initialize`, `tools_call`, `elicitation-sep1034-client-defaults` (the elicitation request +arrives on the GET stream) and `sse-retry` (GET with `Last-Event-ID` after the announced retry time) pass. The +remaining entries of `conformance-baseline.yml` are the authorization scenarios of milestone M6, which belong +to both requirement sets (14 of the 18 scored client scenarios of 2025-11-25). + +The suite starts the client scenarios of a requirement set at the same time; `sse-retry` checks the +reconnection delay with a tolerance of +200 ms, so a heavily loaded machine can make it flaky. The client +reads the GET stream of a legacy session on the caller's thread (no background runspace) to keep its own +share of that load small. ## Requirement sets @@ -52,15 +66,15 @@ authorization scenarios of milestone M6. | `2026-07-28` | 37 | 32 | stateless, per-request `_meta` | | `2025-11-25` | 30 | 18 | stateful `initialize` handshake | -Each set is scored only at its own wire, so the server is run twice (a modern-only instance and a legacy or -dual-era instance) and the client is invoked with `--requirements` for each set. Scenarios classified as +Each set is scored only at its own wire: the server leg runs both sets against the dual-era fixture (started +fresh for each set), and the client is invoked with `--requirements` for each set. Scenarios classified as `extension`, `added-after-release` or `pending` run but never affect the score. ## Commands behind the task ```bash npx --yes @modelcontextprotocol/conformance@ server --url http://127.0.0.1:3001/mcp --requirements 2026-07-28 --expected-failures conformance-baseline.yml -npx --yes @modelcontextprotocol/conformance@ server --url http://127.0.0.1:3002/mcp --requirements 2025-11-25 --expected-failures conformance-baseline.yml +npx --yes @modelcontextprotocol/conformance@ server --url http://127.0.0.1:3001/mcp --requirements 2025-11-25 --expected-failures conformance-baseline.yml npx --yes @modelcontextprotocol/conformance@ client --command "pwsh -NoProfile -NonInteractive -File tests/Conformance/everything-client.ps1" --requirements 2026-07-28 --expected-failures conformance-baseline.yml npx --yes @modelcontextprotocol/conformance@ client --command "pwsh -NoProfile -NonInteractive -File tests/Conformance/everything-client.ps1" --requirements 2025-11-25 --expected-failures conformance-baseline.yml ``` diff --git a/docs/development.md b/docs/development.md index 8280de2..bcd95c9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -42,16 +42,18 @@ built manifest, vendored schema access, a child-process runner with UTF-8 stream | Folder | Scope | Notes | |---|---|---| -| `tests/Unit` | manifest, import behaviour, type accelerators, enums against the schema, custom analyzer rules, JSON codec, JSON-RPC model, `_meta` validation, JSON Schema generation and validation (both engines), tool registry and in-process invocation, `server/discover` and the list shapes against the vendored schema, resources (content shaping, not-found errors, caching hints, file and directory resources including traversal and symbolic-link escapes), RFC 6570 template matching, prompts (argument derivation and validation, message shaping), completion (prefix filter, 100-value cap), icons, content annotations, kind-bound cursors, header value encoding and `x-mcp-header` validation, HTTP status mapping, Origin checks, SSE parsing, `requestState` (signature, expiry, binding to method, target and arguments, key derivation), input requests (answers present and missing, `-Defer`, capability gating with `-32021`, answer validation, the elicitation schema subset) | in-process | -| `tests/Integration` | fresh `pwsh` processes: import must be silent on stdout and stderr, also under `-File`; the client against a server in a background runspace (in-memory transport); `examples/echo-server.ps1` over stdio (encoding, 1 MB payloads, progress, timeouts, stderr capture, BOM-free stdout, EOF shutdown), `examples/weather-server.ps1` (all server primitives) and `examples/elicitation-server.ps1` (input requests and a subscription over stdio); resources, prompts, completion, capability gating, log notifications from handler streams and the client cache over the in-memory transport; multi-round-trip requests on the wire (state accumulation, tampering, invalid answers) and through the client callbacks, in memory and over HTTP; `subscriptions/listen` on the wire (acknowledgement, tagging, filter, dynamic registration, cancel, graceful close), through `Register-McpSubscription` (cache invalidation, `-Action`) and as SSE streams (parallel streams, client disconnect); a Streamable HTTP server in a background runspace (client round trips, SSE progress, header mirroring, disconnect → cancel, and raw requests for every status and error code the specification assigns) | spawns processes, binds loopback ports | +| `tests/Unit` | manifest, import behaviour, type accelerators, enums against the schema, custom analyzer rules, JSON codec, JSON-RPC model, `_meta` validation, JSON Schema generation and validation (both engines), tool registry and in-process invocation, `server/discover` and the list shapes against the vendored schema, resources (content shaping, not-found errors, caching hints, file and directory resources including traversal and symbolic-link escapes), RFC 6570 template matching, prompts (argument derivation and validation, message shaping), completion (prefix filter, 100-value cap), icons, content annotations, kind-bound cursors, header value encoding and `x-mcp-header` validation, HTTP status mapping, Origin checks, SSE parsing, `requestState` (signature, expiry, binding to method, target and arguments, key derivation), input requests (answers present and missing, `-Defer`, capability gating with `-32021`, answer validation, the elicitation schema subset), the era of a request and the legacy serialization of results and errors, legacy sessions (version negotiation, log level, resource subscriptions), the legacy HTTP status mapping, SSE event ids and retry times | in-process | +| `tests/Integration` | fresh `pwsh` processes: import must be silent on stdout and stderr, also under `-File`; the client against a server in a background runspace (in-memory transport); `examples/echo-server.ps1` over stdio (encoding, 1 MB payloads, progress, timeouts, stderr capture, BOM-free stdout, EOF shutdown), `examples/weather-server.ps1` (all server primitives) and `examples/elicitation-server.ps1` (input requests and a subscription over stdio); resources, prompts, completion, capability gating, log notifications from handler streams and the client cache over the in-memory transport; multi-round-trip requests on the wire (state accumulation, tampering, invalid answers) and through the client callbacks, in memory and over HTTP; `subscriptions/listen` on the wire (acknowledgement, tagging, filter, dynamic registration, cancel, graceful close), through `Register-McpSubscription` (cache invalidation, `-Action`) and as SSE streams (parallel streams, client disconnect); a Streamable HTTP server in a background runspace (client round trips, SSE progress, header mirroring, disconnect → cancel, and raw requests for every status and error code the specification assigns); legacy sessions on the wire (the `initialize` handshake, legacy result shapes, server-initiated elicitation, sampling and roots requests, `logging/setLevel`, unsolicited notifications) in memory and over Streamable HTTP (`Mcp-Session-Id`, GET stream, DELETE, session limits and expiry, request ids of several sessions next to the stateless core); the client against legacy servers (era detection, the compatibility matrix of the versioning page, callbacks for the server's requests, re-initialization after 404, resumption with `Last-Event-ID` against a mock, a legacy session over stdio) | spawns processes, binds loopback ports | | `tests/Conformance` | the fixtures of the conformance suite (not Pester; run by the `Conformance` task) | needs Node.js | | `tests/Spec` | vendored schemas: hashes, definition counts, JSON-RPC envelope, checklist | data-driven | | `tests/Compat` | Windows PowerShell 5.1 guard (skipped off Windows), pinned version matrix (`MCP_EXPECTED_PWSH_VERSION`) | tags `PS51Guard`, `VersionMatrix` | ## Manual verification with the Inspector -The Inspector CLI (`@modelcontextprotocol/inspector`) defaults to the legacy `initialize` handshake and parses -single-dash arguments such as `-File` as its own options, so describe the server in a config file: +The Inspector CLI (`@modelcontextprotocol/inspector`) defaults to the legacy `initialize` handshake, which the +example servers answer in a legacy session (dual era); `"protocolEra": "modern"` makes it use the stateless +lifecycle instead. It parses single-dash arguments such as `-File` as its own options, so describe the server +in a config file: ```json { diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 92c760b..199d42b 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -43,7 +43,7 @@ Normative Quelle: modelcontextprotocol.io, Revision **2026-07-28** (final; `late | HTTP-Hosting | **System.Net.HttpListener** (in-box) hinter einer Host-Abstraktion (`McpHttpHost`: Request-Kontext, `WriteJson`, `BeginSse` → SSE-Writer mit Keep-alive und Disconnect→Cancel). Default-Bindung `http://127.0.0.1:/mcp/`; Origin-Allowlist (403); TLS nur über Reverse Proxy (Linux/macOS-Listener kann kein HTTPS) oder http.sys-Zertifikatbindung auf Windows; `SendChunked` + `X-Accel-Buffering: no` + initiales `:`-Kommentar für SSE; JSON-only-Hostmodus als dokumentierter Fallback (keine Listen-Streams). | Einzige in-box, plattformübergreifende Option; Spec verlangt Loopback-Default und Origin-Check. | Kestrel (nicht in pwsh enthalten, ALC-Konflikte), Pode/PSU (optionale spätere Adapter). | | HTTP-Client | `HttpClient` + `SocketsHttpHandler` (`AllowAutoRedirect=$false`, `Timeout = Infinite`, eigene CTS für Connect/Request/Idle), `SendAsync(ResponseHeadersRead)`, Branch auf Content-Type; eigener SSE-Parser (7.4) mit optionaler Nutzung von `System.Net.ServerSentEvents` ab 7.5; Proxy aus Umgebungsvariablen. `Invoke-WebRequest`/`Invoke-RestMethod` nur für One-Shot-OAuth-Metadaten. | Web-Cmdlets puffern Bodies, kein SSE; Redirect-Handler entfernt Authorization und macht aus POST GET. | — | | MRTR-Handler-API | Ein Cmdlet-Satz (`Request-McpElicitation`, `Request-McpSampling`, `Request-McpRoot`) mit **zwei Ausführungsstrategien**: modern → wirft eine Control-Flow-Exception, der Dispatcher antwortet mit `InputRequiredResult` (`inputRequests`, HMAC-signierter `requestState`), Retry führt den Handler erneut aus und die Cmdlets liefern die Antwort aus `inputResponses`; legacy → blockierender server-initiierter Request über die Session mit Response-Korrelation. Handler bleiben era-agnostisch. `requestState`: HMAC-SHA256 (Schlüssel konfigurierbar, Default zufällig pro Prozess) über Principal-Hash, TTL, Methode, Param-Digest, State-Payload; optional AES-GCM bei vertraulichem State; Verifikationsfehler → `-32602`. | MRTR verbietet server-initiierte Requests in 2026-07-28; Legacy braucht sie. | Callback-/Await-Modell (entspricht dem entfernten 2025-11-25-Muster). | -| Legacy-Schichtung | `Legacy/`-Komponente mit `McpLegacySession` (pro stdio-Prozess bzw. pro `Mcp-Session-Id`): initialize/initialized, Capability-Negotiation, ping, logging/setLevel, resources/subscribe/unsubscribe, server-initiierte Requests mit Pending-Tabelle, GET-SSE-Stream, DELETE, 404 bei abgelaufener Session, era-spezifische Fehlercodes (`-32002`, `-32042`), era-spezifische Serialisierung (kein `resultType`/`ttlMs`/`cacheScope` in Legacy-Antworten). Router wählt die Ära pro Nachricht: `_meta`-Pflichtfelder vorhanden → modern; `initialize` → Legacy-Session; Folge-Requests per Session zugeordnet. Resumability (`Last-Event-ID`) wird nicht implementiert (MAY). | Kern bleibt zustandslos; Legacy ist isoliert testbar und später entfernbar. | Legacy-Semantik im Kern (verletzt Statelessness-MUSTs). | +| Legacy-Schichtung | `Legacy/`-Komponente mit `McpLegacySession` (pro stdio-Prozess bzw. pro `Mcp-Session-Id`): initialize/initialized, Capability-Negotiation, ping, logging/setLevel, resources/subscribe/unsubscribe, server-initiierte Requests mit Pending-Tabelle, GET-SSE-Stream, DELETE, 404 bei abgelaufener Session, era-spezifische Fehlercodes (`-32002`, `-32042`), era-spezifische Serialisierung (kein `resultType`/`ttlMs`/`cacheScope` in Legacy-Antworten). Router wählt die Ära pro Nachricht: `_meta`-Pflichtfelder vorhanden → modern (auch bei `initialize`: dann `-32601` für die entfernte Methode); `initialize` ohne sie → Legacy-Session; Folge-Requests per Session zugeordnet. Resumability (`Last-Event-ID`) wird serverseitig nicht implementiert (MAY); der Client nimmt einen abgebrochenen Response-Stream eines Legacy-Servers per GET mit `Last-Event-ID` wieder auf (Conformance `sse-retry`, bewertet). | Kern bleibt zustandslos; Legacy ist isoliert testbar und später entfernbar. | Legacy-Semantik im Kern (verletzt Statelessness-MUSTs). | | Deprecated Features | Roots, Sampling, Logging werden implementiert (als MRTR-Input-Requests und in Legacy als server-initiierte Requests), in Hilfe und Discover-Dokumentation als deprecated markiert; Standard-Logging geht nach stderr. `includeContext` `thisServer`/`allServers` werden akzeptiert, nicht erzeugt. | 12-Monats-Fenster, Legacy-Clients brauchen sie, Conformance-Szenarien (`input-required-result-basic-sampling/list-roots`) verlangen sie. | Weglassen (Scope-Verstoß). | | Extensions | Formale Registry (`Register-McpExtension`): Identifier, Settings-Objekt, zusätzliche Request-Handler, Capability-Advertising in `server/discover`, Pflichtprüfung der Client-Capability pro Request. Tasks, Skills, Apps (Server), Auth-Extensions setzen darauf auf; Extensions sind default-deaktiviert (Spec-Vorgabe). | Extension-Negotiation ist generisch spezifiziert. | Ad-hoc-Implementierung je Extension. | | Authorization | Client: `McpOAuthProvider` (PRM- und AS-Metadata-Discovery in Spec-Reihenfolge, Issuer-Gleichheit, PKCE S256 mit Pflichtprüfung von `code_challenge_methods_supported`, `resource`-Parameter, RFC-9207-`iss`-Tabelle, Registrierung pre-registered > CIMD > DCR (deprecated, `application_type=native`) > Prompt, Scope-Strategie mit Step-up und Retry-Limit, Loopback-Listener mit festen Ports, Token-Store-Abstraktion mit In-Memory-Default und optionalem `Microsoft.PowerShell.SecretManagement`-Adapter, Refresh). Server: Bearer-Middleware (JWT via JWKS oder Introspection-Hook, Audience-Bindung an kanonische URI, 401/403 mit `WWW-Authenticate`, PRM-Endpoint). stdio: Auth deaktiviert (Spec). | Spec-MUSTs; 32 Client-Auth-Szenarien in der Conformance-Suite. | — | @@ -102,7 +102,7 @@ Normative Quelle: modelcontextprotocol.io, Revision **2026-07-28** (final; `late **Subscriptions.** `subscriptions/listen` wird nie an den Pool gegeben: Filter validieren, honorierte Teilmenge aus Server-Capabilities bestimmen, unter Lock registrieren und Ack enqueuen; Fan-out-Cmdlets (`Send-McpToolListChanged` …) sind aus jedem Runspace aufrufbar und taggen jede Notification mit `io.modelcontextprotocol/subscriptionId`. Request-scoped Notifications gehen nie auf Listen-Streams. -**Dual-Era-Auswahl.** Erste Nachricht mit `initialize` → Legacy-Session (stdio: prozessweit; HTTP: `Mcp-Session-Id` minten, GET-SSE-Stream erlauben, DELETE beenden); Nachricht mit `_meta`-Pflichtfeldern → zustandslos. Beide Ären parallel auf demselben Endpoint erlaubt. Client: stdio-Probe `server/discover` (DiscoverResult → modern; erkannter moderner Fehler → modern mit Versionswahl; anderer Fehler/Timeout → Legacy); HTTP: moderner POST, bei 400 Body auf `-32020/-32021/-32022` prüfen, sonst Legacy `initialize`; Ära pro Origin/Prozess cachen. +**Dual-Era-Auswahl.** Nachricht mit `_meta`-Pflichtfeldern → zustandslos; `initialize` ohne sie → Legacy-Session (stdio: prozessweit; HTTP: `Mcp-Session-Id` minten, GET-SSE-Stream erlauben, DELETE beenden). Beide Ären parallel auf demselben Endpoint erlaubt. Client (stdio und HTTP gleich): Probe `server/discover` (DiscoverResult → modern; `-32020/-32021/-32022` → modern mit Versionswahl; alles andere → Legacy `initialize`: anderer Fehler, Timeout, HTTP-Fehler ohne JSON-RPC-Body, Ergebnis ohne DiscoverResult-Form); Ära pro Endpoint-URL cachen. Umsetzung und Details: `docs/concepts/dual-era.md`. ### 3.4 Datenübergabe zwischen Runspaces @@ -329,10 +329,11 @@ Jeder Meilenstein liefert einen nutzbaren, getesteten Zwischenstand; die Conform - InputRequired-Maschinerie, `requestState`-HMAC (AES-GCM und Principal-Bindung folgen mit M6), Capability-Gating, Elicitation-Validator (Primitiv-Subset, LegacyTitledEnum akzeptieren), Sampling- und Roots-Requests, Client-Retry-Loop mit Callbacks; `subscriptions/listen` Server (Registry, Ack-first, Fan-out, stdio-Cancel, Graceful-Close, dynamische Registrierung) und Client (Hintergrund-Reader, Demux, Reconnect über HTTP). - **Exit:** alle 14 `input-required-result-*`; die Listen-Checks von `server-stateless` (`server-sse-multiple-streams` prüft nur parallele Request-Streams und war bereits grün); Client `sep-2322-client-request-state`; Pester für Listen auf stdio und HTTP inkl. Interleaving. -### M5 Dual-Era -- `McpLegacySession` (Server), Router-Ära-Auswahl, era-bewusste Serialisierung, HTTP-Sessions/GET/DELETE, server-initiierte Requests, Legacy-Elicitation, `ping`, `logging/setLevel`, `resources/subscribe`; Client-Legacy-Lifecycle mit Probe-/400-Erkennung, Session-Header, GET-Stream-Handling, Beantwortung server-initiierter Requests, `-32002`-Akzeptanz, `resultType`-Absenz. -- `everything-server.ps1 -Era Legacy|Dual`, zweite Conformance-Instanz am Legacy-Wire. -- **Exit:** `--requirements 2025-11-25` Server 30/30 und Client 18/18; `2026-07-28` weiterhin grün auf der Dual-Instanz; Kompatibilitätsmatrix aus `basic/versioning` als Pester-Tabelle (alle acht Kombinationen). +### M5 Dual-Era (umgesetzt) +- `McpLegacySession` (Server), Router-Ära-Auswahl, era-bewusste Serialisierung, HTTP-Sessions/GET/DELETE, server-initiierte Requests, Legacy-Elicitation, `ping`, `logging/setLevel`, `resources/subscribe`; Client-Legacy-Lifecycle mit Probe-Erkennung, Session-Header, GET-Stream-Handling, Beantwortung server-initiierter Requests, `-32002`-Akzeptanz, `resultType`-Absenz, SSE-Wiederaufnahme mit `Last-Event-ID`. +- `everything-server.ps1 -Era Dual|Modern|Legacy`; beide Anforderungslisten laufen gegen dieselbe Dual-Instanz. +- **Exit (korrigiert):** `--requirements 2025-11-25` Server 30/30, Client 4/4 außerhalb der Authorization (`initialize`, `tools_call`, `elicitation-sep1034-client-defaults`, `sse-retry`); die 14 `auth/*`-Szenarien dieser Liste gehören zu M6. Das ursprüngliche „Client 18/18“ übersah, dass sie Teil der 18 bewerteten Szenarien sind. `2026-07-28` weiterhin grün auf der Dual-Instanz; Kompatibilitätsmatrix aus `basic/versioning` als Pester-Tabelle (Client Auto/Modern/Legacy × Server modern-only/legacy-only/dual). +- **Abweichungen vom Entwurf:** Die Server-Ära ergibt sich aus `-SupportedVersions` (kein separates `-Era` an `New-McpServer`); Default ist Dual. Ein geschlossener POST-Stream bricht den Handler auch in Legacy-Sessions ab (ohne serverseitige Resumability wäre die Antwort ohnehin verloren). `-32042` wird nicht erzeugt; der blockierende server-initiierte Request ersetzt es. ### M6 Authorization - Client-OAuth-Provider (siehe 2.2), Loopback-Listener, Token-Store, Refresh, Step-up; Server-Bearer-Middleware, PRM-Endpoint, JWT-Validierung (JWKS-Cache, RS256/ES256 via .NET, `aud`/`iss`/`exp`), Introspection-Hook, Scope-Hierarchie. diff --git a/src/Private/ClientLegacy.ps1 b/src/Private/ClientLegacy.ps1 index 6ade53b..daba634 100644 --- a/src/Private/ClientLegacy.ps1 +++ b/src/Private/ClientLegacy.ps1 @@ -2,7 +2,8 @@ # memory, the modern POST whose answer is inspected over Streamable HTTP), the initialize handshake with the # servers of 2025-11-25, 2025-06-18 and 2025-03-26, answers to server-initiated requests (elicitation, sampling # and roots through the session's callbacks, ping), resumption of an interrupted SSE response stream with GET -# and Last-Event-ID, the session's GET stream, and DELETE when the session ends. The request path in +# and Last-Event-ID, the session's GET stream (read without blocking on the caller's thread whenever a client +# command runs or waits for a response), and DELETE when the session ends. The request path in # Client.ps1 and HttpClient.ps1 consults Session.Era for the per-request metadata and headers. # The era of HTTP endpoints this process has talked to (keyed by URL), so that a second connection to a legacy @@ -180,6 +181,7 @@ function Initialize-McpLegacyClient { ) $requested = if ($Session.PreferredLegacyVersion) { $Session.PreferredLegacyVersion } else { $script:McpClientLegacyVersions[0] } + Stop-McpLegacyClientStream -Session $Session $Session.Era = 'Legacy' $Session.SessionId = $null $Session.InitializeResult = $null @@ -202,6 +204,8 @@ function Initialize-McpLegacyClient { $Session.ServerInfo = ConvertTo-McpLegacyServerInfoObject -InitializeResult $result $Session.Name = $Session.ServerInfo.Name Send-McpClientNotification -Session $Session -Method 'notifications/initialized' + # Servers send unsolicited notifications and requests that belong to no client request on the GET stream. + if ($Session.Kind -eq 'Http') { Start-McpLegacyClientStream -Session $Session } $Session.LegacyLogLevel = $null if ($null -ne $Session.LogLevel) { Set-McpLegacyClientLogLevel -Session $Session -Level $Session.LogLevel } } @@ -367,88 +371,149 @@ function Send-McpLegacyNotificationToSubscription { } } -function Invoke-McpHttpLegacyStreamLoop { +function Start-McpLegacyClientStream { <# .SYNOPSIS - Background loop of the GET stream of a legacy session: reads its events into the session inbox, reconnecting with Last-Event-ID; ends when the server refuses the stream (405). + Opens the GET stream of a legacy HTTP session (once per session); it is read on the caller's thread by Update-McpLegacyClientStream. #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal stream bookkeeping.')] [CmdletBinding()] param( [Parameter(Mandatory)] - [pscustomobject] $Session, + [pscustomobject] $Session + ) + + if ($Session.Kind -ne 'Http' -or $null -ne $Session.LegacyStream) { return } + $Session.LegacyStream = @{ + Cts = [System.Threading.CancellationTokenSource]::new() + Message = $null + Pending = $null + Response = $null + Sse = $null + Status = 'Opening' + LastEventId = $null + Attempts = 0 + RetryAt = [datetime]::MinValue + } + Open-McpLegacyClientStreamRequest -Session $Session +} + +function Open-McpLegacyClientStreamRequest { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal stream bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session + ) + $stream = $Session.LegacyStream + $stream.Message = New-McpHttpGetMessage -Session $Session -LastEventId $stream.LastEventId + $stream.Pending = $Session.Transport.Client.SendAsync($stream.Message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $stream.Cts.Token) +} + +function Close-McpLegacyClientStreamResponse { + [CmdletBinding()] + param( [Parameter(Mandatory)] [hashtable] $Stream ) - $inbox = $Session.Inbox - $attempt = 0 - $lastEventId = $null - while (-not $Stream.StopRequested) { - $message = New-McpHttpGetMessage -Session $Session -LastEventId $lastEventId - $response = $null - try { - $sendTask = $Session.Transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $Stream.Cts.Token) - while (-not $sendTask.IsCompleted -and -not $Stream.StopRequested) { $null = $sendTask.Wait(250) } - if ($Stream.StopRequested) { break } - $failure = Get-McpTaskFailure -Task $sendTask - if ($null -ne $failure) { throw $failure } - $response = $sendTask.Result - $mediaType = if ($null -ne $response.Content.Headers.ContentType) { $response.Content.Headers.ContentType.MediaType } else { $null } - if (-not $response.IsSuccessStatusCode -or $mediaType -ne 'text/event-stream') { - $Stream.Status = "HTTP $([int] $response.StatusCode)" - break - } - $Stream.Status = 'Open' - $sse = New-McpSseReader -Stream ($response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) - try { - while (-not $Stream.StopRequested) { - $received = Receive-McpSseEvent -Sse $sse -TimeoutMs 250 - if ($received.Status -eq 'Timeout') { continue } - if ($received.Status -eq 'Eof') { break } - if ($null -ne $received.Id) { $lastEventId = $received.Id } - if ([string]::IsNullOrWhiteSpace($received.Data) -or ($null -ne $received.Event -and $received.Event -ne 'message')) { continue } - $attempt = 0 - $inbox.Enqueue(@{ Kind = 'Legacy'; Json = $received.Data }) - } - } finally { - try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } + if ($null -ne $Stream.Sse) { try { $Stream.Sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } } + if ($null -ne $Stream.Response) { try { $Stream.Response.Dispose() } catch { Write-Debug 'Disposing the GET response failed.' } } + if ($null -ne $Stream.Message) { try { $Stream.Message.Dispose() } catch { Write-Debug 'Disposing the GET request failed.' } } + $Stream.Sse = $null + $Stream.Response = $null + $Stream.Message = $null + $Stream.Pending = $null +} + +function Update-McpLegacyClientStream { + <# + .SYNOPSIS + Reads what the GET stream of a legacy session has received so far into the session's legacy inbox, without blocking; reconnects with Last-Event-ID after an abrupt end. + .DESCRIPTION + A refusal (405 or another error status) ends the stream for the session: the server offers none. + An abrupt end is retried with the announced retry time or a backoff of 1, 2, 4, 8 and 16 seconds. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal stream bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session + ) + + $stream = $Session.LegacyStream + if ($null -eq $stream -or $stream.Status -in @('Refused', 'Failed', 'Stopped')) { return } + if ($null -eq $stream.Pending -and $null -eq $stream.Sse) { + if ([datetime]::UtcNow -lt $stream.RetryAt) { return } + Open-McpLegacyClientStreamRequest -Session $Session + } + if ($null -ne $stream.Pending -and $null -eq $stream.Response) { + if (-not $stream.Pending.IsCompleted) { return } + $failure = Get-McpTaskFailure -Task $stream.Pending + if ($null -eq $failure) { + $stream.Response = $stream.Pending.Result + $mediaType = if ($null -ne $stream.Response.Content.Headers.ContentType) { $stream.Response.Content.Headers.ContentType.MediaType } else { $null } + if (-not $stream.Response.IsSuccessStatusCode -or $mediaType -ne 'text/event-stream') { + Write-Verbose "The server offers no GET stream for session $($Session.SessionId) (HTTP $([int] $stream.Response.StatusCode))." + Close-McpLegacyClientStreamResponse -Stream $stream + $stream.Status = 'Refused' + return } - } catch { - $Stream.Status = "failed: $($_.Exception.Message)" - } finally { - if ($null -ne $response) { try { $response.Dispose() } catch { Write-Debug 'Disposing the GET response failed.' } } - $message.Dispose() + $stream.Sse = New-McpSseReader -Stream ($stream.Response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) + $stream.Status = 'Open' + } else { + Close-McpLegacyClientStreamResponse -Stream $stream + $stream.Attempts++ + if ($stream.Attempts -gt 5) { $stream.Status = 'Failed'; return } + $stream.RetryAt = [datetime]::UtcNow.AddSeconds([math]::Min(16, [math]::Pow(2, $stream.Attempts - 1))) + return } - if ($Stream.StopRequested) { break } - $attempt++ - if ($attempt -gt 5) { break } - $until = [datetime]::UtcNow.AddSeconds([math]::Min(16, [math]::Pow(2, $attempt - 1))) - while ([datetime]::UtcNow -lt $until -and -not $Stream.StopRequested) { Start-Sleep -Milliseconds 100 } } - if ($Stream.Status -eq 'Open') { $Stream.Status = 'Closed' } + while ($null -ne $stream.Sse) { + $received = Receive-McpSseEvent -Sse $stream.Sse -TimeoutMs 1 + if ($received.Status -eq 'Timeout') { return } + if ($received.Status -eq 'Eof') { + if ($null -ne $stream.Sse.LastEventId) { $stream.LastEventId = $stream.Sse.LastEventId } + $retry = $stream.Sse.Retry + Close-McpLegacyClientStreamResponse -Stream $stream + $stream.Attempts++ + if ($stream.Attempts -gt 5) { $stream.Status = 'Failed'; return } + $stream.Status = 'Reconnecting' + $delay = if ($null -ne $retry) { [double] $retry } else { 1000 * [math]::Min(16, [math]::Pow(2, $stream.Attempts - 1)) } + $stream.RetryAt = [datetime]::UtcNow.AddMilliseconds($delay) + return + } + if ($null -ne $received.Id) { $stream.LastEventId = $received.Id } + if ([string]::IsNullOrWhiteSpace($received.Data) -or ($null -ne $received.Event -and $received.Event -ne 'message')) { continue } + $stream.Attempts = 0 + $Session.LegacyInbox.Enqueue($received.Data) + } } -function Start-McpLegacyClientStream { +function Invoke-McpLegacyInbox { <# .SYNOPSIS - Opens the GET stream of a legacy HTTP session in the background (once per session). + Handles what the GET stream of a legacy session received: answers the server's requests and dispatches its notifications (also while a request of the session is pending). #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')] [CmdletBinding()] param( [Parameter(Mandatory)] [pscustomobject] $Session ) - if ($Session.Kind -ne 'Http' -or $null -ne $Session.LegacyStream) { return } - $stream = @{ StopRequested = $false; Cts = [System.Threading.CancellationTokenSource]::new(); Status = 'Opening'; Reader = $null } - $stream.Reader = New-McpClientBackgroundRunspace -FunctionName 'Invoke-McpHttpLegacyStreamLoop' -Parameters @{ Session = $Session; Stream = $stream } - $Session.LegacyStream = $stream + if ($null -eq $Session.LegacyInbox) { return } + Update-McpLegacyClientStream -Session $Session + $json = $null + while ($Session.LegacyInbox.TryDequeue([ref] $json)) { + $message = $null + try { $message = ConvertFrom-McpJson -Json $json } catch { $message = $null } + if ($message -is [System.Collections.IDictionary]) { Invoke-McpClientStrayMessage -Session $Session -Message $message } + } } function Stop-McpLegacyClientStream { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal stream bookkeeping.')] [CmdletBinding()] param( [Parameter(Mandatory)] @@ -457,10 +522,10 @@ function Stop-McpLegacyClientStream { $stream = $Session.LegacyStream if ($null -eq $stream) { return } - $stream.StopRequested = $true try { $stream.Cts.Cancel() } catch { Write-Debug 'Cancelling the GET stream failed.' } - Stop-McpClientBackgroundRunspace -Background $stream.Reader -TimeoutMs 5000 + Close-McpLegacyClientStreamResponse -Stream $stream try { $stream.Cts.Dispose() } catch { Write-Debug 'Disposing the token source failed.' } + $stream.Status = 'Stopped' $Session.LegacyStream = $null } diff --git a/src/Private/ClientSubscriptions.ps1 b/src/Private/ClientSubscriptions.ps1 index e447199..9fa894b 100644 --- a/src/Private/ClientSubscriptions.ps1 +++ b/src/Private/ClientSubscriptions.ps1 @@ -345,14 +345,8 @@ function Invoke-McpClientEventPump { } } $item = $null + Invoke-McpLegacyInbox -Session $Session while ($Session.Inbox.TryDequeue([ref] $item)) { - if ($item.Kind -eq 'Legacy') { - # A message of the GET stream of a legacy session. - $message = $null - try { $message = ConvertFrom-McpJson -Json $item.Json } catch { $message = $null } - if ($message -is [System.Collections.IDictionary]) { Invoke-McpClientStrayMessage -Session $Session -Message $message } - continue - } $subscription = $Session.Subscriptions[[string] $item.Subscription] if ($null -eq $subscription) { continue } switch ($item.Kind) { diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index 7b2108a..b75d40a 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -73,17 +73,22 @@ function Wait-McpTask { [System.Threading.Tasks.Task] $Task, [Parameter(Mandatory)] - [datetime] $Deadline + [datetime] $Deadline, + + # Invoked between the slices (every 100 ms), for example to answer requests of a legacy server meanwhile. + [scriptblock] $OnTick ) + $slice = if ($OnTick) { 100 } else { 500 } while (-not $Task.IsCompleted) { $remaining = ($Deadline - [datetime]::UtcNow).TotalMilliseconds if ($remaining -le 0) { return $false } try { - $null = $Task.Wait([int] [math]::Min(500, [math]::Max(1, $remaining))) + $null = $Task.Wait([int] [math]::Min($slice, [math]::Max(1, $remaining))) } catch [System.AggregateException] { return $true } + if ($OnTick -and -not $Task.IsCompleted) { & $OnTick } } $true } @@ -291,19 +296,23 @@ function Receive-McpSseResponse { $Cts.Cancel() throw [System.TimeoutException]::new("No response to '$Method' (id $Id) within the timeout; the response stream was closed, which cancels the request.") } - $received = Receive-McpSseEvent -Sse $sse -TimeoutMs ([int] [math]::Min(500, $remaining)) - if ($received.Status -eq 'Timeout') { continue } + $slice = if ($Session.Era -eq 'Legacy') { 100 } else { 500 } + $received = Receive-McpSseEvent -Sse $sse -TimeoutMs ([int] [math]::Min($slice, $remaining)) + if ($received.Status -eq 'Timeout') { + # The server may ask something on the session's GET stream while this request waits for it. + if ($Session.Era -eq 'Legacy') { Invoke-McpLegacyInbox -Session $Session } + continue + } if ($received.Status -eq 'Eof') { # A legacy server may close the stream after announcing an event id and a retry time: the # response then arrives on a GET stream opened with Last-Event-ID. if ($Session.Era -eq 'Legacy' -and $null -ne $sse.LastEventId -and $resumptions -lt 3) { $resumptions++ $delay = if ($null -ne $sse.Retry) { [int] $sse.Retry } else { 1000 } - $until = [datetime]::UtcNow.AddMilliseconds($delay) - while ([datetime]::UtcNow -lt $until) { Start-Sleep -Milliseconds ([int] [math]::Max(1, [math]::Min(50, ($until - [datetime]::UtcNow).TotalMilliseconds))) } + $reconnectAt = [datetime]::UtcNow.AddMilliseconds($delay) try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } if ($null -ne $resumed) { try { $resumed.Dispose() } catch { Write-Debug 'Disposing the resumed response failed.' } } - $resumed = Open-McpHttpResumedStream -Session $Session -LastEventId $sse.LastEventId -Deadline $Deadline -Cts $Cts -Method $Method -Id $Id + $resumed = Open-McpHttpResumedStream -Session $Session -LastEventId $sse.LastEventId -Deadline $Deadline -Cts $Cts -Method $Method -Id $Id -NotBefore $reconnectAt $retry = $sse.Retry $sse = New-McpSseReader -Stream ($resumed.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) $sse.Retry = $retry @@ -393,6 +402,8 @@ function New-McpHttpGetMessage { $message = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Get, $Session.Transport.Url) $null = $message.Headers.TryAddWithoutValidation('Accept', 'text/event-stream') + # A stream connection is never reused for requests after the stream ended. + $message.Headers.ConnectionClose = $true if ($LastEventId) { $null = $message.Headers.TryAddWithoutValidation('Last-Event-ID', $LastEventId) } Add-McpHttpSessionHeader -Session $Session -Message $message $message @@ -422,11 +433,19 @@ function Open-McpHttpResumedStream { [string] $Method, [Parameter(Mandatory)] - [object] $Id + [object] $Id, + + # The reconnection time the server asked for (the retry field): the request is prepared, then sent at this time. + [datetime] $NotBefore = [datetime]::MinValue ) $message = New-McpHttpGetMessage -Session $Session -LastEventId $LastEventId try { + while ([datetime]::UtcNow -lt $NotBefore) { + if ($Session.Era -eq 'Legacy') { Invoke-McpLegacyInbox -Session $Session } + $wait = ($NotBefore - [datetime]::UtcNow).TotalMilliseconds + if ($wait -gt 0) { [System.Threading.Thread]::Sleep([int] [math]::Min(20, [math]::Ceiling($wait))) } + } 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)) { @@ -546,8 +565,10 @@ function Invoke-McpHttpClientRequest { $response = $null try { Write-Debug "-> POST $($transport.Url) $Method id=$id ($($json.Length) bytes)" + # In a legacy session the server may ask something on the GET stream before it answers this request. + $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)) { + if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline -OnTick $tick)) { $cts.Cancel() throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") } @@ -577,7 +598,7 @@ function Invoke-McpHttpClientRequest { return Receive-McpSseResponse -Session $Session -Response $response -Id $id -Method $Method -Deadline $deadline -Cts $cts -ProgressToken $progressToken -OnProgress $OnProgress } $readTask = $response.Content.ReadAsStringAsync() - if (-not (Wait-McpTask -Task $readTask -Deadline $deadline)) { + if (-not (Wait-McpTask -Task $readTask -Deadline $deadline -OnTick $tick)) { $cts.Cancel() throw [System.TimeoutException]::new("The body of the response to '$Method' (id $id) did not arrive within $TimeoutMs ms.") } diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 index 9af5f47..639c74e 100644 --- a/src/Private/HttpServer.ps1 +++ b/src/Private/HttpServer.ps1 @@ -775,6 +775,9 @@ function Invoke-McpHttpSessionRequest { } $Channel.Session = $session $Channel.Era = 'Legacy' + # The connection of a long-lived stream is not reused afterwards (Connection: close): the managed listener + # resets connections whose streamed response ended while the client was still reading it. + try { $Channel.Response.KeepAlive = $false } catch { Write-Debug 'Disabling keep-alive failed.' } if (-not (Start-McpHttpSse -State $State -Channel $Channel)) { return } # A comment flushes the headers, so that the client sees the stream open at once. if (-not (Write-McpSseChunk -State $State -Channel $Channel -Text ": stream open`n`n")) { return } diff --git a/src/Public/Connect-McpServer.ps1 b/src/Public/Connect-McpServer.ps1 index 8173a65..9c03fdd 100644 --- a/src/Public/Connect-McpServer.ps1 +++ b/src/Public/Connect-McpServer.ps1 @@ -208,6 +208,7 @@ function Connect-McpServer { InitializeResult = $null LegacyLogLevel = $null LegacyStream = $null + LegacyInbox = [System.Collections.Concurrent.ConcurrentQueue[string]]::new() PreferredLegacyVersion = if ($legacyRequested) { $ProtocolVersion } else { $null } PreferredModernVersion = $modernVersion ServerInfo = $null diff --git a/src/Public/Register-McpSubscription.ps1 b/src/Public/Register-McpSubscription.ps1 index 6c52a27..625ed47 100644 --- a/src/Public/Register-McpSubscription.ps1 +++ b/src/Public/Register-McpSubscription.ps1 @@ -21,7 +21,7 @@ function Register-McpSubscription { In a legacy session (a server of revision 2025-11-25 or earlier) there is no listen request: the server sends list changes unsolicited and resource updates after resources/subscribe, which this command sends for -ResourceUri (Unregister-McpSubscription sends resources/unsubscribe). Over Streamable HTTP they arrive - on the session's GET stream, which the first subscription opens. + on the session's GET stream, which the session opens after initialize. .PARAMETER ToolsListChanged Subscribe to notifications/tools/list_changed. .PARAMETER PromptsListChanged diff --git a/src/en-US/about_ModelContextProtocol.help.txt b/src/en-US/about_ModelContextProtocol.help.txt index 46e8a41..9e0518a 100644 --- a/src/en-US/about_ModelContextProtocol.help.txt +++ b/src/en-US/about_ModelContextProtocol.help.txt @@ -17,7 +17,7 @@ LONG DESCRIPTION Supported transports are stdio and Streamable HTTP. CURRENT STATUS - Milestone M4 (input requests and subscriptions): servers expose PowerShell + Milestone M5 (dual era): servers expose PowerShell commands and script blocks as tools, resources (fixed content, files, directories, handlers, RFC 6570 templates) and prompts, with argument completion and caching hints, over stdio and over Streamable HTTP with the @@ -26,9 +26,10 @@ CURRENT STATUS for user input (elicitation), sampling and roots through multi-round-trip requests; clients subscribe to list changes and resource updates with subscriptions/listen. Clients consume all of it over both transports and - cache results for the ttlMs the server sends. The official conformance - suite runs in CI. The legacy revisions, authorization and the extensions - follow in later milestones (ROADMAP.md). + cache results for the ttlMs the server sends. Both sides also speak the + initialize handshake of 2025-11-25 and 2025-06-18 (see DUAL ERA below). The + official conformance suite runs in CI for both requirement sets. + Authorization and the extensions follow in later milestones (ROADMAP.md). COMMANDS Server: New-McpServer, Register-McpTool, Register-McpResource, @@ -45,7 +46,7 @@ COMMANDS Get-McpTool, Invoke-McpTool, Get-McpResource, Read-McpResource, Get-McpPrompt, Invoke-McpPrompt, Get-McpCompletion, Register-McpSubscription, Unregister-McpSubscription, - Receive-McpNotification + Receive-McpNotification, Set-McpLogLevel Start-McpServer serves stdio by default; -Transport Http -Url serves a Streamable HTTP endpoint (POST-only, JSON or SSE responses, request @@ -88,6 +89,28 @@ COMMANDS records are logged to stderr and, when the request asks for it, sent as notifications/message. +DUAL ERA + New-McpServer serves 2026-07-28, 2025-11-25 and 2025-06-18 by default + (-SupportedVersions). A request with the per-request _meta of 2026-07-28 is + served statelessly; an initialize request opens a legacy session: one per + process over stdio, one per Mcp-Session-Id over Streamable HTTP (GET opens + the session's stream for list changes and resource updates, DELETE ends + it; Start-McpServer -SessionIdleTimeoutSeconds and -MaxSessions bound the + sessions). In a legacy session Request-McpElicitation, Request-McpSampling + and Request-McpRoot send a request to the client and wait for its answer + instead of an input round, so handlers work in both eras unchanged. Legacy + results carry no resultType, ttlMs or cacheScope; unknown resources are + -32002. + + Connect-McpServer -Era Auto (default) probes with server/discover and + falls back to initialize when the server does not answer like a + 2026-07-28 server; -Era Modern and -Era Legacy choose the era. The + session's Era property shows the result. A legacy session answers the + server's requests with the -OnElicitation, -OnSampling and -OnRoots + callbacks, sets the log level with logging/setLevel (Set-McpLogLevel), + resumes an interrupted response stream with GET and Last-Event-ID, and + sends DELETE on Disconnect-McpServer. + REQUIREMENTS PowerShell 7.4 or later (Core edition). Windows PowerShell 5.1 is not supported. The module has no runtime dependencies. diff --git a/tests/Conformance/everything-client.ps1 b/tests/Conformance/everything-client.ps1 index 758a212..46ee093 100644 --- a/tests/Conformance/everything-client.ps1 +++ b/tests/Conformance/everything-client.ps1 @@ -2,7 +2,7 @@ <# .SYNOPSIS The conformance fixture client: connects to the scenario server of @modelcontextprotocol/conformance over - Streamable HTTP and exercises what the client scenarios of revision 2026-07-28 observe. + Streamable HTTP and exercises what the client scenarios of revisions 2026-07-28 and 2025-11-25 observe. .DESCRIPTION The suite runs it as pwsh -NoLogo -NoProfile -NonInteractive -File tests/Conformance/everything-client.ps1 @@ -10,8 +10,10 @@ the tool calls to make) and MCP_CONFORMANCE_PROTOCOL_VERSION (when a spec version was requested). It discovers the server, lists the tools and calls them: the calls given in the context, or every listed tool with arguments derived from its input schema. Diagnostics go to stderr; the exit code is 0 unless the - connection fails. Input requests of multi-round-trip requests are answered by fixed callbacks. Scenarios - of later milestones (authorization) are listed in conformance-baseline.yml. + connection fails. The era of the scenario server is detected (Connect-McpServer -Era Auto): servers of the + legacy revisions get the initialize handshake. Input requests of multi-round-trip requests and the requests + of legacy servers are answered by fixed callbacks; form content takes the schema defaults. Scenarios of + later milestones (authorization) are listed in conformance-baseline.yml. #> [CmdletBinding()] param( @@ -69,13 +71,9 @@ if ($env:MCP_CONFORMANCE_CONTEXT) { } $protocolVersion = if ($env:MCP_CONFORMANCE_PROTOCOL_VERSION) { $env:MCP_CONFORMANCE_PROTOCOL_VERSION } else { '2026-07-28' } Write-ClientLog "scenario '$scenario' at $url (protocol version $protocolVersion)" -if ($protocolVersion -ne '2026-07-28') { - Write-ClientLog "Protocol version $protocolVersion uses the initialize handshake, which this client speaks from milestone M5 on." - exit 0 -} -# Answers to the input requests of multi-round-trip requests: form content derived from the requested schema, -# a fixed sampling reply and one root. +# Answers to the input requests of multi-round-trip requests and to the requests of legacy servers: form content +# from the requested schema (its defaults, otherwise a value of the right type), a fixed sampling reply and one root. $onElicitation = { param($Request) $content = [ordered]@{} @@ -83,6 +81,10 @@ $onElicitation = { if ($schema -is [System.Collections.IDictionary] -and $schema['properties'] -is [System.Collections.IDictionary]) { foreach ($name in $schema['properties'].Keys) { $property = $schema['properties'][$name] + if ($property -is [System.Collections.IDictionary] -and $property.Contains('default')) { + $content[[string] $name] = $property['default'] + continue + } $content[[string] $name] = switch ([string] $property['type']) { 'boolean' { $true } 'number' { 1 } diff --git a/tests/Conformance/everything-server.ps1 b/tests/Conformance/everything-server.ps1 index a06ae7a..8b1f315 100644 --- a/tests/Conformance/everything-server.ps1 +++ b/tests/Conformance/everything-server.ps1 @@ -2,13 +2,16 @@ <# .SYNOPSIS The conformance fixture server: the tools, resources, prompts and completions that the server scenarios of - @modelcontextprotocol/conformance exercise for revision 2026-07-28, served over Streamable HTTP. + @modelcontextprotocol/conformance exercise for revisions 2026-07-28 and 2025-11-25, served over Streamable + HTTP by one dual-era server (both requirement sets run against the same instance). .DESCRIPTION The Conformance build task and .github/workflows/conformance.yml start it with pwsh -NoLogo -NoProfile -NonInteractive -File tests/Conformance/everything-server.ps1 -Port 3001 and run the suite against http://127.0.0.1:3001/mcp. The module is imported from $env:MCP_MODULE_MANIFEST when set (the build sets it to the built module), otherwise from the installed ModelContextProtocol module. Scenarios of later milestones are listed in conformance-baseline.yml until their milestone lands. +.PARAMETER Era + Dual (default) serves 2026-07-28 and the legacy revisions; Modern and Legacy restrict the server to one era. .PARAMETER Port The TCP port on the loopback interface. .PARAMETER Hostname @@ -18,6 +21,9 @@ #> [CmdletBinding()] param( + [ValidateSet('Dual', 'Modern', 'Legacy')] + [string] $Era = 'Dual', + [ValidateRange(1, 65535)] [int] $Port = 3001, @@ -36,7 +42,12 @@ if ($env:MCP_MODULE_MANIFEST) { # Handlers run in worker runspaces and see nothing but their parameters, so the payloads (a 1x1 red PNG and a # 44-byte silent WAV header, the smallest valid payloads of their types) are inlined below. -$server = New-McpServer -Name 'ModelContextProtocol-everything-server' -Version '0.1.0' -Title 'Conformance fixture' -Instructions 'A fixture for the MCP conformance suite.' -LogLevel $LogLevel -DefaultTtlMs 0 -DefaultCacheScope private -SetDefault +$versions = switch ($Era) { + 'Modern' { @('2026-07-28') } + 'Legacy' { @('2025-11-25', '2025-06-18') } + default { @('2026-07-28', '2025-11-25', '2025-06-18') } +} +$server = New-McpServer -Name 'ModelContextProtocol-everything-server' -Version '0.1.0' -Title 'Conformance fixture' -Instructions 'A fixture for the MCP conformance suite.' -SupportedVersions $versions -LogLevel $LogLevel -DefaultTtlMs 0 -DefaultCacheScope private -SetDefault Register-McpTool -Name 'test_simple_text' -Description 'Returns a simple text response.' -ScriptBlock { 'This is a simple text response for testing.' @@ -165,6 +176,77 @@ Register-McpTool -Name 'test_input_required_result_capabilities' -Description 'A if ($asked) { 'All declared input types answered.' } else { 'The client declared no input capability.' } } +# The legacy scenarios (requirement set 2025-11-25): the same era-agnostic cmdlets, sent to the client as +# server-initiated requests in a legacy session. + +Register-McpTool -Name 'test_tool_with_logging' -Description 'Logs three messages at info level while it runs (after logging/setLevel).' -ScriptBlock { + param($Context) + Write-McpLog -Context $Context -Level info -Message 'Tool execution started' + Start-Sleep -Milliseconds 50 + Write-McpLog -Context $Context -Level info -Message 'Tool processing data' + Start-Sleep -Milliseconds 50 + Write-McpLog -Context $Context -Level info -Message 'Tool execution completed' + 'Logging test completed' +} + +Register-McpTool -Name 'test_sampling' -Description 'Asks the client to sample a completion for the prompt.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [string] $prompt, + + $Context + ) + $answer = Request-McpSampling -Context $Context -Key 'sampling' -Messages $prompt -MaxTokens 100 + "LLM response: $($answer.Text)" +} + +Register-McpTool -Name 'test_elicitation' -Description 'Asks the user for a user name and an email address.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [string] $message, + + $Context + ) + $schema = [ordered]@{ + username = [ordered]@{ type = 'string'; description = "User's response" } + email = [ordered]@{ type = 'string'; description = "User's email address" } + } + $answer = Request-McpElicitation -Context $Context -Key 'user' -Message $message -Schema $schema -Required username, email + "User response: action=$($answer.Action), content=$(ConvertTo-Json -InputObject $answer.Content -Compress -Depth 5)" +} + +Register-McpTool -Name 'test_elicitation_sep1034_defaults' -Description 'Asks for values whose schemas carry defaults (SEP-1034).' -ScriptBlock { + param($Context) + $schema = [ordered]@{ + name = [ordered]@{ type = 'string'; default = 'John Doe' } + age = [ordered]@{ type = 'integer'; default = 30 } + score = [ordered]@{ type = 'number'; default = 95.5 } + status = [ordered]@{ type = 'string'; enum = @('active', 'inactive', 'pending'); default = 'active' } + verified = [ordered]@{ type = 'boolean'; default = $true } + } + $answer = Request-McpElicitation -Context $Context -Key 'defaults' -Message 'Please review the defaults.' -Schema $schema + "Elicitation completed: action=$($answer.Action), content=$(ConvertTo-Json -InputObject $answer.Content -Compress -Depth 5)" +} + +Register-McpTool -Name 'test_elicitation_sep1330_enums' -Description 'Asks for values of the five enum schema variants (SEP-1330).' -ScriptBlock { + param($Context) + $schema = [ordered]@{ + untitledSingle = [ordered]@{ type = 'string'; enum = @('option1', 'option2', 'option3') } + titledSingle = [ordered]@{ type = 'string'; oneOf = @([ordered]@{ const = 'value1'; title = 'First Option' }, [ordered]@{ const = 'value2'; title = 'Second Option' }, [ordered]@{ const = 'value3'; title = 'Third Option' }) } + legacyEnum = [ordered]@{ type = 'string'; enum = @('opt1', 'opt2', 'opt3'); enumNames = @('Option One', 'Option Two', 'Option Three') } + untitledMulti = [ordered]@{ type = 'array'; items = [ordered]@{ type = 'string'; enum = @('option1', 'option2', 'option3') } } + titledMulti = [ordered]@{ type = 'array'; items = [ordered]@{ anyOf = @([ordered]@{ const = 'value1'; title = 'First Choice' }, [ordered]@{ const = 'value2'; title = 'Second Choice' }, [ordered]@{ const = 'value3'; title = 'Third Choice' }) } } + } + $answer = Request-McpElicitation -Context $Context -Key 'enums' -Message 'Please choose.' -Schema $schema + "Elicitation completed: action=$($answer.Action), content=$(ConvertTo-Json -InputObject $answer.Content -Compress -Depth 5)" +} + +# server-sse-polling (pending in the suite) expects a stream that closes before the response and resumes on GET +# with Last-Event-ID; the server does not implement resumability, so the tool simply answers. +Register-McpTool -Name 'test_reconnection' -Description 'Answers at once (the server does not implement SSE resumability).' -ScriptBlock { + 'Reconnection test completed' +} + # subscriptions/listen: these tools make the server announce list changes to the open listen streams. Register-McpTool -Name 'test_trigger_tool_change' -Description 'Announces a change of the tool list to subscribers.' -ScriptBlock { @@ -224,6 +306,7 @@ Register-McpTool -Name 'json_schema_2020_12_tool' -Description 'Tool with JSON S $png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==' Register-McpResource -Uri 'test://static-text' -Name 'Static text resource' -Description 'A static text resource.' -Content 'This is the content of the static text resource.' Register-McpResource -Uri 'test://static-binary' -Name 'Static binary resource' -Description 'A 1x1 PNG image.' -MimeType 'image/png' -Content ([System.Convert]::FromBase64String($png)) +Register-McpResource -Uri 'test://watched-resource' -Name 'Watched resource' -Description 'A resource for resources/subscribe.' -Content 'Watched resource content.' Register-McpResource -UriTemplate 'test://template/{id}/data' -Name 'Template resource' -Description 'Data for an ID.' -MimeType 'application/json' -ScriptBlock { param([string] $id) [ordered]@{ id = $id; templateTest = $true; data = "Data for ID: $id" } diff --git a/tests/Integration/LegacyClient.Tests.ps1 b/tests/Integration/LegacyClient.Tests.ps1 index 8d80680..8a637eb 100644 --- a/tests/Integration/LegacyClient.Tests.ps1 +++ b/tests/Integration/LegacyClient.Tests.ps1 @@ -173,7 +173,7 @@ Describe 'Compatibility matrix' -Tag 'Integration' { Describe 'Legacy sessions of the client over Streamable HTTP' -Tag 'Integration' { BeforeAll { $script:httpServer = New-TestServer -SupportedVersions '2025-11-25' -Name 'legacy-http' - $script:handle = Start-McpTestHttpServer -Server $script:httpServer -Parameters @{ KeepAliveSeconds = 1; SessionIdleTimeoutSeconds = 2 } + $script:handle = Start-McpTestHttpServer -Server $script:httpServer -Parameters @{ KeepAliveSeconds = 1 } } AfterAll { @@ -200,9 +200,13 @@ Describe 'Legacy sessions of the client over Streamable HTTP' -Tag 'Integration' It 'receives notifications on the GET stream of the session' { $session = Connect-McpServer -Url $script:handle.Url -ConnectTimeoutSeconds 10 try { + # The session opened its GET stream after initialize. $subscription = Register-McpSubscription -ToolsListChanged -Session $session $deadline = [datetime]::UtcNow.AddSeconds(10) - while ($session.LegacyStream.Status -ne 'Open' -and [datetime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 50 } + while ($session.LegacyStream.Status -ne 'Open' -and [datetime]::UtcNow -lt $deadline) { + Invoke-McpInModule { param($s) Invoke-McpLegacyInbox -Session $s } $session + Start-Sleep -Milliseconds 50 + } $session.LegacyStream.Status | Should -Be 'Open' $null = Send-McpToolListChanged -Server $script:httpServer (Receive-McpNotification -Subscription $subscription -TimeoutSeconds 10).Method | Should -Be 'notifications/tools/list_changed' @@ -215,7 +219,8 @@ Describe 'Legacy sessions of the client over Streamable HTTP' -Tag 'Integration' $session = Connect-McpServer -Url $script:handle.Url -ConnectTimeoutSeconds 10 try { $first = $session.SessionId - Start-Sleep -Seconds 4 + # The server ends the session (as after an expiry): the next request gets 404. + (Invoke-McpRawHttp -Url $script:handle.Url -Method DELETE -Body $null -Headers @{ 'Mcp-Session-Id' = $first }).Status | Should -Be 200 (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'again' } -Session $session).Text | Should -Be 'again' $session.SessionId | Should -Not -Be $first } finally {