diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml new file mode 100644 index 0000000..affb40b --- /dev/null +++ b/.github/workflows/conformance.yml @@ -0,0 +1,43 @@ +name: Conformance + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: conformance-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + POWERSHELL_TELEMETRY_OPTOUT: '1' + DOTNET_CLI_TELEMETRY_OPTOUT: '1' + DOTNET_NOLOGO: '1' + +jobs: + conformance: + name: Conformance (2026-07-28) + runs-on: ubuntu-latest + steps: + - name: Check out + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install PowerShell 7.4 + uses: ./.github/actions/install-pwsh + with: + version: '7.4.20' + - name: Node.js version + run: node --version && npm --version + - name: Run the conformance suite (server and client legs) + shell: pwsh + run: ./build.ps1 -Bootstrap -Task Conformance + - name: Upload conformance results + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: conformance-results + path: output/conformance/ + if-no-files-found: warn diff --git a/CHANGELOG.md b/CHANGELOG.md index 33b8394..990dfba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,41 @@ support, dependency and breaking-change policy. ### Added +- Milestone M2 (Streamable HTTP): `Start-McpServer -Transport Http -Url ...` serves the MCP endpoint on + `System.Net.HttpListener`: one JSON-RPC request or notification per POST, responses as a single JSON + object or as a request-scoped SSE stream (progress and log notifications, keep-alive comments, a closed + stream cancels the handler), validation of `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` and + `Mcp-Param-*` against the body including the `=?base64?...?=` sentinel (`-32020`, HTTP 400), `Host` (404) + and `Origin` validation (403, `-AllowedOrigins`), 405 for GET and DELETE, 404 for unknown and removed methods, 202 for + notifications, body limits (`-MaxBodyBytes`) and `-KeepAliveSeconds`. +- `Connect-McpServer -Url` (with `-Headers` and `-NoProxy`): the Streamable HTTP client on `HttpClient` with + the request metadata headers, an SSE reader, timeouts that close the response stream, and `x-mcp-header` + support: `Get-McpTool` excludes tools with invalid annotations (with a warning), `Invoke-McpTool` mirrors + annotated arguments into `Mcp-Param-*` headers and retries once after a header mismatch. +- `Register-McpTool -Header @{ Parameter = 'HeaderName' }` annotates the input schema with `x-mcp-header`; + annotations are validated on registration (field-name tokens, primitive types, uniqueness, reachability). +- Sessions carry `Endpoint`; error responses without a determinable request id omit the `id` member, as the + specification schema requires; `tools.listChanged` is advertised as false until `subscriptions/listen` lands. +- Conformance: `tests/Conformance/everything-server.ps1` and `everything-client.ps1`, the `Conformance` build + task (server and client legs of the pinned `@modelcontextprotocol/conformance` alpha against + `conformance-baseline.yml`), the `Conformance` workflow, and `examples/http-server.ps1`. +- Milestone M1 (protocol core, stdio, tools): the stateless 2026-07-28 lifecycle with `server/discover`, + per-request `_meta` validation (`-32602`, `-32022` with the supported versions), `tools/list` with cursor + pagination and caching hints, `tools/call` with JSON Schema validation of the arguments, typed parameter + binding, result shaping (text, JSON, `structuredContent`, `isError`), `outputSchema` checks, + `notifications/progress`, `notifications/message` on request and `notifications/cancelled`; handlers run in + a hostless runspace pool with per-request cancellation tokens and an optional server-side timeout. +- Server commands `New-McpServer`, `Register-McpTool` (functions, cmdlets, script files and script blocks; + schemas from parameters, validation attributes, comment-based help and defaults), `Start-McpServer`, + `Stop-McpServer`, `Invoke-McpToolHandler`; handler commands `New-McpContent`, `New-McpToolResult`, + `Write-McpProgress`, `Write-McpLog`, `Test-McpClientCapability`. +- Client commands `Connect-McpServer` (stdio server processes with captured stderr, or a server object over an + in-memory transport), `Disconnect-McpServer`, `Get-McpServerInfo`, `Get-McpTool`, `Invoke-McpTool` with + progress callbacks, log notifications, timeouts and cancellation; format views for the result objects. +- A System.Text.Json codec that keeps wire shapes (ordered, case-sensitive objects, arrays never unrolled, + request id types preserved), JSON Schema 2020-12 validation through the bundled JsonSchema.Net with a + PowerShell fallback validator, `McpProtocolException` as a type accelerator, `examples/echo-server.ps1`, + and a `Format` build task (Invoke-Formatter). - Milestone M0 (foundation): the `ModelContextProtocol` module skeleton (PowerShell 7.4+, Core edition only, no runtime dependencies), assembled from `src/` with ModuleBuilder; engine enums `McpEra` and `McpLoggingLevel` exported through type accelerators. @@ -28,3 +63,10 @@ support, dependency and breaking-change policy. dry run and gated PowerShell Gallery publish; label sync; issue and pull request templates; Dependabot. - Governance: roadmap, dependency and support policy, security policy, contributing guide, code of conduct, conformance baseline file, documentation skeleton. + +### Fixed + +- The `Analyze` build task no longer fails or hangs on PSScriptAnalyzer's sporadic rule failures: every path is + analysed in a fresh process with a timeout, and files on which a rule failed are re-analysed in further fresh + processes. + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1c3886e..8c92ba8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ follow. The design is described in [docs/implementation-plan.md](docs/implementa ## Prerequisites - PowerShell 7.4 or later (7.4, 7.5 and 7.6 are tested in CI). Windows PowerShell 5.1 is not supported. -- Node.js 20 or later with `npx` for the conformance suite and the MCP Inspector (from milestone M2). +- Node.js 20 or later with `npx` for the conformance suite and the MCP Inspector. - Build and test dependencies are installed by `./build.ps1 -Bootstrap` (see `requirements.psd1`). In environments without access to the PowerShell Gallery, drop the `.nupkg` files into `tools/packages/` and run `./build.ps1 -Bootstrap -DependencySource Offline` (see `tools/README.md`). @@ -17,7 +17,7 @@ follow. The design is described in [docs/implementation-plan.md](docs/implementa | Path | Content | |---|---| | `src/` | Module sources: `Enums/`, `Classes/` (numbered for deterministic order), `Private/`, `Public/` (one function per file, file name = function name), `Types/`, `Formats/`, `en-US/`, `Suffix.ps1`, `build.psd1` (ModuleBuilder settings) | -| `tests/` | Pester tests: `Unit/`, `Integration/`, `Spec/` (vendored schemas), `Compat/`, `Conformance/` (from M2), `Support/` | +| `tests/` | Pester tests: `Unit/`, `Integration/`, `Spec/` (vendored schemas), `Compat/`, `Conformance/` (fixtures of the conformance suite), `Support/` | | `tools/` | Custom PSScriptAnalyzer rules, maintenance scripts, offline package drop folder | | `docs/` | Concept documentation, generated command help, the implementation plan and research material | | `output/` | Build output (ignored by git) | @@ -27,6 +27,7 @@ follow. The design is described in [docs/implementation-plan.md](docs/implementa ```powershell ./build.ps1 -Bootstrap # install build dependencies (once) ./build.ps1 # Build: assemble output/ModelContextProtocol// +./build.ps1 -Task Format # Invoke-Formatter over the sources, in place ./build.ps1 -Task Analyze # PSScriptAnalyzer with the repository settings and custom rules ./build.ps1 -Task Test # Build + Pester (unit, integration, spec, compat) ./build.ps1 -Task Test -CodeCoverage # same, with JaCoCo coverage under output/coverage/ @@ -62,7 +63,7 @@ Tests import the built module, never `src/` directly. Set `MCP_MODULE_MANIFEST` - Integration tests spawn real `pwsh` processes and use loopback HTTP; files go to `$TestDrive`. - Specification tests derive expectations from the vendored `schema.json`; every schema definition receives a constructor and a parser test as the type model grows (`tests/Spec/definitions-checklist.txt`). -- Conformance runs (from milestone M2) use the pinned `@modelcontextprotocol/conformance` version and +- Conformance runs (`./build.ps1 -Task Conformance`) use the pinned `@modelcontextprotocol/conformance` version and `conformance-baseline.yml`; the baseline may only shrink. ## Pull requests diff --git a/ModelContextProtocol.build.ps1 b/ModelContextProtocol.build.ps1 index 17a01cc..79f0dc3 100644 --- a/ModelContextProtocol.build.ps1 +++ b/ModelContextProtocol.build.ps1 @@ -13,7 +13,10 @@ param( [switch] $CodeCoverage, [string[]] $TestTag, [string[]] $ExcludeTestTag, - [string] $OutputDirectory = (Join-Path $PSScriptRoot 'output') + [string] $OutputDirectory = (Join-Path $PSScriptRoot 'output'), + [string[]] $ConformanceRequirements = @('2026-07-28'), + [string[]] $ConformanceLeg, + [string] $ConformanceScenario ) Set-StrictMode -Version Latest @@ -25,6 +28,7 @@ $script:BuildSettings = Join-Path $script:SourcePath 'build.psd1' $script:TestsPath = Join-Path $PSScriptRoot 'tests' $script:AnalyzerSettings = Join-Path $PSScriptRoot 'PSScriptAnalyzerSettings.psd1' $script:CustomRulePath = Join-Path $PSScriptRoot 'tools' 'ScriptAnalyzerRules' 'McpAnalyzerRules.psm1' +$script:AnalyzerWorker = Join-Path $PSScriptRoot 'tools' 'Invoke-ScriptAnalyzerWorker.ps1' $script:ModuleOutputRoot = Join-Path $OutputDirectory $script:ModuleName $script:PackageDirectory = Join-Path $OutputDirectory 'packages' @@ -55,14 +59,15 @@ function Get-BuildPlatformTag { function Invoke-BuildScriptAnalysis { <# .SYNOPSIS - Runs PSScriptAnalyzer over one path with the repository settings and custom rules. + Runs PSScriptAnalyzer over one path with the repository settings and custom rules; returns the findings. .DESCRIPTION - PSScriptAnalyzer 1.25 occasionally fails while initialising its internal command-info cache and the runspace - that runs custom rules: either with "The term 'Get-Command' is not recognized" or with a - NullReferenceException ("Object reference not set to an instance of an object"). Neither failure is - reproducible on demand and both disappear on the next run, so the analysis (idempotent, a few seconds) is - retried up to three times before it counts as an error. A retry is reported as a build warning so that it - stays visible in the logs. + PSScriptAnalyzer 1.25 runs its rules in parallel tasks that are not entirely thread-safe: now and then a + rule fails on a file with a NullReferenceException or, after a lost command lookup, with "The term + 'Get-Command' is not recognized", the analyzer keeps that state until the process exits, and once in a + while an analysis hangs. Every analysis therefore runs in a fresh pwsh process with a timeout + (tools/Invoke-ScriptAnalyzerWorker.ps1): a failed or timed-out process is retried, and files on which a + rule failed are re-analysed one by one in further fresh processes, so that a failure never hides a + finding. Retries are reported as build warnings so that they stay visible in the logs. #> param( [Parameter(Mandatory)] @@ -71,22 +76,119 @@ function Invoke-BuildScriptAnalysis { $maximumAttempts = 3 for ($attempt = 1; $attempt -le $maximumAttempts; $attempt++) { - try { - return Invoke-ScriptAnalyzer -Path $Path -Recurse -Settings $script:AnalyzerSettings -CustomRulePath $script:CustomRulePath -IncludeDefaultRules -ErrorAction Stop - } catch { - $message = $_.Exception.Message - $transient = $_.Exception -is [System.NullReferenceException] - foreach ($pattern in "*'Get-Command' is not recognized*", '*Object reference not set to an instance of an object*') { - if ($message -like $pattern) { $transient = $true } - } - if ($attempt -lt $maximumAttempts -and $transient) { - Write-Warning ("PSScriptAnalyzer failed transiently on '{0}' (attempt {1} of {2}): {3} Retrying." -f $Path, $attempt, $maximumAttempts, $message.Split("`n")[0].Trim()) - Start-Sleep -Seconds 2 - continue - } - throw + $result = Invoke-BuildScriptAnalyzerWorker -Path $Path + if ($null -eq $result) { + if ($attempt -lt $maximumAttempts) { Start-Sleep -Seconds 2; continue } + throw "PSScriptAnalyzer could not analyse '$Path' in $maximumAttempts attempts." + } + $findings = @($result.Findings) + $affected = @($result.Failures | Select-Object -ExpandProperty File -Unique) + if ($affected.Count -eq 0) { return $findings } + $detail = ($result.Failures | Select-Object -Property File, Message -Unique | Select-Object -First 3 | ForEach-Object { "{0}: {1}" -f (Resolve-Path -Path $_.File -Relative -ErrorAction SilentlyContinue), $_.Message }) -join '; ' + if ($affected.Count -gt 3 -and $attempt -lt $maximumAttempts) { + # A lost command lookup poisons the process: every file analysed after it fails too. Re-running the + # whole path in a fresh process is then cheaper than re-analysing every affected file on its own. + Write-Warning ("PSScriptAnalyzer rules failed on {0} file(s) under '{1}' ({2}); re-running the analysis in a fresh process (attempt {3} of {4})." -f $affected.Count, $Path, $detail, ($attempt + 1), $maximumAttempts) + Start-Sleep -Seconds 2 + continue } + Write-Warning ("PSScriptAnalyzer rules failed on {0} file(s) under '{1}' ({2}); re-analysing those files in fresh processes." -f $affected.Count, $Path, $detail) + $findings = @($findings | Where-Object { $_.ScriptPath -notin $affected }) + foreach ($file in $affected) { + $findings += Invoke-BuildScriptFileAnalysis -Path $file + } + return $findings + } +} + +function Invoke-BuildScriptFileAnalysis { + <# + .SYNOPSIS + Analyses one file in fresh processes until no rule fails on it (at most three attempts). + #> + param( + [Parameter(Mandatory)] + [string] $Path + ) + + $maximumAttempts = 3 + $lastMessage = '' + for ($attempt = 1; $attempt -le $maximumAttempts; $attempt++) { + $result = Invoke-BuildScriptAnalyzerWorker -Path $Path + if ($null -ne $result -and @($result.Failures).Count -eq 0) { return @($result.Findings) } + $lastMessage = if ($null -eq $result) { 'the process failed or timed out' } else { @($result.Failures)[0].Message } + if ($attempt -lt $maximumAttempts) { Start-Sleep -Seconds 2 } } + throw "PSScriptAnalyzer failed on '$Path' in $maximumAttempts attempts: $lastMessage" +} + +function Invoke-BuildScriptAnalyzerWorker { + <# + .SYNOPSIS + Runs tools/Invoke-ScriptAnalyzerWorker.ps1 in a fresh pwsh process with a timeout; returns its result or $null. + #> + param( + [Parameter(Mandatory)] + [string] $Path, + + [int] $TimeoutSeconds = 300 + ) + + $resultFile = Join-Path ([System.IO.Path]::GetTempPath()) ('mcp-analyze-' + [guid]::NewGuid().ToString('n') + '.xml') + $process = $null + try { + $startInfo = [System.Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = (Get-Process -Id $PID).Path + foreach ($argument in @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', $script:AnalyzerWorker, '-Path', $Path, '-Settings', $script:AnalyzerSettings, '-CustomRulePath', $script:CustomRulePath, '-ResultPath', $resultFile)) { + $startInfo.ArgumentList.Add($argument) + } + $startInfo.UseShellExecute = $false + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $process = [System.Diagnostics.Process]::Start($startInfo) + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit($TimeoutSeconds * 1000)) { + $process.Kill($true) + Write-Warning ("PSScriptAnalyzer did not finish '{0}' within {1} s; the process was stopped and the analysis is retried." -f $Path, $TimeoutSeconds) + return $null + } + $process.WaitForExit() + if ($process.ExitCode -ne 0 -or -not (Test-Path -Path $resultFile)) { + $output = (@($stdout.Result, $stderr.Result) -join "`n").Trim() + Write-Warning ("PSScriptAnalyzer process failed on '{0}' (exit code {1}): {2}" -f $Path, $process.ExitCode, $output.Split("`n")[0]) + return $null + } + Import-Clixml -Path $resultFile + } finally { + if ($null -ne $process) { $process.Dispose() } + Remove-Item -Path $resultFile -Force -ErrorAction SilentlyContinue + } +} + +# Synopsis: Format the PowerShell sources in place with Invoke-Formatter and the repository settings. +task Format { + Import-Module -Name PSScriptAnalyzer -MinimumVersion 1.25.0 -ErrorAction Stop + $roots = @('src', 'tests', 'tools', 'examples', 'build.ps1', 'ModelContextProtocol.build.ps1') | ForEach-Object { Join-Path $PSScriptRoot $_ } + $files = foreach ($root in $roots) { + if (Test-Path -Path $root -PathType Container) { + Get-ChildItem -Path $root -Recurse -File -Include '*.ps1', '*.psm1', '*.psd1' + } else { + Get-Item -Path $root + } + } + $utf8 = [System.Text.UTF8Encoding]::new($false) + $changed = 0 + foreach ($file in $files) { + $text = [System.IO.File]::ReadAllText($file.FullName) + $formatted = (Invoke-Formatter -ScriptDefinition $text -Settings $script:AnalyzerSettings).TrimEnd() + "`n" + if ($formatted -ne $text) { + [System.IO.File]::WriteAllText($file.FullName, $formatted, $utf8) + Write-Build Yellow "Format: $(Resolve-Path -Path $file.FullName -Relative)" + $changed++ + } + } + Write-Build Green "Format: $changed file(s) changed." } # Synopsis: Remove the output directory. @@ -111,15 +213,7 @@ task Build { # Synopsis: Run PSScriptAnalyzer (default rules, formatting rules and the repository's custom rules). task Analyze { - Import-Module -Name PSScriptAnalyzer -MinimumVersion 1.25.0 -ErrorAction Stop - # Warm-up on a trivial script: initialises the analyzer's command-info cache and the custom-rule runspace in this - # session, where the transient failures described in Invoke-BuildScriptAnalysis originate. Its outcome is ignored. - try { - $null = Invoke-ScriptAnalyzer -ScriptDefinition 'param() Get-Date' -Settings $script:AnalyzerSettings -CustomRulePath $script:CustomRulePath -IncludeDefaultRules -ErrorAction Stop - } catch { - Write-Warning ("PSScriptAnalyzer warm-up failed: {0}" -f $_.Exception.Message.Split("`n")[0].Trim()) - } - $paths = @('src', 'tests', 'tools', 'build.ps1', 'ModelContextProtocol.build.ps1') | ForEach-Object { Join-Path $PSScriptRoot $_ } + $paths = @('src', 'tests', 'tools', 'examples', 'build.ps1', 'ModelContextProtocol.build.ps1') | ForEach-Object { Join-Path $PSScriptRoot $_ } $findings = @(foreach ($path in $paths) { Invoke-BuildScriptAnalysis -Path $path }) if ($findings.Count -gt 0) { $findings | @@ -260,9 +354,95 @@ task Publish Build, { Write-Build Green "Published $script:ModuleName $(Get-BuildSemVer) to the PowerShell Gallery." } -# Synopsis: Run the MCP conformance suite (available from milestone M2). -task Conformance { - throw 'The conformance harness (tests/Conformance) is introduced in milestone M2; see ROADMAP.md and docs/conformance.md.' +function Start-ConformanceServer { + <# + .SYNOPSIS + Starts tests/Conformance/everything-server.ps1 on a free loopback port and waits until it accepts connections. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Build helper; starts a fixture process for the conformance run.')] + param( + [Parameter(Mandatory)] + [string] $LogPath + ) + + $probe = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) + $probe.Start() + $port = $probe.LocalEndpoint.Port + $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 + $deadline = [datetime]::UtcNow.AddSeconds(60) + while ([datetime]::UtcNow -lt $deadline) { + if ($process.HasExited) { throw "The conformance server exited with code $($process.ExitCode); see $LogPath." } + $client = [System.Net.Sockets.TcpClient]::new() + try { + $client.Connect([System.Net.IPAddress]::Loopback, $port) + if ($client.Connected) { break } + } catch { + Start-Sleep -Milliseconds 250 + } finally { + $client.Dispose() + } + } + if ([datetime]::UtcNow -ge $deadline) { throw "The conformance server did not start listening on port $port within 60 seconds; see $LogPath." } + @{ Process = $process; Url = "http://127.0.0.1:$port/mcp"; Port = $port } +} + +function Stop-ConformanceServer { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Build helper; stops the fixture process of the conformance run.')] + param( + [Parameter(Mandatory)] + [hashtable] $Handle + ) + + $process = $Handle.Process + try { + if (-not $process.HasExited) { + $process.Kill($true) + $null = $process.WaitForExit(10000) + } + } finally { + $process.Dispose() + } +} + +# Synopsis: Run the MCP conformance suite (server and client legs) for the requirement sets given with -ConformanceRequirements. +task Conformance Build, { + $npx = Get-Command -Name npx -ErrorAction SilentlyContinue + assert ($null -ne $npx) 'npx (Node.js 20 or later) is required for the conformance suite.' + $requirements = Import-PowerShellDataFile -Path (Join-Path $PSScriptRoot 'requirements.psd1') + $package = '@modelcontextprotocol/conformance@' + $requirements.Npm['@modelcontextprotocol/conformance'] + $baseline = Join-Path $PSScriptRoot 'conformance-baseline.yml' + $resultRoot = Join-Path $OutputDirectory 'conformance' + $null = New-Item -Path $resultRoot -ItemType Directory -Force + $env:MCP_MODULE_MANIFEST = Get-BuiltModuleManifest + $pwsh = (Get-Process -Id $PID).Path + $clientScript = Join-Path $script:TestsPath 'Conformance' 'everything-client.ps1' + $legs = if ($ConformanceLeg) { @($ConformanceLeg) } else { @('Server', 'Client') } + $selection = if ($ConformanceScenario) { @('--scenario', $ConformanceScenario) } else { $null } + $failures = [System.Collections.Generic.List[string]]::new() + foreach ($revision in $ConformanceRequirements) { + $scope = if ($selection) { $selection } else { @('--requirements', $revision) } + if ('Server' -in $legs) { + $log = Join-Path $resultRoot "server-$revision.log" + $handle = Start-ConformanceServer -LogPath $log + try { + Write-Build Cyan "Conformance: server leg, requirement set $revision, fixture at $($handle.Url) (log: $log)" + & $npx.Source --yes $package server --url $handle.Url @scope --expected-failures $baseline --output-dir (Join-Path $resultRoot "server-$revision") + if ($LASTEXITCODE -ne 0) { $failures.Add("server leg of $revision (exit code $LASTEXITCODE)") } + } finally { + Stop-ConformanceServer -Handle $handle + } + } + if ('Client' -in $legs) { + Write-Build Cyan "Conformance: client leg, requirement set $revision" + & $npx.Source --yes $package client --command "$pwsh -NoLogo -NoProfile -NonInteractive -File $clientScript" @scope --expected-failures $baseline --output-dir (Join-Path $resultRoot "client-$revision") + if ($LASTEXITCODE -ne 0) { $failures.Add("client leg of $revision (exit code $LASTEXITCODE)") } + } + } + assert ($failures.Count -eq 0) "Conformance failed: $($failures -join '; '). Results are under $resultRoot." + Write-Build Green "Conformance: all legs passed against the baseline ($baseline)." } # Synopsis: What CI runs: Analyze, Test, Package, PublishLocal. diff --git a/README.md b/README.md index 3d9a17c..ab0c7b7 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,14 @@ 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 M0 (foundation).** The module is a buildable, analysed and tested skeleton without -> protocol functionality. The milestones are in [ROADMAP.md](ROADMAP.md); the design is in -> [docs/implementation-plan.md](docs/implementation-plan.md). +> **Status: milestone M2 (Streamable HTTP).** Servers expose PowerShell functions, cmdlets, scripts and +> script blocks as tools over stdio and over Streamable HTTP with the stateless 2026-07-28 lifecycle +> (`server/discover`, per-request `_meta`, request metadata headers, progress, cancellation), and the client +> side connects to such servers over both transports. The official conformance suite runs in CI: every +> 2026-07-28 scenario of the tools, HTTP header validation and DNS rebinding groups passes on both legs; +> the remaining scenarios (resources, prompts, completion, input requests, subscriptions, authorization) +> are listed in [conformance-baseline.yml](conformance-baseline.yml) and follow in M3 to M7. The milestones +> are in [ROADMAP.md](ROADMAP.md); the design is in [docs/implementation-plan.md](docs/implementation-plan.md). ## Requirements @@ -14,6 +19,72 @@ and clients, targeting specification revision **2026-07-28** with dual-era suppo - `CompatiblePSEditions = Core`; Windows PowerShell 5.1 is not supported and refuses to import the module. - No runtime dependencies: a pure script module that only uses assemblies shipped with PowerShell. +## Quick start + +A server is a script that registers tools and serves stdio: + +```powershell +#Requires -Version 7.4 +Import-Module ModelContextProtocol + +function Get-Weather { + <# + .SYNOPSIS + Current weather for a location. + .PARAMETER Location + City or postal code. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $Location, + [ValidateSet('metric', 'imperial')] [string] $Units = 'metric' + ) + [pscustomobject]@{ location = $Location; temperature = 21.5; units = $Units } +} + +New-McpServer -Name weather -Version 1.0.0 -Instructions 'Weather lookups.' -SetDefault +Register-McpTool -Command (Get-Command Get-Weather) # schema from the parameters and the help +Register-McpTool -Name echo -ScriptBlock { param([Parameter(Mandatory)][string] $Text) $Text } +Start-McpServer # serves stdio until stdin closes +``` + +Hosts start it with `pwsh -NoLogo -NoProfile -NonInteractive -File ./weather-server.ps1`. Tool arguments are +validated against the generated JSON Schema and bound to the parameters; objects become +`structuredContent`, strings become text, `New-McpContent` builds image, audio and resource blocks, and +`Write-McpProgress`/`Write-McpLog` reach the client through a `Context` parameter. Handlers run in a worker +runspace pool, so nothing they write to the host can reach stdout. + +The client side: + +```powershell +$session = Connect-McpServer -Command pwsh -Arguments '-NoLogo', '-NoProfile', '-NonInteractive', '-File', './weather-server.ps1' +Get-McpServerInfo | Format-List +Get-McpTool | Select-Object Name, Description +$result = Invoke-McpTool -Name Get-Weather -Arguments @{ Location = 'Berlin' } +$result.StructuredContent.temperature +Disconnect-McpServer +``` + +Over Streamable HTTP the same server listens on a URL, and the same client commands connect to it: + +```powershell +Start-McpServer -Transport Http -Url http://127.0.0.1:8080/mcp/ # POST-only endpoint, SSE for progress + +$session = Connect-McpServer -Url http://127.0.0.1:8080/mcp/ +Invoke-McpTool -Name Get-Weather -Arguments @{ Location = 'Berlin' } +``` + +The HTTP server validates the request metadata headers of revision 2026-07-28 (`MCP-Protocol-Version`, +`Mcp-Method`, `Mcp-Name`, `Mcp-Param-*`), the `Host` and `Origin` headers (DNS rebinding protection) and answers with the +HTTP statuses the specification assigns to the JSON-RPC error codes; the client sends those headers, +mirrors parameters registered with `Register-McpTool -Header` into `Mcp-Param-*` headers and reads JSON or +SSE responses. See [docs/concepts/transports.md](docs/concepts/transports.md). + +`Connect-McpServer -Server $serverObject` runs a server in a background runspace over an in-memory transport, +which is how the tests exercise servers without child processes. `Invoke-McpToolHandler` calls a registered +tool directly for unit tests of the tool itself. See `examples/echo-server.ps1`, `examples/http-server.ps1` +and [docs/development.md](docs/development.md) for the Inspector command line. + ## Building from source ```powershell @@ -36,15 +107,16 @@ conventions; [docs/development.md](docs/development.md) has the details of the b separate legacy component that shares the same endpoint and process. - **Transports.** stdio (raw UTF-8 streams, nothing but protocol messages on stdout) and Streamable HTTP on `System.Net.HttpListener` with an SSE writer; an in-memory transport for tests. -- **Conformance first.** The official conformance suite runs in CI from milestone M2 against a baseline that - may only shrink; 1.0.0 requires an empty baseline for the 2026-07-28 and 2025-11-25 requirement sets. +- **Conformance first.** The official conformance suite runs in CI (`.github/workflows/conformance.yml`, + `./build.ps1 -Task Conformance`) against a baseline that may only shrink; 1.0.0 requires an empty baseline + for the 2026-07-28 and 2025-11-25 requirement sets. ## Repository | Path | Purpose | |---|---| | `src/` | Module sources and manifest | -| `tests/` | Pester tests (unit, integration, spec, compat; conformance from M2) | +| `tests/` | Pester tests (unit, integration, spec, compat) and the conformance fixtures (`tests/Conformance`) | | `tools/` | Custom PSScriptAnalyzer rules, maintenance scripts, offline package drop folder | | `docs/` | Concept documentation, implementation plan, research material | | `.github/` | CI matrix, release workflow, label sync, issue templates | diff --git a/ROADMAP.md b/ROADMAP.md index 5f6b9a0..6a2dddc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -15,9 +15,9 @@ against the requirement sets `2026-07-28` (37 server + 32 client scenarios) and | Milestone | Scope | Exit criterion | Status | |---|---|---|---| -| **M0 Foundation** | Toolchain, module skeleton, ModuleBuilder build, analyzer rules, Pester skeleton, vendored schemas, CI matrix, release dry run, governance documents | CI green on all matrix cells with the empty module; side-effect-free import; publishing to a local repository works | In progress | -| **M1 Protocol core, stdio, tools (modern)** | System.Text.Json codec, JSON-RPC model, `_meta` validation, error codes, router, `server/discover`, capabilities, extension registry, in-memory transport, dispatcher and runspace pool, stdio server and client transports, `tools/list`, `tools/call` (text), schema generator and validator, progress, cancellation | Unit and integration tests green; Inspector CLI `tools/list` against `examples/echo-server.ps1`; startup and per-request overhead measured | Planned | -| **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 | Planned | +| **M0 Foundation** | Toolchain, module skeleton, ModuleBuilder build, analyzer rules, Pester skeleton, vendored schemas, CI matrix, release dry run, governance documents | CI green on all matrix cells with the empty module; side-effect-free import; publishing to a local repository works | Done | +| **M1 Protocol core, stdio, tools (modern)** | System.Text.Json codec, JSON-RPC model, `_meta` validation, error codes, router, `server/discover`, capabilities, extension registry, in-memory transport, dispatcher and runspace pool, stdio server and client transports, `tools/list`, `tools/call` (text), schema generator and validator, progress, cancellation | Unit and integration tests green; Inspector CLI `tools/list` against `examples/echo-server.ps1`; startup and per-request overhead measured | Done | +| **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` | Planned | | **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 | All 14 `input-required-result-*`, `server-sse-multiple-streams`; client `sep-2322-client-request-state` | Planned | | **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 | @@ -30,7 +30,7 @@ against the requirement sets `2026-07-28` (37 server + 32 client scenarios) and | Area | Milestone | |---|---| | `server/discover`, `_meta` validation, error codes `-32020`/`-32021`/`-32022`, capabilities | M1 | -| `tools/list`, `tools/call` | M1 (text), M3 (all content types, structured output) | +| `tools/list`, `tools/call` | M1 (text), M2 (all content types, structured output; the `tools-call-*` scenarios pass) | | stdio transport (server and client) | M1 | | Streamable HTTP (server and client), header validation, Origin protection | M2 | | `resources/*`, `prompts/*`, `completion/complete`, caching (`ttlMs`, `cacheScope`), pagination | M3 | diff --git a/build.ps1 b/build.ps1 index ea10711..10f0248 100644 --- a/build.ps1 +++ b/build.ps1 @@ -42,6 +42,15 @@ .PARAMETER ExcludeTestTag 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. + +.PARAMETER ConformanceLeg + Restrict the Conformance task to the Server or the Client leg. + +.PARAMETER ConformanceScenario + Run a single conformance scenario instead of a requirement set. + .EXAMPLE ./build.ps1 -Bootstrap -Task CI @@ -67,7 +76,14 @@ param( [string[]] $TestTag, - [string[]] $ExcludeTestTag + [string[]] $ExcludeTestTag, + + [string[]] $ConformanceRequirements = @('2026-07-28'), + + [ValidateSet('Server', 'Client')] + [string[]] $ConformanceLeg, + + [string] $ConformanceScenario ) $ErrorActionPreference = 'Stop' @@ -353,5 +369,8 @@ if ($SemVer) { $invokeBuildParameters['SemVer'] = $SemVer } if ($CodeCoverage) { $invokeBuildParameters['CodeCoverage'] = $true } if ($TestTag) { $invokeBuildParameters['TestTag'] = $TestTag } if ($ExcludeTestTag) { $invokeBuildParameters['ExcludeTestTag'] = $ExcludeTestTag } +if ($ConformanceRequirements) { $invokeBuildParameters['ConformanceRequirements'] = $ConformanceRequirements } +if ($ConformanceLeg) { $invokeBuildParameters['ConformanceLeg'] = $ConformanceLeg } +if ($ConformanceScenario) { $invokeBuildParameters['ConformanceScenario'] = $ConformanceScenario } Invoke-Build @invokeBuildParameters diff --git a/conformance-baseline.yml b/conformance-baseline.yml index 64d082d..b8fdbf4 100644 --- a/conformance-baseline.yml +++ b/conformance-baseline.yml @@ -5,6 +5,60 @@ # 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). Conformance runs start in milestone M2; see docs/conformance.md. -server: [] -client: [] +# (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. +server: + # M3: resources, prompts, completion and caching hints on their results + - completion-complete + - resources-list + - resources-read-text + - resources-read-binary + - resources-templates-read + - sep-2164-resource-not-found + - prompts-list + - prompts-get-simple + - prompts-get-with-args + - prompts-get-embedded-resource + - prompts-get-with-image + - caching + # M4: input requests (MRTR); the two scenarios that only warn today (SHOULD checks) are listed as well + - input-required-result-basic-elicitation + - input-required-result-basic-sampling + - input-required-result-basic-list-roots + - input-required-result-request-state + - input-required-result-multiple-input-requests + - input-required-result-multi-round + - input-required-result-missing-input-response + - input-required-result-non-tool-request + - input-required-result-result-type + - input-required-result-tampered-state + - input-required-result-capability-check + - input-required-result-ignore-extra-params +client: + # M4: input requests + - sep-2322-client-request-state + # M6: authorization + - auth/metadata-default + - auth/metadata-var1 + - auth/metadata-var2 + - auth/metadata-var3 + - auth/basic-cimd + - auth/scope-from-www-authenticate + - auth/scope-from-scopes-supported + - auth/scope-omitted-when-undefined + - auth/scope-step-up + - auth/scope-retry-limit + - auth/token-endpoint-auth-basic + - auth/token-endpoint-auth-post + - auth/token-endpoint-auth-none + - auth/pre-registration + - auth/offline-access-scope + - auth/offline-access-not-supported + - auth/authorization-server-migration + - auth/iss-supported + - auth/iss-not-advertised + - auth/iss-supported-missing + - auth/iss-wrong-issuer + - auth/iss-unexpected + - auth/iss-normalized + - auth/metadata-issuer-mismatch diff --git a/docs/concepts/transports.md b/docs/concepts/transports.md index ba3ae1c..2811daf 100644 --- a/docs/concepts/transports.md +++ b/docs/concepts/transports.md @@ -1,6 +1,12 @@ # Transports -Implemented in milestones M1 (stdio) and M2 (Streamable HTTP). This page records the design constraints. +stdio (milestone M1) and Streamable HTTP (milestone M2) are implemented. This page records the design and its +constraints. + +Transports are plain data inside the module (a hashtable with a line reader and a line writer per kind) used +only through a handful of private functions, so the same dispatcher and client code runs in whichever +runspace hosts it. Besides stdio there is an in-memory transport (a pair of channels) that +`Connect-McpServer -Server` uses to run a server object in a background runspace of the same process. ## stdio @@ -13,17 +19,66 @@ Implemented in milestones M1 (stdio) and M2 (Streamable HTTP). This page records - Launch contract for hosts: `pwsh -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `. - Shutdown: EOF on stdin ends the server; the client closes the child's stdin, waits, then kills the process tree. +- The client captures the server's stderr in a file (`StandardErrorPath` of the session), unbuffered, so that + diagnostics can be read while the server runs. ## Streamable HTTP -- Host: `System.Net.HttpListener` behind a small host abstraction (request context, JSON writer, SSE writer - with keep-alive and disconnect → cancel). Default binding `http://127.0.0.1:/mcp/`, Origin allowlist - (403), TLS only via a reverse proxy or an http.sys certificate binding on Windows. -- 2026-07-28: POST only; `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` and `Mcp-Param-*` header - validation against the request body (`-32020` on mismatch, 400); notifications answer 202; unknown methods - 404 with `-32601`; GET and DELETE answer 405 unless the legacy layer is enabled. -- Response mode: JSON when the request carries no progress token, log level or listen semantics; SSE - (`data: \n\n`, initial comment line) otherwise. `subscriptions/listen` streams stay open with - keep-alives. -- Client: `HttpClient` with `SocketsHttpHandler` (no auto-redirect, infinite timeout with own cancellation - tokens), `ResponseHeadersRead`, an SSE parser, header mirroring for `x-mcp-header` tool parameters. +`Start-McpServer -Transport Http -Url http://127.0.0.1:8080/mcp/` serves the MCP endpoint; +`Connect-McpServer -Url` connects to one. + +**Server (`src/Private/HttpServer.ps1`)** + +- Host: `System.Net.HttpListener` with exactly the prefix of `-Url` (`scheme://host:port/path/`). The + server answers requests whose `Host` header does not name that host and port with 404, so clients must use + the same host name or address; this is the first line of DNS-rebinding protection and is checked by the + server itself because the listener implementations differ (the managed listener on Linux and macOS rejects + other hosts on its own, http.sys on Windows delivers any `Host` to a prefix bound to an IP address). The + default binding is the loopback address. TLS is not terminated by the module: put a reverse + proxy in front, or use an http.sys certificate binding on Windows. On Windows, users without administrative + rights need a URL reservation (`netsh http add urlacl`) for the prefix. +- The dispatcher loop (`Invoke-McpHttpDispatcherLoop`) accepts connections, reads bodies asynchronously + (`-MaxBodyBytes`, 413 beyond), and gives every request a *channel*: its HTTP response. `server/discover` and + `tools/list` are answered by the dispatcher; `tools/call` runs in the worker pool and its notifications and + 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), + 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 + `_meta.io.modelcontextprotocol/protocolVersion`, `Mcp-Method` equal to the method (case-sensitive, optional + whitespace trimmed), `Mcp-Name` for `tools/call`, `resources/read` and `prompts/get` equal to `params.name` + 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. +- 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`). +- 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 + `-KeepAliveSeconds` (default 5) also switches to SSE and receives keep-alive comments: a failed keep-alive + write means the client closed the connection, which cancels the handler (token and pipeline stop). The + same happens when the final write fails. +- Shutdown (`Stop-McpServer`): the listener stops accepting, running handlers get the grace period, open + channels receive an error response (`-32603`, "shutting down") and are closed. + +**Client (`src/Private/HttpClient.ps1`)** + +- `HttpClient` on `SocketsHttpHandler` (no redirects, no cookies, no proxy for loopback URLs or with + `-NoProxy`, infinite client timeout); every request is a POST with `Content-Type: application/json`, + `Accept: application/json, text/event-stream`, `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` where the + method has one (sentinel-encoded when not header-safe), the session's static `-Headers` and the + `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 + 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). diff --git a/docs/conformance.md b/docs/conformance.md index 2ff96cf..92b0455 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -2,8 +2,34 @@ 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. -Conformance fixtures (`tests/Conformance/everything-server.ps1`, `everything-client.ps1`) and the CI workflow -`conformance.yml` arrive with milestone M2; this page documents the mechanics they will use. +The fixtures live in `tests/Conformance/` (`everything-server.ps1`, a Streamable HTTP server with every tool +the server scenarios call; `everything-client.ps1`, a client that discovers, lists and calls tools 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. + +## Running the suite + +```powershell +./build.ps1 -Task Conformance # both legs, requirement set 2026-07-28 +./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 +(`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 M2 + +Requirement set `2026-07-28`, server leg: `server-stateless` (25 checks), `tools-list`, the seven +`tools-call-*` scenarios, `sep-2164-resource-not-found`, `dns-rebinding-protection` and +`server-sse-multiple-streams` pass; the not-scored `json-schema-2020-12`, `http-header-validation` and +`http-custom-header-server-validation` pass too. Client leg: `tools_call`, `request-metadata`, +`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. Everything else is in +`conformance-baseline.yml`, grouped by the milestone that removes it. ## Requirement sets @@ -16,7 +42,7 @@ Each set is scored only at its own wire, so the server is run twice (a modern-on dual-era instance) 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 (from M2) +## 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 diff --git a/docs/development.md b/docs/development.md index d1b2dd2..b2d9e2d 100644 --- a/docs/development.md +++ b/docs/development.md @@ -10,7 +10,7 @@ | PSScriptAnalyzer | static analysis, formatting, custom rules | `./build.ps1 -Bootstrap` | | Pester 6 | tests | `./build.ps1 -Bootstrap` | | Microsoft.PowerShell.PlatyPS | help generation (optional locally) | `./build.ps1 -Bootstrap` | -| Node.js 20+ | conformance suite and Inspector (from M2) | you | +| Node.js 20+ | conformance suite (`Conformance` task) and Inspector | you | `build.ps1` verifies the declared version ranges (`requirements.psd1`) on every run and installs missing dependencies only with `-Bootstrap`. Sources are tried in the order PowerShell Gallery, `api.nuget.org` @@ -21,16 +21,17 @@ offline folder `tools/packages/` (`-DependencySource Offline`). | Task | Does | |---|---| +| `Format` | `Invoke-Formatter` over `src`, `tests`, `tools`, `examples` and the build scripts with the repository settings, in place | | `Clean` | removes `output/` | | `Build` | ModuleBuilder: `src/{Enums,Classes,Private,Public}` in file-name order + `Suffix.ps1` → `output/ModelContextProtocol//ModelContextProtocol.psm1`; copies `en-US/`, `Types/`, `Formats/`, `LICENSE`; sets version and prerelease from `-SemVer` (default: manifest) | -| `Analyze` | PSScriptAnalyzer over `src`, `tests`, `tools` and the build scripts with `PSScriptAnalyzerSettings.psd1` and the custom rules; any finding fails the task | +| `Analyze` | PSScriptAnalyzer over `src`, `tests`, `tools`, `examples` and the build scripts with `PSScriptAnalyzerSettings.psd1` and the custom rules; any finding fails the task. Each path is analysed in a fresh `pwsh` process with a timeout (`tools/Invoke-ScriptAnalyzerWorker.ps1`), and files on which a rule failed (PSScriptAnalyzer 1.25 runs its rules in parallel and occasionally loses a command lookup or throws a NullReferenceException) are re-analysed in further fresh processes; retries appear as build warnings | | `Test` | `Build`, then Pester over `tests/Unit`, `tests/Integration`, `tests/Spec`, `tests/Compat` against the built module; NUnit XML under `output/test-results/`; `-TestTag`/`-ExcludeTestTag` filter, `-CodeCoverage` adds JaCoCo under `output/coverage/` | | `Coverage` | `Test` with coverage enabled | | `Help` | PlatyPS markdown under `docs/help/` and MAML in the built module (no-op while the module exports nothing) | | `Package` | `Build`, then `Compress-PSResource` → `output/packages/ModelContextProtocol..nupkg` | | `PublishLocal` | `Build`, then `Publish-PSResource` to a file-share repository under `output/local-repository/`, `Find-PSResource`, `Save-PSResource` and an import in a fresh process: the release dry run | | `Publish` | `Publish-PSResource` to the PowerShell Gallery with `PSGALLERY_API_KEY` | -| `Conformance` | conformance suite (from M2) | +| `Conformance` | `Build`, then the server and the client leg of `@modelcontextprotocol/conformance` (pinned in `requirements.psd1`) against `conformance-baseline.yml`; `-ConformanceRequirements`, `-ConformanceLeg`, `-ConformanceScenario`; results under `output/conformance/` (see [conformance.md](conformance.md)) | | `CI` | `Analyze`, `Test`, `Package`, `PublishLocal` | ## Tests @@ -41,16 +42,59 @@ 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 | in-process | -| `tests/Integration` | fresh `pwsh` processes: import must be silent on stdout and stderr, also under `-File` | spawns processes | +| `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 `tools/list` shapes against the vendored schema, header value encoding and `x-mcp-header` validation, HTTP status mapping, Origin checks, SSE parsing | 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); 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/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: + +```json +{ + "mcpServers": { + "echo": { + "command": "pwsh", + "args": ["-NoLogo", "-NoProfile", "-NonInteractive", "-File", "/abs/path/examples/echo-server.ps1"], + "env": { "MCP_MODULE_MANIFEST": "/abs/path/output/ModelContextProtocol/0.1.0/ModelContextProtocol.psd1" }, + "protocolEra": "modern" + } + } +} +``` + +```bash +npx @modelcontextprotocol/inspector --cli --config inspector.json --server echo --method tools/list --format json +npx @modelcontextprotocol/inspector --cli --config inspector.json --server echo --method tools/call --tool-name add --tool-args-json '{"A":2,"B":40}' +``` + +`MCP_MODULE_MANIFEST` makes the example import the built module instead of an installed one. + +## Performance (milestone M1, PowerShell 7.4 on Linux, 4 cores) + +| Measurement | Value | +|---|---| +| `Connect-McpServer` to `examples/echo-server.ps1` (process start, module import, `server/discover`) | about 1 s | +| First `tools/call` after start (worker runspace warm-up) | about 200 ms | +| Sequential `tools/call` round trip, stdio or in-memory | 25 to 30 ms | +| Four parallel calls that each sleep 2 × 200 ms (`-MaxConcurrency 4`) | about 520 ms in total | +| Stopping a cancelled handler that sleeps with `Start-Sleep` | about 25 ms | +| `Connect-McpServer -Url` to a server in the same process (`server/discover`, `tools/list`) | about 400 ms (first request, includes the worker warm-up) | +| Sequential `tools/call` round trip over Streamable HTTP (loopback, JSON response) | 35 to 40 ms | +| Detecting a client that closed its response stream (keep-alive interval + TCP reset) | keep-alive interval + about 2 s | + +A handler blocked in a .NET call that ignores the pipeline stop (for example `[Thread]::Sleep`) is only +stopped when the call returns; handlers should watch `$Context.CancellationToken` in long loops. + ## CI `.github/workflows/ci.yml` runs `lint` (ubuntu, PowerShell 7.4), the `test` matrix (ubuntu, windows, macOS × PowerShell 7.4.20, 7.5.11, 7.6.6), `ps51-guard` (windows) and `package` (ubuntu; `Package` + `PublishLocal`, -uploads the `.nupkg`). The composite action `.github/actions/install-pwsh` downloads the pinned PowerShell +uploads the `.nupkg`). `.github/workflows/conformance.yml` runs the `Conformance` task on ubuntu with the +runner's Node.js and uploads `output/conformance/`. The composite action `.github/actions/install-pwsh` downloads the pinned PowerShell release asset and prepends it to `PATH`, so every `shell: pwsh` step runs the pinned version; the `VersionMatrix` test asserts it. All actions are pinned to commit SHAs (Dependabot keeps them current). diff --git a/examples/echo-server.ps1 b/examples/echo-server.ps1 new file mode 100644 index 0000000..a23ea7e --- /dev/null +++ b/examples/echo-server.ps1 @@ -0,0 +1,76 @@ +#Requires -Version 7.4 +<# +.SYNOPSIS + A small MCP server over stdio: echo, add, count (with progress), fail and shout tools. +.DESCRIPTION + Start it from an MCP client with: + pwsh -NoLogo -NoProfile -NonInteractive -File ./examples/echo-server.ps1 + The module is imported from $env:MCP_MODULE_MANIFEST when set (the repository's tests use the built + module), otherwise from the installed ModelContextProtocol module. +#> +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'The shout tool writes to the host on purpose to show that host output never reaches the client.')] +[CmdletBinding()] +param() + +if ($env:MCP_MODULE_MANIFEST) { + Import-Module -Name $env:MCP_MODULE_MANIFEST -ErrorAction Stop +} else { + Import-Module -Name ModelContextProtocol -ErrorAction Stop +} + +$server = New-McpServer -Name 'echo' -Version '0.1.0' -Title 'Echo server' -Instructions 'A demonstration server: echo text, add numbers, count with progress.' -SetDefault + +Register-McpTool -Name 'echo' -Description 'Returns the text, optionally repeated.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [string] $Text, + + [ValidateRange(1, 10)] + [int] $Repeat = 1 + ) + $Text * $Repeat +} + +Register-McpTool -Name 'add' -Description 'Adds two numbers and returns the sum as structured content.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [double] $A, + + [Parameter(Mandatory)] + [double] $B + ) + [pscustomobject]@{ sum = $A + $B } +} -OutputSchema @{ type = 'object'; properties = @{ sum = @{ type = 'number' } }; required = @('sum') } + +Register-McpTool -Name 'count' -Description 'Counts to N, reporting progress; honours cancellation.' -ScriptBlock { + param( + [ValidateRange(1, 100)] + [int] $To = 3, + + [ValidateRange(0, 5000)] + [int] $DelayMs = 100, + + [object] $Context + ) + for ($i = 1; $i -le $To; $i++) { + if ($Context.CancellationToken.IsCancellationRequested) { return "cancelled at $i" } + Write-McpProgress -Context $Context -Progress $i -Total $To -Message "count $i" + Write-McpLog -Context $Context -Level info -Message "counted $i" + Start-Sleep -Milliseconds $DelayMs + } + "counted to $To" +} + +Register-McpTool -Name 'fail' -Description 'Always fails, as a tool execution error the model can see.' -ScriptBlock { + throw 'This tool always fails.' +} + +Register-McpTool -Name 'shout' -Description 'Writes to the host and streams; only the return value reaches the client.' -ScriptBlock { + param([string] $Text = 'hello') + Write-Host "host output must not reach stdout: $Text" + Write-Verbose 'verbose output' + Write-Warning 'a warning for the server log' + Write-Output $Text.ToUpperInvariant() +} + +Start-McpServer -Server $server diff --git a/examples/http-server.ps1 b/examples/http-server.ps1 new file mode 100644 index 0000000..a8bcb43 --- /dev/null +++ b/examples/http-server.ps1 @@ -0,0 +1,77 @@ +#Requires -Version 7.4 +<# +.SYNOPSIS + The echo tools over Streamable HTTP: an MCP endpoint on the loopback interface. +.DESCRIPTION + Start it with + pwsh -NoLogo -NoProfile -File ./examples/http-server.ps1 -Port 8080 + and connect with + $session = Connect-McpServer -Url http://127.0.0.1:8080/mcp/ + or point an HTTP-capable MCP host at http://127.0.0.1:8080/mcp. Ctrl+C stops the server. The module is + imported from $env:MCP_MODULE_MANIFEST when set, otherwise from the installed ModelContextProtocol module. +.PARAMETER Port + The TCP port on 127.0.0.1. +.PARAMETER AllowedOrigins + Origins accepted in the Origin header (default: loopback origins only). +#> +[CmdletBinding()] +param( + [ValidateRange(1, 65535)] + [int] $Port = 8080, + + [string[]] $AllowedOrigins +) + +if ($env:MCP_MODULE_MANIFEST) { + Import-Module -Name $env:MCP_MODULE_MANIFEST -ErrorAction Stop +} else { + Import-Module -Name ModelContextProtocol -ErrorAction Stop +} + +$server = New-McpServer -Name 'echo-http' -Version '0.1.0' -Title 'Echo server over HTTP' -Instructions 'A demonstration server: echo text, look up a region, count with progress.' -LogLevel Info -SetDefault + +Register-McpTool -Name 'echo' -Description 'Returns the text, optionally repeated.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [string] $Text, + + [ValidateRange(1, 10)] + [int] $Repeat = 1 + ) + $Text * $Repeat +} + +# -Header mirrors the Region argument into the Mcp-Param-Region header, so that proxies can route on it. +Register-McpTool -Name 'lookup' -Description 'Looks something up in a region.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [ValidateSet('eu-central', 'us-west', 'ap-south')] + [string] $Region, + + [Parameter(Mandatory)] + [string] $Query + ) + [pscustomobject]@{ region = $Region; query = $Query; hits = $Query.Length } +} -Header @{ Region = 'Region' } + +Register-McpTool -Name 'count' -Description 'Counts to N, reporting progress on the SSE stream; honours cancellation.' -ScriptBlock { + param( + [ValidateRange(1, 100)] + [int] $To = 3, + + [ValidateRange(0, 5000)] + [int] $DelayMs = 200, + + [object] $Context + ) + for ($i = 1; $i -le $To; $i++) { + if ($Context.CancellationToken.IsCancellationRequested) { return "cancelled at $i" } + Write-McpProgress -Context $Context -Progress $i -Total $To -Message "count $i" + Start-Sleep -Milliseconds $DelayMs + } + "counted to $To" +} + +$startParameters = @{ Server = $server; Transport = 'Http'; Url = "http://127.0.0.1:$Port/mcp/" } +if ($AllowedOrigins) { $startParameters['AllowedOrigins'] = $AllowedOrigins } +Start-McpServer @startParameters diff --git a/src/Classes/.gitkeep b/src/Classes/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Classes/010-McpProtocolException.ps1 b/src/Classes/010-McpProtocolException.ps1 new file mode 100644 index 0000000..3658473 --- /dev/null +++ b/src/Classes/010-McpProtocolException.ps1 @@ -0,0 +1,16 @@ +# A JSON-RPC error as an exception. The router and the handlers throw it; the dispatcher turns it into an +# error response with Code as error.code, Message as error.message and Data (optional) as error.data. +[NoRunspaceAffinity()] +class McpProtocolException : System.Exception { + [int] $Code + [object] $Data + + McpProtocolException([int] $code, [string] $message) : base($message) { + $this.Code = $code + } + + McpProtocolException([int] $code, [string] $message, [object] $data) : base($message) { + $this.Code = $code + $this.Data = $data + } +} diff --git a/src/Formats/ModelContextProtocol.Format.ps1xml b/src/Formats/ModelContextProtocol.Format.ps1xml index 1e67116..ac534d4 100644 --- a/src/Formats/ModelContextProtocol.Format.ps1xml +++ b/src/Formats/ModelContextProtocol.Format.ps1xml @@ -1,9 +1,97 @@ + + Mcp.Session + + Mcp.Session + + + + + 9 + 16 + 7 + + + + + + Name + Kind + ProtocolVersion + Closed + Endpoint + + + + + + + Mcp.ServerInfo + + Mcp.ServerInfo + + + + + + Name + Version + Title + ProtocolVersion + $_.SupportedVersions -join ', ' + if ($_.Capabilities) { @($_.Capabilities.Keys) -join ', ' } + Instructions + + + + + + + Mcp.Tool + + Mcp.Tool + + + + 28 + 20 + + + + + + + Name + Title + Description + + + + + + + Mcp.ToolResult + + Mcp.ToolResult + + + + + + ToolName + IsError + Text + @($_.Content | ForEach-Object { $_.type }) -join ', ' + if ($null -ne $_.StructuredContent) { $_.StructuredContent | ConvertTo-Json -Compress -Depth 20 } + + + + + diff --git a/src/Private/.gitkeep b/src/Private/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Private/Base64.ps1 b/src/Private/Base64.ps1 new file mode 100644 index 0000000..ffa4f7f --- /dev/null +++ b/src/Private/Base64.ps1 @@ -0,0 +1,26 @@ +function ConvertTo-McpBase64 { + <# + .SYNOPSIS + Base64 text for binary content given as byte[] or as an already encoded string. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [object] $Data + ) + + if ($Data -is [byte[]]) { return [System.Convert]::ToBase64String([byte[]] $Data) } + if ($Data -is [string]) { + try { + $null = [System.Convert]::FromBase64String([string] $Data) + return [string] $Data + } catch { + throw [System.ArgumentException]::new('Binary content must be a byte[] or a valid base64 string.') + } + } + if ($Data -is [System.Collections.IEnumerable]) { + return [System.Convert]::ToBase64String([byte[]] @($Data)) + } + throw [System.ArgumentException]::new('Binary content must be a byte[] or a valid base64 string.') +} diff --git a/src/Private/Client.ps1 b/src/Private/Client.ps1 new file mode 100644 index 0000000..fd1d34b --- /dev/null +++ b/src/Private/Client.ps1 @@ -0,0 +1,404 @@ +# Client side: the session object (PSTypeName Mcp.Session), request/response over a transport with progress +# and log notifications dispatched on the way, and the public object shapes (Mcp.ServerInfo, Mcp.Tool, +# Mcp.ToolResult). + +$script:McpDefaultSession = $null + +function Get-McpModuleVersionString { + [CmdletBinding()] + [OutputType([string])] + param() + + $module = $ExecutionContext.SessionState.Module + if ($module -and $module.Version) { return $module.Version.ToString() } + '0.0.0' +} + +function Test-McpSessionObject { + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Session + ) + + $null -ne $Session -and $Session.PSObject.TypeNames -contains 'Mcp.Session' +} + +function Resolve-McpSession { + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [AllowNull()] + [object] $Session + ) + + if ($null -ne $Session) { + if (-not (Test-McpSessionObject -Session $Session)) { + throw [System.ArgumentException]::new('The -Session argument is not a session created by Connect-McpServer.') + } + if ($Session.Closed) { + throw [System.InvalidOperationException]::new('The session is closed.') + } + return $Session + } + if ($null -eq $script:McpDefaultSession -or $script:McpDefaultSession.Closed) { + throw [System.InvalidOperationException]::new('No session given and no default session; connect with Connect-McpServer first.') + } + $script:McpDefaultSession +} + +function New-McpClientRequestMeta { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')] + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [AllowNull()] + [object] $ProgressToken, + + [AllowNull()] + [object] $LogLevel + ) + + $meta = [ordered]@{} + $meta[$script:McpMetaKey.ProtocolVersion] = $Session.ProtocolVersion + $meta[$script:McpMetaKey.ClientCapabilities] = $Session.ClientCapabilities + if ($null -ne $Session.ClientInfo) { $meta[$script:McpMetaKey.ClientInfo] = $Session.ClientInfo } + if ($null -ne $LogLevel) { $meta[$script:McpMetaKey.LogLevel] = (ConvertTo-McpLoggingLevel -Level $LogLevel).ToString().ToLowerInvariant() } + if ($null -ne $ProgressToken) { $meta[$script:McpMetaKey.ProgressToken] = $ProgressToken } + $meta +} + +function Send-McpClientNotification { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [string] $Method, + + [System.Collections.IDictionary] $Params + ) + + if ($Session.Transport.Kind -eq 'Http') { + Send-McpHttpClientNotification -Session $Session -Method $Method -Params $Params + return + } + $notification = New-McpNotification -Method $Method -Params $Params + Send-McpTransportLine -Transport $Session.Transport -Line (ConvertTo-McpJson -InputObject $notification) +} + +function Invoke-McpClientRequest { + <# + .SYNOPSIS + Sends a request with the session's _meta and waits for its response, dispatching notifications meanwhile. + .DESCRIPTION + Returns the result object. A JSON-RPC error response is thrown as McpProtocolException. On timeout a + notifications/cancelled is sent and a TimeoutException thrown. Progress notifications for the request's + token go to -OnProgress; notifications/message go to the session log and -OnLog; other notifications + are queued on the session. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [string] $Method, + + [System.Collections.IDictionary] $Params, + + [scriptblock] $OnProgress, + + [AllowNull()] + [object] $LogLevel, + + [int] $TimeoutMs = 0, + + # Additional HTTP headers of this request (Streamable HTTP only), for example Mcp-Param-* headers. + [hashtable] $Headers + ) + + if ($Session.Transport.Kind -eq 'Http') { + return Invoke-McpHttpClientRequest -Session $Session -Method $Method -Params $Params -OnProgress $OnProgress -LogLevel $LogLevel -TimeoutMs $TimeoutMs -Headers $Headers + } + if ($TimeoutMs -le 0) { $TimeoutMs = [int] $Session.RequestTimeoutMs } + $id = [int] $Session.NextId + $Session.NextId = $id + 1 + $progressToken = if ($OnProgress) { "p-$id" } else { $null } + $requestParams = [ordered]@{} + $requestParams['_meta'] = New-McpClientRequestMeta -Session $Session -ProgressToken $progressToken -LogLevel $LogLevel + if ($null -ne $Params) { + foreach ($key in $Params.Keys) { + if ([string] $key -eq '_meta') { continue } + $requestParams[[string] $key] = $Params[$key] + } + } + $request = New-McpRequest -Id $id -Method $Method -Params $requestParams + Send-McpTransportLine -Transport $Session.Transport -Line (ConvertTo-McpJson -InputObject $request) + + $deadline = [datetime]::UtcNow.AddMilliseconds($TimeoutMs) + while ($true) { + $remaining = [int] [math]::Max(1, [math]::Min(500, ($deadline - [datetime]::UtcNow).TotalMilliseconds)) + $received = Receive-McpTransportLine -Transport $Session.Transport -TimeoutMs $remaining + # (if/elseif rather than switch: inside a switch, continue would apply to the switch, not to the loop.) + if ($received.Status -eq 'Eof') { + $Session.Closed = $true + $hint = if ($Session.StandardErrorPath) { " Its stderr was captured in '$($Session.StandardErrorPath)'." } else { '' } + throw [System.IO.IOException]::new("The server closed the connection while '$Method' (id $id) was pending.$hint") + } elseif ($received.Status -eq 'Timeout') { + if ([datetime]::UtcNow -lt $deadline) { continue } + try { + Send-McpClientNotification -Session $Session -Method 'notifications/cancelled' -Params ([ordered]@{ requestId = $id; reason = "timeout after $TimeoutMs ms" }) + } catch { + Write-Debug 'Sending the cancellation failed.' + } + throw [System.TimeoutException]::new("No response to '$Method' (id $id) within $TimeoutMs ms.") + } + $message = $null + try { + $message = ConvertFrom-McpJson -Json $received.Line + } catch { + Write-Warning "Ignoring a line from the server that is not JSON: $($received.Line.Substring(0, [math]::Min(120, $received.Line.Length)))" + continue + } + switch (Get-McpMessageKind -Message $message) { + 'Response' { + if ([string] $message['id'] -ceq [string] $id) { return $message['result'] } + Write-Debug "Ignoring a response with id $($message['id'])." + } + 'ErrorResponse' { + if ($message.Contains('id') -and [string] $message['id'] -ceq [string] $id) { + $errorObject = $message['error'] + $data = if ($errorObject.Contains('data')) { $errorObject['data'] } else { $null } + throw [McpProtocolException]::new([int] $errorObject['code'], [string] $errorObject['message'], $data) + } + Write-Debug "Ignoring an error response with id $($message['id'])." + } + 'Notification' { + 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)." + } + default { + Write-Warning 'Ignoring an invalid JSON-RPC message from the server.' + } + } + } +} + +function Invoke-McpClientNotificationHandler { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message, + + [AllowNull()] + [object] $ProgressToken, + + [scriptblock] $OnProgress + ) + + $method = [string] $Message['method'] + $params = if ($Message.Contains('params') -and $Message['params'] -is [System.Collections.IDictionary]) { $Message['params'] } else { [ordered]@{} } + switch ($method) { + 'notifications/progress' { + $token = if ($params.Contains('progressToken')) { $params['progressToken'] } else { $null } + if ($null -ne $ProgressToken -and $null -ne $OnProgress -and [string] $token -ceq [string] $ProgressToken) { + $progress = [pscustomobject]@{ + PSTypeName = 'Mcp.Progress' + Progress = $params['progress'] + Total = if ($params.Contains('total')) { $params['total'] } else { $null } + Message = if ($params.Contains('message')) { $params['message'] } else { $null } + Token = $token + } + try { & $OnProgress $progress } catch { Write-Warning "The progress callback failed: $($_.Exception.Message)" } + } else { + $Session.Notifications.Enqueue($Message) + } + } + 'notifications/message' { + $entry = [pscustomobject]@{ + PSTypeName = 'Mcp.LogMessage' + Level = if ($params.Contains('level')) { [string] $params['level'] } else { 'info' } + Logger = if ($params.Contains('logger')) { [string] $params['logger'] } else { $null } + Data = if ($params.Contains('data')) { $params['data'] } else { $null } + Received = [datetime]::UtcNow + } + $Session.Log.Add($entry) + if ($Session.OnLog) { + try { & $Session.OnLog $entry } catch { Write-Warning "The log callback failed: $($_.Exception.Message)" } + } + } + default { + $Session.Notifications.Enqueue($Message) + } + } +} + +function ConvertTo-McpServerInfoObject { + [CmdletBinding()] + [OutputType('Mcp.ServerInfo')] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $DiscoverResult, + + [Parameter(Mandatory)] + [string] $ProtocolVersion + ) + + $info = [ordered]@{} + if ($DiscoverResult.Contains('_meta') -and $DiscoverResult['_meta'] -is [System.Collections.IDictionary] -and $DiscoverResult['_meta'].Contains($script:McpMetaKey.ServerInfo)) { + $info = $DiscoverResult['_meta'][$script:McpMetaKey.ServerInfo] + } + if ($info.Count -eq 0 -and $DiscoverResult.Contains('serverInfo') -and $DiscoverResult['serverInfo'] -is [System.Collections.IDictionary]) { + # Servers written against the drafts before spec PR #3002 put serverInfo into the result body. + $info = $DiscoverResult['serverInfo'] + } + $get = { param($table, $key) if ($table -is [System.Collections.IDictionary] -and $table.Contains($key)) { $table[$key] } else { $null } } + [pscustomobject]@{ + PSTypeName = 'Mcp.ServerInfo' + Name = & $get $info 'name' + Version = & $get $info 'version' + Title = & $get $info 'title' + Description = & $get $info 'description' + WebsiteUrl = & $get $info 'websiteUrl' + Icons = & $get $info 'icons' + ProtocolVersion = $ProtocolVersion + SupportedVersions = @(& $get $DiscoverResult 'supportedVersions') + Capabilities = & $get $DiscoverResult 'capabilities' + Instructions = & $get $DiscoverResult 'instructions' + TtlMs = & $get $DiscoverResult 'ttlMs' + CacheScope = & $get $DiscoverResult 'cacheScope' + Raw = $DiscoverResult + } +} + +function ConvertTo-McpToolObject { + [CmdletBinding()] + [OutputType('Mcp.Tool')] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Tool + ) + + $get = { param($key) if ($Tool.Contains($key)) { $Tool[$key] } else { $null } } + [pscustomobject]@{ + PSTypeName = 'Mcp.Tool' + Name = & $get 'name' + Title = & $get 'title' + Description = & $get 'description' + InputSchema = & $get 'inputSchema' + OutputSchema = & $get 'outputSchema' + Annotations = & $get 'annotations' + Icons = & $get 'icons' + Meta = & $get '_meta' + Raw = $Tool + } +} + +function ConvertTo-McpToolResultObject { + [CmdletBinding()] + [OutputType('Mcp.ToolResult')] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Result, + + [Parameter(Mandatory)] + [string] $ToolName + ) + + $content = @() + if ($Result.Contains('content') -and $null -ne $Result['content']) { + $content = @($Result['content'] | ForEach-Object { if ($_ -is [System.Collections.IDictionary]) { [pscustomobject] $_ } else { $_ } }) + } + $text = ($content | Where-Object { $_.PSObject.Properties['type'] -and $_.type -eq 'text' } | ForEach-Object { [string] $_.text }) -join "`n" + [pscustomobject]@{ + PSTypeName = 'Mcp.ToolResult' + ToolName = $ToolName + IsError = [bool] ($Result.Contains('isError') -and $Result['isError']) + Text = $text + Content = $content + StructuredContent = if ($Result.Contains('structuredContent')) { $Result['structuredContent'] } else { $null } + ResultType = if ($Result.Contains('resultType')) { [string] $Result['resultType'] } else { 'complete' } + Meta = if ($Result.Contains('_meta')) { $Result['_meta'] } else { $null } + Raw = $Result + } +} + +function Start-McpBackgroundServer { + <# + .SYNOPSIS + Runs Start-McpServer in a background runspace (for an in-memory endpoint or with given parameters); returns the runspace handles. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller (Connect-McpServer) owns the ShouldProcess decision.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + # The server end of an in-memory transport pair. + [hashtable] $Endpoint, + + # Alternatively, the parameters of Start-McpServer (for example Transport and Url of an HTTP server). + [hashtable] $Parameters + ) + + $sessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2() + if ($IsWindows) { $sessionState.ExecutionPolicy = [Microsoft.PowerShell.ExecutionPolicy]::Bypass } + $sessionState.ImportPSModule([string[]] @($script:McpModuleManifestPath)) + $runspace = [runspacefactory]::CreateRunspace($sessionState) + $runspace.Open() + $powershell = [powershell]::Create() + $powershell.Runspace = $runspace + $command = $powershell.AddCommand('Start-McpServer').AddParameter('Server', $Server) + if ($null -ne $Endpoint) { + $null = $command.AddParameter('Transport', 'InMemory').AddParameter('Endpoint', $Endpoint) + } elseif ($null -ne $Parameters) { + $null = $command.AddParameters($Parameters) + } else { + throw [System.ArgumentException]::new('Start-McpBackgroundServer needs -Endpoint or -Parameters.') + } + $handle = $powershell.BeginInvoke() + @{ + PowerShell = $powershell + Handle = $handle + Runspace = $runspace + } +} + +function Stop-McpBackgroundServer { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller (Disconnect-McpServer) owns the ShouldProcess decision.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Background, + + [int] $TimeoutSeconds = 10 + ) + + $powershell = $Background.PowerShell + try { + if (-not $Background.Handle.AsyncWaitHandle.WaitOne($TimeoutSeconds * 1000)) { + Write-Warning 'The in-memory server did not stop in time; stopping it forcibly.' + $powershell.Stop() + } + if ($powershell.InvocationStateInfo.State -eq [System.Management.Automation.PSInvocationState]::Failed) { + Write-Warning "The in-memory server failed: $($powershell.InvocationStateInfo.Reason.Message)" + } + foreach ($record in $powershell.Streams.Error) { Write-Warning "In-memory server error: $record" } + } finally { + try { $powershell.Dispose() } catch { Write-Debug 'Disposing the server runspace failed.' } + try { $Background.Runspace.Dispose() } catch { Write-Debug 'Disposing the server runspace failed.' } + } +} diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1 new file mode 100644 index 0000000..977d551 --- /dev/null +++ b/src/Private/Dispatcher.ps1 @@ -0,0 +1,521 @@ +# The dispatcher: the loop that owns a transport, decodes inbound messages, answers server/discover and +# tools/list itself, hands tools/call to the worker runspace pool, forwards the workers' responses and +# notifications, honours notifications/cancelled and shuts down on end of stream or Stop-McpServer. +# +# 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. + +function Get-McpRequestKey { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Id + ) + + if ($Id -is [string]) { return 's:' + $Id } + 'n:' + ([System.Management.Automation.LanguagePrimitives]::ConvertTo($Id, [string])) +} + +function New-McpWorkerPool { + <# + .SYNOPSIS + The hostless runspace pool that runs tool handlers: the module, the registered handlers and preferences. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates a runspace pool for the caller (Start-McpServer), which owns the ShouldProcess decision.')] + [CmdletBinding()] + [OutputType([System.Management.Automation.Runspaces.RunspacePool])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server + ) + + $sessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2() + if ($IsWindows) { + $sessionState.ExecutionPolicy = [Microsoft.PowerShell.ExecutionPolicy]::Bypass + } + $modules = [System.Collections.Generic.List[string]]::new() + $modules.Add($script:McpModuleManifestPath) + foreach ($registration in $Server.Tools.Values) { + $handler = $registration.Handler + if ($handler.ModulePath -and -not $modules.Contains($handler.ModulePath)) { + $modules.Add($handler.ModulePath) + } elseif (-not $handler.ModulePath -and $handler.ModuleName -and -not $modules.Contains($handler.ModuleName)) { + $modules.Add($handler.ModuleName) + } + if ($handler.Definition -and $handler.Kind -in @('ScriptBlock', 'Function')) { + $sessionState.Commands.Add([System.Management.Automation.Runspaces.SessionStateFunctionEntry]::new($handler.CommandName, $handler.Definition)) + } + } + $sessionState.ImportPSModule([string[]] $modules.ToArray()) + foreach ($preference in @(@('ProgressPreference', 'SilentlyContinue'), @('ErrorActionPreference', 'Continue'), @('WarningPreference', 'Continue'), @('InformationPreference', 'Continue'), @('VerbosePreference', 'SilentlyContinue'))) { + $sessionState.Variables.Add([System.Management.Automation.Runspaces.SessionStateVariableEntry]::new($preference[0], $preference[1], 'MCP worker preference')) + } + $pool = [runspacefactory]::CreateRunspacePool($sessionState) + $null = $pool.SetMinRunspaces(1) + $null = $pool.SetMaxRunspaces([int] $Server.Options.MaxConcurrency) + $pool.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::ReuseThread + $pool.Open() + $pool +} + +function Invoke-McpDispatcher { + <# + .SYNOPSIS + Serves a transport until end of stream or Stop-McpServer; returns when the server has shut down. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [Parameter(Mandatory)] + [hashtable] $Transport, + + [ValidateRange(0, 3600)] + [int] $ShutdownGraceSeconds = 5 + ) + + $state = @{ + Server = $Server + Transport = $Transport + Outbound = [System.Collections.Concurrent.ConcurrentQueue[hashtable]]::new() + Signal = [System.Threading.AutoResetEvent]::new($false) + InFlight = @{} + Pool = $null + EofReceived = $false + Stopping = $false + ServerInfo = Get-McpServerInfoObject -Server $Server + LogLevel = $Server.Options.LogLevel + } + $Server.State.Signal = $state.Signal + $Server.State.Started = $true + $Server.State.StopRequested = $false + $where = if ($Transport.Kind -eq 'Http') { "Streamable HTTP at $($Transport.Prefix)" } else { $Transport.Kind } + Write-McpStderr -Level Info -Threshold $state.LogLevel -Logger $Server.Name -Message "Server '$($Server.Name)' $($Server.Version) starting on $where with $($Server.Tools.Count) tool(s)." + try { + $state.Pool = New-McpWorkerPool -Server $Server + if ($Transport.Kind -eq 'Http') { + Invoke-McpHttpDispatcherLoop -State $state -ShutdownGraceSeconds $ShutdownGraceSeconds + } else { + Invoke-McpLineDispatcherLoop -State $state -ShutdownGraceSeconds $ShutdownGraceSeconds + } + } finally { + Stop-McpAllInFlightRequest -State $state + Send-McpOutboundQueue -State $state + if ($null -ne $state.Pool) { + try { $state.Pool.Close(); $state.Pool.Dispose() } catch { Write-Debug 'Closing the runspace pool failed.' } + } + Close-McpTransport -Transport $Transport + $Server.State.Started = $false + $Server.State.Signal = $null + Write-McpStderr -Level Info -Threshold $state.LogLevel -Logger $Server.Name -Message 'Server stopped.' + } +} + +function Invoke-McpLineDispatcherLoop { + <# + .SYNOPSIS + The dispatcher loop of the line-based transports (stdio, in memory): reads lines until end of stream or Stop-McpServer. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [int] $ShutdownGraceSeconds = 5 + ) + + $server = $State.Server + $transport = $State.Transport + $readTask = Read-McpTransportLineAsync -Transport $transport + $stopDeadline = $null + while ($true) { + $handles = if ($State.EofReceived) { @($State.Signal) } else { @((Get-McpTaskWaitHandle -Task $readTask), $State.Signal) } + $index = [System.Threading.WaitHandle]::WaitAny([System.Threading.WaitHandle[]] $handles, 250) + if (-not $State.EofReceived -and $index -eq 0) { + $line = Complete-McpTransportRead -Transport $transport -Task $readTask + if ($null -eq $line) { + $State.EofReceived = $true + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $server.Name -Message 'End of input; shutting down.' + } else { + Invoke-McpInboundLine -State $State -Line $line + $readTask = Read-McpTransportLineAsync -Transport $transport + } + } + Send-McpOutboundQueue -State $State + Update-McpInFlightRequest -State $State + if ($State.Stopping) { break } + if ($State.EofReceived -or $server.State.StopRequested) { + if ($State.InFlight.Count -eq 0) { break } + if ($null -eq $stopDeadline) { $stopDeadline = [datetime]::UtcNow.AddSeconds($ShutdownGraceSeconds) } + if ([datetime]::UtcNow -ge $stopDeadline) { break } + } + } +} + +function Send-McpDispatcherMessage { + <# + .SYNOPSIS + Writes a message built by the dispatcher: to the request's HTTP channel, or to the shared line transport. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message, + + [AllowNull()] + [hashtable] $Channel + ) + + 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'] } + $null = Send-McpHttpResponse -State $State -Channel $Channel -Json (ConvertTo-McpJson -InputObject $Message) -ErrorCode $errorCode + return + } + try { + Send-McpTransportLine -Transport $State.Transport -Line (ConvertTo-McpJson -InputObject $Message) + } 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 + } +} + +function Send-McpOutboundQueue { + <# + .SYNOPSIS + Forwards the responses and notifications that workers enqueued: to the request's channel over HTTP, to the line writer otherwise. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + $item = $null + while ($State.Outbound.TryDequeue([ref] $item)) { + $entry = $null + if ($null -ne $item.RequestId) { + $key = Get-McpRequestKey -Id $item.RequestId + if ($State.InFlight.ContainsKey($key)) { $entry = $State.InFlight[$key] } + } + 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) + if ($State.Transport.Kind -eq 'Http') { + if ($null -eq $entry) { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Dropping a $($item.Kind) for request $($item.RequestId): no open HTTP response." + continue + } + $delivered = if ($item.Kind -eq 'Notification') { + Send-McpHttpNotification -State $State -Channel $entry.Channel -Json $item.Json + } else { + Send-McpHttpResponse -State $State -Channel $entry.Channel -Json $item.Json -ErrorCode $item.ErrorCode + } + if (-not $delivered -and -not $entry.Cancelled) { + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)): the client disconnected; cancelling." + Stop-McpInFlightRequest -Entry $entry + $entry.Responded = $true + } + continue + } + 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 + } + } +} + +function Invoke-McpInboundLine { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Line + ) + + if ([string]::IsNullOrWhiteSpace($Line)) { return } + $message = $null + try { + $message = ConvertFrom-McpJson -Json $Line + } catch { + Send-McpDispatcherMessage -State $State -Message (New-McpErrorResponse -Id $null -ErrorObject (New-McpError -Code $script:McpErrorCode.ParseError -Message 'Parse error')) + return + } + $kind = Get-McpMessageKind -Message $message + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -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 { '' })) + 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.' } + default { + $id = $null + if ($message -is [System.Collections.IDictionary] -and $message.Contains('id') -and (Test-McpRequestId -Id $message['id'])) { $id = $message['id'] } + Send-McpDispatcherMessage -State $State -Message (New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InvalidRequest -Message 'Invalid Request')) + } + } +} + +function Invoke-McpInboundNotification { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message + ) + + $method = [string] $Message['method'] + if ($method -ne 'notifications/cancelled') { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Ignoring notification '$method'." + return + } + $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 (-not $State.InFlight.ContainsKey($key)) { return } + $entry = $State.InFlight[$key] + if ($entry.Cancelled -or $entry.Responded) { return } + $reason = if ($params.Contains('reason') -and $params['reason'] -is [string]) { $params['reason'] } else { 'no reason given' } + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($params['requestId']) cancelled by the client ($reason)." + Stop-McpInFlightRequest -Entry $entry +} + +function Stop-McpInFlightRequest { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Entry + ) + + $Entry.Cancelled = $true + try { $Entry.Cts.Cancel() } catch { Write-Debug 'Cancelling the request token failed.' } + try { $null = $Entry.PowerShell.BeginStop($null, $null) } catch { Write-Debug 'Stopping the worker pipeline failed.' } +} + +function Close-McpRequestChannel { + <# + .SYNOPSIS + Closes the HTTP channel of a finished request; a request that ends without a response gets an internal error first. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Entry, + + [string] $Reason = 'The handler produced no response.' + ) + + $channel = $Entry.Channel + if ($null -eq $channel -or $channel.Kind -ne 'Http' -or $channel.Closed) { return } + if (-not $Entry.Responded) { + $Entry.Responded = $true + $null = Send-McpHttpResponse -State $State -Channel $channel -Json (ConvertTo-McpJson -InputObject (New-McpErrorResponse -Id $Entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $Reason))) -ErrorCode $script:McpErrorCode.InternalError + } + Close-McpHttpChannel -State $State -Channel $channel +} + +function Stop-McpAllInFlightRequest { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + foreach ($entry in @($State.InFlight.Values)) { + if (-not $entry.Cancelled -and -not $entry.Responded) { Stop-McpInFlightRequest -Entry $entry } + Close-McpRequestChannel -State $State -Entry $entry -Reason 'The server is shutting down.' + } + foreach ($entry in @($State.InFlight.Values)) { + try { $null = $entry.PowerShell.InvocationStateInfo; $entry.PowerShell.Dispose() } catch { Write-Debug 'Disposing a worker failed.' } + try { $entry.Cts.Dispose() } catch { Write-Debug 'Disposing a token source failed.' } + } + $State.InFlight.Clear() +} + +function Update-McpInFlightRequest { + <# + .SYNOPSIS + Housekeeping: disposes finished workers, answers crashed ones and enforces the request timeout. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + $timeout = [int] $State.Server.Options.RequestTimeoutSeconds + foreach ($key in @($State.InFlight.Keys)) { + if (-not $State.InFlight.ContainsKey($key)) { continue } + $entry = $State.InFlight[$key] + $invocationState = $entry.PowerShell.InvocationStateInfo.State + $finished = $invocationState -in @([System.Management.Automation.PSInvocationState]::Completed, [System.Management.Automation.PSInvocationState]::Failed, [System.Management.Automation.PSInvocationState]::Stopped) + if (-not $finished) { + if ($timeout -gt 0 -and -not $entry.Cancelled -and -not $entry.Responded -and ([datetime]::UtcNow - $entry.StartedAt).TotalSeconds -gt $timeout) { + Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)) 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.")) + } + continue + } + # A worker enqueues its response before it completes: deliver whatever is queued while the entry exists. + Send-McpOutboundQueue -State $State + if ($invocationState -eq [System.Management.Automation.PSInvocationState]::Failed -and -not $entry.Cancelled -and -not $entry.Responded) { + $reason = $entry.PowerShell.InvocationStateInfo.Reason + $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.ToolName)) 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)) + } + Close-McpRequestChannel -State $State -Entry $entry + try { $entry.PowerShell.Dispose() } catch { Write-Debug 'Disposing a worker failed.' } + try { $entry.Cts.Dispose() } catch { Write-Debug 'Disposing a token source failed.' } + $State.InFlight.Remove($key) + } +} + +function Invoke-McpInboundRequest { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message, + + [AllowNull()] + [hashtable] $Channel + ) + + $server = $State.Server + $id = $Message['id'] + $method = [string] $Message['method'] + $params = if ($Message.Contains('params')) { $Message['params'] } else { $null } + $key = Get-McpRequestKey -Id $id + if ($State.InFlight.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.")) + 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.") + } + $meta = Get-McpRequestMeta -Params $params -SupportedVersions $server.SupportedVersions + switch ($method) { + 'server/discover' { + Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpDiscoverResult -Server $server)) + } + 'tools/list' { + $cursor = if ($params.Contains('cursor')) { $params['cursor'] } else { $null } + Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpToolListResult -Server $server -Cursor $cursor)) + } + 'tools/call' { + if (-not $params.Contains('name') -or $params['name'] -isnot [string]) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "tools/call requires a string parameter 'name'.") + } + $arguments = $null + if ($params.Contains('arguments') -and $null -ne $params['arguments']) { + $arguments = $params['arguments'] + if ($arguments -isnot [System.Collections.IDictionary]) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "tools/call 'arguments' must be an object.") + } + } + $registration = Get-McpToolRegistration -Server $server -Name $params['name'] + if ($null -ne $Channel -and $Channel.Kind -eq 'Http') { + Test-McpToolParameterHeader -HeaderParameters $registration.HeaderParameters -Arguments $arguments -Headers $Channel.Context.Request.Headers + } + Start-McpWorkerRequest -State $State -Id $id -Registration $registration -Arguments $arguments -Meta $meta -Channel $Channel + } + default { + throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "Method not found: $method") + } + } + } catch [McpProtocolException] { + Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $id -ErrorObject (ConvertTo-McpErrorObject -Exception $_.Exception)) + } 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)) + 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)) + } +} + +function Start-McpWorkerRequest { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [object] $Id, + + [Parameter(Mandatory)] + [pscustomobject] $Registration, + + [AllowNull()] + [System.Collections.IDictionary] $Arguments, + + [Parameter(Mandatory)] + [hashtable] $Meta, + + [AllowNull()] + [hashtable] $Channel + ) + + $server = $State.Server + $cts = [System.Threading.CancellationTokenSource]::new() + $envelope = @{ + RequestId = $Id + Method = 'tools/call' + ToolName = $Registration.Name + Registration = $Registration + Arguments = $Arguments + Meta = $Meta + Sink = @{ Queue = $State.Outbound; Signal = $State.Signal } + CancellationToken = $cts.Token + ServerName = $server.Name + ServerLogLevel = $server.Options.LogLevel + ServerInfo = $State.ServerInfo + IncludeServerInfo = [bool] $server.Options.IncludeServerInfo + } + $worker = [powershell]::Create() + $worker.RunspacePool = $State.Pool + $null = $worker.AddScript($script:McpWorkerScript).AddArgument($envelope) + $handle = $worker.BeginInvoke() + $State.InFlight[(Get-McpRequestKey -Id $Id)] = @{ + Id = $Id + ToolName = $Registration.Name + PowerShell = $worker + Handle = $handle + Cts = $cts + StartedAt = [datetime]::UtcNow + Cancelled = $false + Responded = $false + Channel = $Channel + } +} diff --git a/src/Private/Header.ps1 b/src/Private/Header.ps1 new file mode 100644 index 0000000..b2df185 --- /dev/null +++ b/src/Private/Header.ps1 @@ -0,0 +1,425 @@ +# Header mirroring of the Streamable HTTP transport (revision 2026-07-28): the standard request headers +# Mcp-Method and Mcp-Name, the Mcp-Param-{Name} headers derived from x-mcp-header annotations in tool input +# schemas, and the Base64 sentinel encoding of values that cannot travel as plain header values. Shared by the +# client (encoding, annotation validation) and the server (decoding, validation against the body). + +$script:McpHeaderSentinelPrefix = '=?base64?' +$script:McpHeaderSentinelSuffix = '?=' +# tchar of RFC 9110 section 5.6.2: the characters allowed in an HTTP field name. +$script:McpHeaderTokenPattern = '^[!#$%&''*+.^_`|~0-9A-Za-z-]+$' +$script:McpHeaderPrimitiveTypes = @('string', 'integer', 'boolean') +# Methods that mirror a body value into Mcp-Name, and the params member that holds it. +$script:McpNamedMethod = @{ + 'tools/call' = 'name' + 'prompts/get' = 'name' + 'resources/read' = 'uri' +} + +function Get-McpStandardHeaderName { + <# + .SYNOPSIS + The body value that a request mirrors into Mcp-Name (params.name or params.uri), or $null. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string] $Method, + + [AllowNull()] + [object] $Params + ) + + if (-not $script:McpNamedMethod.ContainsKey($Method)) { return $null } + $member = $script:McpNamedMethod[$Method] + if ($Params -is [System.Collections.IDictionary] -and $Params.Contains($member) -and $Params[$member] -is [string]) { + return [string] $Params[$member] + } + $null +} + +function Test-McpHeaderValueSafe { + <# + .SYNOPSIS + True when a value can be sent as a plain header value: visible ASCII and spaces, no leading or trailing + whitespace, and not itself shaped like the Base64 sentinel. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Value + ) + + if ($Value.Length -eq 0) { return $true } + foreach ($char in $Value.ToCharArray()) { + $code = [int] $char + if ($code -lt 0x20 -or $code -gt 0x7E) { return $false } + } + if ($Value[0] -eq ' ' -or $Value[$Value.Length - 1] -eq ' ') { return $false } + if ($Value.StartsWith($script:McpHeaderSentinelPrefix, [System.StringComparison]::Ordinal) -and $Value.EndsWith($script:McpHeaderSentinelSuffix, [System.StringComparison]::Ordinal)) { return $false } + $true +} + +function ConvertTo-McpHeaderText { + <# + .SYNOPSIS + The string representation of a mirrored value: strings as they are, integers as decimal digits, booleans as true/false. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [AllowEmptyString()] + [object] $Value, + + [Parameter(Mandatory)] + [ValidateSet('string', 'integer', 'boolean')] + [string] $Type + ) + + switch ($Type) { + 'boolean' { + if ($Value -is [bool] -or $Value -is [switch]) { return $(if ([bool] $Value) { 'true' } else { 'false' }) } + throw [System.ArgumentException]::new("A boolean header value must be a boolean, not $($Value.GetType().Name).") + } + 'integer' { + $number = $null + try { + $number = [System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, [decimal]) + } catch { + throw [System.ArgumentException]::new("An integer header value must be a number, not '$Value'.") + } + if ($number -ne [decimal]::Truncate($number)) { + throw [System.ArgumentException]::new("An integer header value must be integral, not '$Value'.") + } + return ([decimal]::Truncate($number)).ToString('0', [System.Globalization.CultureInfo]::InvariantCulture) + } + default { + if ($Value -is [string]) { return $Value } + return [System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, [string]) + } + } +} + +function ConvertTo-McpHeaderValue { + <# + .SYNOPSIS + Encodes a value for an Mcp-Name or Mcp-Param-{Name} header: plain when safe, otherwise =?base64?...?=. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [AllowEmptyString()] + [object] $Value, + + [ValidateSet('string', 'integer', 'boolean')] + [string] $Type = 'string' + ) + + $text = ConvertTo-McpHeaderText -Value $Value -Type $Type + if (Test-McpHeaderValueSafe -Value $text) { return $text } + $script:McpHeaderSentinelPrefix + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($text)) + $script:McpHeaderSentinelSuffix +} + +function ConvertFrom-McpHeaderValue { + <# + .SYNOPSIS + Decodes a received Mcp-Name or Mcp-Param-{Name} header value: trims optional whitespace and decodes the + Base64 sentinel; a malformed sentinel is a header mismatch (-32020). + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Value, + + [string] $HeaderName = 'Mcp-Param' + ) + + $trimmed = $Value.Trim(' ', "`t") + $prefix = $script:McpHeaderSentinelPrefix + $suffix = $script:McpHeaderSentinelSuffix + if ($trimmed.Length -ge ($prefix.Length + $suffix.Length) -and $trimmed.StartsWith($prefix, [System.StringComparison]::Ordinal) -and $trimmed.EndsWith($suffix, [System.StringComparison]::Ordinal)) { + $encoded = $trimmed.Substring($prefix.Length, $trimmed.Length - $prefix.Length - $suffix.Length) + try { + return [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encoded)) + } catch { + throw [McpProtocolException]::new($script:McpErrorCode.HeaderMismatch, "Header mismatch: the $HeaderName header value is not valid Base64 inside the =?base64?...?= sentinel.") + } + } + foreach ($char in $trimmed.ToCharArray()) { + $code = [int] $char + if ($code -lt 0x20 -and $code -ne 0x09) { + throw [McpProtocolException]::new($script:McpErrorCode.HeaderMismatch, "Header mismatch: the $HeaderName header value contains control characters.") + } + } + $trimmed +} + +function Test-McpHeaderValueMatch { + <# + .SYNOPSIS + True when a decoded header value equals the body value of the given primitive type (integers compare numerically). + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $HeaderValue, + + [AllowNull()] + [object] $BodyValue, + + [Parameter(Mandatory)] + [ValidateSet('string', 'integer', 'boolean')] + [string] $Type + ) + + if ($null -eq $BodyValue) { return $false } + switch ($Type) { + 'integer' { + $headerNumber = [double] 0 + if (-not [double]::TryParse($HeaderValue, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref] $headerNumber)) { return $false } + if ($BodyValue -is [string] -or $BodyValue -is [bool]) { return $false } + $bodyNumber = [double] 0 + try { $bodyNumber = [System.Management.Automation.LanguagePrimitives]::ConvertTo($BodyValue, [double]) } catch { return $false } + return $headerNumber -eq $bodyNumber + } + 'boolean' { + if ($BodyValue -isnot [bool]) { return $false } + return $HeaderValue -ceq $(if ($BodyValue) { 'true' } else { 'false' }) + } + default { + if ($BodyValue -isnot [string]) { return $false } + return $HeaderValue -ceq [string] $BodyValue + } + } +} + +function Get-McpToolHeaderParameter { + <# + .SYNOPSIS + The x-mcp-header annotations of a tool input schema as property paths, header names and types. + .DESCRIPTION + Walks the schema and collects every property annotated with x-mcp-header that is reachable from the + root through properties keys alone. An annotation that is empty, not an HTTP field-name token, applied + to a non-primitive type, not unique (case-insensitively) or placed anywhere else (items, composition + or conditional keywords, $ref, $defs, the root itself) makes the tool definition invalid: an + ArgumentException names the reason. Returns an array of hashtables with Path (string[]), Header and Type. + #> + [CmdletBinding()] + [OutputType([hashtable[]])] + param( + [AllowNull()] + [object] $InputSchema + ) + + $found = [System.Collections.Generic.List[hashtable]]::new() + if ($InputSchema -is [System.Collections.IDictionary]) { + Find-McpHeaderAnnotation -Schema $InputSchema -Path @() -Reachable $true -Found $found + } + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($entry in $found) { + if (-not $seen.Add($entry.Header)) { + throw [System.ArgumentException]::new("x-mcp-header '$($entry.Header)' is used more than once (header names are case-insensitive).") + } + } + # The elements are emitted one by one; callers collect them with @( ) (no comma trick, so that a single + # annotation is not wrapped twice by @( )). + $found.ToArray() +} + +function Find-McpHeaderAnnotation { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Schema, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]] $Path, + + [Parameter(Mandatory)] + [bool] $Reachable, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [System.Collections.Generic.List[hashtable]] $Found + ) + + if ($Schema.Contains('x-mcp-header')) { + $location = if ($Path.Count -gt 0) { $Path -join '.' } else { '(schema root)' } + if (-not $Reachable -or $Path.Count -eq 0) { + throw [System.ArgumentException]::new("x-mcp-header at '$location' is not on a property reachable from the schema root through properties keys alone.") + } + $name = $Schema['x-mcp-header'] + if ($name -isnot [string] -or $name.Length -eq 0) { + throw [System.ArgumentException]::new("x-mcp-header at '$location' must be a non-empty string.") + } + if ($name -notmatch $script:McpHeaderTokenPattern) { + throw [System.ArgumentException]::new("x-mcp-header '$name' at '$location' is not a valid HTTP field-name token.") + } + $type = if ($Schema.Contains('type')) { $Schema['type'] } else { $null } + if ($type -isnot [string] -or $type -notin $script:McpHeaderPrimitiveTypes) { + $typeText = if ($null -eq $type) { 'none' } elseif ($type -is [string]) { $type } else { ConvertTo-McpJson -InputObject $type } + throw [System.ArgumentException]::new("x-mcp-header '$name' at '$location' is applied to a property of type $typeText; only string, integer and boolean are allowed.") + } + $Found.Add(@{ Path = $Path; Header = $name; Type = $type }) + } + foreach ($key in @($Schema.Keys)) { + $keyText = [string] $key + if ($keyText -eq 'x-mcp-header') { continue } + $value = $Schema[$key] + if ($keyText -eq 'properties' -and $value -is [System.Collections.IDictionary]) { + foreach ($property in @($value.Keys)) { + $child = $value[$property] + if ($child -is [System.Collections.IDictionary]) { + Find-McpHeaderAnnotation -Schema $child -Path ($Path + [string] $property) -Reachable $Reachable -Found $Found + } + } + } elseif ($value -is [System.Collections.IDictionary]) { + Find-McpHeaderAnnotation -Schema $value -Path $Path -Reachable $false -Found $Found + } elseif ($value -is [System.Collections.IList] -and $value -isnot [string]) { + foreach ($item in $value) { + if ($item -is [System.Collections.IDictionary]) { + Find-McpHeaderAnnotation -Schema $item -Path $Path -Reachable $false -Found $Found + } + } + } + } +} + +function Get-McpHeaderArgumentValue { + <# + .SYNOPSIS + The argument value at a property path: a hashtable with Present (a non-null value exists) and Value. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [AllowNull()] + [object] $Arguments, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]] $Path + ) + + $current = $Arguments + foreach ($segment in $Path) { + if ($current -isnot [System.Collections.IDictionary] -or -not $current.Contains($segment)) { return @{ Present = $false; Value = $null } } + $current = $current[$segment] + } + if ($null -eq $current) { return @{ Present = $false; Value = $null } } + @{ Present = $true; Value = $current } +} + +function Get-McpToolCallHeader { + <# + .SYNOPSIS + The Mcp-Param-{Name} headers a client sends for a tools/call: values at the annotated paths, encoded. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [AllowNull()] + [AllowEmptyCollection()] + [hashtable[]] $HeaderParameters, + + [AllowNull()] + [object] $Arguments + ) + + $headers = @{} + foreach ($parameter in @($HeaderParameters)) { + if ($null -eq $parameter) { continue } + $argument = Get-McpHeaderArgumentValue -Arguments $Arguments -Path $parameter.Path + if (-not $argument.Present) { continue } + $headers['Mcp-Param-' + $parameter.Header] = ConvertTo-McpHeaderValue -Value $argument.Value -Type $parameter.Type + } + $headers +} + +function Test-McpToolParameterHeader { + <# + .SYNOPSIS + Validates the Mcp-Param-{Name} headers of a tools/call against the arguments; throws -32020 on mismatch. + #> + [CmdletBinding()] + param( + [AllowNull()] + [AllowEmptyCollection()] + [hashtable[]] $HeaderParameters, + + [AllowNull()] + [object] $Arguments, + + [Parameter(Mandatory)] + [System.Collections.Specialized.NameValueCollection] $Headers + ) + + foreach ($parameter in @($HeaderParameters)) { + if ($null -eq $parameter) { continue } + $headerName = 'Mcp-Param-' + $parameter.Header + $raw = $Headers[$headerName] + $argument = Get-McpHeaderArgumentValue -Arguments $Arguments -Path $parameter.Path + $location = $parameter.Path -join '.' + if (-not $argument.Present) { + if ($null -ne $raw) { + throw [McpProtocolException]::new($script:McpErrorCode.HeaderMismatch, "Header mismatch: $headerName is present but the body has no value for '$location'.") + } + continue + } + if ($null -eq $raw) { + throw [McpProtocolException]::new($script:McpErrorCode.HeaderMismatch, "Header mismatch: $headerName is missing although the body carries a value for '$location'.") + } + $decoded = ConvertFrom-McpHeaderValue -Value $raw -HeaderName $headerName + if (-not (Test-McpHeaderValueMatch -HeaderValue $decoded -BodyValue $argument.Value -Type $parameter.Type)) { + $bodyText = ConvertTo-McpJson -InputObject $argument.Value + throw [McpProtocolException]::new($script:McpErrorCode.HeaderMismatch, "Header mismatch: $headerName value '$decoded' does not match body value $bodyText for '$location'.") + } + } +} + +function Add-McpHeaderAnnotation { + <# + .SYNOPSIS + Adds x-mcp-header annotations to the properties of an input schema from a parameter-name to header-name map. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Schema, + + [Parameter(Mandatory)] + [hashtable] $Header + ) + + $properties = if ($Schema.Contains('properties') -and $Schema['properties'] -is [System.Collections.IDictionary]) { $Schema['properties'] } else { $null } + foreach ($key in $Header.Keys) { + $parameterName = [string] $key + $headerName = [string] $Header[$key] + $propertyKey = $null + if ($null -ne $properties) { + foreach ($candidate in $properties.Keys) { + if ([string] $candidate -ceq $parameterName) { $propertyKey = $candidate; break } + } + if ($null -eq $propertyKey) { + foreach ($candidate in $properties.Keys) { + if ([string] $candidate -ieq $parameterName) { $propertyKey = $candidate; break } + } + } + } + if ($null -eq $propertyKey -or $properties[$propertyKey] -isnot [System.Collections.IDictionary]) { + throw [System.ArgumentException]::new("-Header names the parameter '$parameterName', which is not a property of the input schema.") + } + $properties[$propertyKey]['x-mcp-header'] = $headerName + } +} diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 new file mode 100644 index 0000000..2d84574 --- /dev/null +++ b/src/Private/HttpClient.ps1 @@ -0,0 +1,490 @@ +# Client side of the Streamable HTTP transport (revision 2026-07-28): one HTTP POST per JSON-RPC message with +# the request metadata headers (MCP-Protocol-Version, Mcp-Method, Mcp-Name and the Mcp-Param-* headers of +# 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. + +function New-McpHttpClientTransport { + <# + .SYNOPSIS + An HttpClient-based transport for an MCP endpoint URL. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller (Connect-McpServer) owns the ShouldProcess decision.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [uri] $Url, + + [hashtable] $Headers, + + [switch] $NoProxy + ) + + if (-not $Url.IsAbsoluteUri -or $Url.Scheme -notin @('http', 'https')) { + throw [System.ArgumentException]::new("The server URL must be an absolute http or https URL, not '$Url'.") + } + $handler = [System.Net.Http.SocketsHttpHandler]::new() + $handler.AllowAutoRedirect = $false + $handler.UseCookies = $false + if ($NoProxy -or $Url.IsLoopback) { $handler.UseProxy = $false } + $client = [System.Net.Http.HttpClient]::new($handler) + $client.Timeout = [System.Threading.Timeout]::InfiniteTimeSpan + $static = @{} + if ($Headers) { + foreach ($key in $Headers.Keys) { $static[[string] $key] = [string] $Headers[$key] } + } + @{ + Kind = 'Http' + Url = $Url + Client = $client + Handler = $handler + Headers = $static + Closed = $false + } +} + +function Close-McpHttpClientTransport { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Transport + ) + + if ($Transport.Closed) { return } + $Transport.Closed = $true + try { $Transport.Client.Dispose() } catch { Write-Debug 'Disposing the HTTP client failed.' } + try { $Transport.Handler.Dispose() } catch { Write-Debug 'Disposing the HTTP handler failed.' } +} + +function Wait-McpTask { + <# + .SYNOPSIS + Waits for a task until a deadline in short slices (so that Ctrl+C stays responsive); $false when the deadline passed first. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task, + + [Parameter(Mandatory)] + [datetime] $Deadline + ) + + 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))) + } catch [System.AggregateException] { + return $true + } + } + $true +} + +function Get-McpTaskFailure { + [CmdletBinding()] + [OutputType([System.Exception], [System.OperationCanceledException])] + param( + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task + ) + + if ($Task.IsCanceled) { return [System.OperationCanceledException]::new('The operation was cancelled.') } + if (-not $Task.IsFaulted) { return $null } + $exception = $Task.Exception + while ($exception -is [System.AggregateException] -and $null -ne $exception.InnerException) { $exception = $exception.InnerException } + $exception +} + +function New-McpSseReader { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [System.IO.Stream] $Stream + ) + + @{ + Reader = [System.IO.StreamReader]::new($Stream, [System.Text.UTF8Encoding]::new($false), $false, 65536) + PendingRead = $null + Data = [System.Collections.Generic.List[string]]::new() + EventName = $null + } +} + +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). + .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. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [hashtable] $Sse, + + [Parameter(Mandatory)] + [int] $TimeoutMs + ) + + while ($true) { + if ($null -eq $Sse.PendingRead) { $Sse.PendingRead = $Sse.Reader.ReadLineAsync() } + $task = $Sse.PendingRead + $completed = $false + try { + $completed = $task.Wait([math]::Max(1, $TimeoutMs)) + } catch [System.AggregateException] { + $completed = $true + } + if (-not $completed) { return @{ Status = 'Timeout'; Data = $null; Event = $null } } + $Sse.PendingRead = $null + $line = $null + if ($task.IsFaulted -or $task.IsCanceled) { + $failure = Get-McpTaskFailure -Task $task + if ($failure -is [System.IO.IOException] -or $failure -is [System.ObjectDisposedException] -or $failure -is [System.OperationCanceledException] -or $failure -is [System.Net.Http.HttpRequestException]) { + return @{ Status = 'Eof'; Data = $null; Event = $null } + } + throw $failure + } + $line = $task.Result + if ($null -eq $line) { return @{ Status = 'Eof'; Data = $null; Event = $null } } + 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 } + } + if ($line[0] -eq ':') { continue } + $colon = $line.IndexOf(':') + $field = if ($colon -ge 0) { $line.Substring(0, $colon) } else { $line } + $value = '' + if ($colon -ge 0) { + $value = $line.Substring($colon + 1) + if ($value.StartsWith(' ')) { $value = $value.Substring(1) } + } + switch ($field) { + 'data' { $Sse.Data.Add($value) } + 'event' { $Sse.EventName = $value } + default { Write-Debug "Ignoring the SSE field '$field'." } + } + } +} + +function Convert-McpHttpResponseBody { + <# + .SYNOPSIS + Interprets a JSON body of a POST response: the result of the request, a thrown McpProtocolException, or a transport error. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [Parameter(Mandatory)] + [int] $Status, + + [AllowNull()] + [AllowEmptyString()] + [string] $Body, + + [Parameter(Mandatory)] + [object] $Id, + + [Parameter(Mandatory)] + [string] $Method + ) + + $where = "'$Method' (id $Id) at $($Transport.Url)" + if ([string]::IsNullOrWhiteSpace($Body)) { + throw [System.Net.Http.HttpRequestException]::new("HTTP $Status with an empty body for $where.") + } + $message = $null + try { + $message = ConvertFrom-McpJson -Json $Body + } catch { + $snippet = $Body.Substring(0, [math]::Min(200, $Body.Length)) + throw [System.Net.Http.HttpRequestException]::new("HTTP $Status with a body that is not JSON for $where : $snippet") + } + switch (Get-McpMessageKind -Message $message) { + 'Response' { + if ([string] $message['id'] -ceq [string] $Id) { return $message['result'] } + throw [System.InvalidOperationException]::new("The response to $where carries the id '$($message['id'])'.") + } + 'ErrorResponse' { + $errorObject = $message['error'] + $data = if ($errorObject.Contains('data')) { $errorObject['data'] } else { $null } + throw [McpProtocolException]::new([int] $errorObject['code'], [string] $errorObject['message'], $data) + } + default { + throw [System.Net.Http.HttpRequestException]::new("HTTP $Status with an unexpected body for $where : $($Body.Substring(0, [math]::Min(200, $Body.Length)))") + } + } +} + +function Receive-McpSseResponse { + <# + .SYNOPSIS + Reads a request-scoped SSE stream until the response with the request id arrives, dispatching notifications on the way. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [System.Net.Http.HttpResponseMessage] $Response, + + [Parameter(Mandatory)] + [object] $Id, + + [Parameter(Mandatory)] + [string] $Method, + + [Parameter(Mandatory)] + [datetime] $Deadline, + + [Parameter(Mandatory)] + [System.Threading.CancellationTokenSource] $Cts, + + [AllowNull()] + [object] $ProgressToken, + + [scriptblock] $OnProgress + ) + + $streamTask = $Response.Content.ReadAsStreamAsync() + if (-not (Wait-McpTask -Task $streamTask -Deadline $Deadline)) { + $Cts.Cancel() + throw [System.TimeoutException]::new("The response stream of '$Method' (id $Id) did not open in time.") + } + $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 + try { + while ($true) { + $remaining = ($Deadline - [datetime]::UtcNow).TotalMilliseconds + if ($remaining -le 0) { + $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 } + if ($received.Status -eq 'Eof') { + 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.") + } + if ($null -ne $received.Event -and $received.Event -ne 'message') { + Write-Debug "Ignoring an SSE event named '$($received.Event)'." + continue + } + $message = $null + try { + $message = ConvertFrom-McpJson -Json $received.Data + } catch { + Write-Warning "Ignoring an SSE event from the server that is not JSON: $($received.Data.Substring(0, [math]::Min(120, $received.Data.Length)))" + continue + } + switch (Get-McpMessageKind -Message $message) { + 'Response' { + if ([string] $message['id'] -ceq [string] $Id) { return $message['result'] } + Write-Debug "Ignoring a response with id $($message['id']) on the stream of id $Id." + } + 'ErrorResponse' { + if (-not $message.Contains('id') -or [string] $message['id'] -ceq [string] $Id) { + $errorObject = $message['error'] + $data = if ($errorObject.Contains('data')) { $errorObject['data'] } else { $null } + throw [McpProtocolException]::new([int] $errorObject['code'], [string] $errorObject['message'], $data) + } + Write-Debug "Ignoring an error response with id $($message['id']) on the stream of id $Id." + } + 'Notification' { + 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)." + } + default { + Write-Warning 'Ignoring an invalid JSON-RPC message on the response stream.' + } + } + } + } finally { + try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' } + } +} + +function New-McpHttpRequestMessage { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType([System.Net.Http.HttpRequestMessage])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [string] $Method, + + [AllowNull()] + [System.Collections.IDictionary] $Params, + + [Parameter(Mandatory)] + [string] $Json, + + [hashtable] $Headers + ) + + $transport = $Session.Transport + $message = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $transport.Url) + $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') + $null = $message.Headers.TryAddWithoutValidation('MCP-Protocol-Version', $Session.ProtocolVersion) + $null = $message.Headers.TryAddWithoutValidation('Mcp-Method', $Method) + $bodyName = Get-McpStandardHeaderName -Method $Method -Params $Params + if ($null -ne $bodyName) { + $null = $message.Headers.TryAddWithoutValidation('Mcp-Name', (ConvertTo-McpHeaderValue -Value $bodyName -Type string)) + } + foreach ($key in $transport.Headers.Keys) { + $null = $message.Headers.TryAddWithoutValidation($key, $transport.Headers[$key]) + } + if ($Headers) { + foreach ($key in $Headers.Keys) { + $null = $message.Headers.TryAddWithoutValidation([string] $key, [string] $Headers[$key]) + } + } + $message +} + +function Invoke-McpHttpClientRequest { + <# + .SYNOPSIS + Sends one request as a POST and returns its result; JSON-RPC errors are thrown as McpProtocolException. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [Parameter(Mandatory)] + [string] $Method, + + [System.Collections.IDictionary] $Params, + + [scriptblock] $OnProgress, + + [AllowNull()] + [object] $LogLevel, + + [int] $TimeoutMs = 0, + + [hashtable] $Headers + ) + + $transport = $Session.Transport + if ($transport.Closed) { throw [System.IO.IOException]::new('The transport is closed.') } + if ($TimeoutMs -le 0) { $TimeoutMs = [int] $Session.RequestTimeoutMs } + $id = [int] $Session.NextId + $Session.NextId = $id + 1 + $progressToken = if ($OnProgress) { "p-$id" } else { $null } + $requestParams = [ordered]@{} + $requestParams['_meta'] = New-McpClientRequestMeta -Session $Session -ProgressToken $progressToken -LogLevel $LogLevel + if ($null -ne $Params) { + foreach ($key in $Params.Keys) { + if ([string] $key -eq '_meta') { continue } + $requestParams[[string] $key] = $Params[$key] + } + } + $json = ConvertTo-McpJson -InputObject (New-McpRequest -Id $id -Method $Method -Params $requestParams) + $message = New-McpHttpRequestMessage -Session $Session -Method $Method -Params $Params -Json $json -Headers $Headers + $deadline = [datetime]::UtcNow.AddMilliseconds($TimeoutMs) + $cts = [System.Threading.CancellationTokenSource]::new() + $response = $null + try { + Write-Debug "-> POST $($transport.Url) $Method id=$id ($($json.Length) bytes)" + $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token) + if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline)) { + $cts.Cancel() + throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") + } + $failure = Get-McpTaskFailure -Task $sendTask + if ($null -ne $failure) { + throw [System.Net.Http.HttpRequestException]::new("POST $($transport.Url) failed for '$Method' (id $id): $($failure.Message)", $failure) + } + $response = $sendTask.Result + $status = [int] $response.StatusCode + $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" + if ($mediaType -eq 'text/event-stream') { + 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)) { + $cts.Cancel() + throw [System.TimeoutException]::new("The body of the response to '$Method' (id $id) did not arrive within $TimeoutMs ms.") + } + $failure = Get-McpTaskFailure -Task $readTask + if ($null -ne $failure) { + throw [System.IO.IOException]::new("Reading the response to '$Method' (id $id) failed: $($failure.Message)", $failure) + } + Convert-McpHttpResponseBody -Transport $transport -Status $status -Body $readTask.Result -Id $id -Method $Method + } finally { + if ($null -ne $response) { try { $response.Dispose() } catch { Write-Debug 'Disposing the HTTP response failed.' } } + $cts.Dispose() + $message.Dispose() + } +} + +function Send-McpHttpClientNotification { + <# + .SYNOPSIS + Posts a notification; the server answers 202 without a body. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [pscustomobject] $Session, + + [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 + $cts = [System.Threading.CancellationTokenSource]::new() + $response = $null + try { + $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseContentRead, $cts.Token) + if (-not (Wait-McpTask -Task $sendTask -Deadline ([datetime]::UtcNow.AddMilliseconds($TimeoutMs)))) { + $cts.Cancel() + throw [System.TimeoutException]::new("Posting the notification '$Method' timed out after $TimeoutMs ms.") + } + $failure = Get-McpTaskFailure -Task $sendTask + if ($null -ne $failure) { throw [System.Net.Http.HttpRequestException]::new("Posting the notification '$Method' failed: $($failure.Message)", $failure) } + $response = $sendTask.Result + if (-not $response.IsSuccessStatusCode) { + throw [System.Net.Http.HttpRequestException]::new("The server answered the notification '$Method' with HTTP $([int] $response.StatusCode).") + } + } finally { + if ($null -ne $response) { try { $response.Dispose() } catch { Write-Debug 'Disposing the HTTP response failed.' } } + $cts.Dispose() + $message.Dispose() + } +} diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 new file mode 100644 index 0000000..afe5823 --- /dev/null +++ b/src/Private/HttpServer.ps1 @@ -0,0 +1,748 @@ +# Server side of the Streamable HTTP transport (revision 2026-07-28) on System.Net.HttpListener. The dispatcher +# 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. + +# Built on first use: the error code table (JsonRpc.ps1) is assembled after this file. +$script:McpHttpStatusByErrorCode = $null + +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. + #> + [CmdletBinding()] + [OutputType([int])] + param( + [AllowNull()] + [object] $ErrorCode + ) + + if ($null -eq $ErrorCode) { return 200 } + if ($null -eq $script:McpHttpStatusByErrorCode) { + $table = @{} + foreach ($name in 'ParseError', 'InvalidRequest', 'InvalidParams', 'HeaderMismatch', 'MissingRequiredClientCapability', 'UnsupportedProtocolVersion') { + $table[[int] $script:McpErrorCode[$name]] = 400 + } + $table[[int] $script:McpErrorCode.MethodNotFound] = 404 + $script:McpHttpStatusByErrorCode = $table + } + $code = [int] $ErrorCode + if ($script:McpHttpStatusByErrorCode.ContainsKey($code)) { return $script:McpHttpStatusByErrorCode[$code] } + 200 +} + +function New-McpHttpServerTransport { + <# + .SYNOPSIS + Starts an HttpListener for the MCP endpoint and returns the transport object of the dispatcher. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller (Start-McpServer) owns the ShouldProcess decision.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [uri] $Url, + + [AllowNull()] + [AllowEmptyCollection()] + [string[]] $AllowedOrigins, + + [long] $MaxBodyBytes = 16MB, + + [int] $KeepAliveSeconds = 5, + + [int] $BodyTimeoutSeconds = 30 + ) + + if (-not $Url.IsAbsoluteUri -or $Url.Scheme -notin @('http', 'https')) { + throw [System.ArgumentException]::new("The endpoint URL must be an absolute http or https URL such as http://127.0.0.1:8080/mcp/, not '$Url'.") + } + $path = $Url.AbsolutePath + if ([string]::IsNullOrEmpty($path) -or $path -eq '/') { $path = '/mcp/' } + if (-not $path.EndsWith('/')) { $path += '/' } + $prefix = $Url.GetLeftPart([System.UriPartial]::Authority) + $path + $listener = [System.Net.HttpListener]::new() + $listener.Prefixes.Add($prefix) + try { + $listener.Start() + } catch { + try { $listener.Close() } catch { Write-Debug 'Closing the failed listener failed.' } + throw [System.InvalidOperationException]::new("Cannot listen on $prefix : $($_.Exception.Message) On Windows, users without administrative rights need a URL reservation (netsh http add urlacl url=$prefix user=).", $_.Exception) + } + @{ + Kind = 'Http' + Listener = $listener + Url = $Url + Prefix = $prefix + Path = $path.TrimEnd('/') + AllowedOrigins = @($AllowedOrigins | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + MaxBodyBytes = $MaxBodyBytes + KeepAliveSeconds = $KeepAliveSeconds + BodyTimeoutSeconds = $BodyTimeoutSeconds + PendingBodies = [System.Collections.Generic.List[hashtable]]::new() + OpenChannels = [System.Collections.Generic.List[hashtable]]::new() + Stopped = $false + Closed = $false + } +} + +function Close-McpHttpServerTransport { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Transport + ) + + if ($Transport.Closed) { return } + $Transport.Closed = $true + foreach ($pending in @($Transport.PendingBodies)) { + try { $pending.Channel.Response.Abort() } catch { Write-Debug 'Aborting a pending request failed.' } + } + $Transport.PendingBodies.Clear() + foreach ($channel in @($Transport.OpenChannels)) { + try { $channel.Response.Abort() } catch { Write-Debug 'Aborting an open response failed.' } + $channel.Closed = $true + } + $Transport.OpenChannels.Clear() + try { + if (-not $Transport.Stopped) { $Transport.Listener.Stop() } + } catch { + Write-Debug 'Stopping the listener failed.' + } + $Transport.Stopped = $true + try { $Transport.Listener.Close() } catch { Write-Debug 'Closing the listener failed.' } +} + +function Test-McpHttpOrigin { + <# + .SYNOPSIS + True when a request's Origin header is acceptable: absent, in the allow list, or (by default) a loopback origin or the server's own origin. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [AllowNull()] + [AllowEmptyString()] + [string] $Origin + ) + + if ([string]::IsNullOrEmpty($Origin)) { return $true } + $candidate = $Origin.Trim().TrimEnd('/') + $allowed = @($Transport.AllowedOrigins) + if ($allowed.Count -gt 0) { + foreach ($entry in $allowed) { + if ($entry -eq '*' -or $entry.TrimEnd('/') -ieq $candidate) { return $true } + } + return $false + } + $uri = $null + if (-not [uri]::TryCreate($candidate, [System.UriKind]::Absolute, [ref] $uri)) { return $false } + if ($uri.Scheme -notin @('http', 'https')) { return $false } + if ($uri.IsLoopback) { return $true } + $own = $Transport.Url.GetLeftPart([System.UriPartial]::Authority) + $candidate -ieq $own +} + +function Test-McpHttpHost { + <# + .SYNOPSIS + True when a request's Host header names the endpoint the listener was started with (host and port). + .DESCRIPTION + The managed HttpListener on Linux and macOS only routes requests whose Host header matches the prefix + host, but http.sys on Windows delivers requests with any Host header to a prefix bound to an IP + address, so the server checks the header itself on every platform: DNS rebinding protection must not + depend on the listener implementation. The port may be omitted when it is the default port of the scheme. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [AllowNull()] + [AllowEmptyString()] + [string] $HostHeader + ) + + if ([string]::IsNullOrWhiteSpace($HostHeader)) { return $false } + $value = $HostHeader.Trim() + $expected = $Transport.Url + $hostPart = $value + $portPart = $null + if ($value.StartsWith('[')) { + $close = $value.IndexOf(']') + if ($close -lt 0) { return $false } + $hostPart = $value.Substring(0, $close + 1) + $rest = $value.Substring($close + 1) + if ($rest.Length -gt 0) { + if (-not $rest.StartsWith(':')) { return $false } + $portPart = $rest.Substring(1) + } + } else { + $colon = $value.LastIndexOf(':') + if ($colon -ge 0) { + $hostPart = $value.Substring(0, $colon) + $portPart = $value.Substring($colon + 1) + } + } + $port = if ($expected.Scheme -eq 'https') { 443 } else { 80 } + if ($null -ne $portPart) { + if ($portPart.Length -eq 0 -or -not [int]::TryParse($portPart, [ref] $port)) { return $false } + } + ($hostPart -eq $expected.Host) -and ($port -eq $expected.Port) +} + +function New-McpHttpChannel { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [System.Net.HttpListenerContext] $Context + ) + + @{ + Kind = 'Http' + Context = $Context + Response = $Context.Response + Mode = $null + Stream = $null + Closed = $false + LastWrite = [datetime]::UtcNow + RequestId = $null + } +} + +function New-McpHttpErrorJson { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds a wire message.')] + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [int] $Code, + + [Parameter(Mandatory)] + [string] $Message, + + [AllowNull()] + [object] $Id + ) + + ConvertTo-McpJson -InputObject (New-McpErrorResponse -Id $Id -ErrorObject (New-McpError -Code $Code -Message $Message)) +} + +function Close-McpHttpChannel { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [switch] $Abort + ) + + if ($Channel.Closed) { return } + $Channel.Closed = $true + $null = $State.Transport.OpenChannels.Remove($Channel) + try { + if ($Abort) { + $Channel.Response.Abort() + } else { + if ($null -ne $Channel.Stream) { $Channel.Stream.Close() } + $Channel.Response.Close() + } + } catch { + Write-Debug "Closing an HTTP response failed: $($_.Exception.Message)" + } +} + +function Send-McpHttpStatus { + <# + .SYNOPSIS + Completes a channel with a status code, optional headers and an optional JSON body; returns $false when the client is gone. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [Parameter(Mandatory)] + [int] $StatusCode, + + [string] $Json, + + [hashtable] $Headers + ) + + if ($Channel.Closed) { return $false } + try { + $response = $Channel.Response + $response.StatusCode = $StatusCode + if ($Headers) { + foreach ($name in $Headers.Keys) { $response.AddHeader([string] $name, [string] $Headers[$name]) } + } + if ($Json) { + $bytes = [System.Text.Encoding]::UTF8.GetBytes($Json) + $response.ContentType = 'application/json; charset=utf-8' + $response.ContentLength64 = $bytes.Length + $response.OutputStream.Write($bytes, 0, $bytes.Length) + } else { + $response.ContentLength64 = 0 + } + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("-> HTTP {0} id={1} ({2} bytes)" -f $StatusCode, $Channel.RequestId, $(if ($Json) { $Json.Length } else { 0 })) + $Channel.Closed = $true + $null = $State.Transport.OpenChannels.Remove($Channel) + $response.Close() + return $true + } catch { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing an HTTP response failed: $($_.Exception.Message)" + Close-McpHttpChannel -State $State -Channel $Channel -Abort + return $false + } +} + +function Start-McpHttpSse { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Switches an HTTP response to streaming; part of the request pipeline.')] + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel + ) + + if ($Channel.Closed) { return $false } + if ($Channel.Mode -eq 'Sse') { return $true } + try { + $response = $Channel.Response + $response.StatusCode = 200 + $response.ContentType = 'text/event-stream' + $response.SendChunked = $true + $response.AddHeader('Cache-Control', 'no-cache') + $response.AddHeader('X-Accel-Buffering', 'no') + $Channel.Stream = $response.OutputStream + $Channel.Mode = 'Sse' + $Channel.LastWrite = [datetime]::UtcNow + $State.Transport.OpenChannels.Add($Channel) + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("-> HTTP 200 text/event-stream id={0}" -f $Channel.RequestId) + return $true + } catch { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Starting an SSE response failed: $($_.Exception.Message)" + Close-McpHttpChannel -State $State -Channel $Channel -Abort + return $false + } +} + +function Write-McpSseChunk { + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [Parameter(Mandatory)] + [string] $Text + ) + + if ($Channel.Closed -or $Channel.Mode -ne 'Sse') { return $false } + try { + $bytes = [System.Text.Encoding]::UTF8.GetBytes($Text) + $Channel.Stream.Write($bytes, 0, $bytes.Length) + $Channel.Stream.Flush() + $Channel.LastWrite = [datetime]::UtcNow + return $true + } catch { + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing to an SSE stream failed (id=$($Channel.RequestId)): $($_.Exception.Message)" + Close-McpHttpChannel -State $State -Channel $Channel -Abort + return $false + } +} + +function Send-McpHttpNotification { + <# + .SYNOPSIS + Sends a notification on a request's channel, switching the response to an SSE stream first; $false when the client is gone. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [Parameter(Mandatory)] + [string] $Json + ) + + if (-not (Start-McpHttpSse -State $State -Channel $Channel)) { return $false } + Write-McpSseChunk -State $State -Channel $Channel -Text "event: message`ndata: $Json`n`n" +} + +function Send-McpHttpResponse { + <# + .SYNOPSIS + Sends the final JSON-RPC response of a request: as the last SSE event of an open stream, or as a JSON body with the status of its error code. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [Parameter(Mandatory)] + [string] $Json, + + [AllowNull()] + [object] $ErrorCode + ) + + if ($Channel.Closed) { return $false } + if ($Channel.Mode -eq 'Sse') { + $written = Write-McpSseChunk -State $State -Channel $Channel -Text "event: message`ndata: $Json`n`n" + Close-McpHttpChannel -State $State -Channel $Channel + return $written + } + Send-McpHttpStatus -State $State -Channel $Channel -StatusCode (Get-McpHttpStatusCode -ErrorCode $ErrorCode) -Json $Json +} + +function Update-McpHttpChannel { + <# + .SYNOPSIS + Switches long-running requests to SSE and sends keep-alive comments on idle streams; a failed write means the client closed the stream, which cancels the request. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal housekeeping of the dispatcher loop.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + $transport = $State.Transport + if ($transport.KeepAliveSeconds -le 0) { return } + $now = [datetime]::UtcNow + # A request that outlives the keep-alive interval switches to an SSE stream: only a write can reveal + # that the client closed the connection, and a plain JSON response is written only at the very end. + foreach ($entry in @($State.InFlight.Values)) { + $channel = $entry.Channel + if ($null -eq $channel -or $channel.Kind -ne 'Http' -or $channel.Closed -or $channel.Mode -eq 'Sse') { continue } + if ($entry.Cancelled -or $entry.Responded) { continue } + if (($now - $entry.StartedAt).TotalSeconds -lt $transport.KeepAliveSeconds) { continue } + if (-not (Start-McpHttpSse -State $State -Channel $channel) -or -not (Write-McpSseChunk -State $State -Channel $channel -Text ": keep-alive`n`n")) { + Stop-McpHttpChannelRequest -State $State -Channel $channel + } + } + if ($transport.OpenChannels.Count -eq 0) { return } + foreach ($channel in @($transport.OpenChannels)) { + if ($channel.Closed) { $null = $transport.OpenChannels.Remove($channel); continue } + if (($now - $channel.LastWrite).TotalSeconds -lt $transport.KeepAliveSeconds) { continue } + if (-not (Write-McpSseChunk -State $State -Channel $channel -Text ": keep-alive`n`n")) { + Stop-McpHttpChannelRequest -State $State -Channel $channel + } + } +} + +function Stop-McpHttpChannelRequest { + <# + .SYNOPSIS + Cancels the in-flight request of a channel whose client went away (a write to it failed). + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel + ) + + $key = Get-McpRequestKey -Id $Channel.RequestId + if (-not $State.InFlight.ContainsKey($key)) { return } + $entry = $State.InFlight[$key] + if ($entry.Cancelled -or $entry.Responded) { return } + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)): the client closed the connection; cancelling." + Stop-McpInFlightRequest -Entry $entry + $entry.Responded = $true +} + +function Test-McpHttpRequestHeader { + <# + .SYNOPSIS + Validates the standard request headers of a POST against its JSON-RPC body; throws -32020 on any mismatch. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Net.HttpListenerRequest] $Request, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Message + ) + + $mismatch = $script:McpErrorCode.HeaderMismatch + $headers = $Request.Headers + $versionHeader = $headers['MCP-Protocol-Version'] + if ($null -eq $versionHeader) { + throw [McpProtocolException]::new($mismatch, 'Header mismatch: the MCP-Protocol-Version header is missing.') + } + $versionHeader = $versionHeader.Trim() + $method = [string] $Message['method'] + $methodHeader = $headers['Mcp-Method'] + if ($null -eq $methodHeader) { + throw [McpProtocolException]::new($mismatch, 'Header mismatch: the Mcp-Method header is missing.') + } + if ($methodHeader.Trim() -cne $method) { + throw [McpProtocolException]::new($mismatch, "Header mismatch: Mcp-Method header value '$($methodHeader.Trim())' does not match body method '$method'.") + } + $params = if ($Message.Contains('params')) { $Message['params'] } else { $null } + $bodyName = Get-McpStandardHeaderName -Method $method -Params $params + if ($null -ne $bodyName) { + $nameHeader = $headers['Mcp-Name'] + if ($null -eq $nameHeader) { + throw [McpProtocolException]::new($mismatch, "Header mismatch: the Mcp-Name header is missing for $method.") + } + $decoded = ConvertFrom-McpHeaderValue -Value $nameHeader -HeaderName 'Mcp-Name' + if ($decoded -cne $bodyName) { + throw [McpProtocolException]::new($mismatch, "Header mismatch: Mcp-Name header value '$decoded' does not match body value '$bodyName'.") + } + } + if ($params -is [System.Collections.IDictionary] -and $params.Contains('_meta') -and $params['_meta'] -is [System.Collections.IDictionary]) { + $meta = $params['_meta'] + $key = $script:McpMetaKey.ProtocolVersion + if ($meta.Contains($key) -and $meta[$key] -is [string] -and $meta[$key] -cne $versionHeader) { + throw [McpProtocolException]::new($mismatch, "Header mismatch: MCP-Protocol-Version header '$versionHeader' does not match _meta protocolVersion '$($meta[$key])'.") + } + } +} + +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. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [hashtable] $Channel, + + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Body + ) + + $logger = $State.Server.Name + $message = $null + try { + $message = ConvertFrom-McpJson -Json $Body + } catch { + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 400 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.ParseError -Message 'Parse error') + return + } + $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 { '' })) + switch ($kind) { + 'Request' { + $Channel.RequestId = $message['id'] + if ([string] $message['method'] -ne 'initialize') { + try { + Test-McpHttpRequestHeader -Request $Channel.Context.Request -Message $message + } catch [McpProtocolException] { + Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $message['id'] -ErrorObject (ConvertTo-McpErrorObject -Exception $_.Exception)) + return + } + } + Invoke-McpInboundRequest -State $State -Message $message -Channel $Channel + } + '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)." + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 202 + } + { $_ -in @('Response', 'ErrorResponse') } { + $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 { + $id = $null + if ($message -is [System.Collections.IDictionary] -and $message.Contains('id') -and (Test-McpRequestId -Id $message['id'])) { $id = $message['id'] } + $null = Send-McpHttpStatus -State $State -Channel $Channel -StatusCode 400 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InvalidRequest -Message 'Invalid Request' -Id $id) + } + } +} + +function Invoke-McpHttpAccept { + <# + .SYNOPSIS + Screens an accepted connection (Host, path, Origin, method, content type, size) and starts reading its body. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [Parameter(Mandatory)] + [System.Net.HttpListenerContext] $Context + ) + + $transport = $State.Transport + $request = $Context.Request + $channel = New-McpHttpChannel -Context $Context + Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("<- HTTP {0} {1} from {2}" -f $request.HttpMethod, $request.RawUrl, $request.RemoteEndPoint) + $invalidRequest = $script:McpErrorCode.InvalidRequest + $hostHeader = $request.Headers['Host'] + if (-not (Test-McpHttpHost -Transport $transport -HostHeader $hostHeader)) { + Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Rejected a request with Host '$hostHeader' (the endpoint is $($transport.Url.Authority))." + $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 404 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message "No MCP endpoint for host '$hostHeader'; the endpoint is '$($transport.Url)'.") + return + } + $path = $request.Url.AbsolutePath.TrimEnd('/') + if ($path -cne $transport.Path) { + $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 404 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message "No MCP endpoint at '$($request.Url.AbsolutePath)'; the endpoint is '$($transport.Path)/'.") + return + } + $origin = $request.Headers['Origin'] + if (-not (Test-McpHttpOrigin -Transport $transport -Origin $origin)) { + Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Rejected a request with Origin '$origin' (allowed: $(if ($transport.AllowedOrigins.Count -gt 0) { $transport.AllowedOrigins -join ', ' } else { 'loopback origins' }))." + $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 403 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message "Origin '$origin' is not allowed.") + 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.') + return + } + $contentType = $request.ContentType + if (-not [string]::IsNullOrWhiteSpace($contentType) -and $contentType -notmatch '^\s*application/json\s*(;|$)') { + $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 415 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message "Unsupported Content-Type '$contentType'; the body must be application/json.") + return + } + if ($request.ContentLength64 -gt $transport.MaxBodyBytes) { + $null = Send-McpHttpStatus -State $State -Channel $channel -StatusCode 413 -Json (New-McpHttpErrorJson -Code $invalidRequest -Message "The request body exceeds the limit of $($transport.MaxBodyBytes) bytes.") + return + } + $buffer = [System.IO.MemoryStream]::new() + $task = $request.InputStream.CopyToAsync($buffer) + $transport.PendingBodies.Add(@{ Channel = $channel; Buffer = $buffer; Task = $task; Started = [datetime]::UtcNow }) +} + +function Update-McpHttpPendingBody { + <# + .SYNOPSIS + Hands completed body reads to the message handler and times out slow ones. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal housekeeping of the dispatcher loop.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State + ) + + $transport = $State.Transport + if ($transport.PendingBodies.Count -eq 0) { return } + foreach ($pending in @($transport.PendingBodies)) { + if ($pending.Task.IsCompleted) { + $null = $transport.PendingBodies.Remove($pending) + if ($pending.Task.IsFaulted -or $pending.Task.IsCanceled) { + Close-McpHttpChannel -State $State -Channel $pending.Channel -Abort + continue + } + if ($pending.Buffer.Length -gt $transport.MaxBodyBytes) { + $null = Send-McpHttpStatus -State $State -Channel $pending.Channel -StatusCode 413 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InvalidRequest -Message "The request body exceeds the limit of $($transport.MaxBodyBytes) bytes.") + continue + } + $bytes = $pending.Buffer.ToArray() + $offset = if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { 3 } else { 0 } + $body = [System.Text.Encoding]::UTF8.GetString($bytes, $offset, $bytes.Length - $offset) + Invoke-McpInboundHttpMessage -State $State -Channel $pending.Channel -Body $body + } elseif (([datetime]::UtcNow - $pending.Started).TotalSeconds -gt $transport.BodyTimeoutSeconds) { + $null = $transport.PendingBodies.Remove($pending) + $null = Send-McpHttpStatus -State $State -Channel $pending.Channel -StatusCode 408 -Json (New-McpHttpErrorJson -Code $script:McpErrorCode.InvalidRequest -Message "The request body was not received within $($transport.BodyTimeoutSeconds) seconds.") + } + } +} + +function Complete-McpHttpAccept { + [CmdletBinding()] + [OutputType([System.Net.HttpListenerContext])] + param( + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task + ) + + if ($Task.IsFaulted -or $Task.IsCanceled) { return $null } + $Task.Result +} + +function Invoke-McpHttpDispatcherLoop { + <# + .SYNOPSIS + The dispatcher loop of the Streamable HTTP transport: accepts connections, reads bodies, routes messages, forwards worker output, sends keep-alives. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $State, + + [int] $ShutdownGraceSeconds = 5 + ) + + $server = $State.Server + $transport = $State.Transport + $listener = $transport.Listener + $acceptTask = $listener.GetContextAsync() + $stopDeadline = $null + while ($true) { + $handles = [System.Collections.Generic.List[System.Threading.WaitHandle]]::new() + if (-not $transport.Stopped) { $handles.Add((Get-McpTaskWaitHandle -Task $acceptTask)) } + $handles.Add($State.Signal) + foreach ($pending in $transport.PendingBodies) { + if ($handles.Count -ge 60) { break } + $handles.Add((Get-McpTaskWaitHandle -Task $pending.Task)) + } + $null = [System.Threading.WaitHandle]::WaitAny($handles.ToArray(), 250) + if (-not $transport.Stopped -and $acceptTask.IsCompleted) { + $context = Complete-McpHttpAccept -Task $acceptTask + if ($null -ne $context) { Invoke-McpHttpAccept -State $State -Context $context } + if ($listener.IsListening) { + $acceptTask = $listener.GetContextAsync() + } else { + $transport.Stopped = $true + } + } + Update-McpHttpPendingBody -State $State + Send-McpOutboundQueue -State $State + Update-McpInFlightRequest -State $State + Update-McpHttpChannel -State $State + if ($State.Stopping) { break } + if ($server.State.StopRequested) { + if (-not $transport.Stopped) { + $transport.Stopped = $true + Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $server.Name -Message 'Stop requested; no longer accepting connections.' + try { $listener.Stop() } catch { Write-Debug 'Stopping the listener failed.' } + } + if ($State.InFlight.Count -eq 0 -and $transport.PendingBodies.Count -eq 0) { break } + if ($null -eq $stopDeadline) { $stopDeadline = [datetime]::UtcNow.AddSeconds($ShutdownGraceSeconds) } + if ([datetime]::UtcNow -ge $stopDeadline) { break } + } + } +} diff --git a/src/Private/Json.ps1 b/src/Private/Json.ps1 new file mode 100644 index 0000000..5fd4e7b --- /dev/null +++ b/src/Private/Json.ps1 @@ -0,0 +1,223 @@ +# JSON codec on System.Text.Json (in-box in every supported PowerShell version). +# +# ConvertFrom-McpJson parses one JSON text into plain PowerShell values: objects become insertion-ordered, +# case-sensitive OrderedDictionary instances, arrays become object[], strings stay strings, numbers become +# Int64 when they are integral and fit and Double otherwise, and null stays $null. Nothing is coerced (no +# DateTime detection, no single-element array unrolling), so the wire shape survives a round trip and the +# JSON type of a request id (string versus number) is preserved. +# +# ConvertTo-McpJson serialises PowerShell values to compact, single-line JSON: dictionaries and PSObjects +# become objects (insertion or property order), enumerables become arrays, [switch] becomes a boolean, +# byte[] becomes base64, DateTime becomes ISO 8601 in round-trip format, enums and Guid/Uri/Version become +# strings. Non-ASCII characters of the basic multilingual plane are written unescaped (UTF-8 on the wire); +# characters outside it (emoji) are written as surrogate-pair escapes because System.Text.Json encoders +# always escape them; control characters are escaped, so the output never contains a raw newline. Depth +# beyond -MaxDepth is an error, never a truncation. + +$script:McpJsonWriterOptions = [System.Text.Json.JsonWriterOptions]@{ + Indented = $false + Encoder = [System.Text.Encodings.Web.JavaScriptEncoder]::UnsafeRelaxedJsonEscaping + SkipValidation = $false +} + +function ConvertFrom-McpJson { + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory, Position = 0, ValueFromPipeline)] + [AllowEmptyString()] + [string] $Json, + + [ValidateRange(1, 1024)] + [int] $MaxDepth = 64 + ) + + process { + $options = [System.Text.Json.JsonDocumentOptions]@{ + MaxDepth = $MaxDepth + CommentHandling = [System.Text.Json.JsonCommentHandling]::Disallow + } + $document = [System.Text.Json.JsonDocument]::Parse($Json, $options) + try { + ConvertFrom-McpJsonElement -Element $document.RootElement + } finally { + $document.Dispose() + } + } +} + +function ConvertFrom-McpJsonElement { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary], [object[]], [string], [long], [double], [bool])] + param( + [Parameter(Mandatory)] + [System.Text.Json.JsonElement] $Element + ) + + $kind = $Element.ValueKind + if ($kind -eq [System.Text.Json.JsonValueKind]::Object) { + $dictionary = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + foreach ($property in $Element.EnumerateObject()) { + $dictionary[$property.Name] = ConvertFrom-McpJsonElement -Element $property.Value + } + return $dictionary + } + if ($kind -eq [System.Text.Json.JsonValueKind]::Array) { + $items = [System.Collections.Generic.List[object]]::new() + foreach ($item in $Element.EnumerateArray()) { + $items.Add((ConvertFrom-McpJsonElement -Element $item)) + } + return , $items.ToArray() + } + if ($kind -eq [System.Text.Json.JsonValueKind]::String) { + return $Element.GetString() + } + if ($kind -eq [System.Text.Json.JsonValueKind]::Number) { + $integer = [long] 0 + if ($Element.TryGetInt64([ref] $integer)) { + return $integer + } + return $Element.GetDouble() + } + if ($kind -eq [System.Text.Json.JsonValueKind]::True) { + return $true + } + if ($kind -eq [System.Text.Json.JsonValueKind]::False) { + return $false + } + return $null +} + +function ConvertTo-McpJson { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory, Position = 0)] + [AllowNull()] + [object] $InputObject, + + [ValidateRange(1, 1024)] + [int] $MaxDepth = 64 + ) + + $stream = [System.IO.MemoryStream]::new() + $writer = [System.Text.Json.Utf8JsonWriter]::new($stream, $script:McpJsonWriterOptions) + try { + Write-McpJsonValue -Writer $writer -Value $InputObject -Depth 0 -MaxDepth $MaxDepth + $writer.Flush() + [System.Text.Encoding]::UTF8.GetString($stream.GetBuffer(), 0, [int] $stream.Length) + } finally { + $writer.Dispose() + $stream.Dispose() + } +} + +function Write-McpJsonValue { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Text.Json.Utf8JsonWriter] $Writer, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Value, + + [Parameter(Mandatory)] + [int] $Depth, + + [Parameter(Mandatory)] + [int] $MaxDepth + ) + + if ($null -eq $Value) { + $Writer.WriteNullValue() + return + } + if ($Value -is [string]) { + $Writer.WriteStringValue([string] $Value) + return + } + if ($Value -is [bool]) { + $Writer.WriteBooleanValue([bool] $Value) + return + } + if ($Value -is [switch]) { + $Writer.WriteBooleanValue($Value.IsPresent) + return + } + if ($Value -is [int] -or $Value -is [long] -or $Value -is [int16] -or $Value -is [byte] -or $Value -is [sbyte] -or $Value -is [uint16] -or $Value -is [uint32]) { + $Writer.WriteNumberValue([long] $Value) + return + } + if ($Value -is [ulong]) { + $Writer.WriteNumberValue([ulong] $Value) + return + } + if ($Value -is [double] -or $Value -is [single]) { + $number = [double] $Value + if ([double]::IsNaN($number) -or [double]::IsInfinity($number)) { + throw [System.InvalidOperationException]::new("The value '$number' has no JSON representation.") + } + $Writer.WriteNumberValue($number) + return + } + if ($Value -is [decimal]) { + $Writer.WriteNumberValue([decimal] $Value) + return + } + if ($Value -is [System.Numerics.BigInteger]) { + $Writer.WriteRawValue($Value.ToString(), $true) + return + } + if ($Value -is [datetime]) { + $Writer.WriteStringValue(([datetime] $Value).ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)) + return + } + if ($Value -is [datetimeoffset]) { + $Writer.WriteStringValue(([datetimeoffset] $Value).ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)) + return + } + if ($Value -is [enum] -or $Value -is [guid] -or $Value -is [uri] -or $Value -is [version] -or $Value -is [char] -or $Value -is [timespan]) { + $Writer.WriteStringValue($Value.ToString()) + return + } + if ($Value -is [byte[]]) { + $Writer.WriteBase64StringValue([byte[]] $Value) + return + } + if ($Value -is [System.Text.Json.Nodes.JsonNode]) { + $Value.WriteTo($Writer) + return + } + if ($Value -is [System.Text.Json.JsonElement]) { + $Value.WriteTo($Writer) + return + } + if ($Depth -ge $MaxDepth) { + throw [System.InvalidOperationException]::new("The object graph is deeper than the maximum depth of $MaxDepth.") + } + if ($Value -is [System.Collections.IDictionary]) { + $Writer.WriteStartObject() + foreach ($key in $Value.Keys) { + $Writer.WritePropertyName([string] $key) + Write-McpJsonValue -Writer $Writer -Value $Value[$key] -Depth ($Depth + 1) -MaxDepth $MaxDepth + } + $Writer.WriteEndObject() + return + } + if ($Value -is [System.Collections.IEnumerable]) { + $Writer.WriteStartArray() + foreach ($item in $Value) { + Write-McpJsonValue -Writer $Writer -Value $item -Depth ($Depth + 1) -MaxDepth $MaxDepth + } + $Writer.WriteEndArray() + return + } + # PSCustomObject and any other object: its (adapted and extended) properties, in order. + $Writer.WriteStartObject() + foreach ($property in $Value.PSObject.Properties) { + $Writer.WritePropertyName($property.Name) + Write-McpJsonValue -Writer $Writer -Value $property.Value -Depth ($Depth + 1) -MaxDepth $MaxDepth + } + $Writer.WriteEndObject() +} diff --git a/src/Private/JsonRpc.ps1 b/src/Private/JsonRpc.ps1 new file mode 100644 index 0000000..3c1f8bc --- /dev/null +++ b/src/Private/JsonRpc.ps1 @@ -0,0 +1,214 @@ +# JSON-RPC 2.0 message model: constructors for requests, notifications, responses and errors, message +# classification and the error codes of the specification (JSON-RPC standard codes and the MCP range). + +$script:McpJsonRpcVersion = '2.0' + +# Error codes: the JSON-RPC 2.0 standard codes and the codes MCP allocates in -32020..-32099. +$script:McpErrorCode = @{ + ParseError = -32700 + InvalidRequest = -32600 + MethodNotFound = -32601 + InvalidParams = -32602 + InternalError = -32603 + HeaderMismatch = -32020 + MissingRequiredClientCapability = -32021 + UnsupportedProtocolVersion = -32022 +} + +function Get-McpErrorCode { + [CmdletBinding()] + [OutputType([int])] + param( + [Parameter(Mandatory)] + [ValidateSet('ParseError', 'InvalidRequest', 'MethodNotFound', 'InvalidParams', 'InternalError', 'HeaderMismatch', 'MissingRequiredClientCapability', 'UnsupportedProtocolVersion')] + [string] $Name + ) + + $script:McpErrorCode[$Name] +} + +function New-McpError { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')] + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [int] $Code, + + [Parameter(Mandatory)] + [string] $Message, + + [AllowNull()] + [object] $Data + ) + + $errorObject = [ordered]@{ + code = $Code + message = $Message + } + if ($PSBoundParameters.ContainsKey('Data') -and $null -ne $Data) { + $errorObject['data'] = $Data + } + $errorObject +} + +function New-McpErrorResponse { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')] + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + # The id of the request being answered; $null when the request could not be parsed. + [Parameter(Mandatory)] + [AllowNull()] + [object] $Id, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $ErrorObject + ) + + # The specification types id as string or integer: when the request id could not be determined, the member + # is omitted rather than sent as null (schema.json rejects null; JSON-RPC 2.0 would use it). + $response = [ordered]@{ jsonrpc = $script:McpJsonRpcVersion } + if ($null -ne $Id) { $response['id'] = $Id } + $response['error'] = $ErrorObject + $response +} + +function New-McpResultResponse { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')] + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [object] $Id, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Result + ) + + [ordered]@{ + jsonrpc = $script:McpJsonRpcVersion + id = $Id + result = $Result + } +} + +function New-McpRequest { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')] + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [object] $Id, + + [Parameter(Mandatory)] + [string] $Method, + + [System.Collections.IDictionary] $Params + ) + + $request = [ordered]@{ + jsonrpc = $script:McpJsonRpcVersion + id = $Id + method = $Method + } + if ($PSBoundParameters.ContainsKey('Params') -and $null -ne $Params) { + $request['params'] = $Params + } + $request +} + +function New-McpNotification { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')] + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [string] $Method, + + [System.Collections.IDictionary] $Params + ) + + $notification = [ordered]@{ + jsonrpc = $script:McpJsonRpcVersion + method = $Method + } + if ($PSBoundParameters.ContainsKey('Params') -and $null -ne $Params) { + $notification['params'] = $Params + } + $notification +} + +function Test-McpRequestId { + <# + .SYNOPSIS + True when the value is a valid JSON-RPC request id for MCP: a string or an integer (null is not allowed). + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Id + ) + + if ($null -eq $Id) { return $false } + if ($Id -is [string]) { return $true } + if ($Id -is [long] -or $Id -is [int] -or $Id -is [int16] -or $Id -is [byte]) { return $true } + if ($Id -is [double]) { return [math]::Floor([double] $Id) -eq [double] $Id } + $false +} + +function Get-McpMessageKind { + <# + .SYNOPSIS + Classifies a decoded JSON-RPC message: Request, Notification, Response, ErrorResponse or Invalid. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [AllowNull()] + [object] $Message + ) + + if ($Message -isnot [System.Collections.IDictionary]) { return 'Invalid' } + if (-not $Message.Contains('jsonrpc') -or $Message['jsonrpc'] -ne $script:McpJsonRpcVersion) { return 'Invalid' } + if ($Message.Contains('method')) { + if ($Message['method'] -isnot [string] -or [string]::IsNullOrEmpty($Message['method'])) { return 'Invalid' } + if ($Message.Contains('params') -and $null -ne $Message['params'] -and $Message['params'] -isnot [System.Collections.IDictionary]) { return 'Invalid' } + if ($Message.Contains('id')) { + if (Test-McpRequestId -Id $Message['id']) { return 'Request' } + return 'Invalid' + } + return 'Notification' + } + if ($Message.Contains('result')) { + if ($Message.Contains('id') -and (Test-McpRequestId -Id $Message['id'])) { return 'Response' } + return 'Invalid' + } + if ($Message.Contains('error')) { + if ($Message['error'] -isnot [System.Collections.IDictionary]) { return 'Invalid' } + return 'ErrorResponse' + } + 'Invalid' +} + +function ConvertTo-McpErrorObject { + <# + .SYNOPSIS + The error object for an exception: the code and data of an McpProtocolException, otherwise an internal error. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [System.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 + } + return New-McpError -Code $Exception.Code -Message $Exception.Message -Data $Exception.Data + } + New-McpError -Code $script:McpErrorCode.InternalError -Message $Exception.Message +} diff --git a/src/Private/Log.ps1 b/src/Private/Log.ps1 new file mode 100644 index 0000000..f52bde3 --- /dev/null +++ b/src/Private/Log.ps1 @@ -0,0 +1,46 @@ +# Diagnostics go to stderr: over stdio, stdout carries protocol messages only. Lines are "timestamp [level] +# [logger] message" in UTF-8; the level threshold comes from the server options (default: warning). + +$script:McpDefaultLogLevel = [McpLoggingLevel]::Warning + +function ConvertTo-McpLoggingLevel { + [CmdletBinding()] + [OutputType([McpLoggingLevel])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Level + ) + + if ($null -eq $Level) { return $script:McpDefaultLogLevel } + if ($Level -is [McpLoggingLevel]) { return $Level } + $parsed = [McpLoggingLevel]::Debug + if ([System.Enum]::TryParse([McpLoggingLevel], [string] $Level, $true, [ref] $parsed)) { return $parsed } + throw [System.ArgumentException]::new("'$Level' is not a logging level (debug, info, notice, warning, error, critical, alert, emergency).") +} + +function Write-McpStderr { + <# + .SYNOPSIS + Writes a diagnostic line to stderr when its level reaches the threshold. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Message, + + [object] $Level = [McpLoggingLevel]::Info, + + [object] $Threshold = $script:McpDefaultLogLevel, + + [string] $Logger + ) + + $levelValue = ConvertTo-McpLoggingLevel -Level $Level + $thresholdValue = ConvertTo-McpLoggingLevel -Level $Threshold + if ([int] $levelValue -lt [int] $thresholdValue) { return } + $prefix = if ($Logger) { "[$Logger] " } else { '' } + $line = '{0} [{1}] {2}{3}' -f [datetime]::UtcNow.ToString('o', [System.Globalization.CultureInfo]::InvariantCulture), $levelValue.ToString().ToLowerInvariant(), $prefix, $Message + [Console]::Error.WriteLine($line) +} diff --git a/src/Private/RequestMeta.ps1 b/src/Private/RequestMeta.ps1 new file mode 100644 index 0000000..cdb10ff --- /dev/null +++ b/src/Private/RequestMeta.ps1 @@ -0,0 +1,143 @@ +# Per-request metadata of revision 2026-07-28: every request carries _meta with the protocol version and the +# client capabilities (required), the client info, the log level and a progress token (optional). + +$script:McpMetaKey = @{ + ProtocolVersion = 'io.modelcontextprotocol/protocolVersion' + ClientCapabilities = 'io.modelcontextprotocol/clientCapabilities' + ClientInfo = 'io.modelcontextprotocol/clientInfo' + LogLevel = 'io.modelcontextprotocol/logLevel' + ServerInfo = 'io.modelcontextprotocol/serverInfo' + SubscriptionId = 'io.modelcontextprotocol/subscriptionId' + ProgressToken = 'progressToken' +} + +$script:McpLoggingLevelNames = @('debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency') + +function Get-McpMetaKey { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [ValidateSet('ProtocolVersion', 'ClientCapabilities', 'ClientInfo', 'LogLevel', 'ServerInfo', 'SubscriptionId', 'ProgressToken')] + [string] $Name + ) + + $script:McpMetaKey[$Name] +} + +function Get-McpRequestMeta { + <# + .SYNOPSIS + Validates params._meta of a modern request and returns its fields; throws McpProtocolException on violations. + .DESCRIPTION + Missing or malformed required fields are an invalid-params error (-32602). A protocol version the server + does not support is an unsupported-protocol-version error (-32022) whose data lists the supported + versions and the requested one. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [AllowNull()] + [object] $Params, + + [Parameter(Mandatory)] + [string[]] $SupportedVersions + ) + + $invalidParams = $script:McpErrorCode.InvalidParams + if ($Params -isnot [System.Collections.IDictionary] -or -not $Params.Contains('_meta') -or $Params['_meta'] -isnot [System.Collections.IDictionary]) { + throw [McpProtocolException]::new($invalidParams, "Missing required _meta: every request must carry params._meta with '$($script:McpMetaKey.ProtocolVersion)' and '$($script:McpMetaKey.ClientCapabilities)'.") + } + $meta = $Params['_meta'] + + $versionKey = $script:McpMetaKey.ProtocolVersion + if (-not $meta.Contains($versionKey) -or $meta[$versionKey] -isnot [string] -or [string]::IsNullOrEmpty($meta[$versionKey])) { + throw [McpProtocolException]::new($invalidParams, "Missing required _meta field '$versionKey'.") + } + $protocolVersion = [string] $meta[$versionKey] + + $capabilitiesKey = $script:McpMetaKey.ClientCapabilities + if (-not $meta.Contains($capabilitiesKey) -or $meta[$capabilitiesKey] -isnot [System.Collections.IDictionary]) { + throw [McpProtocolException]::new($invalidParams, "Missing required _meta field '$capabilitiesKey' (an object).") + } + $clientCapabilities = $meta[$capabilitiesKey] + + if ($protocolVersion -notin $SupportedVersions) { + $data = [ordered]@{ + supported = @($SupportedVersions) + requested = $protocolVersion + } + throw [McpProtocolException]::new($script:McpErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version '$protocolVersion'; supported: $($SupportedVersions -join ', ').", $data) + } + + $clientInfo = $null + $infoKey = $script:McpMetaKey.ClientInfo + if ($meta.Contains($infoKey) -and $null -ne $meta[$infoKey]) { + $clientInfo = $meta[$infoKey] + if ($clientInfo -isnot [System.Collections.IDictionary] -or -not $clientInfo.Contains('name') -or $clientInfo['name'] -isnot [string] -or -not $clientInfo.Contains('version') -or $clientInfo['version'] -isnot [string]) { + throw [McpProtocolException]::new($invalidParams, "_meta field '$infoKey' must be an object with string members 'name' and 'version'.") + } + } + + $logLevel = $null + $levelKey = $script:McpMetaKey.LogLevel + if ($meta.Contains($levelKey) -and $null -ne $meta[$levelKey]) { + $logLevel = $meta[$levelKey] + if ($logLevel -isnot [string] -or $logLevel -cnotin $script:McpLoggingLevelNames) { + throw [McpProtocolException]::new($invalidParams, "_meta field '$levelKey' must be one of: $($script:McpLoggingLevelNames -join ', ').") + } + } + + $progressToken = $null + $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($invalidParams, "_meta field '$tokenKey' must be a string or an integer.") + } + } + + @{ + ProtocolVersion = $protocolVersion + ClientCapabilities = $clientCapabilities + ClientInfo = $clientInfo + LogLevel = $logLevel + ProgressToken = $progressToken + } +} + +function Test-McpCapabilityPath { + <# + .SYNOPSIS + True when a dotted capability path (for example 'elicitation.form' or 'extensions.io.modelcontextprotocol/tasks') exists in a capabilities object. + .DESCRIPTION + Segments are separated by '.'; a segment that contains '/' is an extension identifier and may itself + contain dots, so a path is matched greedily: the longest key that starts the remaining path wins. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Capabilities, + + [Parameter(Mandatory)] + [string] $Path + ) + + $current = $Capabilities + $remaining = $Path + while ($remaining.Length -gt 0) { + if ($current -isnot [System.Collections.IDictionary]) { return $false } + $match = $null + foreach ($key in $current.Keys) { + $keyText = [string] $key + if ($remaining -ceq $keyText -or $remaining.StartsWith($keyText + '.', [System.StringComparison]::Ordinal)) { + if ($null -eq $match -or $keyText.Length -gt $match.Length) { $match = $keyText } + } + } + if ($null -eq $match) { return $false } + $current = $current[$match] + $remaining = if ($remaining.Length -gt $match.Length) { $remaining.Substring($match.Length + 1) } else { '' } + } + $true +} diff --git a/src/Private/Schema.ps1 b/src/Private/Schema.ps1 new file mode 100644 index 0000000..c2bb636 --- /dev/null +++ b/src/Private/Schema.ps1 @@ -0,0 +1,741 @@ +# JSON Schema support: generation of tool input schemas from PowerShell parameter metadata and validation of +# instances against JSON Schema 2020-12. +# +# Validation prefers the JsonSchema.Net assembly that ships with PowerShell (used through its API, not through +# Test-Json, so that schemas without $schema evaluate as 2020-12 and external $ref values are never fetched). +# A validator written in PowerShell covers the common keyword subset as a fallback and for environments where +# the assembly cannot be loaded; both engines are exercised by the tests. + +$script:McpJsonSchemaEngine = $null +$script:McpSchemaMaxDepth = 32 +$script:McpSchemaMaxNodes = 16384 +$script:McpSupportedSchemaDialects = @( + 'https://json-schema.org/draft/2020-12/schema' + 'https://json-schema.org/draft/2019-09/schema' + 'http://json-schema.org/draft-07/schema#' + 'http://json-schema.org/draft-07/schema' + 'http://json-schema.org/draft-06/schema#' + 'http://json-schema.org/draft-06/schema' +) + +function Get-McpJsonSchemaEngine { + <# + .SYNOPSIS + The validation engine in use: JsonSchemaNet when the bundled assembly loads, otherwise PowerShell. + #> + [CmdletBinding()] + [OutputType([string])] + param() + + if ($script:McpJsonSchemaEngine) { return $script:McpJsonSchemaEngine } + $engine = 'PowerShell' + try { + $type = 'Json.Schema.JsonSchema' -as [type] + if (-not $type) { + $assemblyPath = Join-Path $PSHOME 'JsonSchema.Net.dll' + if (Test-Path -Path $assemblyPath) { + Add-Type -Path $assemblyPath -ErrorAction Stop + $type = 'Json.Schema.JsonSchema' -as [type] + } + } + if ($type -and ('Json.Schema.EvaluationOptions' -as [type]) -and ([Json.Schema.EvaluationOptions].GetProperty('EvaluateAs'))) { + $engine = 'JsonSchemaNet' + } + } catch { + $engine = 'PowerShell' + } + $script:McpJsonSchemaEngine = $engine + $engine +} + +function ConvertTo-McpSchemaObject { + <# + .SYNOPSIS + Normalises a schema given as JSON text, hashtable or PSObject into ordered dictionaries. + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Schema + ) + + if ($Schema -is [string]) { + return ConvertFrom-McpJson -Json $Schema -MaxDepth 256 + } + ConvertFrom-McpJson -Json (ConvertTo-McpJson -InputObject $Schema -MaxDepth 256) -MaxDepth 256 +} + +function Test-McpSchemaLimit { + <# + .SYNOPSIS + Rejects schemas that are too deep or too large and schemas with external $ref values or unsupported dialects. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Schema + ) + + if ($Schema -is [System.Collections.IDictionary] -and $Schema.Contains('$schema')) { + $dialect = [string] $Schema['$schema'] + if ($dialect -notin $script:McpSupportedSchemaDialects) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Unsupported JSON Schema dialect '$dialect'. Supported: 2020-12 (default), 2019-09, draft-07, draft-06.") + } + } + $count = 0 + $stack = [System.Collections.Generic.Stack[object]]::new() + $stack.Push(@{ Node = $Schema; Depth = 0 }) + while ($stack.Count -gt 0) { + $entry = $stack.Pop() + $node = $entry.Node + if ($entry.Depth -gt $script:McpSchemaMaxDepth) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The JSON Schema is nested deeper than $($script:McpSchemaMaxDepth) levels.") + } + if ($node -is [System.Collections.IDictionary]) { + $count++ + if ($count -gt $script:McpSchemaMaxNodes) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The JSON Schema has more than $($script:McpSchemaMaxNodes) subschemas.") + } + if ($node.Contains('$ref') -and $node['$ref'] -is [string]) { + $reference = [string] $node['$ref'] + if (-not $reference.StartsWith('#')) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The JSON Schema references '$reference'; only local references (#/...) are supported and external references are never fetched.") + } + } + foreach ($value in $node.Values) { + if ($value -is [System.Collections.IDictionary] -or ($value -is [System.Collections.IList] -and $value -isnot [string])) { + $stack.Push(@{ Node = $value; Depth = $entry.Depth + 1 }) + } + } + } elseif ($node -is [System.Collections.IList]) { + foreach ($value in $node) { + if ($value -is [System.Collections.IDictionary] -or ($value -is [System.Collections.IList] -and $value -isnot [string])) { + $stack.Push(@{ Node = $value; Depth = $entry.Depth + 1 }) + } + } + } + } +} + +function Test-McpJsonSchema { + <# + .SYNOPSIS + Validates an instance against a JSON Schema and returns IsValid plus a list of error messages. + .DESCRIPTION + The schema may be JSON text, a hashtable or a PSObject. Schemas without $schema are evaluated as JSON + Schema 2020-12. External $ref values are rejected before evaluation. -Engine selects the engine + explicitly (JsonSchemaNet, PowerShell); Auto uses JsonSchema.Net when it is available. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Schema, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Instance, + + [ValidateSet('Auto', 'JsonSchemaNet', 'PowerShell')] + [string] $Engine = 'Auto' + ) + + $schemaObject = ConvertTo-McpSchemaObject -Schema $Schema + Test-McpSchemaLimit -Schema $schemaObject + if ($Engine -eq 'Auto') { + $Engine = Get-McpJsonSchemaEngine + } + if ($Engine -eq 'JsonSchemaNet') { + if ((Get-McpJsonSchemaEngine) -ne 'JsonSchemaNet') { + throw [System.InvalidOperationException]::new('JsonSchema.Net is not available in this PowerShell installation.') + } + return Test-McpJsonSchemaWithJsonSchemaNet -Schema $schemaObject -Instance $Instance + } + Test-McpJsonSchemaWithPowerShell -Schema $schemaObject -Instance $Instance +} + +function Test-McpJsonSchemaWithJsonSchemaNet { + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Schema, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Instance + ) + + $schemaText = ConvertTo-McpJson -InputObject $Schema + $instanceText = ConvertTo-McpJson -InputObject $Instance + $jsonSchema = [Json.Schema.JsonSchema]::FromText($schemaText) + $node = [System.Text.Json.Nodes.JsonNode]::Parse($instanceText) + $options = [Json.Schema.EvaluationOptions]::new() + $options.OutputFormat = [Json.Schema.OutputFormat]::List + $options.EvaluateAs = [Json.Schema.SpecVersion]::Draft202012 + $options.SchemaRegistry.Fetch = [System.Func[System.Uri, Json.Schema.IBaseDocument]] { + param($uri) + throw [System.InvalidOperationException]::new("Refusing to fetch the external schema '$uri'.") + } + $results = $null + try { + $results = $jsonSchema.Evaluate($node, $options) + } catch { + # JsonSchema.Net 7.0 (PowerShell 7.4) reports a circular reference for valid recursive schemas such as + # the specification's JSONValue/JSONObject pair; the PowerShell engine evaluates them depth-limited. + $message = if ($_.Exception.InnerException) { $_.Exception.InnerException.Message } else { $_.Exception.Message } + if ($message -like '*circular reference*') { + return Test-McpJsonSchemaWithPowerShell -Schema $Schema -Instance $Instance + } + throw + } + $errors = [System.Collections.Generic.List[string]]::new() + if (-not $results.IsValid) { + foreach ($detail in $results.Details) { + if (-not $detail.HasErrors) { continue } + $location = [string] $detail.InstanceLocation + if ([string]::IsNullOrEmpty($location)) { $location = '/' } elseif (-not $location.StartsWith('/')) { $location = '/' + $location } + foreach ($entry in $detail.Errors.GetEnumerator()) { + $errors.Add(('{0}: {1}' -f $location, $entry.Value)) + } + } + if ($errors.Count -eq 0) { $errors.Add('/: the instance is not valid against the schema') } + } + [pscustomobject]@{ + IsValid = [bool] $results.IsValid + Errors = $errors.ToArray() + Engine = 'JsonSchemaNet' + } +} + +function Test-McpJsonSchemaWithPowerShell { + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Schema, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Instance + ) + + $errors = [System.Collections.Generic.List[string]]::new() + Test-McpSchemaNode -Schema $Schema -Instance $Instance -Path '' -Root $Schema -Errors $errors -Depth 0 + [pscustomobject]@{ + IsValid = ($errors.Count -eq 0) + Errors = $errors.ToArray() + Engine = 'PowerShell' + } +} + +function Get-McpJsonType { + <# + .SYNOPSIS + The JSON type name of a decoded value: null, boolean, integer, number, string, array or object. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [AllowNull()] + [object] $Value + ) + + if ($null -eq $Value) { return 'null' } + if ($Value -is [bool] -or $Value -is [switch]) { return 'boolean' } + if ($Value -is [string] -or $Value -is [char] -or $Value -is [datetime] -or $Value -is [guid] -or $Value -is [uri] -or $Value -is [enum]) { return 'string' } + if ($Value -is [int] -or $Value -is [long] -or $Value -is [int16] -or $Value -is [byte] -or $Value -is [sbyte] -or $Value -is [uint16] -or $Value -is [uint32] -or $Value -is [ulong] -or $Value -is [System.Numerics.BigInteger]) { return 'integer' } + if ($Value -is [double] -or $Value -is [single] -or $Value -is [decimal]) { + $number = [double] $Value + if ([math]::Floor($number) -eq $number -and -not [double]::IsInfinity($number)) { return 'integer' } + return 'number' + } + if ($Value -is [System.Collections.IDictionary]) { return 'object' } + if ($Value -is [System.Collections.IEnumerable]) { return 'array' } + 'object' +} + +function Resolve-McpSchemaReference { + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory)] + [string] $Reference, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Root + ) + + if ($Reference -eq '#' -or $Reference -eq '#/') { return $Root } + if (-not $Reference.StartsWith('#/')) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Unsupported JSON Schema reference '$Reference'.") + } + $current = $Root + foreach ($segment in $Reference.Substring(2).Split('/')) { + $key = $segment.Replace('~1', '/').Replace('~0', '~') + $key = [System.Uri]::UnescapeDataString($key) + if ($current -is [System.Collections.IDictionary]) { + if (-not $current.Contains($key)) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The JSON Schema reference '$Reference' cannot be resolved.") + } + $current = $current[$key] + } elseif ($current -is [System.Collections.IList]) { + $index = 0 + if (-not [int]::TryParse($key, [ref] $index) -or $index -lt 0 -or $index -ge $current.Count) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The JSON Schema reference '$Reference' cannot be resolved.") + } + $current = $current[$index] + } else { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The JSON Schema reference '$Reference' cannot be resolved.") + } + } + $current +} + +function Get-McpSchemaInstanceValue { + <# + .SYNOPSIS + A member of an object instance (dictionary or PSObject) without unrolling array values. + #> + [CmdletBinding()] + [OutputType([object], [object[]])] + param( + [Parameter(Mandatory)] + [object] $Instance, + + [Parameter(Mandatory)] + [string] $Name + ) + + if ($Instance -is [System.Collections.IDictionary]) { + return , $Instance[$Name] + } + return , $Instance.PSObject.Properties[$Name].Value +} + +function Test-McpSchemaValueEqual { + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Left, + + [AllowNull()] + [object] $Right + ) + + (ConvertTo-McpJson -InputObject $Left) -ceq (ConvertTo-McpJson -InputObject $Right) +} + +function Test-McpSchemaNode { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [AllowNull()] + [object] $Schema, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Instance, + + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Path, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Root, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [System.Collections.Generic.List[string]] $Errors, + + [Parameter(Mandatory)] + [int] $Depth + ) + + $location = if ($Path) { $Path } else { '/' } + if ($Depth -gt 64) { + $Errors.Add("${location}: schema evaluation exceeded the maximum depth") + return + } + if ($Schema -is [bool]) { + if (-not $Schema) { $Errors.Add("${location}: the schema 'false' rejects every value") } + return + } + if ($Schema -isnot [System.Collections.IDictionary]) { + return + } + if ($Schema.Contains('$ref')) { + $target = Resolve-McpSchemaReference -Reference ([string] $Schema['$ref']) -Root $Root + Test-McpSchemaNode -Schema $target -Instance $Instance -Path $Path -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + + $instanceType = Get-McpJsonType -Value $Instance + + if ($Schema.Contains('type')) { + $allowed = @($Schema['type']) + $typeMatches = $false + foreach ($candidate in $allowed) { + if ($candidate -eq $instanceType) { $typeMatches = $true } + if ($candidate -eq 'number' -and $instanceType -eq 'integer') { $typeMatches = $true } + } + if (-not $typeMatches) { + $Errors.Add(("{0}: value is '{1}' but should be '{2}'" -f $location, $instanceType, ($allowed -join ' or '))) + return + } + } + if ($Schema.Contains('enum')) { + $found = $false + foreach ($candidate in @($Schema['enum'])) { + if (Test-McpSchemaValueEqual -Left $candidate -Right $Instance) { $found = $true; break } + } + if (-not $found) { $Errors.Add("${location}: value is not one of the allowed values") } + } + if ($Schema.Contains('const')) { + if (-not (Test-McpSchemaValueEqual -Left $Schema['const'] -Right $Instance)) { $Errors.Add("${location}: value does not equal the constant") } + } + + switch ($instanceType) { + 'string' { + $text = [string] $Instance + $length = [System.Globalization.StringInfo]::new($text).LengthInTextElements + if ($Schema.Contains('minLength') -and $length -lt [int] $Schema['minLength']) { $Errors.Add("${location}: string is shorter than $($Schema['minLength']) characters") } + if ($Schema.Contains('maxLength') -and $length -gt [int] $Schema['maxLength']) { $Errors.Add("${location}: string is longer than $($Schema['maxLength']) characters") } + if ($Schema.Contains('pattern') -and -not [regex]::IsMatch($text, [string] $Schema['pattern'], [System.Text.RegularExpressions.RegexOptions]::ECMAScript)) { $Errors.Add("${location}: string does not match the pattern '$($Schema['pattern'])'") } + } + { $_ -in 'integer', 'number' } { + $number = [double] $Instance + if ($Schema.Contains('minimum') -and $number -lt [double] $Schema['minimum']) { $Errors.Add("${location}: $number is less than the minimum $($Schema['minimum'])") } + if ($Schema.Contains('maximum') -and $number -gt [double] $Schema['maximum']) { $Errors.Add("${location}: $number is greater than the maximum $($Schema['maximum'])") } + if ($Schema.Contains('exclusiveMinimum') -and $number -le [double] $Schema['exclusiveMinimum']) { $Errors.Add("${location}: $number is not greater than $($Schema['exclusiveMinimum'])") } + if ($Schema.Contains('exclusiveMaximum') -and $number -ge [double] $Schema['exclusiveMaximum']) { $Errors.Add("${location}: $number is not less than $($Schema['exclusiveMaximum'])") } + if ($Schema.Contains('multipleOf')) { + $divisor = [double] $Schema['multipleOf'] + if ($divisor -gt 0) { + $quotient = $number / $divisor + if ([math]::Abs($quotient - [math]::Round($quotient)) -gt 1e-9) { $Errors.Add("${location}: $number is not a multiple of $divisor") } + } + } + } + 'array' { + $items = @($Instance) + if ($Schema.Contains('minItems') -and $items.Count -lt [int] $Schema['minItems']) { $Errors.Add("${location}: array has fewer than $($Schema['minItems']) items") } + if ($Schema.Contains('maxItems') -and $items.Count -gt [int] $Schema['maxItems']) { $Errors.Add("${location}: array has more than $($Schema['maxItems']) items") } + if ($Schema.Contains('uniqueItems') -and [bool] $Schema['uniqueItems']) { + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + foreach ($item in $items) { + if (-not $seen.Add((ConvertTo-McpJson -InputObject $item))) { $Errors.Add("${location}: array items are not unique"); break } + } + } + $prefixCount = 0 + if ($Schema.Contains('prefixItems')) { + $prefix = @($Schema['prefixItems']) + $prefixCount = $prefix.Count + for ($i = 0; $i -lt [math]::Min($prefixCount, $items.Count); $i++) { + Test-McpSchemaNode -Schema $prefix[$i] -Instance $items[$i] -Path "$Path/$i" -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } + if ($Schema.Contains('items')) { + for ($i = $prefixCount; $i -lt $items.Count; $i++) { + Test-McpSchemaNode -Schema $Schema['items'] -Instance $items[$i] -Path "$Path/$i" -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } + } + 'object' { + $keys = @(if ($Instance -is [System.Collections.IDictionary]) { $Instance.Keys } else { $Instance.PSObject.Properties.Name }) + if ($Schema.Contains('required')) { + foreach ($name in @($Schema['required'])) { + if ($name -cnotin $keys) { $Errors.Add("${location}: required property '$name' is missing") } + } + } + if ($Schema.Contains('minProperties') -and $keys.Count -lt [int] $Schema['minProperties']) { $Errors.Add("${location}: object has fewer than $($Schema['minProperties']) properties") } + if ($Schema.Contains('maxProperties') -and $keys.Count -gt [int] $Schema['maxProperties']) { $Errors.Add("${location}: object has more than $($Schema['maxProperties']) properties") } + $declared = @{} + if ($Schema.Contains('properties') -and $Schema['properties'] -is [System.Collections.IDictionary]) { + foreach ($name in $Schema['properties'].Keys) { + $declared[[string] $name] = $true + if ($name -cin $keys) { + Test-McpSchemaNode -Schema $Schema['properties'][$name] -Instance (Get-McpSchemaInstanceValue -Instance $Instance -Name $name) -Path "$Path/$name" -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } + } + $patternKeys = @() + if ($Schema.Contains('patternProperties') -and $Schema['patternProperties'] -is [System.Collections.IDictionary]) { + foreach ($pattern in $Schema['patternProperties'].Keys) { + foreach ($name in $keys) { + if ([regex]::IsMatch([string] $name, [string] $pattern, [System.Text.RegularExpressions.RegexOptions]::ECMAScript)) { + $patternKeys += [string] $name + Test-McpSchemaNode -Schema $Schema['patternProperties'][$pattern] -Instance (Get-McpSchemaInstanceValue -Instance $Instance -Name $name) -Path "$Path/$name" -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } + } + } + if ($Schema.Contains('additionalProperties')) { + $additional = $Schema['additionalProperties'] + foreach ($name in $keys) { + if ($declared.ContainsKey([string] $name) -or ([string] $name) -cin $patternKeys) { continue } + if ($additional -is [bool]) { + if (-not $additional) { $Errors.Add("${location}: property '$name' is not allowed") } + } else { + Test-McpSchemaNode -Schema $additional -Instance (Get-McpSchemaInstanceValue -Instance $Instance -Name $name) -Path "$Path/$name" -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } + } + } + } + + if ($Schema.Contains('allOf')) { + foreach ($subschema in @($Schema['allOf'])) { + Test-McpSchemaNode -Schema $subschema -Instance $Instance -Path $Path -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } + if ($Schema.Contains('anyOf')) { + $anyValid = $false + foreach ($subschema in @($Schema['anyOf'])) { + $branchErrors = [System.Collections.Generic.List[string]]::new() + Test-McpSchemaNode -Schema $subschema -Instance $Instance -Path $Path -Root $Root -Errors $branchErrors -Depth ($Depth + 1) + if ($branchErrors.Count -eq 0) { $anyValid = $true; break } + } + if (-not $anyValid) { $Errors.Add("${location}: value does not match any of the anyOf schemas") } + } + if ($Schema.Contains('oneOf')) { + $validCount = 0 + foreach ($subschema in @($Schema['oneOf'])) { + $branchErrors = [System.Collections.Generic.List[string]]::new() + Test-McpSchemaNode -Schema $subschema -Instance $Instance -Path $Path -Root $Root -Errors $branchErrors -Depth ($Depth + 1) + if ($branchErrors.Count -eq 0) { $validCount++ } + } + if ($validCount -ne 1) { $Errors.Add("${location}: value matches $validCount of the oneOf schemas instead of exactly one") } + } + if ($Schema.Contains('not')) { + $branchErrors = [System.Collections.Generic.List[string]]::new() + Test-McpSchemaNode -Schema $Schema['not'] -Instance $Instance -Path $Path -Root $Root -Errors $branchErrors -Depth ($Depth + 1) + if ($branchErrors.Count -eq 0) { $Errors.Add("${location}: value matches the 'not' schema") } + } + if ($Schema.Contains('if')) { + $conditionErrors = [System.Collections.Generic.List[string]]::new() + Test-McpSchemaNode -Schema $Schema['if'] -Instance $Instance -Path $Path -Root $Root -Errors $conditionErrors -Depth ($Depth + 1) + $branch = if ($conditionErrors.Count -eq 0) { 'then' } else { 'else' } + if ($Schema.Contains($branch)) { + Test-McpSchemaNode -Schema $Schema[$branch] -Instance $Instance -Path $Path -Root $Root -Errors $Errors -Depth ($Depth + 1) + } + } +} + +# --- Schema generation from PowerShell parameters --------------------------------------------------------- + +$script:McpExcludedParameterNames = @( + [System.Management.Automation.PSCmdlet]::CommonParameters + + [System.Management.Automation.PSCmdlet]::OptionalCommonParameters + + @('Context') +) + +function ConvertTo-McpSchemaTypeFragment { + <# + .SYNOPSIS + The JSON Schema fragment for a .NET parameter type (type, format, items, enum). + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [type] $Type, + + [int] $Depth = 0 + ) + + $fragment = [ordered]@{} + if ($Depth -gt 8) { return $fragment } + if ($Type.IsGenericType -and $Type.GetGenericTypeDefinition() -eq [System.Nullable`1]) { + $inner = ConvertTo-McpSchemaTypeFragment -Type $Type.GetGenericArguments()[0] -Depth ($Depth + 1) + if ($inner.Contains('type')) { $inner['type'] = @($inner['type'], 'null') } + return $inner + } + if ($Type -in @([System.Security.SecureString], [pscredential], [scriptblock])) { + throw [System.ArgumentException]::new("Parameters of type $($Type.Name) cannot be exposed as tool arguments.") + } + if ($Type -eq [string] -or $Type -eq [char]) { $fragment['type'] = 'string'; return $fragment } + if ($Type -eq [bool] -or $Type -eq [switch]) { $fragment['type'] = 'boolean'; return $fragment } + if ($Type -in @([int], [long], [int16], [byte], [sbyte], [uint16], [uint32], [ulong], [System.Numerics.BigInteger])) { $fragment['type'] = 'integer'; return $fragment } + if ($Type -in @([double], [single], [decimal])) { $fragment['type'] = 'number'; return $fragment } + if ($Type -eq [datetime] -or $Type -eq [datetimeoffset]) { $fragment['type'] = 'string'; $fragment['format'] = 'date-time'; return $fragment } + if ($Type -eq [guid]) { $fragment['type'] = 'string'; $fragment['format'] = 'uuid'; return $fragment } + if ($Type -eq [uri]) { $fragment['type'] = 'string'; $fragment['format'] = 'uri'; return $fragment } + if ($Type -eq [timespan] -or $Type -eq [version]) { $fragment['type'] = 'string'; return $fragment } + if ($Type.IsEnum) { $fragment['type'] = 'string'; $fragment['enum'] = @([enum]::GetNames($Type)); return $fragment } + if ($Type.IsArray) { + $fragment['type'] = 'array' + $fragment['items'] = ConvertTo-McpSchemaTypeFragment -Type $Type.GetElementType() -Depth ($Depth + 1) + return $fragment + } + if ([System.Collections.IDictionary].IsAssignableFrom($Type) -or $Type -eq [psobject] -or $Type -eq [object] -or $Type -eq [System.Management.Automation.PSCustomObject]) { + if ($Type -eq [object]) { return $fragment } + $fragment['type'] = 'object' + return $fragment + } + if ($Type.IsGenericType -and [System.Collections.IEnumerable].IsAssignableFrom($Type)) { + $enumerable = @($Type.GetInterfaces() | Where-Object { $_.IsGenericType -and $_.GetGenericTypeDefinition() -eq [System.Collections.Generic.IEnumerable`1] }) + @($Type) + $elementType = ($enumerable | Where-Object { $_.IsGenericType -and $_.GetGenericTypeDefinition() -eq [System.Collections.Generic.IEnumerable`1] } | Select-Object -First 1) + $fragment['type'] = 'array' + if ($elementType) { $fragment['items'] = ConvertTo-McpSchemaTypeFragment -Type $elementType.GetGenericArguments()[0] -Depth ($Depth + 1) } + return $fragment + } + if ([System.Collections.IEnumerable].IsAssignableFrom($Type)) { $fragment['type'] = 'array'; return $fragment } + # Any other type: accept any JSON value and let the parameter binder convert it. + $fragment +} + +function Get-McpParameterDefaultValue { + <# + .SYNOPSIS + Constant default values of the parameters of a script block or function AST, keyed by parameter name. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [AllowNull()] + [System.Management.Automation.Language.Ast] $Ast + ) + + $defaults = @{} + if ($null -eq $Ast) { return $defaults } + $paramBlock = $null + if ($Ast -is [System.Management.Automation.Language.FunctionDefinitionAst]) { $paramBlock = $Ast.Body.ParamBlock } + elseif ($Ast -is [System.Management.Automation.Language.ScriptBlockAst]) { $paramBlock = $Ast.ParamBlock } + if ($null -eq $paramBlock) { return $defaults } + foreach ($parameter in $paramBlock.Parameters) { + if ($null -eq $parameter.DefaultValue) { continue } + try { + $defaults[$parameter.Name.VariablePath.UserPath] = $parameter.DefaultValue.SafeGetValue() + } catch { + Write-Debug "The default value of parameter '$($parameter.Name.VariablePath.UserPath)' is not a constant; it is not part of the schema." + } + } + $defaults +} + +function Get-McpCommandHelp { + <# + .SYNOPSIS + Synopsis, description and parameter descriptions from comment-based help of a function, script or script block. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [AllowNull()] + [System.Management.Automation.Language.Ast] $Ast + ) + + $help = @{ Synopsis = $null; Description = $null; Parameters = @{} } + if ($null -eq $Ast) { return $help } + $content = $null + try { $content = $Ast.GetHelpContent() } catch { $content = $null } + if ($null -eq $content) { return $help } + if ($content.Synopsis) { $help.Synopsis = $content.Synopsis.Trim() } + if ($content.Description) { $help.Description = $content.Description.Trim() } + if ($content.Parameters) { + # CommentHelpInfo upper-cases the parameter names. + foreach ($entry in $content.Parameters.GetEnumerator()) { + $help.Parameters[[string] $entry.Key] = ([string] $entry.Value).Trim() + } + } + $help +} + +function New-McpToolInputSchema { + <# + .SYNOPSIS + Builds the JSON Schema of a tool's arguments from parameter metadata, help content and default values. + .OUTPUTS + A hashtable with Schema (ordered dictionary) and ParameterTypes (name -> type) for typed binding. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory schema.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Parameters, + + [hashtable] $Help = @{ Parameters = @{} }, + + [hashtable] $Defaults = @{}, + + [switch] $AllowAdditionalProperties + ) + + $properties = [ordered]@{} + $required = [System.Collections.Generic.List[string]]::new() + $types = @{} + foreach ($entry in $Parameters.GetEnumerator()) { + $metadata = $entry.Value + $name = [string] $metadata.Name + if ($name -in $script:McpExcludedParameterNames) { continue } + $property = ConvertTo-McpSchemaTypeFragment -Type $metadata.ParameterType + $types[$name] = $metadata.ParameterType + + $description = $null + foreach ($helpKey in $Help.Parameters.Keys) { + if ($helpKey -ieq $name) { $description = $Help.Parameters[$helpKey] } + } + $mandatorySets = 0 + $sets = 0 + foreach ($attribute in $metadata.Attributes) { + if ($attribute -is [System.Management.Automation.ParameterAttribute]) { + $sets++ + if ($attribute.Mandatory) { $mandatorySets++ } + if (-not $description -and $attribute.HelpMessage) { $description = $attribute.HelpMessage } + } elseif ($attribute -is [System.Management.Automation.ValidateSetAttribute]) { + $values = @($attribute.ValidValues) + if ($property['type'] -eq 'integer') { $property['enum'] = @($values | ForEach-Object { [long] $_ }) } + elseif ($property['type'] -eq 'number') { $property['enum'] = @($values | ForEach-Object { [double] $_ }) } + else { $property['enum'] = @($values | ForEach-Object { [string] $_ }) } + } elseif ($attribute -is [System.Management.Automation.ValidateRangeAttribute]) { + $kind = $null + if ($attribute.PSObject.Properties['RangeKind']) { $kind = $attribute.RangeKind } + if ($null -ne $kind) { + switch ([string] $kind) { + 'Positive' { $property['exclusiveMinimum'] = 0 } + 'NonNegative' { $property['minimum'] = 0 } + 'Negative' { $property['exclusiveMaximum'] = 0 } + 'NonPositive' { $property['maximum'] = 0 } + } + } else { + if ($null -ne $attribute.MinRange) { $property['minimum'] = $attribute.MinRange } + if ($null -ne $attribute.MaxRange) { $property['maximum'] = $attribute.MaxRange } + } + } elseif ($attribute -is [System.Management.Automation.ValidateLengthAttribute]) { + $property['minLength'] = $attribute.MinLength + $property['maxLength'] = $attribute.MaxLength + } elseif ($attribute -is [System.Management.Automation.ValidatePatternAttribute]) { + $property['pattern'] = $attribute.RegexPattern + } elseif ($attribute -is [System.Management.Automation.ValidateCountAttribute]) { + $property['minItems'] = $attribute.MinLength + $property['maxItems'] = $attribute.MaxLength + } + } + if ($description) { $property['description'] = $description } + if ($Defaults.ContainsKey($name)) { + $default = $Defaults[$name] + if ($null -ne $default) { $property['default'] = $default } + } + if ($sets -gt 0 -and $mandatorySets -eq $sets) { $required.Add($name) } + $properties[$name] = $property + } + + $schema = [ordered]@{ type = 'object' } + if ($properties.Count -gt 0) { $schema['properties'] = $properties } + if ($required.Count -gt 0) { $schema['required'] = $required.ToArray() } + if (-not $AllowAdditionalProperties) { $schema['additionalProperties'] = $false } + @{ + Schema = $schema + ParameterTypes = $types + } +} diff --git a/src/Private/Server.ps1 b/src/Private/Server.ps1 new file mode 100644 index 0000000..8c30a4e --- /dev/null +++ b/src/Private/Server.ps1 @@ -0,0 +1,116 @@ +# The server object (a PSCustomObject with PSTypeName Mcp.Server) and the results that describe the server: +# server/discover and the serverInfo metadata added to every result. + +$script:McpLatestProtocolVersion = '2026-07-28' +$script:McpModernProtocolVersions = @('2026-07-28') +$script:McpDefaultServer = $null + +function Test-McpServerObject { + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Server + ) + + $null -ne $Server -and $Server.PSObject.TypeNames -contains 'Mcp.Server' +} + +function Resolve-McpServer { + <# + .SYNOPSIS + The server passed to a command, or the default server set with New-McpServer -SetDefault. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [AllowNull()] + [object] $Server + ) + + if ($null -ne $Server) { + if (-not (Test-McpServerObject -Server $Server)) { + throw [System.ArgumentException]::new('The -Server argument is not a server created by New-McpServer.') + } + return $Server + } + if ($null -eq $script:McpDefaultServer) { + throw [System.InvalidOperationException]::new('No server given and no default server set. Create one with New-McpServer -SetDefault or pass -Server.') + } + $script:McpDefaultServer +} + +function Get-McpServerInfoObject { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server + ) + + $info = [ordered]@{ + name = $Server.Name + version = $Server.Version + } + if ($Server.Title) { $info['title'] = $Server.Title } + if ($Server.Description) { $info['description'] = $Server.Description } + if ($Server.WebsiteUrl) { $info['websiteUrl'] = $Server.WebsiteUrl } + if ($Server.Icons -and @($Server.Icons).Count -gt 0) { $info['icons'] = @($Server.Icons) } + $info +} + +function Get-McpServerCapability { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server + ) + + $capabilities = [ordered]@{ + tools = [ordered]@{ listChanged = [bool] $Server.Options.ListChanged } + } + $capabilities +} + +function Add-McpResultMeta { + <# + .SYNOPSIS + Adds _meta with the server info to a result (unless the server is configured without server info). + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [System.Collections.Specialized.OrderedDictionary] $Result, + + [Parameter(Mandatory)] + [pscustomobject] $Server + ) + + if ($Server.Options.IncludeServerInfo) { + $meta = if ($Result.Contains('_meta') -and $Result['_meta'] -is [System.Collections.IDictionary]) { $Result['_meta'] } else { [ordered]@{} } + $meta[$script:McpMetaKey.ServerInfo] = Get-McpServerInfoObject -Server $Server + $Result['_meta'] = $meta + } + $Result +} + +function Get-McpDiscoverResult { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server + ) + + $result = [ordered]@{ + resultType = 'complete' + supportedVersions = @($Server.SupportedVersions) + capabilities = Get-McpServerCapability -Server $Server + } + if ($Server.Instructions) { $result['instructions'] = $Server.Instructions } + $result['ttlMs'] = [long] $Server.Options.DefaultTtlMs + $result['cacheScope'] = $Server.Options.DefaultCacheScope + Add-McpResultMeta -Result $result -Server $Server +} diff --git a/src/Private/Tools.ps1 b/src/Private/Tools.ps1 new file mode 100644 index 0000000..5603723 --- /dev/null +++ b/src/Private/Tools.ps1 @@ -0,0 +1,385 @@ +# Tool registry: registrations (PSTypeName Mcp.ToolRegistration), the Tool definitions of tools/list, cursor +# pagination, typed argument binding and the shaping of handler output into CallToolResult. + +$script:McpToolNamePattern = '^[A-Za-z0-9_.-]{1,128}$' +$script:McpContentTypes = @('text', 'image', 'audio', 'resource_link', 'resource') + +function Get-McpToolRegistration { + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Name + ) + + if ($Name -isnot [string] -or -not $Server.Tools.Contains([string] $Name)) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Unknown tool '$Name'.") + } + $Server.Tools[[string] $Name] +} + +function ConvertTo-McpToolDefinition { + <# + .SYNOPSIS + The Tool object (as sent in tools/list) of a registration. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Registration + ) + + $tool = [ordered]@{ name = $Registration.Name } + if ($Registration.Title) { $tool['title'] = $Registration.Title } + if ($Registration.Description) { $tool['description'] = $Registration.Description } + $tool['inputSchema'] = $Registration.InputSchema + if ($null -ne $Registration.OutputSchema) { $tool['outputSchema'] = $Registration.OutputSchema } + if ($null -ne $Registration.Annotations -and $Registration.Annotations.Count -gt 0) { $tool['annotations'] = $Registration.Annotations } + if ($null -ne $Registration.Icons -and @($Registration.Icons).Count -gt 0) { $tool['icons'] = @($Registration.Icons) } + if ($null -ne $Registration.Meta -and $Registration.Meta.Count -gt 0) { $tool['_meta'] = $Registration.Meta } + $tool +} + +function ConvertTo-McpAnnotationObject { + <# + .SYNOPSIS + Normalises ToolAnnotations given with PowerShell-style keys (ReadOnlyHint) to the wire keys (readOnlyHint). + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [AllowNull()] + [System.Collections.IDictionary] $Annotations + ) + + $result = [ordered]@{} + if ($null -eq $Annotations) { return $result } + $known = @{ title = 'title'; readonlyhint = 'readOnlyHint'; destructivehint = 'destructiveHint'; idempotenthint = 'idempotentHint'; openworldhint = 'openWorldHint' } + foreach ($key in $Annotations.Keys) { + $lower = ([string] $key).ToLowerInvariant() + $wireKey = if ($known.ContainsKey($lower)) { $known[$lower] } else { [string] $key } + $value = $Annotations[$key] + if ($wireKey -ne 'title' -and $known.ContainsKey($lower)) { $value = [bool] $value } + $result[$wireKey] = $value + } + $result +} + +function New-McpCursor { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Encodes a value.')] + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [int] $Offset + ) + + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("mcp-cursor:offset=$Offset")) +} + +function Read-McpCursor { + [CmdletBinding()] + [OutputType([int])] + param( + [AllowNull()] + [object] $Cursor + ) + + if ($null -eq $Cursor) { return 0 } + if ($Cursor -is [string]) { + $text = $null + try { + $text = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Cursor)) + } catch { + $text = $null + } + if ($null -ne $text -and $text -match '^mcp-cursor:offset=(\d{1,9})$') { return [int] $Matches[1] } + } + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Invalid cursor.') +} + +function Get-McpToolListResult { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [AllowNull()] + [object] $Cursor + ) + + $offset = Read-McpCursor -Cursor $Cursor + $registrations = @($Server.Tools.Values) + if ($offset -gt $registrations.Count) { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Invalid cursor.') + } + $pageSize = [int] $Server.Options.PageSize + $page = @() + if ($offset -lt $registrations.Count) { + $end = [math]::Min($offset + $pageSize, $registrations.Count) - 1 + $page = @($registrations[$offset..$end] | ForEach-Object { ConvertTo-McpToolDefinition -Registration $_ }) + } + $result = [ordered]@{ + resultType = 'complete' + tools = $page + } + if ($offset + $pageSize -lt $registrations.Count) { + $result['nextCursor'] = New-McpCursor -Offset ($offset + $pageSize) + } + $result['ttlMs'] = [long] $Server.Options.DefaultTtlMs + $result['cacheScope'] = $Server.Options.DefaultCacheScope + Add-McpResultMeta -Result $result -Server $Server +} + +function ConvertTo-McpToolArgument { + <# + .SYNOPSIS + Binds validated JSON arguments to the handler's parameters: a splatting table with converted values. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Registration, + + [AllowNull()] + [System.Collections.IDictionary] $Arguments, + + [AllowNull()] + [object] $Context + ) + + $handler = $Registration.Handler + $splat = @{} + if ($handler.ArgumentStyle -eq 'Arguments') { + $splat['Arguments'] = if ($null -ne $Arguments) { $Arguments } else { [ordered]@{} } + } elseif ($null -ne $Arguments) { + $types = $handler.ParameterTypes + foreach ($key in $Arguments.Keys) { + $name = [string] $key + $parameterName = $null + if ($types.ContainsKey($name)) { + $parameterName = $name + } else { + foreach ($candidate in $types.Keys) { + if ($candidate -ieq $name) { $parameterName = $candidate; break } + } + } + $value = $Arguments[$key] + if ($null -eq $parameterName) { + $splat[$name] = $value + continue + } + $splat[$parameterName] = ConvertTo-McpParameterValue -Value $value -Type $types[$parameterName] -Name $parameterName + } + } + if ($handler.ContextParameter -and $null -ne $Context) { + $splat[$handler.ContextParameter] = $Context + } + $splat +} + +function ConvertTo-McpParameterValue { + [CmdletBinding()] + [OutputType([object], [switch], [hashtable])] + param( + [AllowNull()] + [object] $Value, + + [Parameter(Mandatory)] + [type] $Type, + + [Parameter(Mandatory)] + [string] $Name + ) + + if ($null -eq $Value) { return $null } + if ($Type -eq [object] -or $Type -eq [psobject]) { return $Value } + if ($Type -eq [switch]) { return [switch] ([bool] $Value) } + if ($Type -eq [hashtable] -and $Value -is [System.Collections.IDictionary]) { + $table = @{} + foreach ($key in $Value.Keys) { $table[[string] $key] = $Value[$key] } + return $table + } + try { + return [System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, $Type) + } catch { + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Argument '$Name' cannot be converted to $($Type.Name): $($_.Exception.Message)") + } +} + +function Test-McpContentObject { + [CmdletBinding()] + [OutputType([bool])] + param( + [AllowNull()] + [object] $Value + ) + + if ($null -eq $Value) { return $false } + if ($Value.PSObject.TypeNames -contains 'Mcp.Content') { return $true } + if ($Value -is [System.Collections.IDictionary] -and $Value.Contains('type') -and $Value['type'] -in $script:McpContentTypes) { return $true } + $false +} + +function ConvertTo-McpTextBlock { + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Text + ) + + [ordered]@{ type = 'text'; text = $Text } +} + +function ConvertTo-McpCallToolResult { + <# + .SYNOPSIS + Shapes handler output into a CallToolResult. + .DESCRIPTION + A single Mcp.ToolResult (New-McpToolResult) is taken as is. Otherwise content blocks pass through, + strings and primitives become text blocks, and other objects become JSON text blocks; a single object + also becomes structuredContent. Non-terminating errors of the handler are appended as text and mark + the result as an error. When the tool declares an outputSchema, structuredContent is required and + validated against it. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [AllowNull()] + [AllowEmptyCollection()] + [object[]] $Output, + + [Parameter(Mandatory)] + [pscustomobject] $Registration, + + [AllowNull()] + [AllowEmptyCollection()] + [System.Management.Automation.ErrorRecord[]] $ErrorRecords + ) + + $content = [System.Collections.Generic.List[object]]::new() + $structured = $null + $hasStructured = $false + $isError = $false + $meta = $null + $items = @($Output | Where-Object { $null -ne $_ }) + + if ($items.Count -eq 1 -and $items[0].PSObject.TypeNames -contains 'Mcp.ToolResult') { + $given = $items[0] + foreach ($block in @($given.content)) { $content.Add($block) } + if ($given.PSObject.Properties['structuredContent'] -and $null -ne $given.structuredContent) { $structured = $given.structuredContent; $hasStructured = $true } + if ($given.PSObject.Properties['isError'] -and $given.isError) { $isError = $true } + if ($given.PSObject.Properties['_meta'] -and $null -ne $given._meta) { $meta = $given._meta } + } else { + $objects = [System.Collections.Generic.List[object]]::new() + foreach ($item in $items) { + if (Test-McpContentObject -Value $item) { + $content.Add($item) + } elseif ($item -is [string]) { + $content.Add((ConvertTo-McpTextBlock -Text $item)) + } elseif ($item -is [bool] -or $item -is [switch]) { + $content.Add((ConvertTo-McpTextBlock -Text ([bool] $item).ToString().ToLowerInvariant())) + } elseif ($item -is [valuetype] -or $item -is [enum] -or $item -is [uri] -or $item -is [version]) { + $content.Add((ConvertTo-McpTextBlock -Text ([System.Management.Automation.LanguagePrimitives]::ConvertTo($item, [string])))) + } else { + $objects.Add($item) + } + } + if ($objects.Count -eq 1 -and ($objects[0] -is [System.Collections.IDictionary] -or $objects[0] -is [System.Management.Automation.PSCustomObject] -or $objects[0] -isnot [System.Collections.IEnumerable])) { + $structured = $objects[0] + $hasStructured = $true + $content.Add((ConvertTo-McpTextBlock -Text (ConvertTo-McpJson -InputObject $structured))) + } else { + foreach ($object in $objects) { + $content.Add((ConvertTo-McpTextBlock -Text (ConvertTo-McpJson -InputObject $object))) + } + } + } + + foreach ($record in @($ErrorRecords | Where-Object { $null -ne $_ })) { + $content.Add((ConvertTo-McpTextBlock -Text ('Error: ' + $record.ToString()))) + $isError = $true + } + + if ($null -ne $Registration.OutputSchema -and -not $isError) { + if (-not $hasStructured) { + $content.Add((ConvertTo-McpTextBlock -Text "Error: the tool '$($Registration.Name)' declares an output schema but returned no structured content.")) + $isError = $true + } else { + $validation = Test-McpJsonSchema -Schema $Registration.OutputSchema -Instance $structured + if (-not $validation.IsValid) { + $content.Add((ConvertTo-McpTextBlock -Text ("Error: the structured content of tool '{0}' does not match its output schema: {1}" -f $Registration.Name, ($validation.Errors -join '; ')))) + $isError = $true + } + } + } + + $result = [ordered]@{ content = $content.ToArray() } + if ($hasStructured) { $result['structuredContent'] = $structured } + if ($isError) { $result['isError'] = $true } + $result['resultType'] = 'complete' + if ($null -ne $meta) { $result['_meta'] = $meta } + $result +} + +function Split-McpHandlerOutput { + <# + .SYNOPSIS + Separates merged handler output into output objects, error records and diagnostic records. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [AllowNull()] + [AllowEmptyCollection()] + [object[]] $Merged + ) + + $output = [System.Collections.Generic.List[object]]::new() + $errors = [System.Collections.Generic.List[System.Management.Automation.ErrorRecord]]::new() + $diagnostics = [System.Collections.Generic.List[object]]::new() + foreach ($item in @($Merged)) { + if ($item -is [System.Management.Automation.ErrorRecord]) { $errors.Add($item) } + elseif ($item -is [System.Management.Automation.WarningRecord] -or $item -is [System.Management.Automation.VerboseRecord] -or $item -is [System.Management.Automation.DebugRecord] -or $item -is [System.Management.Automation.InformationRecord]) { $diagnostics.Add($item) } + else { $output.Add($item) } + } + @{ + Output = $output.ToArray() + Errors = $errors.ToArray() + Diagnostics = $diagnostics.ToArray() + } +} + +function Write-McpHandlerDiagnostic { + [CmdletBinding()] + param( + [AllowNull()] + [AllowEmptyCollection()] + [object[]] $Diagnostics, + + [Parameter(Mandatory)] + [string] $ToolName, + + [object] $Threshold = $script:McpDefaultLogLevel + ) + + foreach ($record in @($Diagnostics)) { + $level = switch ($record) { + { $_ -is [System.Management.Automation.WarningRecord] } { [McpLoggingLevel]::Warning } + { $_ -is [System.Management.Automation.VerboseRecord] } { [McpLoggingLevel]::Debug } + { $_ -is [System.Management.Automation.DebugRecord] } { [McpLoggingLevel]::Debug } + default { [McpLoggingLevel]::Info } + } + $text = if ($record -is [System.Management.Automation.InformationRecord]) { [string] $record.MessageData } else { $record.Message } + Write-McpStderr -Level $level -Threshold $Threshold -Logger $ToolName -Message $text + } +} diff --git a/src/Private/Transport.ps1 b/src/Private/Transport.ps1 new file mode 100644 index 0000000..4715db4 --- /dev/null +++ b/src/Private/Transport.ps1 @@ -0,0 +1,282 @@ +# Transports as data: a transport is a hashtable with Kind (Stdio, Process, InMemory or Http), used only +# through functions so that the same code runs in whichever runspace hosts the dispatcher or the client. The +# line-based kinds have a line reader and a line writer: Stdio and Process transports wrap raw UTF-8 streams +# (no BOM, "\n" newlines), the in-memory transport is a pair of System.Threading.Channels channels for tests +# and in-process clients. The Http kinds (HttpServer.ps1, HttpClient.ps1) carry a listener or an HttpClient. +# +# This file is the only place in the module that touches the console streams (see Measure-McpStdoutPurity). + +$script:McpAsyncWaitHandleProperty = [System.IAsyncResult].GetProperty('AsyncWaitHandle') + +function Get-McpTaskWaitHandle { + [CmdletBinding()] + [OutputType([System.Threading.WaitHandle])] + param( + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task + ) + + $script:McpAsyncWaitHandleProperty.GetValue($Task) +} + +function New-McpUtf8Encoding { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an encoding object.')] + [CmdletBinding()] + [OutputType([System.Text.UTF8Encoding])] + param() + + [System.Text.UTF8Encoding]::new($false) +} + +function New-McpStdioServerTransport { + <# + .SYNOPSIS + A transport over the process's standard input and output streams. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType([hashtable])] + param() + + $encoding = New-McpUtf8Encoding + $reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), $encoding, $false, 65536) + $writer = [System.IO.StreamWriter]::new([Console]::OpenStandardOutput(), $encoding, 65536) + $writer.NewLine = "`n" + $writer.AutoFlush = $true + @{ + Kind = 'Stdio' + Reader = $reader + Writer = $writer + PendingRead = $null + Closed = $false + } +} + +function New-McpProcessTransport { + <# + .SYNOPSIS + Starts a server process and returns a transport over its standard input and output; stderr goes to a file. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller (Connect-McpServer) owns the ShouldProcess decision.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [string] $FilePath, + + [string[]] $ArgumentList = @(), + + [string] $WorkingDirectory, + + [hashtable] $Environment, + + [string] $StandardErrorPath + ) + + $encoding = New-McpUtf8Encoding + $startInfo = [System.Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $FilePath + foreach ($argument in $ArgumentList) { $startInfo.ArgumentList.Add($argument) } + $startInfo.UseShellExecute = $false + $startInfo.CreateNoWindow = $true + $startInfo.RedirectStandardInput = $true + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $startInfo.StandardOutputEncoding = $encoding + $startInfo.StandardErrorEncoding = $encoding + $startInfo.StandardInputEncoding = $encoding + if ($WorkingDirectory) { $startInfo.WorkingDirectory = $WorkingDirectory } + if ($Environment) { + foreach ($key in $Environment.Keys) { $startInfo.Environment[[string] $key] = [string] $Environment[$key] } + } + if (-not $StandardErrorPath) { + $StandardErrorPath = Join-Path ([System.IO.Path]::GetTempPath()) ('mcp-server-' + [guid]::NewGuid().ToString('n') + '.stderr.log') + } + $process = [System.Diagnostics.Process]::Start($startInfo) + $process.StandardInput.AutoFlush = $true + $process.StandardInput.NewLine = "`n" + # Buffer size 1 turns buffering off, so that the file shows the server's stderr while it runs. + $stderrFile = [System.IO.FileStream]::new($StandardErrorPath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::ReadWrite, 1) + $stderrPump = $process.StandardError.BaseStream.CopyToAsync($stderrFile) + @{ + Kind = 'Process' + Reader = $process.StandardOutput + Writer = $process.StandardInput + PendingRead = $null + Closed = $false + Process = $process + StandardErrorPath = $StandardErrorPath + StandardErrorPump = $stderrPump + StandardErrorFile = $stderrFile + } +} + +function New-McpInMemoryTransportPair { + <# + .SYNOPSIS + Two connected in-memory transports: Server (read from the client, write to the client) and Client. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates in-memory objects.')] + [CmdletBinding()] + [OutputType([hashtable])] + param() + + $toServer = [System.Threading.Channels.Channel]::CreateUnbounded[string]() + $toClient = [System.Threading.Channels.Channel]::CreateUnbounded[string]() + @{ + Server = @{ Kind = 'InMemory'; Reader = $toServer.Reader; Writer = $toClient.Writer; PendingRead = $null; Closed = $false } + Client = @{ Kind = 'InMemory'; Reader = $toClient.Reader; Writer = $toServer.Writer; PendingRead = $null; Closed = $false } + } +} + +function Read-McpTransportLineAsync { + <# + .SYNOPSIS + The pending read task of a transport, started if none is pending. The task yields $null at end of stream. + #> + [CmdletBinding()] + [OutputType([System.Threading.Tasks.Task])] + param( + [Parameter(Mandatory)] + [hashtable] $Transport + ) + + if ($null -ne $Transport.PendingRead) { return $Transport.PendingRead } + $task = if ($Transport.Kind -eq 'InMemory') { + $Transport.Reader.ReadAsync([System.Threading.CancellationToken]::None).AsTask() + } else { + $Transport.Reader.ReadLineAsync() + } + $Transport.PendingRead = $task + $task +} + +function Complete-McpTransportRead { + <# + .SYNOPSIS + The line of a completed read task, or $null at end of stream; clears the pending read. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task + ) + + $Transport.PendingRead = $null + if ($Task.IsCanceled) { return $null } + if ($Task.IsFaulted) { + $inner = $Task.Exception.InnerException + if ($inner -is [System.Threading.Channels.ChannelClosedException] -or $inner -is [System.IO.IOException] -or $inner -is [System.ObjectDisposedException]) { + return $null + } + throw $inner + } + $Task.Result +} + +function Receive-McpTransportLine { + <# + .SYNOPSIS + Waits up to a timeout for the next line; returns a hashtable with Status (Line, Eof or Timeout) and Line. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [Parameter(Mandatory)] + [int] $TimeoutMs + ) + + $task = Read-McpTransportLineAsync -Transport $Transport + $completed = $false + try { + $completed = $task.Wait($TimeoutMs) + } catch [System.AggregateException] { + $completed = $true + } + if (-not $completed) { + return @{ Status = 'Timeout'; Line = $null } + } + $line = Complete-McpTransportRead -Transport $Transport -Task $task + if ($null -eq $line) { return @{ Status = 'Eof'; Line = $null } } + @{ Status = 'Line'; Line = $line } +} + +function Send-McpTransportLine { + <# + .SYNOPSIS + Writes one message line; the line must not contain a newline. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [Parameter(Mandatory)] + [string] $Line + ) + + if ($Transport.Closed) { throw [System.IO.IOException]::new('The transport is closed.') } + if ($Transport.Kind -eq 'InMemory') { + if (-not $Transport.Writer.TryWrite($Line)) { throw [System.IO.IOException]::new('The transport is closed.') } + return + } + $Transport.Writer.WriteLine($Line) +} + +function Close-McpTransport { + <# + .SYNOPSIS + Closes the write side (and, for a server process, waits for it to exit before killing it). + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Transport, + + [int] $ExitTimeoutSeconds = 5 + ) + + if ($Transport.Closed) { return } + if ($Transport.Kind -eq 'Http') { + if ($Transport.ContainsKey('Listener')) { Close-McpHttpServerTransport -Transport $Transport } else { Close-McpHttpClientTransport -Transport $Transport } + return + } + $Transport.Closed = $true + try { + if ($Transport.Kind -eq 'InMemory') { + # TryComplete has an optional parameter, which PowerShell cannot omit. + $null = $Transport.Writer.TryComplete($null) + } else { + $Transport.Writer.Dispose() + } + } catch { + Write-McpStderr -Level Warning -Message "Closing the transport writer failed: $($_.Exception.Message)" + } + if ($Transport.Kind -eq 'Process' -and $null -ne $Transport.Process) { + $process = $Transport.Process + try { + if (-not $process.HasExited -and -not $process.WaitForExit($ExitTimeoutSeconds * 1000)) { + $process.Kill($true) + $null = $process.WaitForExit(5000) + } + } catch { + Write-McpStderr -Level Warning -Message "Stopping the server process failed: $($_.Exception.Message)" + } + try { + if ($null -ne $Transport.StandardErrorPump) { $null = $Transport.StandardErrorPump.Wait(2000) } + $Transport.StandardErrorFile.Dispose() + } catch { + Write-Debug "Closing the stderr capture failed: $($_.Exception.Message)" + } + } + if ($Transport.Kind -eq 'Stdio') { + try { $Transport.Reader.Dispose() } catch { Write-Debug 'Closing stdin failed.' } + } +} diff --git a/src/Private/Worker.ps1 b/src/Private/Worker.ps1 new file mode 100644 index 0000000..cf09857 --- /dev/null +++ b/src/Private/Worker.ps1 @@ -0,0 +1,107 @@ +# Worker side of a tools/call request: runs in a runspace of the server's pool, builds the request context, +# invokes the handler through Invoke-McpToolHandler and enqueues the response for the dispatcher. + +$script:McpModuleManifestPath = Join-Path $PSScriptRoot 'ModelContextProtocol.psd1' + +# The script the dispatcher adds to a worker PowerShell instance. The nested block runs in the module's scope +# of the worker runspace, where the private worker function is visible. +$script:McpWorkerScript = 'param($Envelope) & (Get-Module -Name ModelContextProtocol) { param($e) Invoke-McpWorkerRequest -Envelope $e } $Envelope' + +function New-McpRequestContext { + <# + .SYNOPSIS + The Mcp.RequestContext object handed to handlers (their Context parameter) for one request. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object.')] + [CmdletBinding()] + [OutputType('Mcp.RequestContext')] + param( + [Parameter(Mandatory)] + [hashtable] $Envelope + ) + + $meta = $Envelope.Meta + [pscustomobject]@{ + PSTypeName = 'Mcp.RequestContext' + RequestId = $Envelope.RequestId + Method = $Envelope.Method + ToolName = $Envelope.ToolName + Era = 'Modern' + ProtocolVersion = $meta.ProtocolVersion + ClientInfo = $meta.ClientInfo + ClientCapabilities = $meta.ClientCapabilities + LogLevel = $meta.LogLevel + ProgressToken = $meta.ProgressToken + CancellationToken = $Envelope.CancellationToken + Sink = $Envelope.Sink + ServerName = $Envelope.ServerName + ServerLogLevel = $Envelope.ServerLogLevel + ProgressState = @{ Last = $null } + } +} + +function Send-McpSinkMessage { + <# + .SYNOPSIS + Enqueues a serialised message for the dispatcher and wakes it. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Sink, + + [Parameter(Mandatory)] + [ValidateSet('Response', 'Notification')] + [string] $Kind, + + [AllowNull()] + [object] $RequestId, + + [Parameter(Mandatory)] + [string] $Json, + + # The JSON-RPC error code of an error response; the HTTP transport derives the status code from it. + [AllowNull()] + [object] $ErrorCode + ) + + $Sink.Queue.Enqueue(@{ Kind = $Kind; RequestId = $RequestId; Json = $Json; ErrorCode = $ErrorCode }) + $null = $Sink.Signal.Set() +} + +function Invoke-McpWorkerRequest { + <# + .SYNOPSIS + Handles one tools/call request in a worker runspace and enqueues the response. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Envelope + ) + + $context = New-McpRequestContext -Envelope $Envelope + $response = $null + $errorCode = $null + try { + $result = Invoke-McpToolHandler -Registration $Envelope.Registration -Arguments $Envelope.Arguments -Context $context -UseCommandName + if ($Envelope.IncludeServerInfo -and $null -ne $Envelope.ServerInfo) { + $meta = if ($result.Contains('_meta') -and $result['_meta'] -is [System.Collections.IDictionary]) { $result['_meta'] } else { [ordered]@{} } + $meta[$script:McpMetaKey.ServerInfo] = $Envelope.ServerInfo + $result['_meta'] = $meta + } + $response = New-McpResultResponse -Id $Envelope.RequestId -Result $result + } catch [System.Management.Automation.PipelineStoppedException] { + throw + } catch { + $exception = $_.Exception + if ($exception -is [System.Management.Automation.RuntimeException] -and $null -ne $exception.InnerException -and $exception.GetType() -eq [System.Management.Automation.RuntimeException]) { + $exception = $exception.InnerException + } + $errorObject = ConvertTo-McpErrorObject -Exception $exception + $errorCode = $errorObject['code'] + $response = New-McpErrorResponse -Id $Envelope.RequestId -ErrorObject $errorObject + } + if ($Envelope.CancellationToken.IsCancellationRequested) { return } + Send-McpSinkMessage -Sink $Envelope.Sink -Kind Response -RequestId $Envelope.RequestId -Json (ConvertTo-McpJson -InputObject $response) -ErrorCode $errorCode +} diff --git a/src/Public/.gitkeep b/src/Public/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Public/Connect-McpServer.ps1 b/src/Public/Connect-McpServer.ps1 new file mode 100644 index 0000000..816daba --- /dev/null +++ b/src/Public/Connect-McpServer.ps1 @@ -0,0 +1,211 @@ +function Connect-McpServer { + <# + .SYNOPSIS + Connects to an MCP server over stdio (a server process), Streamable HTTP (a URL) or in memory (a server object) and returns a session. + .DESCRIPTION + For stdio the command is started with redirected standard streams; its stderr is captured in a file + (see the session's StandardErrorPath). Over Streamable HTTP every request is its own POST to the URL + 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. + + 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. + + The first session becomes the default session for the other client commands; -SetDefault makes a later + session the default. + .PARAMETER Command + The server executable (for a PowerShell server: pwsh). + .PARAMETER Arguments + The command-line arguments, for example -NoLogo, -NoProfile, -NonInteractive, -File, ./server.ps1. + .PARAMETER WorkingDirectory + The working directory of the server process. + .PARAMETER Environment + Additional environment variables for the server process. + .PARAMETER StandardErrorPath + The file that receives the server's stderr (default: a file in the temp folder). + .PARAMETER Url + The URL of a Streamable HTTP endpoint, for example http://127.0.0.1:8080/mcp/. + .PARAMETER Headers + Additional HTTP headers sent with every request to -Url (for example an Authorization header). + .PARAMETER NoProxy + Do not use the system or environment proxy for -Url (loopback URLs never use a proxy). + .PARAMETER Server + A server object (New-McpServer) to run in-process over an in-memory transport. + .PARAMETER ClientInfo + The clientInfo sent with every request (name and version); defaults to this module. + .PARAMETER Capabilities + The client capabilities declared with every request (default: none). + .PARAMETER ProtocolVersion + The preferred protocol version (default: 2026-07-28). + .PARAMETER RequestTimeoutSeconds + The default timeout for requests (default: 60). + .PARAMETER ConnectTimeoutSeconds + The timeout for the initial server/discover (default: 30). + .PARAMETER LogLevel + Ask the server for notifications/message at this level and above (io.modelcontextprotocol/logLevel). + .PARAMETER OnLog + A script block invoked with each notifications/message received (Mcp.LogMessage). + .PARAMETER SetDefault + Make this session the default session. + .EXAMPLE + $session = Connect-McpServer -Command pwsh -Arguments '-NoLogo', '-NoProfile', '-NonInteractive', '-File', './examples/echo-server.ps1' + .EXAMPLE + $session = Connect-McpServer -Url http://127.0.0.1:8080/mcp/ + .EXAMPLE + $session = Connect-McpServer -Server $server + .OUTPUTS + Mcp.Session + #> + [CmdletBinding(DefaultParameterSetName = 'Stdio', SupportsShouldProcess)] + [OutputType('Mcp.Session')] + param( + [Parameter(ParameterSetName = 'Stdio', Mandatory, Position = 0)] + [ValidateNotNullOrEmpty()] + [string] $Command, + + [Parameter(ParameterSetName = 'Stdio', Position = 1)] + [string[]] $Arguments = @(), + + [Parameter(ParameterSetName = 'Stdio')] + [string] $WorkingDirectory, + + [Parameter(ParameterSetName = 'Stdio')] + [hashtable] $Environment, + + [Parameter(ParameterSetName = 'Stdio')] + [string] $StandardErrorPath, + + [Parameter(ParameterSetName = 'Http', Mandatory)] + [ValidateNotNull()] + [uri] $Url, + + [Parameter(ParameterSetName = 'Http')] + [hashtable] $Headers, + + [Parameter(ParameterSetName = 'Http')] + [switch] $NoProxy, + + [Parameter(ParameterSetName = 'InMemory', Mandatory)] + [ValidateNotNull()] + [object] $Server, + + [hashtable] $ClientInfo, + + [hashtable] $Capabilities, + + [ValidateNotNullOrEmpty()] + [string] $ProtocolVersion = '2026-07-28', + + [ValidateRange(1, 86400)] + [int] $RequestTimeoutSeconds = 60, + + [ValidateRange(1, 3600)] + [int] $ConnectTimeoutSeconds = 30, + + [McpLoggingLevel] $LogLevel, + + [scriptblock] $OnLog, + + [switch] $SetDefault + ) + + $target = switch ($PSCmdlet.ParameterSetName) { + 'InMemory' { "server '$($Server.Name)' in memory" } + 'Http' { $Url.AbsoluteUri } + default { "$Command $($Arguments -join ' ')" } + } + if (-not $PSCmdlet.ShouldProcess($target, 'Connect')) { return } + + $clientInfoObject = [ordered]@{ name = 'ModelContextProtocol'; version = Get-McpModuleVersionString } + if ($ClientInfo) { + foreach ($key in $ClientInfo.Keys) { $clientInfoObject[[string] $key] = $ClientInfo[$key] } + } + if (-not $clientInfoObject.Contains('name') -or -not $clientInfoObject.Contains('version')) { + throw [System.ArgumentException]::new('-ClientInfo needs name and version.') + } + $capabilityObject = if ($Capabilities) { ConvertFrom-McpJson -Json (ConvertTo-McpJson -InputObject $Capabilities) } else { [ordered]@{} } + + $transport = $null + $background = $null + $stderrPath = $null + if ($PSCmdlet.ParameterSetName -eq 'InMemory') { + if (-not (Test-McpServerObject -Server $Server)) { throw [System.ArgumentException]::new('-Server must be a server created by New-McpServer.') } + $pair = New-McpInMemoryTransportPair + $background = Start-McpBackgroundServer -Server $Server -Endpoint $pair.Server + $transport = $pair.Client + } elseif ($PSCmdlet.ParameterSetName -eq 'Http') { + $transport = New-McpHttpClientTransport -Url $Url -Headers $Headers -NoProxy:$NoProxy + } else { + $transport = New-McpProcessTransport -FilePath $Command -ArgumentList $Arguments -WorkingDirectory $WorkingDirectory -Environment $Environment -StandardErrorPath $StandardErrorPath + $stderrPath = $transport.StandardErrorPath + } + + $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) + NextId = 1 + RequestTimeoutMs = $RequestTimeoutSeconds * 1000 + LogLevel = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $null } + OnLog = $OnLog + Log = [System.Collections.Generic.List[object]]::new() + Notifications = [System.Collections.Generic.Queue[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 + } 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 + } + $session +} diff --git a/src/Public/Disconnect-McpServer.ps1 b/src/Public/Disconnect-McpServer.ps1 new file mode 100644 index 0000000..03f2e32 --- /dev/null +++ b/src/Public/Disconnect-McpServer.ps1 @@ -0,0 +1,39 @@ +function Disconnect-McpServer { + <# + .SYNOPSIS + Closes a session: closes the server's standard input, waits for the process to exit and kills it if it does not. + .DESCRIPTION + For an in-memory session the background server runspace is stopped as well. Closing the default session + clears the default. + .PARAMETER Session + The session to close; defaults to the default session. + .PARAMETER ExitTimeoutSeconds + How long to wait for a server process to exit before it is killed (default: 5). + .EXAMPLE + Disconnect-McpServer -Session $session + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [object] $Session, + + [ValidateRange(0, 600)] + [int] $ExitTimeoutSeconds = 5 + ) + + $target = if ($null -ne $Session) { $Session } else { $script:McpDefaultSession } + if ($null -eq $target) { return } + if (-not (Test-McpSessionObject -Session $target)) { + throw [System.ArgumentException]::new('The -Session argument is not a session created by Connect-McpServer.') + } + if ($target.Closed) { return } + if (-not $PSCmdlet.ShouldProcess("session '$($target.Name)'", 'Disconnect')) { return } + $target.Closed = $true + Close-McpTransport -Transport $target.Transport -ExitTimeoutSeconds $ExitTimeoutSeconds + if ($null -ne $target.Background) { + Stop-McpBackgroundServer -Background $target.Background + $target.Background = $null + } + if ($null -ne $script:McpDefaultSession -and [object]::ReferenceEquals($script:McpDefaultSession, $target)) { + $script:McpDefaultSession = $null + } +} diff --git a/src/Public/Get-McpServerInfo.ps1 b/src/Public/Get-McpServerInfo.ps1 new file mode 100644 index 0000000..3f8dc0a --- /dev/null +++ b/src/Public/Get-McpServerInfo.ps1 @@ -0,0 +1,29 @@ +function Get-McpServerInfo { + <# + .SYNOPSIS + The server's implementation info, capabilities, instructions and supported versions (from server/discover). + .PARAMETER Session + The session; defaults to the default session. + .PARAMETER Refresh + Query server/discover again instead of returning the cached result. + .EXAMPLE + Get-McpServerInfo | Format-List + .OUTPUTS + Mcp.ServerInfo + #> + [CmdletBinding()] + [OutputType('Mcp.ServerInfo')] + param( + [object] $Session, + + [switch] $Refresh + ) + + $target = Resolve-McpSession -Session $Session + if ($Refresh -or $null -eq $target.ServerInfo) { + $discover = Invoke-McpClientRequest -Session $target -Method 'server/discover' + $target.ServerInfo = ConvertTo-McpServerInfoObject -DiscoverResult $discover -ProtocolVersion $target.ProtocolVersion + $target.Name = $target.ServerInfo.Name + } + $target.ServerInfo +} diff --git a/src/Public/Get-McpTool.ps1 b/src/Public/Get-McpTool.ps1 new file mode 100644 index 0000000..09920d0 --- /dev/null +++ b/src/Public/Get-McpTool.ps1 @@ -0,0 +1,74 @@ +function Get-McpTool { + <# + .SYNOPSIS + Lists the server's tools (tools/list, following all pages) or gets one tool by name. + .DESCRIPTION + The list is cached in the session; -Refresh queries the server again. Over Streamable HTTP a tool whose + x-mcp-header annotations are invalid is excluded from the list with a warning, as the specification + requires; the valid annotations tell Invoke-McpTool which arguments to mirror into Mcp-Param-* headers. + .PARAMETER Name + The name of a tool (exact match); an unknown name is an error. + .PARAMETER Session + The session; defaults to the default session. + .PARAMETER Refresh + Query tools/list again instead of using the cached list. + .EXAMPLE + Get-McpTool | Select-Object Name, Description + .OUTPUTS + Mcp.Tool + #> + [CmdletBinding()] + [OutputType('Mcp.Tool')] + param( + [Parameter(Position = 0)] + [string] $Name, + + [object] $Session, + + [switch] $Refresh + ) + + $target = Resolve-McpSession -Session $Session + if ($Refresh -or $null -eq $target.Tools) { + $tools = [System.Collections.Generic.List[object]]::new() + $headers = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + $cursor = $null + $pages = 0 + do { + $params = [ordered]@{} + if ($null -ne $cursor) { $params['cursor'] = $cursor } + $result = Invoke-McpClientRequest -Session $target -Method 'tools/list' -Params $params + if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains('tools')) { + throw [System.InvalidOperationException]::new('The tools/list result has no tools member.') + } + foreach ($tool in @($result['tools'])) { + if ($tool -isnot [System.Collections.IDictionary]) { continue } + if ($target.Kind -eq 'Http') { + $toolName = if ($tool.Contains('name')) { [string] $tool['name'] } else { '(unnamed)' } + $headerParameters = @() + try { + $headerParameters = @(Get-McpToolHeaderParameter -InputSchema $(if ($tool.Contains('inputSchema')) { $tool['inputSchema'] } else { $null })) + } catch [System.ArgumentException] { + Write-Warning "Excluding tool '$toolName' from the list: $($_.Exception.Message)" + continue + } + $headers[$toolName] = $headerParameters + } + $tools.Add((ConvertTo-McpToolObject -Tool $tool)) + } + $cursor = if ($result.Contains('nextCursor') -and $null -ne $result['nextCursor']) { [string] $result['nextCursor'] } else { $null } + $pages++ + if ($pages -gt 10000) { throw [System.InvalidOperationException]::new('tools/list paged more than 10000 times.') } + } while ($null -ne $cursor) + $target.Tools = $tools.ToArray() + $target.ToolHeaders = $headers + } + if ($Name) { + $tool = $target.Tools | Where-Object { $_.Name -ceq $Name } | Select-Object -First 1 + if (-not $tool) { + throw [System.ArgumentException]::new("The server has no tool named '$Name'.") + } + return $tool + } + $target.Tools +} diff --git a/src/Public/Invoke-McpTool.ps1 b/src/Public/Invoke-McpTool.ps1 new file mode 100644 index 0000000..a1e6c43 --- /dev/null +++ b/src/Public/Invoke-McpTool.ps1 @@ -0,0 +1,73 @@ +function Invoke-McpTool { + <# + .SYNOPSIS + Calls a tool (tools/call) and returns its result as an Mcp.ToolResult. + .DESCRIPTION + A tool execution error (isError) is returned as a result with IsError set, so that the caller can show + it to a model. Protocol errors (unknown tool, invalid arguments, timeouts) are thrown. Progress + notifications are delivered to -OnProgress while the call is running. + .PARAMETER Name + The tool name. + .PARAMETER Arguments + The arguments (hashtable with JSON-compatible values). + .PARAMETER Session + The session; defaults to the default session. + .PARAMETER OnProgress + A script block invoked with each progress notification (Mcp.Progress: Progress, Total, Message). + .PARAMETER TimeoutSeconds + The timeout for this call; defaults to the session's request timeout. + .PARAMETER LogLevel + Ask for notifications/message at this level and above for this call (see the session's Log). + .EXAMPLE + (Invoke-McpTool -Name echo -Arguments @{ Text = 'hi' }).Text + .OUTPUTS + Mcp.ToolResult + #> + [CmdletBinding()] + [OutputType('Mcp.ToolResult')] + param( + [Parameter(Mandatory, Position = 0)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + [Parameter(Position = 1)] + [System.Collections.IDictionary] $Arguments, + + [object] $Session, + + [scriptblock] $OnProgress, + + [ValidateRange(0, 86400)] + [int] $TimeoutSeconds = 0, + + [McpLoggingLevel] $LogLevel + ) + + $target = Resolve-McpSession -Session $Session + $params = [ordered]@{ name = $Name } + if ($null -ne $Arguments) { $params['arguments'] = $Arguments } else { $params['arguments'] = [ordered]@{} } + $level = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $target.LogLevel } + $timeoutMs = $TimeoutSeconds * 1000 + $result = $null + if ($target.Kind -ne 'Http') { + $result = Invoke-McpClientRequest -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs + } else { + # Streamable HTTP mirrors x-mcp-header parameters into Mcp-Param-* headers; the annotations come from the + # cached tool list. A header mismatch reported by the server refreshes the list and retries once. + if ($null -eq $target.Tools) { $null = Get-McpTool -Session $target } + $headers = Get-McpToolCallHeader -HeaderParameters $target.ToolHeaders[$Name] -Arguments $params['arguments'] + try { + $result = Invoke-McpClientRequest -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs -Headers $headers + } catch [McpProtocolException] { + if ($_.Exception.Code -ne $script:McpErrorCode.HeaderMismatch) { throw } + Write-Verbose "The server reported a header mismatch for '$Name'; refreshing the tool list and retrying once." + $null = Get-McpTool -Session $target -Refresh + $headers = Get-McpToolCallHeader -HeaderParameters $target.ToolHeaders[$Name] -Arguments $params['arguments'] + $result = Invoke-McpClientRequest -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs -Headers $headers + } + } + if ($result -isnot [System.Collections.IDictionary]) { + throw [System.InvalidOperationException]::new('The tools/call result is not an object.') + } + ConvertTo-McpToolResultObject -Result $result -ToolName $Name +} diff --git a/src/Public/Invoke-McpToolHandler.ps1 b/src/Public/Invoke-McpToolHandler.ps1 new file mode 100644 index 0000000..6bc81a7 --- /dev/null +++ b/src/Public/Invoke-McpToolHandler.ps1 @@ -0,0 +1,93 @@ +function Invoke-McpToolHandler { + <# + .SYNOPSIS + Runs a registered tool in the current runspace and returns its CallToolResult, as a client would see it. + .DESCRIPTION + Validates the arguments against the tool's input schema, binds them to the handler's parameters, runs + the handler and shapes its output. Use it to test tools without a transport. Protocol errors (unknown + tool, invalid arguments) are thrown as McpProtocolException; errors inside the handler become a result + with isError. + .PARAMETER Name + The registered tool name. + .PARAMETER Arguments + The arguments as a dictionary (JSON-compatible values). + .PARAMETER Server + The server the tool is registered on; defaults to the default server. + .PARAMETER Registration + A registration object instead of -Name and -Server. + .PARAMETER Context + The request context passed to a handler's Context parameter (built by the server at call time). + .PARAMETER UseCommandName + Invoke the handler by its command name in the current runspace (used by the worker runspaces, where + handlers exist as functions) instead of the script block or command object captured at registration. + .EXAMPLE + Invoke-McpToolHandler -Name echo -Arguments @{ Text = 'hi' } + .OUTPUTS + System.Collections.Specialized.OrderedDictionary (a CallToolResult) + #> + [CmdletBinding(DefaultParameterSetName = 'Name')] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(ParameterSetName = 'Name', Mandatory, Position = 0)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + [Parameter(Position = 1)] + [AllowNull()] + [System.Collections.IDictionary] $Arguments, + + [Parameter(ParameterSetName = 'Name')] + [object] $Server, + + [Parameter(ParameterSetName = 'Registration', Mandatory)] + [ValidateNotNull()] + [object] $Registration, + + [object] $Context, + + [switch] $UseCommandName + ) + + if ($PSCmdlet.ParameterSetName -eq 'Name') { + $Registration = Get-McpToolRegistration -Server (Resolve-McpServer -Server $Server) -Name $Name + } + if ($null -eq $Arguments) { $Arguments = [ordered]@{} } + + $validation = Test-McpJsonSchema -Schema $Registration.InputSchema -Instance $Arguments + if (-not $validation.IsValid) { + $data = [ordered]@{ errors = @($validation.Errors) } + throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Invalid arguments for tool '$($Registration.Name)': $($validation.Errors -join '; ')", $data) + } + $splat = ConvertTo-McpToolArgument -Registration $Registration -Arguments $Arguments -Context $Context + $handler = $Registration.Handler + $threshold = if ($null -ne $Context -and $Context.PSObject.Properties['ServerLogLevel'] -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel } + + $merged = $null + try { + if ($UseCommandName) { + $merged = @(& $handler.CommandName @splat *>&1) + } elseif ($handler.Kind -eq 'ScriptBlock') { + $merged = @(& $handler.ScriptBlock @splat *>&1) + } else { + $merged = @(& $handler.CommandInfo @splat *>&1) + } + } catch [System.Management.Automation.PipelineStoppedException] { + throw + } catch { + $exception = $_.Exception + if ($exception -is [System.Management.Automation.RuntimeException] -and $null -ne $exception.InnerException -and $exception.GetType() -eq [System.Management.Automation.RuntimeException]) { + $exception = $exception.InnerException + } + if ($exception -is [McpProtocolException]) { throw } + $failure = ConvertTo-McpTextBlock -Text ('Error: ' + $exception.Message) + $result = [ordered]@{ + content = @($failure) + isError = $true + resultType = 'complete' + } + return $result + } + $parts = Split-McpHandlerOutput -Merged $merged + Write-McpHandlerDiagnostic -Diagnostics $parts.Diagnostics -ToolName $Registration.Name -Threshold $threshold + ConvertTo-McpCallToolResult -Output $parts.Output -Registration $Registration -ErrorRecords $parts.Errors +} diff --git a/src/Public/New-McpContent.ps1 b/src/Public/New-McpContent.ps1 new file mode 100644 index 0000000..e764113 --- /dev/null +++ b/src/Public/New-McpContent.ps1 @@ -0,0 +1,140 @@ +function New-McpContent { + <# + .SYNOPSIS + Creates a content block (text, image, audio, resource link or embedded resource) for tool results. + .DESCRIPTION + Content blocks are the items of CallToolResult.content. Return them from a tool handler, or pass them + to New-McpToolResult. Binary data may be given as byte[] or as a base64 string. + .PARAMETER Text + The text of a text block. + .PARAMETER Image + Image data (byte[] or base64 string) of an image block; -MimeType is required. + .PARAMETER Audio + Audio data (byte[] or base64 string) of an audio block; -MimeType is required. + .PARAMETER ResourceLink + The URI of a resource link block; -Name is required. + .PARAMETER EmbeddedResource + The URI of an embedded resource block; give its contents with -ResourceText or -ResourceBlob. + .PARAMETER Name + The resource name of a resource link. + .PARAMETER Title + The title of a resource link. + .PARAMETER Description + The description of a resource link. + .PARAMETER MimeType + The MIME type of image or audio data, of a resource link or of an embedded resource. + .PARAMETER Size + The size in bytes of a linked resource. + .PARAMETER ResourceText + The text contents of an embedded resource. + .PARAMETER ResourceBlob + The binary contents (byte[] or base64 string) of an embedded resource. + .PARAMETER Annotations + Annotations (audience, priority, lastModified) of the block. + .PARAMETER Meta + Additional _meta members of the block. + .EXAMPLE + New-McpContent -Text 'Hello' + .EXAMPLE + New-McpContent -Image (Get-Content ./chart.png -AsByteStream -Raw) -MimeType image/png + .OUTPUTS + Mcp.Content + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object only.')] + [CmdletBinding(DefaultParameterSetName = 'Text')] + [OutputType('Mcp.Content')] + param( + [Parameter(ParameterSetName = 'Text', Mandatory, Position = 0)] + [AllowEmptyString()] + [string] $Text, + + [Parameter(ParameterSetName = 'Image', Mandatory)] + [ValidateNotNull()] + [object] $Image, + + [Parameter(ParameterSetName = 'Audio', Mandatory)] + [ValidateNotNull()] + [object] $Audio, + + [Parameter(ParameterSetName = 'ResourceLink', Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $ResourceLink, + + [Parameter(ParameterSetName = 'EmbeddedResource', Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $EmbeddedResource, + + [Parameter(ParameterSetName = 'ResourceLink', Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + [Parameter(ParameterSetName = 'ResourceLink')] + [string] $Title, + + [Parameter(ParameterSetName = 'ResourceLink')] + [string] $Description, + + [Parameter(ParameterSetName = 'Image', Mandatory)] + [Parameter(ParameterSetName = 'Audio', Mandatory)] + [Parameter(ParameterSetName = 'ResourceLink')] + [Parameter(ParameterSetName = 'EmbeddedResource')] + [ValidateNotNullOrEmpty()] + [string] $MimeType, + + [Parameter(ParameterSetName = 'ResourceLink')] + [ValidateRange(0, [long]::MaxValue)] + [long] $Size = -1, + + [Parameter(ParameterSetName = 'EmbeddedResource')] + [string] $ResourceText, + + [Parameter(ParameterSetName = 'EmbeddedResource')] + [object] $ResourceBlob, + + [hashtable] $Annotations, + + [hashtable] $Meta + ) + + $block = [ordered]@{} + switch ($PSCmdlet.ParameterSetName) { + 'Text' { + $block['type'] = 'text' + $block['text'] = $Text + } + 'Image' { + $block['type'] = 'image' + $block['data'] = ConvertTo-McpBase64 -Data $Image + $block['mimeType'] = $MimeType + } + 'Audio' { + $block['type'] = 'audio' + $block['data'] = ConvertTo-McpBase64 -Data $Audio + $block['mimeType'] = $MimeType + } + 'ResourceLink' { + $block['type'] = 'resource_link' + $block['uri'] = $ResourceLink + $block['name'] = $Name + if ($Title) { $block['title'] = $Title } + if ($Description) { $block['description'] = $Description } + if ($MimeType) { $block['mimeType'] = $MimeType } + if ($Size -ge 0) { $block['size'] = $Size } + } + 'EmbeddedResource' { + if (-not $PSBoundParameters.ContainsKey('ResourceText') -and $null -eq $ResourceBlob) { + throw [System.ArgumentException]::new('An embedded resource needs -ResourceText or -ResourceBlob.') + } + $resource = [ordered]@{ uri = $EmbeddedResource } + if ($MimeType) { $resource['mimeType'] = $MimeType } + if ($PSBoundParameters.ContainsKey('ResourceText')) { $resource['text'] = $ResourceText } else { $resource['blob'] = ConvertTo-McpBase64 -Data $ResourceBlob } + $block['type'] = 'resource' + $block['resource'] = $resource + } + } + if ($Annotations -and $Annotations.Count -gt 0) { $block['annotations'] = $Annotations } + if ($Meta -and $Meta.Count -gt 0) { $block['_meta'] = $Meta } + $object = [pscustomobject] $block + $object.PSObject.TypeNames.Insert(0, 'Mcp.Content') + $object +} diff --git a/src/Public/New-McpServer.ps1 b/src/Public/New-McpServer.ps1 new file mode 100644 index 0000000..defa97d --- /dev/null +++ b/src/Public/New-McpServer.ps1 @@ -0,0 +1,131 @@ +function New-McpServer { + <# + .SYNOPSIS + Creates an MCP server object to register tools on and to start with Start-McpServer. + .DESCRIPTION + The server object carries the implementation info (name, version, title, description, website URL, + icons), the instructions for clients, the supported protocol versions and the runtime options. It is + a plain object (PSTypeName Mcp.Server); tools are registered on it with Register-McpTool. With + -SetDefault the object becomes the default for the other server commands of this session. + .PARAMETER Name + The implementation name reported as serverInfo.name. + .PARAMETER Version + The implementation version reported as serverInfo.version. + .PARAMETER Title + A human-readable title (serverInfo.title). + .PARAMETER Description + A description of the server (serverInfo.description). + .PARAMETER WebsiteUrl + A website with more information (serverInfo.websiteUrl). + .PARAMETER Icons + Icon objects (hashtables with src, and optionally mimeType, sizes, theme) reported as serverInfo.icons. + .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. + .PARAMETER MaxConcurrency + The maximum number of tool handlers running at the same time (the size of the worker runspace pool). + .PARAMETER RequestTimeoutSeconds + Seconds after which a running tool handler is stopped and the request answered with an error; 0 disables the timeout. + .PARAMETER DefaultTtlMs + The ttlMs caching hint sent with server/discover and tools/list results. + .PARAMETER DefaultCacheScope + The cacheScope caching hint sent with server/discover and tools/list results (public or private). + .PARAMETER PageSize + The number of tools per tools/list page. + .PARAMETER LogLevel + The minimum level of diagnostics written to stderr (default: warning). + .PARAMETER NoServerInfo + Do not add io.modelcontextprotocol/serverInfo to results. + .PARAMETER SetDefault + Make the new server the default for Register-McpTool, Start-McpServer and the other server commands. + .EXAMPLE + $server = New-McpServer -Name 'weather' -Version '1.0.0' -Instructions 'Weather lookups.' -SetDefault + .OUTPUTS + Mcp.Server + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object only.')] + [CmdletBinding()] + [OutputType('Mcp.Server')] + param( + [Parameter(Mandatory, Position = 0)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + [Parameter(Mandatory, Position = 1)] + [ValidateNotNullOrEmpty()] + [string] $Version, + + [string] $Title, + + [string] $Description, + + [string] $WebsiteUrl, + + [object[]] $Icons, + + [string] $Instructions, + + [ValidateNotNullOrEmpty()] + [string[]] $SupportedVersions = @('2026-07-28'), + + [ValidateRange(1, 64)] + [int] $MaxConcurrency = [System.Math]::Max(1, [System.Environment]::ProcessorCount), + + [ValidateRange(0, 86400)] + [int] $RequestTimeoutSeconds = 0, + + [ValidateRange(0, 2147483647)] + [int] $DefaultTtlMs = 0, + + [ValidateSet('public', 'private')] + [string] $DefaultCacheScope = 'public', + + [ValidateRange(1, 1000)] + [int] $PageSize = 100, + + [McpLoggingLevel] $LogLevel = [McpLoggingLevel]::Warning, + + [switch] $NoServerInfo, + + [switch] $SetDefault + ) + + 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 ', ').") + } + } + + $server = [pscustomobject]@{ + PSTypeName = 'Mcp.Server' + Name = $Name + Version = $Version + Title = $Title + Description = $Description + WebsiteUrl = $WebsiteUrl + Icons = $Icons + Instructions = $Instructions + SupportedVersions = [string[]] $SupportedVersions + Tools = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + Options = @{ + MaxConcurrency = $MaxConcurrency + RequestTimeoutSeconds = $RequestTimeoutSeconds + DefaultTtlMs = $DefaultTtlMs + DefaultCacheScope = $DefaultCacheScope + PageSize = $PageSize + LogLevel = $LogLevel + IncludeServerInfo = -not $NoServerInfo + # tools.listChanged is advertised once subscriptions/listen can deliver the notification (milestone M4). + ListChanged = $false + } + State = @{ + Started = $false + StopRequested = $false + } + } + if ($SetDefault) { + $script:McpDefaultServer = $server + } + $server +} diff --git a/src/Public/New-McpToolResult.ps1 b/src/Public/New-McpToolResult.ps1 new file mode 100644 index 0000000..f43e43c --- /dev/null +++ b/src/Public/New-McpToolResult.ps1 @@ -0,0 +1,58 @@ +function New-McpToolResult { + <# + .SYNOPSIS + Creates a complete tool result (content blocks, structured content, error flag) to return from a handler. + .DESCRIPTION + Use it when a handler needs control over the CallToolResult: several content blocks, structured content + that differs from the text, or an error result (isError) that the model should see and recover from. + Plain output (strings, objects, New-McpContent blocks) does not need it. + .PARAMETER Content + Content blocks (New-McpContent) or strings (text blocks). + .PARAMETER Text + A single text block; shorthand for -Content. + .PARAMETER StructuredContent + A JSON-serialisable object placed in structuredContent (and, when -Content is empty, also as JSON text). + .PARAMETER IsError + Mark the result as a tool execution error. + .PARAMETER Meta + Additional _meta members of the result. + .EXAMPLE + New-McpToolResult -IsError -Text 'The location is unknown.' + .OUTPUTS + Mcp.ToolResult + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object only.')] + [CmdletBinding()] + [OutputType('Mcp.ToolResult')] + param( + [object[]] $Content, + + [AllowEmptyString()] + [string] $Text, + + [object] $StructuredContent, + + [switch] $IsError, + + [hashtable] $Meta + ) + + $blocks = [System.Collections.Generic.List[object]]::new() + if ($PSBoundParameters.ContainsKey('Text')) { $blocks.Add((ConvertTo-McpTextBlock -Text $Text)) } + foreach ($item in @($Content)) { + if ($null -eq $item) { continue } + if (Test-McpContentObject -Value $item) { $blocks.Add($item) } + elseif ($item -is [string]) { $blocks.Add((ConvertTo-McpTextBlock -Text $item)) } + else { throw [System.ArgumentException]::new('-Content accepts content blocks (New-McpContent) and strings.') } + } + if ($PSBoundParameters.ContainsKey('StructuredContent') -and $blocks.Count -eq 0) { + $blocks.Add((ConvertTo-McpTextBlock -Text (ConvertTo-McpJson -InputObject $StructuredContent))) + } + $result = [ordered]@{ content = $blocks.ToArray() } + if ($PSBoundParameters.ContainsKey('StructuredContent')) { $result['structuredContent'] = $StructuredContent } + if ($IsError) { $result['isError'] = $true } + if ($Meta -and $Meta.Count -gt 0) { $result['_meta'] = $Meta } + $object = [pscustomobject] $result + $object.PSObject.TypeNames.Insert(0, 'Mcp.ToolResult') + $object +} diff --git a/src/Public/Register-McpTool.ps1 b/src/Public/Register-McpTool.ps1 new file mode 100644 index 0000000..fedff7b --- /dev/null +++ b/src/Public/Register-McpTool.ps1 @@ -0,0 +1,243 @@ +function Register-McpTool { + <# + .SYNOPSIS + Registers a PowerShell command or script block as an MCP tool on a server. + .DESCRIPTION + A tool is a function, cmdlet, script file or script block. Its input schema is generated from the + parameters (types, validation attributes, comment-based help and constant defaults) unless -InputSchema + is given. Common parameters and a parameter named Context are never part of the schema; a Context + parameter receives the request context (Mcp.RequestContext) at call time. + + Arguments of a tools/call request are validated against the input schema, converted to the parameter + types and splatted onto the command. With -InputSchema, a handler that declares a parameter named + Arguments receives the raw argument dictionary instead. Handler output becomes the CallToolResult: + content blocks from New-McpContent pass through, strings become text blocks, and objects become JSON + text (a single object also becomes structuredContent). + + Handlers run in a worker runspace pool without a host: they must receive everything through their + parameters, and nothing they write to stdout or the host reaches the client. + .PARAMETER Command + The command to expose: a name (resolved with Get-Command) or a CommandInfo of a function, cmdlet or script file. + .PARAMETER ScriptBlock + The handler as a script block; its param() block defines the arguments. + .PARAMETER Name + The tool name (1-128 characters: letters, digits, '_', '-', '.'); defaults to the command name. + .PARAMETER Title + A human-readable title. + .PARAMETER Description + The tool description; defaults to the synopsis of the command's comment-based help. + .PARAMETER InputSchema + An explicit JSON Schema (hashtable or JSON text) for the arguments; replaces the generated schema. + .PARAMETER OutputSchema + A JSON Schema (hashtable or JSON text) that structuredContent must satisfy. + .PARAMETER Annotations + Tool annotations: Title, ReadOnlyHint, DestructiveHint, IdempotentHint, OpenWorldHint. + .PARAMETER Icons + Icon objects (hashtables with src, and optionally mimeType, sizes, theme). + .PARAMETER Meta + Additional _meta members of the tool definition. + .PARAMETER Header + Parameters to mirror into HTTP headers over Streamable HTTP, as a map of parameter name to header name + (the x-mcp-header annotation of the input schema): @{ Region = 'Region' } makes clients send + Mcp-Param-Region with the value of -Region. Only string, integer and boolean parameters can be + mirrored; never mirror secrets, header values are visible to intermediaries. + .PARAMETER AllowAdditionalProperties + Let the generated schema accept arguments that are not parameters (they are passed through by name). + .PARAMETER Server + The server to register on; defaults to the server set with New-McpServer -SetDefault. + .PARAMETER Force + Replace an existing registration with the same name. + .PARAMETER PassThru + Return the registration object. + .EXAMPLE + Register-McpTool -Command Get-Weather -Description 'Current weather for a location.' + .EXAMPLE + Register-McpTool -Name echo -ScriptBlock { param([Parameter(Mandatory)][string] $Text) $Text } + .OUTPUTS + Mcp.ToolRegistration (with -PassThru) + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Changes an in-memory registry only.')] + [CmdletBinding(DefaultParameterSetName = 'Command')] + [OutputType('Mcp.ToolRegistration')] + param( + [Parameter(ParameterSetName = 'Command', Mandatory, Position = 0)] + [ValidateNotNull()] + [object] $Command, + + [Parameter(ParameterSetName = 'ScriptBlock', Mandatory)] + [scriptblock] $ScriptBlock, + + [Parameter(ParameterSetName = 'ScriptBlock', Mandatory)] + [Parameter(ParameterSetName = 'Command')] + [string] $Name, + + [string] $Title, + + [string] $Description, + + [object] $InputSchema, + + [object] $OutputSchema, + + [hashtable] $Annotations, + + [object[]] $Icons, + + [hashtable] $Meta, + + [hashtable] $Header, + + [switch] $AllowAdditionalProperties, + + [object] $Server, + + [switch] $Force, + + [switch] $PassThru + ) + + $target = Resolve-McpServer -Server $Server + $handler = @{ + Kind = $null + CommandName = $null + Definition = $null + ModuleName = $null + ModulePath = $null + CommandInfo = $null + ScriptBlock = $null + ArgumentStyle = 'Splat' + ContextParameter = $null + ParameterTypes = @{} + } + $ast = $null + $parameters = $null + + if ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') { + if (-not $Name) { throw [System.ArgumentException]::new('A script block tool needs a -Name.') } + $handler.Kind = 'ScriptBlock' + $handler.ScriptBlock = $ScriptBlock + $handler.Definition = $ScriptBlock.ToString() + $handler.CommandName = 'McpTool_' + ($Name -replace '[^A-Za-z0-9_]', '_') + $ast = $ScriptBlock.Ast + $temporaryName = 'McpTemporaryTool_' + [guid]::NewGuid().ToString('n') + Set-Item -Path "function:script:$temporaryName" -Value $ScriptBlock + try { + $parameters = (Get-Command -Name $temporaryName -CommandType Function).Parameters + } finally { + Remove-Item -Path "function:script:$temporaryName" -ErrorAction SilentlyContinue + } + } else { + $commandInfo = $Command + if ($Command -is [string]) { + # Resolve the name in the caller's scope first so that functions of the calling script are found; + # functions defined in nested scopes must be passed as CommandInfo (Get-Command) or script block. + $commandInfo = $PSCmdlet.SessionState.InvokeCommand.GetCommand($Command, [System.Management.Automation.CommandTypes]::All) + if ($null -eq $commandInfo) { + $commandInfo = Get-Command -Name $Command -ErrorAction SilentlyContinue | Select-Object -First 1 + } + if ($null -eq $commandInfo) { + throw [System.Management.Automation.CommandNotFoundException]::new("The command '$Command' was not found. Pass the result of Get-Command for functions defined in a nested scope.") + } + } + if ($commandInfo -isnot [System.Management.Automation.CommandInfo]) { + throw [System.ArgumentException]::new('-Command must be a command name or a CommandInfo object.') + } + if ($commandInfo -is [System.Management.Automation.AliasInfo]) { + $commandInfo = $commandInfo.ResolvedCommand + } + $handler.CommandInfo = $commandInfo + if (-not $Name) { $Name = $commandInfo.Name } + switch ($commandInfo.GetType().Name) { + 'FunctionInfo' { + $handler.Kind = 'Function' + $handler.CommandName = $commandInfo.Name + $ast = $commandInfo.ScriptBlock.Ast + if ($commandInfo.Module -and $commandInfo.Module.Path) { + $handler.ModuleName = $commandInfo.Module.Name + $handler.ModulePath = $commandInfo.Module.Path + } else { + $handler.Definition = $commandInfo.Definition + } + } + 'CmdletInfo' { + $handler.Kind = 'Cmdlet' + $handler.CommandName = $commandInfo.Name + if ($commandInfo.Module) { + $handler.ModuleName = $commandInfo.Module.Name + $handler.ModulePath = $commandInfo.Module.Path + } elseif ($commandInfo.ModuleName) { + $handler.ModuleName = $commandInfo.ModuleName + } + } + 'ExternalScriptInfo' { + $handler.Kind = 'Script' + $handler.CommandName = $commandInfo.Path + $ast = $commandInfo.ScriptBlock.Ast + } + default { + throw [System.ArgumentException]::new("Commands of type $($commandInfo.CommandType) cannot be registered as tools.") + } + } + $parameters = $commandInfo.Parameters + } + + if ($Name -notmatch $script:McpToolNamePattern) { + throw [System.ArgumentException]::new("'$Name' is not a valid tool name: 1-128 characters from A-Z, a-z, 0-9, '_', '-' and '.'.") + } + if ($target.Tools.Contains($Name) -and -not $Force) { + throw [System.InvalidOperationException]::new("A tool named '$Name' is already registered; use -Force to replace it.") + } + + $help = Get-McpCommandHelp -Ast $ast + if (-not $Description) { + $Description = if ($help.Synopsis) { $help.Synopsis } elseif ($help.Description) { $help.Description } else { $null } + } + if ($null -ne $parameters) { + foreach ($entry in $parameters.GetEnumerator()) { + if ($entry.Key -ieq 'Context') { $handler.ContextParameter = $entry.Value.Name } + } + $generated = New-McpToolInputSchema -Parameters $parameters -Help $help -Defaults (Get-McpParameterDefaultValue -Ast $ast) -AllowAdditionalProperties:$AllowAdditionalProperties + $handler.ParameterTypes = $generated.ParameterTypes + $schema = $generated.Schema + } else { + $schema = [ordered]@{ type = 'object'; additionalProperties = $false } + } + if ($PSBoundParameters.ContainsKey('InputSchema') -and $null -ne $InputSchema) { + $schema = ConvertTo-McpSchemaObject -Schema $InputSchema + if ($schema -isnot [System.Collections.IDictionary] -or $schema['type'] -ne 'object') { + throw [System.ArgumentException]::new('-InputSchema must be a JSON Schema object with "type": "object".') + } + Test-McpSchemaLimit -Schema $schema + if ($handler.ParameterTypes.ContainsKey('Arguments')) { $handler.ArgumentStyle = 'Arguments' } + } + if ($Header -and $Header.Count -gt 0) { + Add-McpHeaderAnnotation -Schema $schema -Header $Header + } + $headerParameters = @() + try { + $headerParameters = @(Get-McpToolHeaderParameter -InputSchema $schema) + } catch [System.ArgumentException] { + throw [System.ArgumentException]::new("Tool '$Name' has an invalid x-mcp-header annotation: $($_.Exception.Message)") + } + $outputSchemaObject = $null + if ($PSBoundParameters.ContainsKey('OutputSchema') -and $null -ne $OutputSchema) { + $outputSchemaObject = ConvertTo-McpSchemaObject -Schema $OutputSchema + Test-McpSchemaLimit -Schema $outputSchemaObject + } + + $registration = [pscustomobject]@{ + PSTypeName = 'Mcp.ToolRegistration' + Name = $Name + Title = $Title + Description = $Description + InputSchema = $schema + OutputSchema = $outputSchemaObject + Annotations = ConvertTo-McpAnnotationObject -Annotations $Annotations + Icons = $Icons + Meta = $Meta + HeaderParameters = $headerParameters + Handler = $handler + } + $target.Tools[$Name] = $registration + if ($PassThru) { $registration } +} diff --git a/src/Public/Start-McpServer.ps1 b/src/Public/Start-McpServer.ps1 new file mode 100644 index 0000000..2ea9dad --- /dev/null +++ b/src/Public/Start-McpServer.ps1 @@ -0,0 +1,87 @@ +function Start-McpServer { + <# + .SYNOPSIS + Serves a transport with the registered tools until the client disconnects or Stop-McpServer is called. + .DESCRIPTION + Over stdio (the default) the server reads JSON-RPC messages from standard input and writes responses + to standard output, one per line, and exits when standard input is closed. Nothing but protocol + messages may reach stdout: diagnostics go to stderr (see -LogLevel of New-McpServer). + + Over Streamable HTTP (-Transport Http) the server listens on -Url with System.Net.HttpListener. Every + 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 + 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). + + Tool handlers run in a runspace pool of the size given by -MaxConcurrency of New-McpServer. The + command blocks until the server has shut down. For tests and in-process clients, Connect-McpServer + -Server starts the same loop in a background runspace over an in-memory transport. + .PARAMETER Server + The server to start; defaults to the default server. + .PARAMETER Transport + Stdio (default), Http (with -Url) or InMemory (with -Endpoint). + .PARAMETER Url + The MCP endpoint of the HTTP transport (default: http://127.0.0.1:8080/mcp/). Clients must use the + same host name or address: requests whose Host header names another host or port are answered with 404. + .PARAMETER AllowedOrigins + Origins (scheme://host[:port]) accepted in the Origin header, or '*' for any; the default accepts + loopback origins and the server's own origin. Requests without an Origin header are always accepted. + .PARAMETER MaxBodyBytes + The largest request body accepted over HTTP (default: 16 MB; larger bodies answer 413). + .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 Endpoint + The server end of an in-memory transport pair (internal use by Connect-McpServer). + .PARAMETER ShutdownGraceSeconds + How long running handlers may finish after the input ends or Stop-McpServer was called before they are stopped. + .EXAMPLE + New-McpServer -Name echo -Version 1.0.0 -SetDefault + Register-McpTool -Name echo -ScriptBlock { param([string] $Text) $Text } + Start-McpServer + .EXAMPLE + Start-McpServer -Transport Http -Url http://127.0.0.1:3001/mcp/ + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [object] $Server, + + [ValidateSet('Stdio', 'Http', 'InMemory')] + [string] $Transport = 'Stdio', + + [ValidateNotNull()] + [uri] $Url = 'http://127.0.0.1:8080/mcp/', + + [string[]] $AllowedOrigins, + + [ValidateRange(1KB, 1GB)] + [long] $MaxBodyBytes = 16MB, + + [ValidateRange(0, 3600)] + [int] $KeepAliveSeconds = 5, + + [hashtable] $Endpoint, + + [ValidateRange(0, 3600)] + [int] $ShutdownGraceSeconds = 5 + ) + + $target = Resolve-McpServer -Server $Server + if ($target.State.Started) { + throw [System.InvalidOperationException]::new("Server '$($target.Name)' is already running.") + } + if ($Transport -eq 'InMemory' -and ($null -eq $Endpoint -or $Endpoint.Kind -ne 'InMemory')) { + throw [System.ArgumentException]::new('-Transport InMemory requires -Endpoint (the server end of New-McpInMemoryTransportPair).') + } + $where = if ($Transport -eq 'Http') { "Streamable HTTP at $Url" } else { $Transport } + 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 } + default { $Endpoint } + } + Invoke-McpDispatcher -Server $target -Transport $transportObject -ShutdownGraceSeconds $ShutdownGraceSeconds +} diff --git a/src/Public/Stop-McpServer.ps1 b/src/Public/Stop-McpServer.ps1 new file mode 100644 index 0000000..9bb47f3 --- /dev/null +++ b/src/Public/Stop-McpServer.ps1 @@ -0,0 +1,23 @@ +function Stop-McpServer { + <# + .SYNOPSIS + Asks a running server to shut down: no new requests are accepted and running handlers get a grace period. + .DESCRIPTION + Can be called from a tool handler (it runs in a worker runspace) or from another runspace that holds + the server object. Start-McpServer returns once the shutdown has completed. + .PARAMETER Server + The server to stop; defaults to the default server. + .EXAMPLE + Stop-McpServer -Server $server + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [object] $Server + ) + + $target = Resolve-McpServer -Server $Server + if (-not $PSCmdlet.ShouldProcess("server '$($target.Name)'", 'Stop')) { return } + $target.State.StopRequested = $true + $signal = $target.State.Signal + if ($null -ne $signal) { $null = $signal.Set() } +} diff --git a/src/Public/Test-McpClientCapability.ps1 b/src/Public/Test-McpClientCapability.ps1 new file mode 100644 index 0000000..864e913 --- /dev/null +++ b/src/Public/Test-McpClientCapability.ps1 @@ -0,0 +1,29 @@ +function Test-McpClientCapability { + <# + .SYNOPSIS + True when the client of the current request declared a capability, given as a dotted path. + .DESCRIPTION + Capabilities are declared per request in _meta. Paths use '.' between levels, for example + 'elicitation.form', 'sampling' or 'extensions.io.modelcontextprotocol/tasks'. + .PARAMETER Context + The request context (the handler's Context parameter). + .PARAMETER Path + The dotted capability path. + .EXAMPLE + if (Test-McpClientCapability -Context $Context -Path 'elicitation.form') { ... } + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [ValidateNotNull()] + [object] $Context, + + [Parameter(Mandatory, Position = 0)] + [ValidateNotNullOrEmpty()] + [string] $Path + ) + + $capabilities = if ($Context.PSObject.Properties['ClientCapabilities']) { $Context.ClientCapabilities } else { $null } + Test-McpCapabilityPath -Capabilities $capabilities -Path $Path +} diff --git a/src/Public/Write-McpLog.ps1 b/src/Public/Write-McpLog.ps1 new file mode 100644 index 0000000..eb795bb --- /dev/null +++ b/src/Public/Write-McpLog.ps1 @@ -0,0 +1,51 @@ +function Write-McpLog { + <# + .SYNOPSIS + Logs a message to stderr and, when the request asked for it, as a notifications/message to the client. + .DESCRIPTION + The message goes to stderr when its level reaches the server's log level. It is also sent to the + client as notifications/message when the request carried io.modelcontextprotocol/logLevel in its _meta + and the level reaches that level. Without a context only stderr is written. + .PARAMETER Message + The message text. + .PARAMETER Level + The severity: debug, info, notice, warning, error, critical, alert or emergency (default: info). + .PARAMETER Context + The request context (the handler's Context parameter). + .PARAMETER Logger + An optional logger name. + .PARAMETER Data + Structured data sent instead of the message text in the notification (any JSON-serialisable value). + .EXAMPLE + Write-McpLog -Context $Context -Level warning -Message 'Rate limit is close.' + #> + [CmdletBinding()] + param( + [Parameter(Mandatory, Position = 0)] + [AllowEmptyString()] + [string] $Message, + + [McpLoggingLevel] $Level = [McpLoggingLevel]::Info, + + [object] $Context, + + [string] $Logger, + + [object] $Data + ) + + $threshold = if ($null -ne $Context -and $Context.PSObject.Properties['ServerLogLevel'] -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel } + $loggerName = if ($Logger) { $Logger } elseif ($null -ne $Context -and $Context.PSObject.Properties['ToolName']) { $Context.ToolName } else { $null } + Write-McpStderr -Level $Level -Threshold $threshold -Logger $loggerName -Message $Message + + if ($null -eq $Context -or -not $Context.PSObject.Properties['LogLevel'] -or $null -eq $Context.LogLevel -or $null -eq $Context.Sink) { return } + $requested = ConvertTo-McpLoggingLevel -Level $Context.LogLevel + if ([int] $Level -lt [int] $requested) { return } + $params = [ordered]@{ + level = $Level.ToString().ToLowerInvariant() + } + if ($loggerName) { $params['logger'] = $loggerName } + $params['data'] = if ($PSBoundParameters.ContainsKey('Data')) { $Data } else { $Message } + $notification = New-McpNotification -Method 'notifications/message' -Params $params + Send-McpSinkMessage -Sink $Context.Sink -Kind Notification -RequestId $Context.RequestId -Json (ConvertTo-McpJson -InputObject $notification) +} diff --git a/src/Public/Write-McpProgress.ps1 b/src/Public/Write-McpProgress.ps1 new file mode 100644 index 0000000..e762423 --- /dev/null +++ b/src/Public/Write-McpProgress.ps1 @@ -0,0 +1,48 @@ +function Write-McpProgress { + <# + .SYNOPSIS + Sends a notifications/progress message for the request a tool handler is serving. + .DESCRIPTION + Nothing is sent when the client did not include a progressToken in the request. Progress values must + increase from call to call; a value that does not increase is ignored with a diagnostic on stderr. + .PARAMETER Context + The request context (the handler's Context parameter). + .PARAMETER Progress + The progress so far (any increasing number). + .PARAMETER Total + The total, when known. + .PARAMETER Message + A human-readable status. + .EXAMPLE + Write-McpProgress -Context $Context -Progress 1 -Total 3 -Message 'Fetching' + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNull()] + [object] $Context, + + [Parameter(Mandatory)] + [double] $Progress, + + [double] $Total = [double]::NaN, + + [string] $Message + ) + + if ($null -eq $Context.ProgressToken -or $null -eq $Context.Sink) { return } + $state = $Context.ProgressState + if ($null -ne $state -and $null -ne $state.Last -and $Progress -le [double] $state.Last) { + Write-McpStderr -Level Warning -Threshold $Context.ServerLogLevel -Logger $Context.ToolName -Message "Progress $Progress does not increase over $($state.Last); the notification is not sent." + return + } + if ($null -ne $state) { $state.Last = $Progress } + $params = [ordered]@{ + progressToken = $Context.ProgressToken + progress = $Progress + } + if (-not [double]::IsNaN($Total)) { $params['total'] = $Total } + if ($Message) { $params['message'] = $Message } + $notification = New-McpNotification -Method 'notifications/progress' -Params $params + Send-McpSinkMessage -Sink $Context.Sink -Kind Notification -RequestId $Context.RequestId -Json (ConvertTo-McpJson -InputObject $notification) +} diff --git a/src/Suffix.ps1 b/src/Suffix.ps1 index 8eb799d..9b11d3e 100644 --- a/src/Suffix.ps1 +++ b/src/Suffix.ps1 @@ -8,6 +8,7 @@ $script:McpTypeAccelerators = @( @{ Name = 'McpEra'; Type = [McpEra] } @{ Name = 'McpLoggingLevel'; Type = [McpLoggingLevel] } + @{ Name = 'McpProtocolException'; Type = [McpProtocolException] } ) $script:McpTypeAcceleratorRegistry = [psobject].Assembly.GetType('System.Management.Automation.TypeAccelerators') diff --git a/src/en-US/about_ModelContextProtocol.help.txt b/src/en-US/about_ModelContextProtocol.help.txt index 8a53abd..f0f00fa 100644 --- a/src/en-US/about_ModelContextProtocol.help.txt +++ b/src/en-US/about_ModelContextProtocol.help.txt @@ -17,9 +17,36 @@ LONG DESCRIPTION Supported transports are stdio and Streamable HTTP. CURRENT STATUS - Milestone M0 (foundation): the module builds, imports without side effects - and is tested on PowerShell 7.4, 7.5 and 7.6, but exports no commands yet. - See ROADMAP.md in the repository for the milestones. + Milestone M2 (Streamable HTTP): servers expose PowerShell commands and + script blocks as tools over stdio and over Streamable HTTP with the + stateless 2026-07-28 lifecycle (server/discover, per-request _meta, + request metadata headers, progress, cancellation), and clients connect to + such servers over both transports. The official conformance suite runs in + CI. Resources, prompts, input requests, subscriptions, the legacy + revisions, authorization and the extensions follow in later milestones + (ROADMAP.md). + +COMMANDS + Server: New-McpServer, Register-McpTool, Start-McpServer, Stop-McpServer, + Invoke-McpToolHandler + Handlers: New-McpContent, New-McpToolResult, Write-McpProgress, Write-McpLog, + Test-McpClientCapability + Client: Connect-McpServer, Disconnect-McpServer, Get-McpServerInfo, + Get-McpTool, Invoke-McpTool + + Start-McpServer serves stdio by default; -Transport Http -Url serves a + Streamable HTTP endpoint (POST-only, JSON or SSE responses, request + metadata header validation, Origin checks). Connect-McpServer -Command + starts a server process over stdio; Connect-McpServer -Url connects to a + Streamable HTTP endpoint. Register-McpTool -Header maps tool parameters to + Mcp-Param-* headers (the x-mcp-header annotation), which the client + mirrors and the server validates. + + A tool handler receives the request context through a parameter named + Context (request id, protocol version, client info and capabilities, log + level, progress token, cancellation token). Handlers run in a worker + runspace pool: pass everything they need as parameters; nothing they write + to the host reaches the client. REQUIREMENTS PowerShell 7.4 or later (Core edition). Windows PowerShell 5.1 is not diff --git a/tests/Conformance/everything-client.ps1 b/tests/Conformance/everything-client.ps1 new file mode 100644 index 0000000..408cf87 --- /dev/null +++ b/tests/Conformance/everything-client.ps1 @@ -0,0 +1,123 @@ +#Requires -Version 7.4 +<# +.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. +.DESCRIPTION + The suite runs it as + pwsh -NoLogo -NoProfile -NonInteractive -File tests/Conformance/everything-client.ps1 + with MCP_CONFORMANCE_SCENARIO (the scenario name), MCP_CONFORMANCE_CONTEXT (JSON with scenario data such as + 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. Scenarios of later milestones (input requests, authorization) are listed in + conformance-baseline.yml. +#> +[CmdletBinding()] +param( + [Parameter(ValueFromRemainingArguments)] + [string[]] $Arguments +) + +$ErrorActionPreference = 'Stop' +if ($env:MCP_MODULE_MANIFEST) { + Import-Module -Name $env:MCP_MODULE_MANIFEST -ErrorAction Stop +} else { + Import-Module -Name ModelContextProtocol -ErrorAction Stop +} + +function Write-ClientLog { + param([string] $Message) + [Console]::Error.WriteLine("[everything-client] $Message") +} + +function ConvertTo-ToolArgument { + <# + .SYNOPSIS + Arguments for a tool call: a value of the right type for every required property of the input schema. + #> + param([object] $Schema) + $arguments = [ordered]@{} + if ($Schema -isnot [System.Collections.IDictionary] -or -not $Schema.Contains('properties') -or $Schema['properties'] -isnot [System.Collections.IDictionary]) { return $arguments } + $required = if ($Schema.Contains('required')) { @($Schema['required']) } else { @() } + foreach ($name in $required) { + $property = $Schema['properties'][$name] + $type = if ($property -is [System.Collections.IDictionary] -and $property.Contains('type')) { [string] $property['type'] } else { 'string' } + $arguments[[string] $name] = switch ($type) { + 'integer' { 1 } + 'number' { 1 } + 'boolean' { $true } + 'object' { [ordered]@{} } + 'array' { @() } + 'null' { $null } + default { if ($property -is [System.Collections.IDictionary] -and $property.Contains('enum')) { @($property['enum'])[0] } else { 'test' } } + } + } + $arguments +} + +$url = if ($Arguments.Count -gt 0) { $Arguments[-1] } else { $null } +if (-not $url) { + Write-ClientLog 'Usage: everything-client.ps1 ' + exit 2 +} +$scenario = $env:MCP_CONFORMANCE_SCENARIO +$context = @{} +if ($env:MCP_CONFORMANCE_CONTEXT) { + try { $context = ConvertFrom-Json -InputObject $env:MCP_CONFORMANCE_CONTEXT -AsHashtable -Depth 50 } catch { Write-ClientLog "Ignoring MCP_CONFORMANCE_CONTEXT: $($_.Exception.Message)" } + if ($null -eq $context) { $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 +} + +$connectParameters = @{ + Url = $url + ClientInfo = @{ name = 'ModelContextProtocol-everything-client'; version = '0.1.0' } + Capabilities = @{ elicitation = @{ form = @{} }; sampling = @{}; roots = @{ listChanged = $true } } + ProtocolVersion = $protocolVersion + RequestTimeoutSeconds = 20 + ConnectTimeoutSeconds = 20 +} +$session = Connect-McpServer @connectParameters +try { + $info = Get-McpServerInfo -Session $session + Write-ClientLog "connected to '$($info.Name)' $($info.Version) (supports $($info.SupportedVersions -join ', '))" + $tools = @(Get-McpTool -Session $session -WarningVariable exclusions) + foreach ($warning in @($exclusions)) { Write-ClientLog "warning: $warning" } + Write-ClientLog "tools: $(if ($tools.Count -gt 0) { ($tools | ForEach-Object Name) -join ', ' } else { '(none)' })" + + $calls = [System.Collections.Generic.List[hashtable]]::new() + if ($context.ContainsKey('toolCalls') -and $null -ne $context['toolCalls']) { + foreach ($call in @($context['toolCalls'])) { + if ($call -is [System.Collections.IDictionary] -and $call.Contains('name')) { + $calls.Add(@{ name = [string] $call['name']; arguments = $(if ($call.Contains('arguments') -and $null -ne $call['arguments']) { $call['arguments'] } else { @{} }) }) + } + } + } else { + $echo = $tools | Where-Object { $_.Name -eq 'json_schema_echo' } | Select-Object -First 1 + $focal = $tools | Where-Object { $_.Name -eq 'json_schema_2020_12_tool' } | Select-Object -First 1 + foreach ($tool in $tools) { + if ($tool.Name -eq 'json_schema_echo' -and $null -ne $focal) { + # The preservation scenario wants the focal tool's schema back exactly as the client observed it. + $calls.Add(@{ name = $echo.Name; arguments = @{ schema = $focal.InputSchema } }) + } else { + $calls.Add(@{ name = $tool.Name; arguments = (ConvertTo-ToolArgument -Schema $tool.InputSchema) }) + } + } + } + foreach ($call in $calls) { + try { + $result = Invoke-McpTool -Name $call.name -Arguments $call.arguments -Session $session + Write-ClientLog "tools/call $($call.name): isError=$($result.IsError) text=$($result.Text.Substring(0, [math]::Min(80, $result.Text.Length)))" + } catch { + Write-ClientLog "tools/call $($call.name) failed: $($_.Exception.Message)" + } + } +} finally { + Disconnect-McpServer -Session $session +} +exit 0 diff --git a/tests/Conformance/everything-server.ps1 b/tests/Conformance/everything-server.ps1 new file mode 100644 index 0000000..dd217a4 --- /dev/null +++ b/tests/Conformance/everything-server.ps1 @@ -0,0 +1,141 @@ +#Requires -Version 7.4 +<# +.SYNOPSIS + The conformance fixture server: the tools that the server scenarios of @modelcontextprotocol/conformance + exercise for revision 2026-07-28, served over Streamable HTTP. +.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 (resources, prompts, completion, subscriptions, input requests) are listed in + conformance-baseline.yml until their milestone lands. +.PARAMETER Port + The TCP port on the loopback interface. +.PARAMETER Hostname + The host part of the endpoint URL; clients must use the same value. +.PARAMETER LogLevel + The stderr log level (debug shows every request). +#> +[CmdletBinding()] +param( + [ValidateRange(1, 65535)] + [int] $Port = 3001, + + [string] $Hostname = '127.0.0.1', + + [ValidateSet('debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency')] + [string] $LogLevel = 'info' +) + +if ($env:MCP_MODULE_MANIFEST) { + Import-Module -Name $env:MCP_MODULE_MANIFEST -ErrorAction Stop +} else { + Import-Module -Name ModelContextProtocol -ErrorAction Stop +} + +# 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 + +Register-McpTool -Name 'test_simple_text' -Description 'Returns a simple text response.' -ScriptBlock { + 'This is a simple text response for testing.' +} + +Register-McpTool -Name 'test_image_content' -Description 'Returns a 1x1 PNG image.' -ScriptBlock { + New-McpContent -Image 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==' -MimeType 'image/png' +} + +Register-McpTool -Name 'test_audio_content' -Description 'Returns a minimal WAV clip.' -ScriptBlock { + New-McpContent -Audio 'UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA=' -MimeType 'audio/wav' +} + +Register-McpTool -Name 'test_embedded_resource' -Description 'Returns an embedded text resource.' -ScriptBlock { + New-McpContent -EmbeddedResource 'test://embedded-resource' -MimeType 'text/plain' -ResourceText 'This is an embedded resource content.' +} + +Register-McpTool -Name 'test_multiple_content_types' -Description 'Returns text, an image and an embedded resource.' -ScriptBlock { + New-McpContent -Text 'Multiple content types test:' + New-McpContent -Image 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==' -MimeType 'image/png' + New-McpContent -EmbeddedResource 'test://mixed-content-resource' -MimeType 'application/json' -ResourceText '{"test":"data","value":123}' +} + +Register-McpTool -Name 'test_error_handling' -Description 'Always fails, as a tool execution error.' -ScriptBlock { + throw 'This tool intentionally returns an error for testing' +} + +Register-McpTool -Name 'test_tool_with_progress' -Description 'Reports progress 0, 50 and 100 of 100 while it runs.' -ScriptBlock { + param($Context) + Write-McpProgress -Context $Context -Progress 0 -Total 100 -Message 'Starting' + Start-Sleep -Milliseconds 50 + Write-McpProgress -Context $Context -Progress 50 -Total 100 -Message 'Half way' + Start-Sleep -Milliseconds 50 + Write-McpProgress -Context $Context -Progress 100 -Total 100 -Message 'Done' + 'Progress test completed' +} + +Register-McpTool -Name 'test_logging_tool' -Description 'Logs three messages; they reach the client only when the request asked for a log level.' -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_missing_capability' -Description 'Requires the sampling capability; rejects requests that do not declare it.' -ScriptBlock { + param($Context) + if (-not (Test-McpClientCapability -Context $Context -Path 'sampling')) { + throw [McpProtocolException]::new(-32021, 'This tool requires the sampling capability.', @{ requiredCapabilities = @{ sampling = @{} } }) + } + 'The client declared the sampling capability.' +} + +Register-McpTool -Name 'test_streaming_elicitation' -Description 'Streams a result; asks the client for input from milestone M4 on.' -ScriptBlock { + 'No input required yet.' +} + +Register-McpTool -Name 'test_custom_headers' -Description 'Mirrors region and priority into Mcp-Param headers.' -ScriptBlock { + param( + [Parameter(Mandatory)] + [string] $region, + + [int] $priority = 0, + + [string] $query = '' + ) + "region=$region priority=$priority query=$query" +} -Header @{ region = 'Region'; priority = 'Priority' } + +# The JSON Schema 2020-12 vocabulary of the json-schema-2020-12 scenario: kept verbatim in tools/list. +$jsonSchemaTool = [ordered]@{ + '$schema' = 'https://json-schema.org/draft/2020-12/schema' + type = 'object' + '$defs' = [ordered]@{ + address = [ordered]@{ + '$anchor' = 'addressDef' + type = 'object' + properties = [ordered]@{ street = [ordered]@{ type = 'string' }; city = [ordered]@{ type = 'string' } } + } + } + properties = [ordered]@{ + name = [ordered]@{ type = 'string' } + address = [ordered]@{ '$ref' = '#/$defs/address' } + contactMethod = [ordered]@{ type = 'string'; enum = @('phone', 'email') } + phone = [ordered]@{ type = 'string' } + email = [ordered]@{ type = 'string' } + } + allOf = @([ordered]@{ anyOf = @([ordered]@{ required = @('phone') }, [ordered]@{ required = @('email') }) }) + if = [ordered]@{ properties = [ordered]@{ contactMethod = [ordered]@{ const = 'phone' } }; required = @('contactMethod') } + then = [ordered]@{ required = @('phone') } + else = [ordered]@{ required = @('email') } + additionalProperties = $false +} +Register-McpTool -Name 'json_schema_2020_12_tool' -Description 'Tool with JSON Schema 2020-12 features' -InputSchema $jsonSchemaTool -ScriptBlock { + param([hashtable] $Arguments) + "Received $($Arguments.Count) argument(s)." +} + +Start-McpServer -Server $server -Transport Http -Url "http://${Hostname}:$Port/mcp/" diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1 new file mode 100644 index 0000000..cfe692d --- /dev/null +++ b/tests/Integration/HttpServer.Tests.ps1 @@ -0,0 +1,309 @@ +[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 + + $script:server = New-McpServer -Name 'http' -Version '2.0.0' -Title 'HTTP test server' -Instructions 'Test server over Streamable HTTP.' -RequestTimeoutSeconds 30 + Register-McpTool -Name 'echo' -Description 'Echoes.' -ScriptBlock { param([Parameter(Mandatory)][string] $Text) $Text } -Server $script:server + Register-McpTool -Name 'add' -Description 'Adds.' -ScriptBlock { param([int] $A, [int] $B) [pscustomobject]@{ sum = $A + $B } } -OutputSchema @{ type = 'object'; properties = @{ sum = @{ type = 'integer' } }; required = @('sum') } -Server $script:server + Register-McpTool -Name 'count' -Description 'Counts with progress; a marker file records where it stopped.' -ScriptBlock { + param([int] $To = 3, [int] $DelayMs = 20, [string] $MarkerPath = '', $Context) + $i = 0 + try { + for ($i = 1; $i -le $To; $i++) { + if ($Context.CancellationToken.IsCancellationRequested) { return "cancelled at $i" } + Write-McpProgress -Context $Context -Progress $i -Total $To -Message "step $i" + Write-McpLog -Context $Context -Level info -Message "log $i" -Logger 'counter' + Start-Sleep -Milliseconds $DelayMs + } + "counted to $To" + } finally { + # Runs when the pipeline is stopped, too; cmdlets cannot be called then, .NET methods can. + if ($MarkerPath) { [System.IO.File]::WriteAllText($MarkerPath, "stopped at $i of $To") } + } + } -Server $script:server + Register-McpTool -Name 'fail' -Description 'Fails.' -ScriptBlock { throw 'nope' } -Server $script:server + Register-McpTool -Name 'region' -Description 'Mirrors parameters into headers.' -ScriptBlock { param([Parameter(Mandatory)][string] $Region, [int] $Priority = 1, [string] $Query = '') "$Region/$Priority/$Query" } -Header @{ Region = 'Region'; Priority = 'Priority' } -Server $script:server + Register-McpTool -Name 'needs_sampling' -Description 'Requires the sampling capability.' -ScriptBlock { + param($Context) + if (-not (Test-McpClientCapability -Context $Context -Path 'sampling')) { + throw [McpProtocolException]::new(-32021, 'This tool requires the sampling capability.', @{ requiredCapabilities = @{ sampling = @{} } }) + } + 'sampled' + } -Server $script:server + $script:handle = Start-McpTestHttpServer -Server $script:server -Parameters @{ KeepAliveSeconds = 1 } + $script:url = $script:handle.Url + $script:meta = '"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}' + $script:session = Connect-McpServer -Url $script:url -Capabilities @{ elicitation = @{ form = @{} } } +} + +AfterAll { + if ($script:session) { Disconnect-McpServer -Session $script:session } + if ($script:handle) { Stop-McpTestHttpServer -Handle $script:handle } +} + +Describe 'Connect-McpServer over Streamable HTTP' -Tag 'Integration' { + It 'connects, discovers and lists the tools with their header annotations' { + $script:session.Kind | Should -Be 'Http' + $script:session.Endpoint | Should -Be $script:url + $script:session.Name | Should -Be 'http' + $script:session.ProtocolVersion | Should -Be '2026-07-28' + (Get-McpServerInfo -Session $script:session).Title | Should -Be 'HTTP test server' + @(Get-McpTool -Session $script:session | ForEach-Object Name) | Should -Be @('echo', 'add', 'count', 'fail', 'region', 'needs_sampling') + @($script:session.ToolHeaders['region'] | ForEach-Object { $_.Header }) | Should -Be @('Region', 'Priority') + $script:session.ToolHeaders['echo'].Count | Should -Be 0 + } + + It 'round-trips text, structured content and tool errors' { + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'héllo 😀 日本' } -Session $script:session).Text | Should -Be 'héllo 😀 日本' + $big = 'x' * 1MB + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = $big } -Session $script:session).Text.Length | Should -Be 1MB + $result = Invoke-McpTool -Name 'add' -Arguments @{ A = 2; B = 40 } -Session $script:session + $result.StructuredContent['sum'] | Should -Be 42 + $result.Meta['io.modelcontextprotocol/serverInfo']['name'] | Should -Be 'http' + $failed = Invoke-McpTool -Name 'fail' -Session $script:session + $failed.IsError | Should -BeTrue + $failed.Text | Should -Be 'Error: nope' + } + + It 'streams progress and log notifications on the response stream' { + $progress = [System.Collections.Generic.List[object]]::new() + $script:session.Log.Clear() + $result = Invoke-McpTool -Name 'count' -Arguments @{ To = 3 } -OnProgress { param($p) $progress.Add($p.Progress) } -LogLevel info -Session $script:session + $result.Text | Should -Be 'counted to 3' + @($progress) | Should -Be @(1, 2, 3) + $script:session.Log.Count | Should -Be 3 + $script:session.Log[0].Logger | Should -Be 'counter' + } + + It 'mirrors annotated parameters into Mcp-Param headers that the server validates' { + (Invoke-McpTool -Name 'region' -Arguments @{ Region = 'Hello, 世界'; Priority = 42; Query = 'q' } -Session $script:session).Text | Should -Be 'Hello, 世界/42/q' + (Invoke-McpTool -Name 'region' -Arguments @{ Region = ' padded ' } -Session $script:session).Text | Should -Be ' padded /1/' + } + + It 'surfaces protocol errors as McpProtocolException' { + $exception = $null + try { Invoke-McpTool -Name 'needs_sampling' -Session $script:session } catch { $exception = $_.Exception } + $exception | Should -BeOfType [McpProtocolException] + $exception.Code | Should -Be -32021 + $exception.Data['requiredCapabilities'].Contains('sampling') | Should -BeTrue + try { Invoke-McpTool -Name 'missing' -Session $script:session } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32602 + try { Invoke-McpTool -Name 'echo' -Arguments @{ Text = 5 } -Session $script:session } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32602 + } + + It 'stops the handler when the client closes the connection on timeout' { + $marker = Join-Path ([System.IO.Path]::GetTempPath()) ('mcp-cancel-' + [guid]::NewGuid().ToString('n') + '.txt') + try { + # 200 x 50 ms = 10 s of work; the client gives up after 1 s, the server notices through the + # keep-alive (1 s interval in this fixture) and stops the handler long before it would finish. + { Invoke-McpTool -Name 'count' -Arguments @{ To = 200; DelayMs = 50; MarkerPath = $marker } -TimeoutSeconds 1 -Session $script:session } | Should -Throw -ExceptionType ([System.TimeoutException]) + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'alive' } -Session $script:session).Text | Should -Be 'alive' + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Milliseconds 100 } + Test-Path -Path $marker | Should -BeTrue + $text = [System.IO.File]::ReadAllText($marker) + $text | Should -Match '^stopped at (\d+) of 200$' + [int] ($text -replace '^stopped at (\d+) of 200$', '$1') | Should -BeLessThan 150 + } finally { + Remove-Item -Path $marker -ErrorAction SilentlyContinue + } + } + + It 'answers 20 calls in well under a second each' { + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + 1..20 | ForEach-Object { $null = Invoke-McpTool -Name 'echo' -Arguments @{ Text = "x$_" } -Session $script:session } + ($stopwatch.ElapsedMilliseconds / 20) | Should -BeLessThan 1000 + } +} + +Describe 'Raw Streamable HTTP behaviour' -Tag 'Integration' { + BeforeAll { + function script:Send-Raw { + param([string] $Body, [hashtable] $Headers = @{}, [string] $Method = 'POST', [switch] $NoVersion) + $all = @{} + if (-not $NoVersion) { $all['MCP-Protocol-Version'] = '2026-07-28' } + foreach ($key in $Headers.Keys) { $all[$key] = $Headers[$key] } + Invoke-McpRawHttp -Url ($script:url.TrimEnd('/')) -Body $(if ($Method -eq 'POST') { $Body } else { $null }) -Headers $all -Method $Method + } + $script:listCall = "{`"jsonrpc`":`"2.0`",`"id`":1,`"method`":`"tools/list`",`"params`":{$($script:meta)}}" + $script:echoCall = "{`"jsonrpc`":`"2.0`",`"id`":10,`"method`":`"tools/call`",`"params`":{$($script:meta),`"name`":`"echo`",`"arguments`":{`"Text`":`"hi`"}}}" + $script:regionCall = "{`"jsonrpc`":`"2.0`",`"id`":11,`"method`":`"tools/call`",`"params`":{$($script:meta),`"name`":`"region`",`"arguments`":{`"Region`":`"Hello`",`"Query`":`"q`",`"Priority`":42}}}" + } + + It 'answers GET and DELETE with 405 and an Allow header' { + foreach ($method in 'GET', 'DELETE') { + $response = Send-Raw -Method $method + $response.Status | Should -Be 405 + $response.Headers['Allow'] | Should -Be 'POST' + $response.Json['error']['code'] | Should -Be -32600 + $response.Json.ContainsKey('id') | Should -BeFalse + } + } + + It 'rejects foreign origins with 403 and accepts loopback origins' { + (Send-Raw -Body $script:listCall -Headers @{ Origin = 'http://evil.example.com'; 'Mcp-Method' = 'tools/list' }).Status | Should -Be 403 + (Send-Raw -Body $script:listCall -Headers @{ Origin = 'http://localhost:5173'; 'Mcp-Method' = 'tools/list' }).Status | Should -Be 200 + } + + It 'rejects other hosts and ports (DNS rebinding) with 404 and unsupported media types with 415' { + (Send-Raw -Body $script:listCall -Headers @{ Host = 'evil.example.com'; 'Mcp-Method' = 'tools/list' }).Status | Should -Be 404 + (Send-Raw -Body $script:listCall -Headers @{ Host = "evil.example.com:$(([uri] $script:url).Port)"; 'Mcp-Method' = 'tools/list' }).Status | Should -Be 404 + (Send-Raw -Body $script:listCall -Headers @{ Host = '127.0.0.1:1'; 'Mcp-Method' = 'tools/list' }).Status | Should -Be 404 + (Send-Raw -Body $script:listCall -Headers @{ Host = ([uri] $script:url).Authority; 'Mcp-Method' = 'tools/list' }).Status | Should -Be 200 + (Invoke-McpRawHttp -Url $script:url -Body 'text' -ContentType 'text/plain' -Headers @{ 'MCP-Protocol-Version' = '2026-07-28'; 'Mcp-Method' = 'x' }).Status | Should -Be 415 + } + + It 'answers parse errors with 400 and an id-less error, notifications with 202 and responses with 400' { + $parse = Send-Raw -Body '{not json' -Headers @{ 'Mcp-Method' = 'x' } + $parse.Status | Should -Be 400 + $parse.Json['error']['code'] | Should -Be -32700 + $parse.Json.ContainsKey('id') | Should -BeFalse + (Test-McpSpecShape -Definition 'JSONRPCErrorResponse' -Instance $parse.Json).IsValid | Should -BeTrue + $notification = Send-Raw -Body '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}' + $notification.Status | Should -Be 202 + $notification.Body | Should -BeNullOrEmpty + (Send-Raw -Body '{"jsonrpc":"2.0","id":1,"result":{}}').Status | Should -Be 400 + (Send-Raw -Body '{"jsonrpc":"2.0","id":null,"method":"tools/list"}' -Headers @{ 'Mcp-Method' = 'tools/list' }).Json['error']['code'] | Should -Be -32600 + } + + It 'validates the standard headers ()' -TestCases @( + @{ Name = 'missing Mcp-Method'; Headers = @{}; Status = 400; Code = -32020 } + @{ Name = 'mismatched Mcp-Method'; Headers = @{ 'Mcp-Method' = 'prompts/list' }; Status = 400; Code = -32020 } + @{ Name = 'case-mismatched Mcp-Method value'; Headers = @{ 'Mcp-Method' = 'TOOLS/LIST' }; Status = 400; Code = -32020 } + @{ Name = 'lowercase header name'; Headers = @{ 'mcp-method' = 'tools/list' }; Status = 200; Code = $null } + @{ Name = 'uppercase header name'; Headers = @{ 'MCP-METHOD' = 'tools/list' }; Status = 200; Code = $null } + @{ Name = 'whitespace around the value'; Headers = @{ 'Mcp-Method' = ' tools/list ' }; Status = 200; Code = $null } + ) { + $response = Send-Raw -Body $script:listCall -Headers $Headers + $response.Status | Should -Be $Status + if ($null -ne $Code) { + $response.Json['error']['code'] | Should -Be $Code + $response.Json['id'] | Should -Be 1 + } else { + $response.Json['result']['tools'].Count | Should -BeGreaterThan 0 + } + } + + It 'validates the protocol version header against _meta and the supported versions' { + $missing = Send-Raw -Body $script:listCall -Headers @{ 'Mcp-Method' = 'tools/list' } -NoVersion + $missing.Status | Should -Be 400 + $missing.Json['error']['code'] | Should -Be -32020 + $body = "{`"jsonrpc`":`"2.0`",`"id`":2,`"method`":`"tools/list`",`"params`":{`"_meta`":{`"io.modelcontextprotocol/protocolVersion`":`"v999.0.0`",`"io.modelcontextprotocol/clientCapabilities`":{}}}}" + $mismatch = Send-Raw -Body $body -Headers @{ 'Mcp-Method' = 'tools/list' } + $mismatch.Status | Should -Be 400 + $mismatch.Json['error']['code'] | Should -Be -32020 + $unsupported = Send-Raw -Body $body -Headers @{ 'Mcp-Method' = 'tools/list'; 'MCP-Protocol-Version' = 'v999.0.0' } + $unsupported.Status | Should -Be 400 + $unsupported.Json['error']['code'] | Should -Be -32022 + $unsupported.Json['error']['data']['supported'] | Should -Be @('2026-07-28') + $unsupported.Json['error']['data']['requested'] | Should -Be 'v999.0.0' + $unsupported.Json['id'] | Should -Be 2 + } + + It 'answers missing _meta with 400 and -32602, removed and unknown methods with 404 and -32601' { + $noMeta = Send-Raw -Body '{"jsonrpc":"2.0","id":3,"method":"tools/list","params":{}}' -Headers @{ 'Mcp-Method' = 'tools/list' } + $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') { + $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' { + (Send-Raw -Body $script:echoCall -Headers @{ 'Mcp-Method' = 'tools/call' }).Json['error']['code'] | Should -Be -32020 + (Send-Raw -Body $script:echoCall -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'other' }).Status | Should -Be 400 + (Send-Raw -Body $script:echoCall -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = ' echo ' }).Json['result']['content'][0]['text'] | Should -Be 'hi' + (Send-Raw -Body $script:echoCall -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = '=?base64?ZWNobw==?=' }).Status | Should -Be 200 + } + + It 'validates Mcp-Param headers ()' -TestCases @( + @{ Name = 'plain value'; Headers = @{ 'Mcp-Param-Region' = 'Hello'; 'Mcp-Param-Priority' = '42' }; Status = 200 } + @{ Name = 'Base64 sentinel'; Headers = @{ 'Mcp-Param-Region' = '=?base64?SGVsbG8=?='; 'Mcp-Param-Priority' = '42.0' }; Status = 200 } + @{ Name = 'invalid Base64 padding'; Headers = @{ 'Mcp-Param-Region' = '=?base64?SGVsbG8?='; 'Mcp-Param-Priority' = '42' }; Status = 400 } + @{ Name = 'invalid Base64 characters'; Headers = @{ 'Mcp-Param-Region' = '=?base64?SGVs!!!bG8=?='; 'Mcp-Param-Priority' = '42' }; Status = 400 } + @{ Name = 'missing header with a body value'; Headers = @{ 'Mcp-Param-Priority' = '42' }; Status = 400 } + @{ Name = 'mismatched value'; Headers = @{ 'Mcp-Param-Region' = 'World'; 'Mcp-Param-Priority' = '42' }; Status = 400 } + @{ Name = 'mismatched integer'; Headers = @{ 'Mcp-Param-Region' = 'Hello'; 'Mcp-Param-Priority' = '41' }; Status = 400 } + ) { + $all = @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'region' } + foreach ($key in $Headers.Keys) { $all[$key] = $Headers[$key] } + $response = Send-Raw -Body $script:regionCall -Headers $all + $response.Status | Should -Be $Status + if ($Status -eq 400) { $response.Json['error']['code'] | Should -Be -32020 } else { $response.Json['result']['content'][0]['text'] | Should -Be 'Hello/42/q' } + } + + It 'treats values without the full sentinel as literals' { + $body = "{`"jsonrpc`":`"2.0`",`"id`":12,`"method`":`"tools/call`",`"params`":{$($script:meta),`"name`":`"region`",`"arguments`":{`"Region`":`"=?base64?SGVsbG8=`",`"Query`":`"q`"}}}" + (Send-Raw -Body $body -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'region'; 'Mcp-Param-Region' = '=?base64?SGVsbG8=' }).Json['result']['content'][0]['text'] | Should -Be '=?base64?SGVsbG8=/1/q' + } + + It 'streams SSE events for a request with a progress token and validates the wire shapes' { + $body = "{`"jsonrpc`":`"2.0`",`"id`":13,`"method`":`"tools/call`",`"params`":{`"_meta`":{`"io.modelcontextprotocol/protocolVersion`":`"2026-07-28`",`"io.modelcontextprotocol/clientCapabilities`":{},`"progressToken`":`"progress-test-1`"},`"name`":`"count`",`"arguments`":{`"To`":3,`"DelayMs`":10}}}" + $response = Send-Raw -Body $body -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'count' } + $response.Status | Should -Be 200 + $response.ContentType | Should -Be 'text/event-stream' + $response.Headers['X-Accel-Buffering'] | Should -Be 'no' + $events = @($response.Body -split "`n`n" | Where-Object { $_ -match 'data:' }) + $events.Count | Should -Be 4 + $messages = @($events | ForEach-Object { ($_ -split "`n" | Where-Object { $_ -like 'data:*' }) -replace '^data:\s*', '' } | ForEach-Object { ConvertFrom-Json -InputObject $_ -AsHashtable }) + @($messages[0..2] | ForEach-Object { $_['params']['progress'] }) | Should -Be @(1, 2, 3) + $messages[0]['params']['progressToken'] | Should -Be 'progress-test-1' + $messages[3]['id'] | Should -Be 13 + $messages[3]['result']['content'][0]['text'] | Should -Be 'counted to 3' + (Test-McpSpecShape -Definition 'ProgressNotification' -Instance $messages[0]).IsValid | Should -BeTrue + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $messages[3]['result']).IsValid | Should -BeTrue + $response.Body | Should -Not -Match 'notifications/message' + } + + It 'answers -32021 from a handler with 400 and the required capabilities' { + $body = "{`"jsonrpc`":`"2.0`",`"id`":14,`"method`":`"tools/call`",`"params`":{$($script:meta),`"name`":`"needs_sampling`",`"arguments`":{}}}" + $response = Send-Raw -Body $body -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'needs_sampling' } + $response.Status | Should -Be 400 + $response.Json['error']['code'] | Should -Be -32021 + $response.Json['error']['data']['requiredCapabilities'].ContainsKey('sampling') | Should -BeTrue + $response.Json['id'] | Should -Be 14 + } +} + +Describe 'Start-McpServer -Transport Http' -Tag 'Integration' { + It 'fails clearly when the port is in use' { + $blocker = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) + $blocker.Start() + try { + $port = $blocker.LocalEndpoint.Port + $server = New-McpServer -Name 'busy' -Version '1' + { Start-McpServer -Server $server -Transport Http -Url "http://127.0.0.1:$port/mcp/" } | Should -Throw -ExpectedMessage '*Cannot listen*' + $server.State.Started | Should -BeFalse + } finally { + $blocker.Stop() + } + } + + It 'rejects URLs that are not absolute http or https' { + $server = New-McpServer -Name 'bad' -Version '1' + { Start-McpServer -Server $server -Transport Http -Url 'ftp://127.0.0.1/mcp' } | Should -Throw -ExpectedMessage '*http or https*' + } + + It 'stops on Stop-McpServer and refuses connections afterwards' { + $server = New-McpServer -Name 'short' -Version '1' + Register-McpTool -Name 'echo' -ScriptBlock { param([string] $Text) $Text } -Server $server + $handle = Start-McpTestHttpServer -Server $server + $session = Connect-McpServer -Url $handle.Url + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'x' } -Session $session).Text | Should -Be 'x' + Disconnect-McpServer -Session $session + Stop-McpTestHttpServer -Handle $handle + $server.State.Started | Should -BeFalse + { Invoke-McpRawHttp -Url $handle.Url -Body '{}' -TimeoutSeconds 5 } | Should -Throw + } +} diff --git a/tests/Integration/InMemoryClient.Tests.ps1 b/tests/Integration/InMemoryClient.Tests.ps1 new file mode 100644 index 0000000..a84d7c2 --- /dev/null +++ b/tests/Integration/InMemoryClient.Tests.ps1 @@ -0,0 +1,231 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseCorrectCasing', '', Justification = 'PSScriptAnalyzer attributes -ScriptBlock of commands nested in BeforeAll to BeforeAll itself.')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'A fixture tool writes to the host on purpose to prove that host output never reaches the client.')] +param() + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force + + $script:server = New-McpServer -Name 'memory' -Version '1.2.3' -Title 'In memory' -Instructions 'Test server.' -PageSize 2 -RequestTimeoutSeconds 5 + Register-McpTool -Name 'echo' -Description 'Echoes.' -ScriptBlock { param([Parameter(Mandatory)][string] $Text) $Text } -Server $script:server + Register-McpTool -Name 'add' -ScriptBlock { param([int] $A, [int] $B) [pscustomobject]@{ sum = $A + $B } } -OutputSchema @{ type = 'object'; properties = @{ sum = @{ type = 'integer' } }; required = @('sum') } -Server $script:server + Register-McpTool -Name 'count' -ScriptBlock { + param([int] $To = 3, [int] $DelayMs = 20, $Context) + for ($i = 1; $i -le $To; $i++) { + if ($Context.CancellationToken.IsCancellationRequested) { return "cancelled at $i" } + Write-McpProgress -Context $Context -Progress $i -Total $To -Message "step $i" + Write-McpLog -Context $Context -Level info -Message "log $i" -Logger 'counter' + Start-Sleep -Milliseconds $DelayMs + } + "counted to $To" + } -Server $script:server + Register-McpTool -Name 'fail' -ScriptBlock { throw 'nope' } -Server $script:server + Register-McpTool -Name 'context' -ScriptBlock { param($Context) [pscustomobject]@{ id = $Context.RequestId; version = $Context.ProtocolVersion; client = $Context.ClientInfo['name']; elicitation = (Test-McpClientCapability -Context $Context -Path 'elicitation.form') } } -Server $script:server + Register-McpTool -Name 'host' -ScriptBlock { Write-Host 'to the host'; Write-Warning 'warned'; Write-Verbose 'verbose'; 'clean' } -Server $script:server + $script:session = Connect-McpServer -Server $script:server -ClientInfo @{ name = 'pester'; version = '1' } -Capabilities @{ elicitation = @{ form = @{} } } +} + +AfterAll { + if ($script:session) { Disconnect-McpServer -Session $script:session } +} + +Describe 'Connect-McpServer over the in-memory transport' { + It 'probes server/discover and exposes the server info' { + $script:session.PSObject.TypeNames | Should -Contain 'Mcp.Session' + $script:session.Kind | Should -Be 'InMemory' + $script:session.ProtocolVersion | Should -Be '2026-07-28' + $script:session.Name | Should -Be 'memory' + $info = Get-McpServerInfo -Session $script:session + $info.PSObject.TypeNames | Should -Contain 'Mcp.ServerInfo' + $info.Name | Should -Be 'memory' + $info.Version | Should -Be '1.2.3' + $info.Title | Should -Be 'In memory' + $info.Instructions | Should -Be 'Test server.' + $info.SupportedVersions | Should -Be @('2026-07-28') + $info.Capabilities['tools']['listChanged'] | Should -BeFalse + (Get-McpServerInfo -Session $script:session -Refresh).Name | Should -Be 'memory' + } + + It 'is the default session' { + (Get-McpServerInfo).Name | Should -Be 'memory' + } + + It 'lists tools across pages' { + $tools = Get-McpTool -Session $script:session + @($tools | ForEach-Object Name) | Should -Be @('echo', 'add', 'count', 'fail', 'context', 'host') + $tools[0].PSObject.TypeNames | Should -Contain 'Mcp.Tool' + $tools[0].Description | Should -Be 'Echoes.' + $tools[0].InputSchema['required'] | Should -Be @('Text') + (Get-McpTool -Name 'add' -Session $script:session).OutputSchema['required'] | Should -Be @('sum') + { Get-McpTool -Name 'missing' -Session $script:session } | Should -Throw -ExpectedMessage '*no tool named*' + } + + It 'calls a tool and returns text' { + $result = Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'héllo 😀' } -Session $script:session + $result.PSObject.TypeNames | Should -Contain 'Mcp.ToolResult' + $result.IsError | Should -BeFalse + $result.Text | Should -Be 'héllo 😀' + $result.Content[0].type | Should -Be 'text' + $result.ResultType | Should -Be 'complete' + $result.Meta['io.modelcontextprotocol/serverInfo']['name'] | Should -Be 'memory' + } + + It 'returns structured content validated against the output schema' { + $result = Invoke-McpTool -Name 'add' -Arguments @{ A = 2; B = 3 } -Session $script:session + $result.StructuredContent['sum'] | Should -Be 5 + $result.Text | Should -Be '{"sum":5}' + } + + It 'delivers progress and log notifications while a call runs' { + $progress = [System.Collections.Generic.List[object]]::new() + $script:session.Log.Clear() + $result = Invoke-McpTool -Name 'count' -Arguments @{ To = 3 } -OnProgress { param($p) $progress.Add($p) } -LogLevel info -Session $script:session + $result.Text | Should -Be 'counted to 3' + @($progress | ForEach-Object Progress) | Should -Be @(1, 2, 3) + $progress[0].Total | Should -Be 3 + $progress[2].Message | Should -Be 'step 3' + $script:session.Log.Count | Should -Be 3 + $script:session.Log[0].Level | Should -Be 'info' + $script:session.Log[0].Logger | Should -Be 'counter' + $script:session.Log[0].Data | Should -Be 'log 1' + } + + It 'does not send log notifications without a log level' { + $script:session.Log.Clear() + $null = Invoke-McpTool -Name 'count' -Arguments @{ To = 1 } -Session $script:session + $script:session.Log.Count | Should -Be 0 + } + + It 'passes the request context to handlers' { + $result = Invoke-McpTool -Name 'context' -Session $script:session + $result.StructuredContent['version'] | Should -Be '2026-07-28' + $result.StructuredContent['client'] | Should -Be 'pester' + $result.StructuredContent['elicitation'] | Should -BeTrue + $result.StructuredContent['id'] | Should -BeGreaterThan 0 + } + + It 'returns tool execution errors as results with IsError' { + $result = Invoke-McpTool -Name 'fail' -Session $script:session + $result.IsError | Should -BeTrue + $result.Text | Should -Be 'Error: nope' + } + + It 'throws protocol errors for unknown tools and invalid arguments' { + $exception = $null + try { Invoke-McpTool -Name 'missing' -Session $script:session } catch { $exception = $_.Exception } + $exception | Should -BeOfType [McpProtocolException] + $exception.Code | Should -Be -32602 + try { Invoke-McpTool -Name 'echo' -Arguments @{ Text = 5 } -Session $script:session } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32602 + $exception.Data['errors'] | Should -Not -BeNullOrEmpty + } + + It 'keeps host and stream output of handlers away from the client' { + $result = Invoke-McpTool -Name 'host' -Session $script:session + $result.Text | Should -Be 'clean' + $result.IsError | Should -BeFalse + $result.Content.Count | Should -Be 1 + } + + It 'cancels a call on timeout and the session stays usable' { + { Invoke-McpTool -Name 'count' -Arguments @{ To = 100; DelayMs = 100 } -TimeoutSeconds 1 -Session $script:session } | Should -Throw -ExceptionType ([System.TimeoutException]) + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'alive' } -Session $script:session).Text | Should -Be 'alive' + } + + It 'enforces the server-side request timeout' { + $slow = New-McpServer -Name 'slow' -Version '1' -RequestTimeoutSeconds 1 + Register-McpTool -Name 'sleep' -ScriptBlock { Start-Sleep -Seconds 30; 'late' } -Server $slow + $session = Connect-McpServer -Server $slow + try { + $exception = $null + try { Invoke-McpTool -Name 'sleep' -Session $session } catch { $exception = $_.Exception } + $exception | Should -BeOfType [McpProtocolException] + $exception.Code | Should -Be -32603 + $exception.Message | Should -Match 'timed out' + } finally { + Disconnect-McpServer -Session $session + } + } + + It 'runs handlers concurrently up to MaxConcurrency' { + $parallel = New-McpServer -Name 'parallel' -Version '1' -MaxConcurrency 4 + Register-McpTool -Name 'sleep' -ScriptBlock { param([int] $Ms) Start-Sleep -Milliseconds $Ms; 'ok' } -Server $parallel + $pair = Invoke-McpInModule { New-McpInMemoryTransportPair } + $background = Invoke-McpInModule { param($s, $e) Start-McpBackgroundServer -Server $s -Endpoint $e } $parallel $pair.Server + try { + $meta = '"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}' + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + foreach ($n in 1..4) { + Invoke-McpInModule { param($t, $l) Send-McpTransportLine -Transport $t -Line $l } $pair.Client "{`"jsonrpc`":`"2.0`",`"id`":$n,`"method`":`"tools/call`",`"params`":{$meta,`"name`":`"sleep`",`"arguments`":{`"Ms`":400}}}" + } + $responses = foreach ($n in 1..4) { + $received = Invoke-McpInModule { param($t) Receive-McpTransportLine -Transport $t -TimeoutMs 10000 } $pair.Client + $received.Status | Should -Be 'Line' + Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } $received.Line + } + $stopwatch.Stop() + @($responses | ForEach-Object { $_['result']['content'][0]['text'] }) | Should -Be @('ok', 'ok', 'ok', 'ok') + $stopwatch.ElapsedMilliseconds | Should -BeLessThan 1500 + } finally { + Invoke-McpInModule { param($t) Close-McpTransport -Transport $t } $pair.Client + Invoke-McpInModule { param($b) Stop-McpBackgroundServer -Background $b } $background + } + } + + It 'answers raw protocol violations like the specification requires' { + $raw = New-McpServer -Name 'raw' -Version '1' + 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 + try { + $send = { param($line) Invoke-McpInModule { param($t, $l) Send-McpTransportLine -Transport $t -Line $l } $pair.Client $line } + $receive = { + $received = Invoke-McpInModule { param($t) Receive-McpTransportLine -Transport $t -TimeoutMs 10000 } $pair.Client + $received.Status | Should -Be 'Line' + Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } $received.Line + } + & $send 'not json' + $parseError = & $receive + $parseError['id'] | Should -BeNull + $parseError['error']['code'] | Should -Be -32700 + & $send '{"jsonrpc":"2.0","id":null,"method":"tools/list"}' + (& $receive)['error']['code'] | Should -Be -32600 + & $send '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' + (& $receive)['error']['code'] | Should -Be -32602 + & $send '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"1999-01-01","io.modelcontextprotocol/clientCapabilities":{}}}}' + $version = & $receive + $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"}}}' + $legacy = & $receive + $legacy['error']['code'] | Should -Be -32601 + $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 + & $send '{"jsonrpc":"2.0","id":"s-1","method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"echo","arguments":{"Text":"id kept"}}}' + $response = & $receive + $response['id'] | Should -BeOfType [string] + $response['id'] | Should -Be 's-1' + $response['result']['content'][0]['text'] | Should -Be 'id kept' + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $response['result']).IsValid | Should -BeTrue + & $send '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"never-sent"}}' + & $send '{"jsonrpc":"2.0","id":5,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}' + $discover = & $receive + $discover['id'] | Should -Be 5 + (Test-McpSpecShape -Definition 'DiscoverResult' -Instance $discover['result']).IsValid | Should -BeTrue + } finally { + Invoke-McpInModule { param($t) Close-McpTransport -Transport $t } $pair.Client + Invoke-McpInModule { param($b) Stop-McpBackgroundServer -Background $b } $background + } + } + + It 'stops the background server on disconnect' { + $server = New-McpServer -Name 'short' -Version '1' + $session = Connect-McpServer -Server $server + $server.State.Started | Should -BeTrue + Disconnect-McpServer -Session $session + $session.Closed | Should -BeTrue + $server.State.Started | Should -BeFalse + { Get-McpServerInfo -Session $session } | Should -Throw -ExpectedMessage '*closed*' + } +} diff --git a/tests/Integration/StdioServer.Tests.ps1 b/tests/Integration/StdioServer.Tests.ps1 new file mode 100644 index 0000000..6cc0106 --- /dev/null +++ b/tests/Integration/StdioServer.Tests.ps1 @@ -0,0 +1,128 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + $script:manifest = Get-McpBuiltModuleManifest + Import-Module $script:manifest -Force + $script:pwsh = Get-McpPowerShellPath + $script:serverScript = Join-Path (Get-McpRepositoryRoot) 'examples' 'echo-server.ps1' + $script:serverArguments = @('-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $script:serverScript) + $env:MCP_MODULE_MANIFEST = $script:manifest + $env:POWERSHELL_TELEMETRY_OPTOUT = '1' +} + +Describe 'The example server over stdio' -Tag 'Integration' { + BeforeAll { + $script:stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + $script:session = Connect-McpServer -Command $script:pwsh -Arguments $script:serverArguments -ConnectTimeoutSeconds 60 + $script:connectMs = $script:stopwatch.ElapsedMilliseconds + } + + AfterAll { + if ($script:session) { Disconnect-McpServer -Session $script:session } + } + + It 'connects, discovers and lists the tools' { + $script:session.Kind | Should -Be 'Process' + $script:session.Name | Should -Be 'echo' + (Get-McpServerInfo -Session $script:session).Title | Should -Be 'Echo server' + @(Get-McpTool -Session $script:session | ForEach-Object Name) | Should -Be @('echo', 'add', 'count', 'fail', 'shout') + Write-Verbose "Connected in $($script:connectMs) ms" -Verbose:$false + } + + It 'round-trips non-ASCII text and a 1 MB payload' { + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'héllo 😀 日本'; Repeat = 2 } -Session $script:session).Text | Should -Be 'héllo 😀 日本héllo 😀 日本' + $big = 'x' * 1MB + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = $big } -Session $script:session).Text.Length | Should -Be 1MB + } + + It 'returns structured content, error results and progress' { + (Invoke-McpTool -Name 'add' -Arguments @{ A = 1.5; B = 2 } -Session $script:session).StructuredContent['sum'] | Should -Be 3.5 + (Invoke-McpTool -Name 'fail' -Session $script:session).IsError | Should -BeTrue + $progress = [System.Collections.Generic.List[object]]::new() + (Invoke-McpTool -Name 'count' -Arguments @{ To = 2; DelayMs = 10 } -OnProgress { param($p) $progress.Add($p.Progress) } -Session $script:session).Text | Should -Be 'counted to 2' + @($progress) | Should -Be @(1, 2) + } + + It 'keeps Write-Host and streams of handlers off stdout and logs warnings to stderr' { + $result = Invoke-McpTool -Name 'shout' -Arguments @{ Text = 'quiet' } -Session $script:session + $result.Text | Should -Be 'QUIET' + $result.Content.Count | Should -Be 1 + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'still fine' } -Session $script:session).Text | Should -Be 'still fine' + Get-Content -Path $script:session.StandardErrorPath -Raw | Should -Match 'a warning for the server log' + } + + It 'recovers from a client-side timeout' { + { Invoke-McpTool -Name 'count' -Arguments @{ To = 100; DelayMs = 100 } -TimeoutSeconds 1 -Session $script:session } | Should -Throw -ExceptionType ([System.TimeoutException]) + (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'alive' } -Session $script:session).Text | Should -Be 'alive' + } + + It 'answers 20 calls in well under a second each' { + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + 1..20 | ForEach-Object { $null = Invoke-McpTool -Name 'echo' -Arguments @{ Text = "x$_" } -Session $script:session } + ($stopwatch.ElapsedMilliseconds / 20) | Should -BeLessThan 1000 + } +} + +Describe 'Raw stdio behaviour of the example server' -Tag 'Integration' { + BeforeAll { + function script:Invoke-RawServer { + param([string[]] $Lines, [int] $TimeoutSeconds = 60) + $startInfo = [System.Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $script:pwsh + foreach ($argument in $script:serverArguments) { $startInfo.ArgumentList.Add($argument) } + $startInfo.UseShellExecute = $false + $startInfo.RedirectStandardInput = $true + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $startInfo.StandardInputEncoding = [System.Text.UTF8Encoding]::new($false) + $process = [System.Diagnostics.Process]::Start($startInfo) + try { + $stdoutTask = $process.StandardOutput.BaseStream.CopyToAsync(($stdout = [System.IO.MemoryStream]::new())) + $stderrTask = $process.StandardError.ReadToEndAsync() + $process.StandardInput.NewLine = "`n" + foreach ($line in $Lines) { $process.StandardInput.WriteLine($line) } + $process.StandardInput.Flush() + Start-Sleep -Milliseconds 1500 + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + $process.StandardInput.Close() + $exited = $process.WaitForExit($TimeoutSeconds * 1000) + if (-not $exited) { $process.Kill($true) } + $null = $stdoutTask.Wait(5000) + @{ + Exited = $exited + ExitMs = $stopwatch.ElapsedMilliseconds + ExitCode = if ($exited) { $process.ExitCode } else { $null } + StdOutBytes = $stdout.ToArray() + StdOut = [System.Text.Encoding]::UTF8.GetString($stdout.ToArray()) + StdErr = $stderrTask.GetAwaiter().GetResult() + } + } finally { + $process.Dispose() + } + } + } + + It 'writes nothing but JSON lines to stdout, without a BOM, and exits promptly when stdin closes' { + $meta = '"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}' + $result = Invoke-RawServer -Lines @( + "{`"jsonrpc`":`"2.0`",`"id`":1,`"method`":`"server/discover`",`"params`":{$meta}}" + 'garbage' + "{`"jsonrpc`":`"2.0`",`"id`":2,`"method`":`"tools/call`",`"params`":{$meta,`"name`":`"shout`",`"arguments`":{`"Text`":`"x`"}}}" + ) + $result.Exited | Should -BeTrue + $result.ExitMs | Should -BeLessThan 15000 + $result.ExitCode | Should -Be 0 + $result.StdOutBytes.Count | Should -BeGreaterThan 3 + ($result.StdOutBytes[0] -eq 0xEF -and $result.StdOutBytes[1] -eq 0xBB) | Should -BeFalse + $result.StdOut | Should -Not -Match "`r" + $lines = @($result.StdOut -split "`n" | Where-Object { $_ -ne '' }) + $lines.Count | Should -Be 3 + foreach ($line in $lines) { { Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } $line } | Should -Not -Throw } + $messages = $lines | ForEach-Object { Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } $_ } + $messages[0]['id'] | Should -Be 1 + $messages[0]['result']['supportedVersions'] | Should -Be @('2026-07-28') + $messages[1]['error']['code'] | Should -Be -32700 + $messages[2]['result']['content'][0]['text'] | Should -Be 'X' + $result.StdOut | Should -Not -Match 'host output must not reach stdout' + $result.StdErr | Should -Match 'a warning for the server log' + } +} diff --git a/tests/Support/McpTestSupport.psm1 b/tests/Support/McpTestSupport.psm1 index aa56cf9..d39c11e 100644 --- a/tests/Support/McpTestSupport.psm1 +++ b/tests/Support/McpTestSupport.psm1 @@ -151,3 +151,181 @@ function Get-McpPowerShellPath { } Export-ModuleMember -Function Get-McpRepositoryRoot, Get-McpBuiltModuleManifest, Get-McpSpecSchemaPath, Get-McpSpecSchema, Get-McpSpecDefinition, Invoke-McpChildProcess, Get-McpPowerShellPath + +function Invoke-McpInModule { + <# + .SYNOPSIS + Runs a script block in the scope of the imported ModelContextProtocol module (access to private functions). + #> + [CmdletBinding()] + [OutputType([object])] + param( + [Parameter(Mandatory, Position = 0)] + [scriptblock] $ScriptBlock, + + # Named arguments for the script block's param() block; use this for arrays and other enumerables, + # which positional binding would unroll. + [hashtable] $Parameters = @{}, + + [Parameter(Position = 1, ValueFromRemainingArguments)] + [object[]] $ArgumentList = @() + ) + + $module = Get-Module -Name ModelContextProtocol + if (-not $module) { throw 'The ModelContextProtocol module is not imported.' } + & $module $ScriptBlock @Parameters @ArgumentList +} + +function Test-McpSpecShape { + <# + .SYNOPSIS + Validates a wire object against a definition of the vendored specification schema; returns IsValid and Errors. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [string] $Definition, + + [Parameter(Mandatory)] + [AllowNull()] + [object] $Instance, + + [string] $Revision = '2026-07-28' + ) + + $definitions = Get-McpSpecDefinition -Revision $Revision + $schema = @{ '$ref' = "#/`$defs/$Definition"; '$defs' = $definitions } + Invoke-McpInModule { param($s, $i) Test-McpJsonSchema -Schema $s -Instance $i } -Parameters @{ s = $schema; i = $Instance } +} + +function Get-McpFreeTcpPort { + <# + .SYNOPSIS + A TCP port on the loopback interface that is free at the time of the call. + #> + [CmdletBinding()] + [OutputType([int])] + param() + + $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) + $listener.Start() + try { + $listener.LocalEndpoint.Port + } finally { + $listener.Stop() + } +} + +function Start-McpTestHttpServer { + <# + .SYNOPSIS + Runs a server object over Streamable HTTP on a free loopback port in a background runspace; returns a handle with Url, Port, Server and Background. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper.')] + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Server, + + [hashtable] $Parameters = @{}, + + [int] $TimeoutSeconds = 15 + ) + + $port = Get-McpFreeTcpPort + $url = "http://127.0.0.1:$port/mcp/" + $startParameters = @{ Transport = 'Http'; Url = $url } + foreach ($key in $Parameters.Keys) { $startParameters[$key] = $Parameters[$key] } + $background = Invoke-McpInModule { param($s, $p) Start-McpBackgroundServer -Server $s -Parameters $p } -Parameters @{ s = $Server; p = $startParameters } + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + while (-not $Server.State.Started) { + if ($background.PowerShell.InvocationStateInfo.State -in @('Failed', 'Completed', 'Stopped')) { + throw "The HTTP test server did not start: $($background.PowerShell.InvocationStateInfo.Reason)" + } + if ($stopwatch.Elapsed.TotalSeconds -gt $TimeoutSeconds) { throw "The HTTP test server did not start within $TimeoutSeconds seconds." } + Start-Sleep -Milliseconds 25 + } + @{ Url = $url; Port = $port; Server = $Server; Background = $background } +} + +function Stop-McpTestHttpServer { + <# + .SYNOPSIS + Stops a server started with Start-McpTestHttpServer and waits for its runspace. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [hashtable] $Handle + ) + + Stop-McpServer -Server $Handle.Server + Invoke-McpInModule { param($b) Stop-McpBackgroundServer -Background $b -TimeoutSeconds 20 } -Parameters @{ b = $Handle.Background } +} + +function Invoke-McpRawHttp { + <# + .SYNOPSIS + Sends one raw HTTP request (no proxy) and returns Status, ContentType, Headers, Body and, when the body is JSON, Json (hashtables). + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [string] $Url, + + [AllowNull()] + [AllowEmptyString()] + [string] $Body, + + [hashtable] $Headers = @{}, + + [string] $Method = 'POST', + + [string] $ContentType = 'application/json', + + [int] $TimeoutSeconds = 30 + ) + + $handler = [System.Net.Http.SocketsHttpHandler]::new() + $handler.UseProxy = $false + $handler.AllowAutoRedirect = $false + $client = [System.Net.Http.HttpClient]::new($handler) + $client.Timeout = [timespan]::FromSeconds($TimeoutSeconds) + try { + $request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::new($Method), $Url) + if ($null -ne $Body) { + $request.Content = [System.Net.Http.ByteArrayContent]::new([System.Text.Encoding]::UTF8.GetBytes($Body)) + if ($ContentType) { $request.Content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::new($ContentType) } + } + foreach ($key in $Headers.Keys) { $null = $request.Headers.TryAddWithoutValidation([string] $key, [string] $Headers[$key]) } + $response = $client.SendAsync($request).GetAwaiter().GetResult() + try { + $text = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() + $json = $null + if ($text -and $response.Content.Headers.ContentType -and $response.Content.Headers.ContentType.MediaType -eq 'application/json') { + try { $json = ConvertFrom-Json -InputObject $text -AsHashtable -Depth 50 } catch { $json = $null } + } + $headerTable = @{} + foreach ($header in $response.Headers) { $headerTable[$header.Key] = @($header.Value) -join ', ' } + foreach ($header in $response.Content.Headers) { $headerTable[$header.Key] = @($header.Value) -join ', ' } + @{ + Status = [int] $response.StatusCode + ContentType = if ($response.Content.Headers.ContentType) { $response.Content.Headers.ContentType.MediaType } else { $null } + Headers = $headerTable + Body = $text + Json = $json + } + } finally { + $response.Dispose() + } + } finally { + $client.Dispose() + $handler.Dispose() + } +} + +Export-ModuleMember -Function Invoke-McpInModule, Test-McpSpecShape, Get-McpFreeTcpPort, Start-McpTestHttpServer, Stop-McpTestHttpServer, Invoke-McpRawHttp diff --git a/tests/Unit/Header.Tests.ps1 b/tests/Unit/Header.Tests.ps1 new file mode 100644 index 0000000..319089a --- /dev/null +++ b/tests/Unit/Header.Tests.ps1 @@ -0,0 +1,268 @@ +[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 'Header value encoding (SEP-2243 value encoding table)' { + It 'encodes as ' -TestCases @( + @{ Name = 'plain ASCII'; Value = 'us-west1'; Type = 'string'; Expected = 'us-west1' } + @{ Name = 'internal spaces'; Value = 'us west 1'; Type = 'string'; Expected = 'us west 1' } + @{ Name = 'an empty string'; Value = ''; Type = 'string'; Expected = '' } + @{ Name = 'non-ASCII text'; Value = 'Hello, 世界'; Type = 'string'; Expected = '=?base64?SGVsbG8sIOS4lueVjA==?=' } + @{ Name = 'padded text'; Value = ' padded '; Type = 'string'; Expected = '=?base64?IHBhZGRlZCA=?=' } + @{ Name = 'a newline'; Value = "line1`nline2"; Type = 'string'; Expected = '=?base64?bGluZTEKbGluZTI=?=' } + @{ Name = 'the sentinel pattern itself'; Value = '=?base64?literal?='; Type = 'string'; Expected = '=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=' } + @{ Name = 'a leading tab'; Value = "`tindented"; Type = 'string'; Expected = '=?base64?CWluZGVudGVk?=' } + @{ Name = 'an integer'; Value = 42; Type = 'integer'; Expected = '42' } + @{ Name = 'a negative long'; Value = [long] -7; Type = 'integer'; Expected = '-7' } + @{ Name = 'an integral double'; Value = [double] 42; Type = 'integer'; Expected = '42' } + @{ Name = 'true'; Value = $true; Type = 'boolean'; Expected = 'true' } + @{ Name = 'false'; Value = $false; Type = 'boolean'; Expected = 'false' } + ) { + Invoke-McpInModule { param($v, $t) ConvertTo-McpHeaderValue -Value $v -Type $t } -Parameters @{ v = $Value; t = $Type } | Should -BeExactly $Expected + } + + It 'rejects non-integral and non-boolean values for integer and boolean headers' { + { Invoke-McpInModule { ConvertTo-McpHeaderValue -Value 1.5 -Type integer } } | Should -Throw -ExpectedMessage '*integral*' + { Invoke-McpInModule { ConvertTo-McpHeaderValue -Value 'yes' -Type boolean } } | Should -Throw -ExpectedMessage '*boolean*' + } + + It 'decodes the sentinel, trims whitespace and keeps literals' { + Invoke-McpInModule { ConvertFrom-McpHeaderValue -Value '=?base64?SGVsbG8sIOS4lueVjA==?=' } | Should -BeExactly 'Hello, 世界' + Invoke-McpInModule { ConvertFrom-McpHeaderValue -Value ' echo ' } | Should -BeExactly 'echo' + Invoke-McpInModule { ConvertFrom-McpHeaderValue -Value 'SGVsbG8=' } | Should -BeExactly 'SGVsbG8=' + Invoke-McpInModule { ConvertFrom-McpHeaderValue -Value '=?base64?SGVsbG8=' } | Should -BeExactly '=?base64?SGVsbG8=' + Invoke-McpInModule { ConvertFrom-McpHeaderValue -Value '=?base64??=' } | Should -BeExactly '' + } + + It 'reports malformed Base64 in the sentinel as a header mismatch' -TestCases @( + @{ Value = '=?base64?SGVsbG8?=' } + @{ Value = '=?base64?SGVs!!!bG8=?=' } + ) { + $exception = $null + try { Invoke-McpInModule { param($v) ConvertFrom-McpHeaderValue -Value $v } -Parameters @{ v = $Value } } catch { $exception = $_.Exception } + $exception | Should -BeOfType [McpProtocolException] + $exception.Code | Should -Be -32020 + } + + It 'compares integers numerically, booleans and strings exactly' { + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue '42.0' -BodyValue 42 -Type integer } | Should -BeTrue + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue '41' -BodyValue 42 -Type integer } | Should -BeFalse + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue '42' -BodyValue '42' -Type integer } | Should -BeFalse + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue 'true' -BodyValue $true -Type boolean } | Should -BeTrue + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue 'True' -BodyValue $true -Type boolean } | Should -BeFalse + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue 'Region' -BodyValue 'region' -Type string } | Should -BeFalse + Invoke-McpInModule { Test-McpHeaderValueMatch -HeaderValue 'x' -BodyValue $null -Type string } | Should -BeFalse + } + + It 'derives Mcp-Name from params.name or params.uri for the named methods only' { + Invoke-McpInModule { Get-McpStandardHeaderName -Method 'tools/call' -Params ([ordered]@{ name = 'echo' }) } | Should -Be 'echo' + Invoke-McpInModule { Get-McpStandardHeaderName -Method 'prompts/get' -Params ([ordered]@{ name = 'p' }) } | Should -Be 'p' + Invoke-McpInModule { Get-McpStandardHeaderName -Method 'resources/read' -Params ([ordered]@{ uri = 'file:///a' }) } | Should -Be 'file:///a' + Invoke-McpInModule { Get-McpStandardHeaderName -Method 'tools/list' -Params ([ordered]@{ name = 'x' }) } | Should -BeNullOrEmpty + Invoke-McpInModule { Get-McpStandardHeaderName -Method 'tools/call' -Params ([ordered]@{ name = 5 }) } | Should -BeNullOrEmpty + } +} + +Describe 'x-mcp-header annotations (SEP-2243 schema extension)' { + It 'collects annotations reachable through properties chains with their paths and types' { + $schema = [ordered]@{ + type = 'object' + properties = [ordered]@{ + region = [ordered]@{ type = 'string'; 'x-mcp-header' = 'Region' } + options = [ordered]@{ type = 'object'; properties = [ordered]@{ priority = [ordered]@{ type = 'integer'; 'x-mcp-header' = 'Priority' } } } + verbose = [ordered]@{ type = 'boolean'; 'x-mcp-header' = 'Verbose' } + query = [ordered]@{ type = 'string' } + } + } + $parameters = @(Invoke-McpInModule { param($s) Get-McpToolHeaderParameter -InputSchema $s } -Parameters @{ s = $schema }) + $parameters.Count | Should -Be 3 + @($parameters | ForEach-Object { ($_.Path -join '.') + '=' + $_.Header + ':' + $_.Type }) | Should -Be @('region=Region:string', 'options.priority=Priority:integer', 'verbose=Verbose:boolean') + @(Invoke-McpInModule { Get-McpToolHeaderParameter -InputSchema ([ordered]@{ type = 'object' }) }).Count | Should -Be 0 + @(Invoke-McpInModule { Get-McpToolHeaderParameter -InputSchema $null }).Count | Should -Be 0 + } + + It 'rejects ' -TestCases @( + @{ Name = 'an empty header name'; Property = @{ type = 'string'; 'x-mcp-header' = '' }; Reason = 'non-empty' } + @{ Name = 'an object-typed property'; Property = @{ type = 'object'; 'x-mcp-header' = 'Data' }; Reason = 'only string, integer and boolean' } + @{ Name = 'an array-typed property'; Property = @{ type = 'array'; items = @{ type = 'string' }; 'x-mcp-header' = 'Items' }; Reason = 'only string, integer and boolean' } + @{ Name = 'a null-typed property'; Property = @{ type = 'null'; 'x-mcp-header' = 'Nil' }; Reason = 'only string, integer and boolean' } + @{ Name = 'a number-typed property'; Property = @{ type = 'number'; 'x-mcp-header' = 'Amount' }; Reason = 'only string, integer and boolean' } + @{ Name = 'a property without a type'; Property = @{ 'x-mcp-header' = 'Untyped' }; Reason = 'only string, integer and boolean' } + @{ Name = 'a space in the header name'; Property = @{ type = 'string'; 'x-mcp-header' = 'My Region' }; Reason = 'field-name token' } + @{ Name = 'a colon in the header name'; Property = @{ type = 'string'; 'x-mcp-header' = 'Region:Primary' }; Reason = 'field-name token' } + @{ Name = 'a non-ASCII header name'; Property = @{ type = 'string'; 'x-mcp-header' = 'Région' }; Reason = 'field-name token' } + @{ Name = 'a control character in the header name'; Property = @{ type = 'string'; 'x-mcp-header' = "Region`t1" }; Reason = 'field-name token' } + @{ Name = 'a non-string header name'; Property = @{ type = 'string'; 'x-mcp-header' = 5 }; Reason = 'non-empty string' } + ) { + $schema = @{ type = 'object'; properties = @{ value = $Property } } + { Invoke-McpInModule { param($s) Get-McpToolHeaderParameter -InputSchema $s } -Parameters @{ s = $schema } } | Should -Throw -ExpectedMessage "*$Reason*" + } + + It 'rejects duplicate header names, also across letter case' { + $same = @{ type = 'object'; properties = @{ a = @{ type = 'string'; 'x-mcp-header' = 'Region' }; b = @{ type = 'string'; 'x-mcp-header' = 'Region' } } } + { Invoke-McpInModule { param($s) Get-McpToolHeaderParameter -InputSchema $s } -Parameters @{ s = $same } } | Should -Throw -ExpectedMessage '*more than once*' + $mixed = @{ type = 'object'; properties = @{ a = @{ type = 'string'; 'x-mcp-header' = 'MyField' }; b = @{ type = 'string'; 'x-mcp-header' = 'myfield' } } } + { Invoke-McpInModule { param($s) Get-McpToolHeaderParameter -InputSchema $s } -Parameters @{ s = $mixed } } | Should -Throw -ExpectedMessage '*more than once*' + } + + It 'rejects annotations that are not statically reachable' -TestCases @( + @{ Name = 'inside items'; Schema = @{ type = 'object'; properties = @{ list = @{ type = 'array'; items = @{ type = 'string'; 'x-mcp-header' = 'Item' } } } } } + @{ Name = 'inside anyOf'; Schema = @{ type = 'object'; properties = @{ v = @{ anyOf = @(@{ type = 'string'; 'x-mcp-header' = 'V' }, @{ type = 'integer' }) } } } } + @{ Name = 'inside $defs'; Schema = @{ type = 'object'; '$defs' = @{ region = @{ type = 'string'; 'x-mcp-header' = 'Region' } }; properties = @{ region = @{ '$ref' = '#/$defs/region' } } } } + @{ Name = 'inside then'; Schema = @{ type = 'object'; if = @{ properties = @{ a = @{ const = 1 } } }; then = @{ properties = @{ b = @{ type = 'string'; 'x-mcp-header' = 'B' } } } } } + @{ Name = 'on the root'; Schema = @{ type = 'object'; 'x-mcp-header' = 'Root'; properties = @{} } } + ) { + { Invoke-McpInModule { param($s) Get-McpToolHeaderParameter -InputSchema $s } -Parameters @{ s = $Schema } } | Should -Throw -ExpectedMessage '*reachable*' + } + + It 'builds Mcp-Param headers from arguments and omits absent or null values' { + $parameters = @( + @{ Path = @('region'); Header = 'Region'; Type = 'string' } + @{ Path = @('priority'); Header = 'Priority'; Type = 'integer' } + @{ Path = @('verbose'); Header = 'Verbose'; Type = 'boolean' } + @{ Path = @('nested', 'value'); Header = 'Nested'; Type = 'string' } + ) + $arguments = [ordered]@{ region = 'Hello, 世界'; priority = 3; verbose = $null; nested = [ordered]@{ value = 'x' }; query = 'q' } + $headers = Invoke-McpInModule { param($p, $a) Get-McpToolCallHeader -HeaderParameters $p -Arguments $a } -Parameters @{ p = $parameters; a = $arguments } + $headers.Count | Should -Be 3 + $headers['Mcp-Param-Region'] | Should -Be '=?base64?SGVsbG8sIOS4lueVjA==?=' + $headers['Mcp-Param-Priority'] | Should -Be '3' + $headers['Mcp-Param-Nested'] | Should -Be 'x' + (Invoke-McpInModule { param($p) Get-McpToolCallHeader -HeaderParameters $p -Arguments $null } -Parameters @{ p = $parameters }).Count | Should -Be 0 + } + + It 'validates received Mcp-Param headers against the body' { + $parameters = @(@{ Path = @('region'); Header = 'Region'; Type = 'string' }, @{ Path = @('priority'); Header = 'Priority'; Type = 'integer' }) + $check = { + param($headerTable, $arguments) + $collection = [System.Collections.Specialized.NameValueCollection]::new() + foreach ($key in $headerTable.Keys) { $collection.Add($key, $headerTable[$key]) } + try { + Invoke-McpInModule { param($p, $a, $h) Test-McpToolParameterHeader -HeaderParameters $p -Arguments $a -Headers $h } -Parameters @{ p = $parameters; a = $arguments; h = $collection } + 'accepted' + } catch { + "$($_.Exception.Code)" + } + } + & $check @{ 'Mcp-Param-Region' = 'Hello'; 'mcp-param-priority' = '42.0' } ([ordered]@{ region = 'Hello'; priority = 42 }) | Should -Be 'accepted' + & $check @{ 'Mcp-Param-Region' = '=?base64?SGVsbG8=?=' } ([ordered]@{ region = 'Hello' }) | Should -Be 'accepted' + & $check @{ 'Mcp-Param-Region' = 'SGVsbG8=' } ([ordered]@{ region = 'SGVsbG8=' }) | Should -Be 'accepted' + & $check @{} ([ordered]@{ query = 'q' }) | Should -Be 'accepted' + & $check @{} ([ordered]@{ region = $null }) | Should -Be 'accepted' + & $check @{} ([ordered]@{ region = 'Hello' }) | Should -Be '-32020' + & $check @{ 'Mcp-Param-Region' = 'World' } ([ordered]@{ region = 'Hello' }) | Should -Be '-32020' + & $check @{ 'Mcp-Param-Region' = '=?base64?SGVsbG8?=' } ([ordered]@{ region = 'Hello' }) | Should -Be '-32020' + & $check @{ 'Mcp-Param-Region' = 'Hello' } ([ordered]@{ query = 'q' }) | Should -Be '-32020' + & $check @{ 'Mcp-Param-Priority' = '41' } ([ordered]@{ priority = 42 }) | Should -Be '-32020' + } +} + +Describe 'Register-McpTool -Header' { + It 'annotates the generated schema and records the header parameters' { + $server = New-McpServer -Name 'headers' -Version '1' + $registration = Register-McpTool -Name 'lookup' -ScriptBlock { param([Parameter(Mandatory)][string] $Region, [int] $Priority = 1, [string] $Query = '') "$Region $Priority $Query" } -Header @{ region = 'Region'; Priority = 'Priority' } -Server $server -PassThru + $registration.InputSchema['properties']['Region']['x-mcp-header'] | Should -Be 'Region' + $registration.InputSchema['properties']['Priority']['x-mcp-header'] | Should -Be 'Priority' + $registration.InputSchema['properties']['Query'].Contains('x-mcp-header') | Should -BeFalse + @($registration.HeaderParameters | ForEach-Object { $_.Path -join '.' }) | Should -Be @('Region', 'Priority') + (Test-McpSpecShape -Definition 'Tool' -Instance (Invoke-McpInModule { param($r) ConvertTo-McpToolDefinition -Registration $r } -Parameters @{ r = $registration })).IsValid | Should -BeTrue + } + + It 'rejects unknown parameters, non-primitive parameters and invalid header names' { + $server = New-McpServer -Name 'headers' -Version '1' + { Register-McpTool -Name 'a' -ScriptBlock { param([string] $Region) $Region } -Header @{ Missing = 'X' } -Server $server } | Should -Throw -ExpectedMessage '*not a property*' + { Register-McpTool -Name 'b' -ScriptBlock { param([hashtable] $Options) $Options } -Header @{ Options = 'Options' } -Server $server } | Should -Throw -ExpectedMessage '*only string, integer and boolean*' + { Register-McpTool -Name 'c' -ScriptBlock { param([string] $Region) $Region } -Header @{ Region = 'My Region' } -Server $server } | Should -Throw -ExpectedMessage '*field-name token*' + { Register-McpTool -Name 'd' -ScriptBlock { param([string] $A, [string] $B) "$A$B" } -Header @{ A = 'Same'; B = 'same' } -Server $server } | Should -Throw -ExpectedMessage '*more than once*' + { Register-McpTool -Name 'e' -ScriptBlock { param([hashtable] $Arguments) $Arguments } -InputSchema @{ type = 'object'; properties = @{ v = @{ type = 'object'; 'x-mcp-header' = 'V' } } } -Server $server } | Should -Throw -ExpectedMessage '*invalid x-mcp-header*' + } +} + +Describe 'HTTP status codes and Origin validation' { + It 'maps JSON-RPC error codes to HTTP statuses' -TestCases @( + @{ Code = $null; Expected = 200 } + @{ Code = -32700; Expected = 400 } + @{ Code = -32600; Expected = 400 } + @{ Code = -32602; Expected = 400 } + @{ Code = -32020; Expected = 400 } + @{ Code = -32021; Expected = 400 } + @{ Code = -32022; Expected = 400 } + @{ Code = -32601; Expected = 404 } + @{ Code = -32603; Expected = 200 } + @{ Code = -32000; Expected = 200 } + ) { + Invoke-McpInModule { param($c) Get-McpHttpStatusCode -ErrorCode $c } -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 + & $test 'http://127.0.0.1:8080/mcp/' ' 127.0.0.1:8080 ' | Should -BeTrue + & $test 'http://localhost:8080/mcp/' 'LOCALHOST:8080' | Should -BeTrue + & $test 'http://localhost/mcp/' 'localhost' | Should -BeTrue + & $test 'http://localhost/mcp/' 'localhost:80' | Should -BeTrue + & $test 'https://mcp.example.com/mcp/' 'mcp.example.com' | Should -BeTrue + & $test 'https://mcp.example.com/mcp/' 'mcp.example.com:443' | Should -BeTrue + & $test 'http://[::1]:8080/mcp/' '[::1]:8080' | Should -BeTrue + & $test 'http://127.0.0.1:8080/mcp/' '127.0.0.1' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' '127.0.0.1:1' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' 'evil.example.com' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' 'evil.example.com:8080' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' '127.0.0.1:' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' '127.0.0.1:x' | Should -BeFalse + & $test 'http://[::1]:8080/mcp/' '[::1' | Should -BeFalse + & $test 'http://[::1]:8080/mcp/' '[::1]8080' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' '' | Should -BeFalse + & $test 'http://127.0.0.1:8080/mcp/' $null | Should -BeFalse + } + + It 'accepts loopback and own origins by default and honours an allow list' { + $transport = @{ Url = [uri] 'http://127.0.0.1:8080/mcp/'; AllowedOrigins = @() } + $test = { param($t, $o) Invoke-McpInModule { param($t, $o) Test-McpHttpOrigin -Transport $t -Origin $o } -Parameters @{ t = $t; o = $o } } + & $test $transport $null | Should -BeTrue + & $test $transport 'http://localhost:3000' | Should -BeTrue + & $test $transport 'http://127.0.0.1' | Should -BeTrue + & $test $transport 'https://[::1]:8443' | Should -BeTrue + & $test $transport 'http://127.0.0.1:8080' | Should -BeTrue + & $test $transport 'http://evil.example.com' | Should -BeFalse + & $test $transport 'null' | Should -BeFalse + & $test $transport 'file://x' | Should -BeFalse + $listed = @{ Url = [uri] 'http://127.0.0.1:8080/mcp/'; AllowedOrigins = @('https://app.example.com') } + & $test $listed 'https://app.example.com' | Should -BeTrue + & $test $listed 'https://APP.example.com/' | Should -BeTrue + & $test $listed 'http://localhost:3000' | Should -BeFalse + $any = @{ Url = [uri] 'http://127.0.0.1:8080/mcp/'; AllowedOrigins = @('*') } + & $test $any 'http://evil.example.com' | Should -BeTrue + } +} + +Describe 'SSE parsing' { + It 'reads events with data lines, ignores comments, ids 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)) + $events = Invoke-McpInModule { + param($s) + $sse = New-McpSseReader -Stream $s + $result = [System.Collections.Generic.List[object]]::new() + while ($true) { + $received = Receive-McpSseEvent -Sse $sse -TimeoutMs 2000 + $result.Add($received) + if ($received.Status -ne 'Event') { break } + } + $result.ToArray() + } -Parameters @{ s = $stream } + $events.Count | Should -Be 5 + $events[0].Event | Should -Be 'message' + $events[0].Data | Should -Be '{"a":1}' + $events[1].Event | Should -BeNullOrEmpty + $events[1].Data | Should -Be "first`nsecond" + $events[2].Event | Should -Be 'other' + $events[3].Data | Should -Be '{"b":2}' + $events[4].Status | Should -Be 'Eof' + } +} diff --git a/tests/Unit/Json.Tests.ps1 b/tests/Unit/Json.Tests.ps1 new file mode 100644 index 0000000..60e4bc6 --- /dev/null +++ b/tests/Unit/Json.Tests.ps1 @@ -0,0 +1,131 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force +} + +Describe 'ConvertFrom-McpJson' { + It 'keeps object key order, is case-sensitive and preserves JSON types' { + $value = Invoke-McpInModule { ConvertFrom-McpJson '{"b":1,"a":2.5,"A":"x","n":null,"t":true,"f":false,"o":{},"l":[]}' } + $value | Should -BeOfType [System.Collections.Specialized.OrderedDictionary] + @($value.Keys) | Should -Be @('b', 'a', 'A', 'n', 't', 'f', 'o', 'l') + $value['b'] | Should -BeOfType [long] + $value['a'] | Should -BeOfType [double] + $value['A'] | Should -Be 'x' + $value['n'] | Should -BeNull + $value.Contains('n') | Should -BeTrue + $value['t'] | Should -BeTrue + $value['f'] | Should -BeFalse + $value['o'] | Should -BeOfType [System.Collections.Specialized.OrderedDictionary] + $value['o'].Count | Should -Be 0 + $value['l'].GetType().IsArray | Should -BeTrue + $value['l'].Count | Should -Be 0 + } + + It 'does not unroll single-element arrays and keeps nested arrays' { + $value = Invoke-McpInModule { ConvertFrom-McpJson '{"one":[1],"nested":[[1,2],[3]],"top":[{"a":1}]}' } + $value['one'].GetType().IsArray | Should -BeTrue + $value['one'].Count | Should -Be 1 + $value['nested'].Count | Should -Be 2 + $value['nested'][0].Count | Should -Be 2 + $value['nested'][1].Count | Should -Be 1 + $value['top'][0]['a'] | Should -Be 1 + } + + It 'preserves the JSON type of a request id ()' -ForEach @( + @{ Json = '{"id":"1"}'; Type = [string] } + @{ Json = '{"id":1}'; Type = [long] } + @{ Json = '{"id":1.5}'; Type = [double] } + ) { + $value = Invoke-McpInModule { param($j) ConvertFrom-McpJson $j } $Json + $value['id'] | Should -BeOfType $Type + } + + It 'does not coerce date-like strings' { + $value = Invoke-McpInModule { ConvertFrom-McpJson '{"when":"2026-07-28T00:00:00Z"}' } + $value['when'] | Should -BeOfType [string] + $value['when'] | Should -Be '2026-07-28T00:00:00Z' + } + + It 'handles large integers, unicode and escapes' { + $value = Invoke-McpInModule { ConvertFrom-McpJson '{"big":9007199254740993,"huge":1e300,"u":"héllo 😀","esc":"a\nb\"c"}' } + $value['big'] | Should -Be 9007199254740993 + $value['huge'] | Should -BeOfType [double] + $value['u'] | Should -Be "héllo 😀" + $value['esc'] | Should -Be "a`nb`"c" + } + + It 'returns scalars for scalar documents' { + Invoke-McpInModule { ConvertFrom-McpJson '"text"' } | Should -Be 'text' + Invoke-McpInModule { ConvertFrom-McpJson '42' } | Should -Be 42 + Invoke-McpInModule { ConvertFrom-McpJson 'null' } | Should -BeNull + } + + It 'throws on invalid JSON and on comments' { + { Invoke-McpInModule { ConvertFrom-McpJson '{"a":' } } | Should -Throw + { Invoke-McpInModule { ConvertFrom-McpJson '{"a":1} // c' } } | Should -Throw + { Invoke-McpInModule { ConvertFrom-McpJson '' } } | Should -Throw + } + + It 'enforces the maximum depth' { + $deep = ('[' * 100) + (']' * 100) + { Invoke-McpInModule { param($d) ConvertFrom-McpJson $d -MaxDepth 32 } $deep } | Should -Throw + { Invoke-McpInModule { param($d) ConvertFrom-McpJson $d -MaxDepth 128 } $deep } | Should -Not -Throw + } +} + +Describe 'ConvertTo-McpJson' { + It 'writes compact single-line JSON with insertion order' { + $json = Invoke-McpInModule { ConvertTo-McpJson ([ordered]@{ b = 1; a = @{ x = $null }; s = 'text'; l = @(1, 'two', $true) }) } + $json | Should -Be '{"b":1,"a":{"x":null},"s":"text","l":[1,"two",true]}' + $json | Should -Not -Match "`n" + } + + It 'serialises PSCustomObject, switch, byte[], DateTime, enum, Guid, Uri and Version' { + $guid = [guid] '12345678-1234-1234-1234-123456789abc' + $object = [pscustomobject]@{ + flag = [switch] $true + bytes = [byte[]] @(1, 2, 3) + when = [datetime]::new(2026, 7, 28, 12, 0, 0, [System.DateTimeKind]::Utc) + level = [McpLoggingLevel]::Warning + id = $guid + uri = [uri] 'https://example.com/a' + version = [version] '1.2.3' + } + $json = Invoke-McpInModule { param($o) ConvertTo-McpJson $o } $object + $json | Should -Be '{"flag":true,"bytes":"AQID","when":"2026-07-28T12:00:00.0000000Z","level":"Warning","id":"12345678-1234-1234-1234-123456789abc","uri":"https://example.com/a","version":"1.2.3"}' + } + + It 'keeps non-ASCII text unescaped (astral characters as surrogate escapes) and escapes control characters' { + $json = Invoke-McpInModule { ConvertTo-McpJson @{ t = "héllo 😀 a`nb`tc <>&'" } } + $json | Should -Be '{"t":"héllo \uD83D\uDE00 a\nb\tc <>&''"}' + Invoke-McpInModule { param($j) (ConvertFrom-McpJson $j)['t'] } $json | Should -Be "héllo 😀 a`nb`tc <>&'" + } + + It 'writes numbers of every integer and floating type as JSON numbers' { + $json = Invoke-McpInModule { ConvertTo-McpJson ([ordered]@{ i = [int] 1; l = [long] 2; d = [double] 2.5; f = [single] 0.5; m = [decimal] 1.25; u = [uint64] 3; big = [bigint]::Parse('123456789012345678901234567890') }) } + $json | Should -Be '{"i":1,"l":2,"d":2.5,"f":0.5,"m":1.25,"u":3,"big":123456789012345678901234567890}' + } + + It 'round-trips a decoded message byte for byte' { + $text = '{"jsonrpc":"2.0","id":"a-1","method":"tools/call","params":{"_meta":{"progressToken":7},"name":"x","arguments":{"list":[1,[2,3],{"k":null}],"e":{}}}}' + $roundTrip = Invoke-McpInModule { param($t) ConvertTo-McpJson (ConvertFrom-McpJson $t) } $text + $roundTrip | Should -Be $text + } + + It 'rejects NaN, infinity and excessive depth' { + { Invoke-McpInModule { ConvertTo-McpJson @{ x = [double]::NaN } } } | Should -Throw + { Invoke-McpInModule { ConvertTo-McpJson @{ x = [double]::PositiveInfinity } } } | Should -Throw + $nested = @{ a = 1 } + 1..40 | ForEach-Object { $nested = @{ a = $nested } } + { Invoke-McpInModule { param($n) ConvertTo-McpJson $n -MaxDepth 32 } $nested } | Should -Throw + { Invoke-McpInModule { param($n) ConvertTo-McpJson $n -MaxDepth 64 } $nested } | Should -Not -Throw + } + + It 'writes null, empty containers and generic lists' { + Invoke-McpInModule { ConvertTo-McpJson $null } | Should -Be 'null' + Invoke-McpInModule { ConvertTo-McpJson @{} } | Should -Be '{}' + Invoke-McpInModule { ConvertTo-McpJson @() } | Should -Be '[]' + $list = [System.Collections.Generic.List[object]]::new(); $list.Add(1); $list.Add('a') + Invoke-McpInModule { param($l) ConvertTo-McpJson $l } -Parameters @{ l = $list } | Should -Be '[1,"a"]' + } +} diff --git a/tests/Unit/JsonRpc.Tests.ps1 b/tests/Unit/JsonRpc.Tests.ps1 new file mode 100644 index 0000000..3ebc8fc --- /dev/null +++ b/tests/Unit/JsonRpc.Tests.ps1 @@ -0,0 +1,67 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force +} + +Describe 'JSON-RPC message model' { + It 'builds requests, notifications and responses with the fixed member order' { + Invoke-McpInModule { ConvertTo-McpJson (New-McpRequest -Id 1 -Method 'tools/list' -Params ([ordered]@{ cursor = 'c' })) } | + Should -Be '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"cursor":"c"}}' + Invoke-McpInModule { ConvertTo-McpJson (New-McpNotification -Method 'notifications/cancelled' -Params ([ordered]@{ requestId = 'r' })) } | + Should -Be '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"r"}}' + Invoke-McpInModule { ConvertTo-McpJson (New-McpResultResponse -Id 'x' -Result ([ordered]@{ resultType = 'complete' })) } | + Should -Be '{"jsonrpc":"2.0","id":"x","result":{"resultType":"complete"}}' + Invoke-McpInModule { ConvertTo-McpJson (New-McpErrorResponse -Id $null -ErrorObject (New-McpError -Code -32700 -Message 'Parse error')) } | + Should -Be '{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"}}' + } + + It 'omits params and data when they are not given' { + Invoke-McpInModule { ConvertTo-McpJson (New-McpNotification -Method 'notifications/initialized') } | Should -Be '{"jsonrpc":"2.0","method":"notifications/initialized"}' + Invoke-McpInModule { ConvertTo-McpJson (New-McpError -Code -32603 -Message 'm') } | Should -Be '{"code":-32603,"message":"m"}' + Invoke-McpInModule { ConvertTo-McpJson (New-McpError -Code -32022 -Message 'm' -Data ([ordered]@{ supported = @('2026-07-28'); requested = 'x' })) } | + Should -Be '{"code":-32022,"message":"m","data":{"supported":["2026-07-28"],"requested":"x"}}' + } + + It 'knows the error codes of the specification' { + $codes = Invoke-McpInModule { $script:McpErrorCode } + $codes.ParseError | Should -Be -32700 + $codes.InvalidRequest | Should -Be -32600 + $codes.MethodNotFound | Should -Be -32601 + $codes.InvalidParams | Should -Be -32602 + $codes.InternalError | Should -Be -32603 + $codes.HeaderMismatch | Should -Be -32020 + $codes.MissingRequiredClientCapability | Should -Be -32021 + $codes.UnsupportedProtocolVersion | Should -Be -32022 + Invoke-McpInModule { Get-McpErrorCode -Name InvalidParams } | Should -Be -32602 + } + + It 'classifies as ' -ForEach @( + @{ Json = '{"jsonrpc":"2.0","id":1,"method":"m"}'; Kind = 'Request' } + @{ Json = '{"jsonrpc":"2.0","id":"s","method":"m","params":{}}'; Kind = 'Request' } + @{ Json = '{"jsonrpc":"2.0","method":"m"}'; Kind = 'Notification' } + @{ Json = '{"jsonrpc":"2.0","id":1,"result":{}}'; Kind = 'Response' } + @{ Json = '{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"x"}}'; Kind = 'ErrorResponse' } + @{ Json = '{"jsonrpc":"2.0","id":null,"method":"m"}'; Kind = 'Invalid' } + @{ Json = '{"jsonrpc":"2.0","id":1.5,"method":"m"}'; Kind = 'Invalid' } + @{ Json = '{"jsonrpc":"2.0","id":{"a":1},"method":"m"}'; Kind = 'Invalid' } + @{ Json = '{"jsonrpc":"1.0","id":1,"method":"m"}'; Kind = 'Invalid' } + @{ Json = '{"id":1,"method":"m"}'; Kind = 'Invalid' } + @{ Json = '{"jsonrpc":"2.0","id":1,"method":"m","params":[1]}'; Kind = 'Invalid' } + @{ Json = '{"jsonrpc":"2.0","id":1}'; Kind = 'Invalid' } + @{ Json = '[]'; Kind = 'Invalid' } + @{ Json = '"text"'; Kind = 'Invalid' } + ) { + Invoke-McpInModule { param($j) Get-McpMessageKind -Message (ConvertFrom-McpJson $j) } $Json | Should -Be $Kind + } + + It 'turns exceptions into error objects' { + $protocol = Invoke-McpInModule { ConvertTo-McpErrorObject -Exception ([McpProtocolException]::new(-32602, 'bad', ([ordered]@{ detail = 1 }))) } + $protocol['code'] | Should -Be -32602 + $protocol['message'] | Should -Be 'bad' + $protocol['data']['detail'] | Should -Be 1 + $internal = Invoke-McpInModule { ConvertTo-McpErrorObject -Exception ([System.InvalidOperationException]::new('boom')) } + $internal['code'] | Should -Be -32603 + $internal['message'] | Should -Be 'boom' + $internal.Contains('data') | Should -BeFalse + } +} diff --git a/tests/Unit/RequestMeta.Tests.ps1 b/tests/Unit/RequestMeta.Tests.ps1 new file mode 100644 index 0000000..fcb9768 --- /dev/null +++ b/tests/Unit/RequestMeta.Tests.ps1 @@ -0,0 +1,64 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force + $script:supported = @('2026-07-28') +} + +Describe 'Get-McpRequestMeta' { + It 'returns the fields of a valid _meta' { + $params = Invoke-McpInModule { ConvertFrom-McpJson '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}},"io.modelcontextprotocol/clientInfo":{"name":"c","version":"1"},"io.modelcontextprotocol/logLevel":"info","progressToken":"p1"},"name":"x"}' } + $meta = Invoke-McpInModule { param($p, $v) Get-McpRequestMeta -Params $p -SupportedVersions $v } $params $script:supported + $meta.ProtocolVersion | Should -Be '2026-07-28' + $meta.ClientCapabilities['elicitation']['form'] | Should -Not -BeNull + $meta.ClientInfo['name'] | Should -Be 'c' + $meta.LogLevel | Should -Be 'info' + $meta.ProgressToken | Should -Be 'p1' + } + + It 'leaves optional fields null' { + $params = Invoke-McpInModule { ConvertFrom-McpJson '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}' } + $meta = Invoke-McpInModule { param($p, $v) Get-McpRequestMeta -Params $p -SupportedVersions $v } $params $script:supported + $meta.ClientInfo | Should -BeNull + $meta.LogLevel | Should -BeNull + $meta.ProgressToken | Should -BeNull + } + + It 'rejects with -32602' -ForEach @( + @{ Case = 'missing params'; Json = 'null' } + @{ Case = 'missing _meta'; Json = '{"name":"x"}' } + @{ Case = 'missing protocolVersion'; Json = '{"_meta":{"io.modelcontextprotocol/clientCapabilities":{}}}' } + @{ Case = 'missing clientCapabilities'; Json = '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}' } + @{ Case = 'non-object clientCapabilities'; Json = '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":"x"}}' } + @{ Case = 'clientInfo without version'; Json = '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"c"}}}' } + @{ Case = 'unknown logLevel'; Json = '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/logLevel":"loud"}}' } + @{ Case = 'object progressToken'; Json = '{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"progressToken":{}}}' } + ) { + $params = Invoke-McpInModule { param($j) ConvertFrom-McpJson $j } $Json + $exception = $null + try { Invoke-McpInModule { param($p, $v) Get-McpRequestMeta -Params $p -SupportedVersions $v } $params $script:supported } catch { $exception = $_.Exception } + $exception | Should -Not -BeNull + $exception.Code | Should -Be -32602 + } + + It 'rejects an unsupported protocol version with -32022 and lists the supported ones' { + $params = Invoke-McpInModule { ConvertFrom-McpJson '{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}}' } + $exception = $null + try { Invoke-McpInModule { param($p, $v) Get-McpRequestMeta -Params $p -SupportedVersions $v } $params @('2026-07-28', '2025-11-25') } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32022 + $exception.Data['supported'] | Should -Be @('2026-07-28', '2025-11-25') + $exception.Data['requested'] | Should -Be '1900-01-01' + } +} + +Describe 'Test-McpCapabilityPath' { + It 'resolves dotted paths and extension identifiers' { + $capabilities = Invoke-McpInModule { ConvertFrom-McpJson '{"elicitation":{"form":{}},"extensions":{"io.modelcontextprotocol/tasks":{"requests":{}}},"roots":{}}' } + Invoke-McpInModule { param($c) Test-McpCapabilityPath -Capabilities $c -Path 'elicitation.form' } $capabilities | Should -BeTrue + Invoke-McpInModule { param($c) Test-McpCapabilityPath -Capabilities $c -Path 'elicitation.url' } $capabilities | Should -BeFalse + Invoke-McpInModule { param($c) Test-McpCapabilityPath -Capabilities $c -Path 'extensions.io.modelcontextprotocol/tasks' } $capabilities | Should -BeTrue + Invoke-McpInModule { param($c) Test-McpCapabilityPath -Capabilities $c -Path 'extensions.io.modelcontextprotocol/tasks.requests' } $capabilities | Should -BeTrue + Invoke-McpInModule { param($c) Test-McpCapabilityPath -Capabilities $c -Path 'roots' } $capabilities | Should -BeTrue + Invoke-McpInModule { param($c) Test-McpCapabilityPath -Capabilities $c -Path 'sampling' } $capabilities | Should -BeFalse + Invoke-McpInModule { Test-McpCapabilityPath -Capabilities $null -Path 'roots' } | Should -BeFalse + } +} diff --git a/tests/Unit/Schema.Tests.ps1 b/tests/Unit/Schema.Tests.ps1 new file mode 100644 index 0000000..6a1886a --- /dev/null +++ b/tests/Unit/Schema.Tests.ps1 @@ -0,0 +1,187 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force + $script:engines = @('PowerShell') + if ((Invoke-McpInModule { Get-McpJsonSchemaEngine }) -eq 'JsonSchemaNet') { $script:engines += 'JsonSchemaNet' } + $script:engineCases = @($script:engines | ForEach-Object { @{ Engine = $_ } }) +} + +Describe 'Test-McpJsonSchema' { + It 'uses JsonSchema.Net when PowerShell ships it' { + $expected = if (Test-Path (Join-Path $PSHOME 'JsonSchema.Net.dll')) { 'JsonSchemaNet' } else { 'PowerShell' } + Invoke-McpInModule { Get-McpJsonSchemaEngine } | Should -Be $expected + } + + Context 'engine ' -ForEach @(@{ Engine = 'PowerShell' }, @{ Engine = 'JsonSchemaNet' }) { + BeforeAll { + $script:skip = $Engine -notin $script:engines + } + + It 'accepts a valid object and reports type violations with locations' { + if ($script:skip) { Set-ItResult -Skipped -Because "$Engine is not available"; return } + $schema = '{"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},"required":["a"],"additionalProperties":false}' + $ok = Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson '{"a":1,"b":"x"}') -Engine $e } $schema $Engine + $ok.IsValid | Should -BeTrue + $ok.Errors | Should -BeNullOrEmpty + $bad = Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson '{"a":"one","c":true}') -Engine $e } $schema $Engine + $bad.IsValid | Should -BeFalse + ($bad.Errors -join "`n") | Should -Match '/a' + ($bad.Errors -join "`n") | Should -Match 'c' + } + + It 'evaluates schemas without $schema as 2020-12 (prefixItems, dependentRequired-free subset)' { + if ($script:skip) { Set-ItResult -Skipped -Because "$Engine is not available"; return } + $schema = '{"type":"array","prefixItems":[{"type":"integer"},{"type":"string"}],"items":{"type":"boolean"}}' + (Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson '[1,"a",true,false]') -Engine $e } $schema $Engine).IsValid | Should -BeTrue + (Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson '[1,"a",1]') -Engine $e } $schema $Engine).IsValid | Should -BeFalse + } + + It 'validates ' -ForEach @( + @{ Keyword = 'enum'; Schema = '{"enum":["a",1,null]}'; Valid = @('"a"', '1', 'null'); Invalid = @('"b"', '2', 'true') } + @{ Keyword = 'const'; Schema = '{"const":{"x":[1,2]}}'; Valid = @('{"x":[1,2]}'); Invalid = @('{"x":[2,1]}') } + @{ Keyword = 'minimum/maximum'; Schema = '{"type":"number","minimum":1,"maximum":2}'; Valid = @('1', '1.5', '2'); Invalid = @('0.5', '2.5') } + @{ Keyword = 'exclusiveMinimum'; Schema = '{"type":"integer","exclusiveMinimum":0}'; Valid = @('1'); Invalid = @('0', '1.5') } + @{ Keyword = 'minLength/maxLength'; Schema = '{"type":"string","minLength":2,"maxLength":3}'; Valid = @('"ab"', '"abc"'); Invalid = @('"a"', '"abcd"') } + @{ Keyword = 'pattern'; Schema = '{"type":"string","pattern":"^[a-z]+$"}'; Valid = @('"abc"'); Invalid = @('"ab1"') } + @{ Keyword = 'minItems/maxItems'; Schema = '{"type":"array","minItems":1,"maxItems":2}'; Valid = @('[1]', '[1,2]'); Invalid = @('[]', '[1,2,3]') } + @{ Keyword = 'uniqueItems'; Schema = '{"type":"array","uniqueItems":true}'; Valid = @('[1,2]'); Invalid = @('[1,1]') } + @{ Keyword = 'anyOf'; Schema = '{"anyOf":[{"type":"string"},{"type":"integer"}]}'; Valid = @('"a"', '1'); Invalid = @('true') } + @{ Keyword = 'oneOf'; Schema = '{"oneOf":[{"type":"number"},{"type":"integer"}]}'; Valid = @('1.5'); Invalid = @('1', '"a"') } + @{ Keyword = 'allOf'; Schema = '{"allOf":[{"type":"integer"},{"minimum":5}]}'; Valid = @('5'); Invalid = @('4', '5.5') } + @{ Keyword = 'not'; Schema = '{"not":{"type":"string"}}'; Valid = @('1'); Invalid = @('"a"') } + @{ Keyword = 'type array'; Schema = '{"type":["string","null"]}'; Valid = @('"a"', 'null'); Invalid = @('1') } + @{ Keyword = 'local $ref'; Schema = '{"$defs":{"n":{"type":"integer"}},"type":"object","properties":{"v":{"$ref":"#/$defs/n"}}}'; Valid = @('{"v":1}'); Invalid = @('{"v":"x"}') } + @{ Keyword = 'if/then/else'; Schema = '{"if":{"type":"string"},"then":{"minLength":2},"else":{"type":"integer"}}'; Valid = @('"ab"', '3'); Invalid = @('"a"', 'true') } + @{ Keyword = 'additionalProperties schema'; Schema = '{"type":"object","additionalProperties":{"type":"integer"}}'; Valid = @('{"a":1}'); Invalid = @('{"a":"x"}') } + @{ Keyword = 'boolean schema'; Schema = '{"type":"object","properties":{"a":false}}'; Valid = @('{}'); Invalid = @('{"a":1}') } + ) { + if ($script:skip) { Set-ItResult -Skipped -Because "$Engine is not available"; return } + foreach ($instance in $Valid) { + $result = Invoke-McpInModule { param($s, $i, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson $i) -Engine $e } $Schema $instance $Engine + $result.IsValid | Should -BeTrue -Because "$instance should satisfy $Schema ($Engine)" + } + foreach ($instance in $Invalid) { + $result = Invoke-McpInModule { param($s, $i, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson $i) -Engine $e } $Schema $instance $Engine + $result.IsValid | Should -BeFalse -Because "$instance should violate $Schema ($Engine)" + } + } + + It 'accepts hashtable and PSObject instances' { + if ($script:skip) { Set-ItResult -Skipped -Because "$Engine is not available"; return } + $schema = @{ type = 'object'; properties = @{ n = @{ type = 'integer' } }; required = @('n') } + (Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance @{ n = 1 } -Engine $e } $schema $Engine).IsValid | Should -BeTrue + (Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance ([pscustomobject]@{ n = 'x' }) -Engine $e } $schema $Engine).IsValid | Should -BeFalse + } + } + + It 'rejects external references, unsupported dialects and oversized schemas before evaluation' { + { Invoke-McpInModule { Test-McpJsonSchema -Schema '{"$ref":"https://example.com/schema.json"}' -Instance 1 } } | Should -Throw -ExpectedMessage '*external*' + { Invoke-McpInModule { Test-McpJsonSchema -Schema '{"properties":{"a":{"$ref":"http://example.com/x"}}}' -Instance 1 } } | Should -Throw + { Invoke-McpInModule { Test-McpJsonSchema -Schema '{"$schema":"http://json-schema.org/draft-04/schema#","type":"string"}' -Instance 'x' } } | Should -Throw -ExpectedMessage '*dialect*' + $deep = ('{"properties":{"a":' * 40) + '{}' + ('}}' * 40) + { Invoke-McpInModule { param($s) Test-McpJsonSchema -Schema $s -Instance @{} } $deep } | Should -Throw -ExpectedMessage '*deeper*' + } +} + +Describe 'New-McpToolInputSchema' { + BeforeAll { + function script:Get-McpTestWeather { + <# + .SYNOPSIS + Returns the weather. + .PARAMETER Location + City or postal code. + .PARAMETER Units + Unit system. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Schema fixture; the parameters are only inspected.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Location, + + [ValidateSet('metric', 'imperial')] + [string] $Units = 'metric', + + [ValidateRange(1, 10)] + [int] $Days = 3, + + [switch] $Detailed, + + [ValidateLength(1, 5)] + [string[]] $Tags, + + [datetime] $When, + + [System.DayOfWeek] $Day, + + [Parameter(HelpMessage = 'Ignored by the tool.')] + [hashtable] $Options, + + [object] $Context + ) + } + $script:command = Get-Command -Name Get-McpTestWeather + } + + It 'maps parameter types, validation attributes, help and defaults' { + $generated = Invoke-McpInModule { + param($c) + $help = Get-McpCommandHelp -Ast $c.ScriptBlock.Ast + $defaults = Get-McpParameterDefaultValue -Ast $c.ScriptBlock.Ast + New-McpToolInputSchema -Parameters $c.Parameters -Help $help -Defaults $defaults + } $script:command + $schema = $generated.Schema + $schema['type'] | Should -Be 'object' + $schema['additionalProperties'] | Should -BeFalse + @($schema['required']) | Should -Be @('Location') + @($schema['properties'].Keys) | Should -Be @('Location', 'Units', 'Days', 'Detailed', 'Tags', 'When', 'Day', 'Options') + $schema['properties']['Location']['type'] | Should -Be 'string' + $schema['properties']['Location']['description'] | Should -Be 'City or postal code.' + $schema['properties']['Units']['enum'] | Should -Be @('metric', 'imperial') + $schema['properties']['Units']['default'] | Should -Be 'metric' + $schema['properties']['Days']['type'] | Should -Be 'integer' + $schema['properties']['Days']['minimum'] | Should -Be 1 + $schema['properties']['Days']['maximum'] | Should -Be 10 + $schema['properties']['Days']['default'] | Should -Be 3 + $schema['properties']['Detailed']['type'] | Should -Be 'boolean' + $schema['properties']['Tags']['type'] | Should -Be 'array' + $schema['properties']['Tags']['items']['type'] | Should -Be 'string' + $schema['properties']['Tags']['minLength'] | Should -Be 1 + $schema['properties']['When']['format'] | Should -Be 'date-time' + $schema['properties']['Day']['enum'] | Should -Contain 'Monday' + $schema['properties']['Options']['type'] | Should -Be 'object' + $schema['properties']['Options']['description'] | Should -Be 'Ignored by the tool.' + $generated.ParameterTypes['Days'] | Should -Be ([int]) + (Invoke-McpInModule { param($s) ConvertTo-McpJson $s } $schema) | Should -Match '"required":\["Location"\]' + } + + It 'excludes common parameters and the Context parameter' { + $generated = Invoke-McpInModule { param($c) New-McpToolInputSchema -Parameters $c.Parameters } $script:command + $generated.Schema['properties'].Contains('Verbose') | Should -BeFalse + $generated.Schema['properties'].Contains('ErrorAction') | Should -BeFalse + $generated.Schema['properties'].Contains('Context') | Should -BeFalse + } + + It 'produces the recommended schema for a command without parameters' { + function script:Get-McpTestNothing { [CmdletBinding()] param() } + $generated = Invoke-McpInModule { param($c) New-McpToolInputSchema -Parameters $c.Parameters } (Get-Command Get-McpTestNothing) + Invoke-McpInModule { param($s) ConvertTo-McpJson $s } $generated.Schema | Should -Be '{"type":"object","additionalProperties":false}' + } + + It 'rejects SecureString, PSCredential and ScriptBlock parameters' { + function script:Get-McpTestSecret { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Schema fixture.')] param([securestring] $Secret) } + { Invoke-McpInModule { param($c) New-McpToolInputSchema -Parameters $c.Parameters } (Get-Command Get-McpTestSecret) } | Should -Throw -ExpectedMessage '*SecureString*' + } + + It 'validates generated schemas with both engines identically' { + $generated = Invoke-McpInModule { param($c) New-McpToolInputSchema -Parameters $c.Parameters } $script:command + foreach ($engine in $script:engines) { + $ok = Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson '{"Location":"Berlin","Days":2,"Units":"metric"}') -Engine $e } $generated.Schema $engine + $ok.IsValid | Should -BeTrue -Because $engine + $bad = Invoke-McpInModule { param($s, $e) Test-McpJsonSchema -Schema $s -Instance (ConvertFrom-McpJson '{"Days":"two","Units":"kelvin","Extra":1}') -Engine $e } $generated.Schema $engine + $bad.IsValid | Should -BeFalse -Because $engine + $bad.Errors.Count | Should -BeGreaterOrEqual 3 -Because $engine + } + } +} diff --git a/tests/Unit/Server.Tests.ps1 b/tests/Unit/Server.Tests.ps1 new file mode 100644 index 0000000..8704590 --- /dev/null +++ b/tests/Unit/Server.Tests.ps1 @@ -0,0 +1,94 @@ +[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 '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.Tools.Count | Should -Be 0 + $server.Options.MaxConcurrency | Should -BeGreaterOrEqual 1 + $server.Options.PageSize | Should -Be 100 + $server.Options.DefaultCacheScope | Should -Be 'public' + $server.Options.IncludeServerInfo | Should -BeTrue + $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 'sets the default server with -SetDefault' { + $server = New-McpServer -Name 'default' -Version '1' -SetDefault + (Invoke-McpInModule { Resolve-McpServer -Server $null }).Name | Should -Be 'default' + $server.Name | Should -Be 'default' + } +} + +Describe 'server/discover' { + It 'builds a DiscoverResult that matches the specification schema' { + $server = New-McpServer -Name 'demo' -Version '0.1.0' -Title 'Demo' -Instructions 'Use it.' -WebsiteUrl 'https://example.com' -DefaultTtlMs 5000 -DefaultCacheScope private + $result = Invoke-McpInModule { param($s) Get-McpDiscoverResult -Server $s } $server + @($result.Keys) | Should -Be @('resultType', 'supportedVersions', 'capabilities', 'instructions', 'ttlMs', 'cacheScope', '_meta') + $result['resultType'] | Should -Be 'complete' + $result['supportedVersions'] | Should -Be @('2026-07-28') + $result['capabilities']['tools']['listChanged'] | Should -BeFalse + $result['ttlMs'] | Should -Be 5000 + $result['cacheScope'] | Should -Be 'private' + $result['_meta']['io.modelcontextprotocol/serverInfo']['name'] | Should -Be 'demo' + $result['_meta']['io.modelcontextprotocol/serverInfo']['title'] | Should -Be 'Demo' + $result['_meta']['io.modelcontextprotocol/serverInfo']['websiteUrl'] | Should -Be 'https://example.com' + (Test-McpSpecShape -Definition 'DiscoverResult' -Instance $result).IsValid | Should -BeTrue + } + + It 'omits serverInfo with -NoServerInfo' { + $server = New-McpServer -Name 'demo' -Version '0.1.0' -NoServerInfo + $result = Invoke-McpInModule { param($s) Get-McpDiscoverResult -Server $s } $server + $result.Contains('_meta') | Should -BeFalse + (Test-McpSpecShape -Definition 'DiscoverResult' -Instance $result).IsValid | Should -BeTrue + } +} + +Describe 'tools/list' { + BeforeAll { + $script:server = New-McpServer -Name 'demo' -Version '0.1.0' -PageSize 2 + foreach ($name in 'a', 'b', 'c', 'd', 'e') { + Register-McpTool -Name $name -ScriptBlock { 1 } -Server $script:server + } + } + + It 'pages deterministically with opaque cursors and matches the specification schema' { + $first = Invoke-McpInModule { param($s) Get-McpToolListResult -Server $s -Cursor $null } $script:server + @($first['tools'] | ForEach-Object { $_['name'] }) | Should -Be @('a', 'b') + $first['nextCursor'] | Should -Not -BeNullOrEmpty + $first['ttlMs'] | Should -Be 0 + $first['cacheScope'] | Should -Be 'public' + (Test-McpSpecShape -Definition 'ListToolsResult' -Instance $first).IsValid | Should -BeTrue + $second = Invoke-McpInModule { param($s, $c) Get-McpToolListResult -Server $s -Cursor $c } $script:server $first['nextCursor'] + @($second['tools'] | ForEach-Object { $_['name'] }) | Should -Be @('c', 'd') + $third = Invoke-McpInModule { param($s, $c) Get-McpToolListResult -Server $s -Cursor $c } $script:server $second['nextCursor'] + @($third['tools'] | ForEach-Object { $_['name'] }) | Should -Be @('e') + $third.Contains('nextCursor') | Should -BeFalse + } + + It 'rejects invalid cursors with -32602' { + $exception = $null + try { Invoke-McpInModule { param($s) Get-McpToolListResult -Server $s -Cursor 'nonsense' } $script:server } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32602 + try { Invoke-McpInModule { param($s) Get-McpToolListResult -Server $s -Cursor 12 } $script:server } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32602 + } + + It 'returns everything in one page when the page size is large enough' { + $server = New-McpServer -Name 'demo' -Version '0.1.0' + Register-McpTool -Name 'only' -ScriptBlock { 1 } -Server $server + $result = Invoke-McpInModule { param($s) Get-McpToolListResult -Server $s -Cursor $null } $server + @($result['tools']).Count | Should -Be 1 + $result.Contains('nextCursor') | Should -BeFalse + } +} diff --git a/tests/Unit/Tools.Tests.ps1 b/tests/Unit/Tools.Tests.ps1 new file mode 100644 index 0000000..c7e802c --- /dev/null +++ b/tests/Unit/Tools.Tests.ps1 @@ -0,0 +1,207 @@ +[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 + + function script:Get-McpTestEcho { + <# + .SYNOPSIS + Echoes text. + .PARAMETER Text + The text to echo. + .PARAMETER Repeat + How often. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Context is inspected by the registration, not used by the fixture.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Text, + + [ValidateRange(1, 5)] + [int] $Repeat = 1, + + [switch] $Upper, + + [object] $Context + ) + $result = $Text * $Repeat + if ($Upper) { $result.ToUpperInvariant() } else { $result } + } +} + +Describe 'Register-McpTool' { + BeforeEach { + $script:server = New-McpServer -Name 'test' -Version '1.0.0' + } + + It 'registers a function with a generated schema and the synopsis as description' { + $registration = Register-McpTool -Command (Get-Command Get-McpTestEcho) -Server $script:server -PassThru + $registration.PSObject.TypeNames | Should -Contain 'Mcp.ToolRegistration' + $registration.Name | Should -Be 'Get-McpTestEcho' + $registration.Description | Should -Be 'Echoes text.' + $registration.InputSchema['required'] | Should -Be @('Text') + $registration.InputSchema['properties']['Repeat']['maximum'] | Should -Be 5 + $registration.InputSchema['properties'].Contains('Context') | Should -BeFalse + $registration.Handler.Kind | Should -Be 'Function' + $registration.Handler.CommandName | Should -Be 'Get-McpTestEcho' + $registration.Handler.Definition | Should -Match 'Repeat' + $registration.Handler.ContextParameter | Should -Be 'Context' + $registration.Handler.ArgumentStyle | Should -Be 'Splat' + $script:server.Tools.Contains('Get-McpTestEcho') | Should -BeTrue + } + + It 'registers a script block with a generated schema' { + $registration = Register-McpTool -Name 'add' -ScriptBlock { param([Parameter(Mandatory)][int] $A, [int] $B = 1) $A + $B } -Server $script:server -PassThru + $registration.Handler.Kind | Should -Be 'ScriptBlock' + $registration.Handler.CommandName | Should -Be 'McpTool_add' + $registration.InputSchema['properties']['A']['type'] | Should -Be 'integer' + $registration.InputSchema['properties']['B']['default'] | Should -Be 1 + $registration.InputSchema['required'] | Should -Be @('A') + $registration.Handler.Definition | Should -Match '\$A \+ \$B' + } + + It 'uses an explicit input schema and the Arguments style when the handler declares Arguments' { + $schema = @{ type = 'object'; properties = @{ q = @{ type = 'string' } }; required = @('q') } + $registration = Register-McpTool -Name 'search' -ScriptBlock { param($Arguments) $Arguments['q'] } -InputSchema $schema -Server $script:server -PassThru + $registration.Handler.ArgumentStyle | Should -Be 'Arguments' + $registration.InputSchema['required'] | Should -Be @('q') + $registration.InputSchema['properties']['q']['type'] | Should -Be 'string' + } + + It 'registers a cmdlet with its module' { + $registration = Register-McpTool -Command Get-Date -Name 'date' -Server $script:server -PassThru + $registration.Handler.Kind | Should -Be 'Cmdlet' + $registration.Handler.ModuleName | Should -Be 'Microsoft.PowerShell.Utility' + $registration.InputSchema['properties']['Format']['type'] | Should -Be 'string' + } + + It 'normalises annotations, keeps title, icons and meta' { + $registration = Register-McpTool -Command (Get-Command Get-McpTestEcho) -Name 'echo' -Title 'Echo' -Annotations @{ ReadOnlyHint = $true; DestructiveHint = 0; Title = 'Echo tool' } -Icons @(@{ src = 'https://example.com/i.png'; mimeType = 'image/png' }) -Meta @{ 'x.example/flag' = 1 } -Server $script:server -PassThru + $registration.Annotations['readOnlyHint'] | Should -BeTrue + $registration.Annotations['destructiveHint'] | Should -BeFalse + $registration.Annotations['title'] | Should -Be 'Echo tool' + $definition = Invoke-McpInModule { param($r) ConvertTo-McpToolDefinition -Registration $r } $registration + @($definition.Keys) | Should -Be @('name', 'title', 'description', 'inputSchema', 'annotations', 'icons', '_meta') + (Test-McpSpecShape -Definition 'Tool' -Instance $definition).IsValid | Should -BeTrue + } + + It 'rejects invalid names and duplicates unless -Force' { + { Register-McpTool -Name 'bad name' -ScriptBlock { 1 } -Server $script:server } | Should -Throw -ExpectedMessage '*not a valid tool name*' + Register-McpTool -Name 'one' -ScriptBlock { 1 } -Server $script:server + { Register-McpTool -Name 'one' -ScriptBlock { 2 } -Server $script:server } | Should -Throw -ExpectedMessage '*already registered*' + Register-McpTool -Name 'one' -ScriptBlock { 2 } -Server $script:server -Force + (Invoke-McpToolHandler -Name 'one' -Server $script:server)['content'][0]['text'] | Should -Be '2' + } + + It 'uses the default server when none is given' { + $default = New-McpServer -Name 'default' -Version '1' -SetDefault + Register-McpTool -Name 'ping' -ScriptBlock { 'pong' } + $default.Tools.Contains('ping') | Should -BeTrue + } +} + +Describe 'Invoke-McpToolHandler' { + BeforeAll { + $script:server = New-McpServer -Name 'test' -Version '1.0.0' + Register-McpTool -Command (Get-Command Get-McpTestEcho) -Name 'echo' -Server $script:server + Register-McpTool -Name 'object' -ScriptBlock { [pscustomobject]@{ answer = 42; list = @(1, 2) } } -Server $script:server + Register-McpTool -Name 'objects' -ScriptBlock { @{ a = 1 }; @{ b = 2 } } -Server $script:server + Register-McpTool -Name 'throws' -ScriptBlock { throw 'boom' } -Server $script:server + Register-McpTool -Name 'writes-error' -ScriptBlock { Write-Error 'soft'; 'partial' } -Server $script:server + Register-McpTool -Name 'result' -ScriptBlock { New-McpToolResult -IsError -Text 'nope' -StructuredContent @{ code = 1 } } -Server $script:server + Register-McpTool -Name 'image' -ScriptBlock { New-McpContent -Image ([byte[]] @(1, 2, 3)) -MimeType 'image/png'; 'and text' } -Server $script:server + Register-McpTool -Name 'typed' -ScriptBlock { param([datetime] $When, [string[]] $Tags, [hashtable] $Map, [System.DayOfWeek] $Day) "$($When.Year)|$($Tags.Count)|$($Map['k'])|$([int] $Day)" } -Server $script:server + Register-McpTool -Name 'context' -ScriptBlock { param($Context) $Context.RequestId } -Server $script:server + Register-McpTool -Name 'raw' -ScriptBlock { param($Arguments) $Arguments.Keys -join ',' } -InputSchema @{ type = 'object'; additionalProperties = $true } -Server $script:server + Register-McpTool -Name 'structured' -ScriptBlock { param([int] $N) @{ n = $N } } -OutputSchema @{ type = 'object'; properties = @{ n = @{ type = 'integer'; minimum = 1 } }; required = @('n') } -Server $script:server + Register-McpTool -Name 'nothing' -ScriptBlock { } -Server $script:server + } + + It 'returns text content for string output and validates against CallToolResult' { + $result = Invoke-McpToolHandler -Name 'echo' -Arguments @{ Text = 'hi'; Repeat = 2; Upper = $true } -Server $script:server + $result['content'][0]['type'] | Should -Be 'text' + $result['content'][0]['text'] | Should -Be 'HIHI' + $result['resultType'] | Should -Be 'complete' + $result.Contains('isError') | Should -BeFalse + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $result).IsValid | Should -BeTrue + } + + It 'throws -32602 for invalid arguments and unknown tools' { + $exception = $null + try { Invoke-McpToolHandler -Name 'echo' -Arguments @{ Repeat = 9 } -Server $script:server } catch { $exception = $_.Exception } + $exception | Should -BeOfType [McpProtocolException] + $exception.Code | Should -Be -32602 + @($exception.Data['errors']).Count | Should -BeGreaterOrEqual 2 + try { Invoke-McpToolHandler -Name 'missing' -Server $script:server } catch { $exception = $_.Exception } + $exception.Code | Should -Be -32602 + $exception.Message | Should -Match 'Unknown tool' + } + + It 'turns a single object into structuredContent plus JSON text' { + $result = Invoke-McpToolHandler -Name 'object' -Server $script:server + $result['structuredContent'].answer | Should -Be 42 + $result['content'][0]['text'] | Should -Be '{"answer":42,"list":[1,2]}' + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $result).IsValid | Should -BeTrue + } + + It 'turns several objects into JSON text blocks without structuredContent' { + $result = Invoke-McpToolHandler -Name 'objects' -Server $script:server + $result['content'].Count | Should -Be 2 + $result.Contains('structuredContent') | Should -BeFalse + } + + It 'reports handler exceptions and non-terminating errors as isError results' { + $thrown = Invoke-McpToolHandler -Name 'throws' -Server $script:server + $thrown['isError'] | Should -BeTrue + $thrown['content'][0]['text'] | Should -Be 'Error: boom' + # Whether Write-Error terminates the handler depends on the caller's ErrorActionPreference in-process; + # either way the result is an error result that names the error. + $soft = Invoke-McpToolHandler -Name 'writes-error' -Server $script:server + $soft['isError'] | Should -BeTrue + @($soft['content'] | ForEach-Object { $_['text'] }) | Should -Contain 'Error: soft' + } + + It 'passes New-McpToolResult through' { + $result = Invoke-McpToolHandler -Name 'result' -Server $script:server + $result['isError'] | Should -BeTrue + $result['content'][0]['text'] | Should -Be 'nope' + $result['structuredContent']['code'] | Should -Be 1 + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $result).IsValid | Should -BeTrue + } + + It 'passes content blocks through and encodes binary data' { + $result = Invoke-McpToolHandler -Name 'image' -Server $script:server + $result['content'][0].type | Should -Be 'image' + $result['content'][0].data | Should -Be 'AQID' + $result['content'][1]['text'] | Should -Be 'and text' + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $result).IsValid | Should -BeTrue + } + + It 'binds typed parameters from JSON values' { + $arguments = Invoke-McpInModule { ConvertFrom-McpJson '{"When":"2026-07-28T10:00:00Z","Tags":["a","b"],"Map":{"k":"v"},"Day":"Tuesday"}' } + $result = Invoke-McpToolHandler -Name 'typed' -Arguments $arguments -Server $script:server + $result['content'][0]['text'] | Should -Be '2026|2|v|2' + } + + It 'injects the context and supports the Arguments style' { + $context = [pscustomobject]@{ PSTypeName = 'Mcp.RequestContext'; RequestId = 'r-7'; LogLevel = 'warning' } + (Invoke-McpToolHandler -Name 'context' -Context $context -Server $script:server)['content'][0]['text'] | Should -Be 'r-7' + (Invoke-McpToolHandler -Name 'raw' -Arguments ([ordered]@{ x = 1; y = 2 }) -Server $script:server)['content'][0]['text'] | Should -Be 'x,y' + } + + It 'validates structured content against the output schema' { + (Invoke-McpToolHandler -Name 'structured' -Arguments @{ N = 3 } -Server $script:server).Contains('isError') | Should -BeFalse + $invalid = Invoke-McpToolHandler -Name 'structured' -Arguments @{ N = 0 } -Server $script:server + $invalid['isError'] | Should -BeTrue + $invalid['content'][-1]['text'] | Should -Match 'output schema' + } + + It 'returns an empty content array for a handler without output' { + $result = Invoke-McpToolHandler -Name 'nothing' -Server $script:server + @($result['content']).Count | Should -Be 0 + (Test-McpSpecShape -Definition 'CallToolResult' -Instance $result).IsValid | Should -BeTrue + } +} diff --git a/tools/Invoke-ScriptAnalyzerWorker.ps1 b/tools/Invoke-ScriptAnalyzerWorker.ps1 new file mode 100644 index 0000000..e102b6a --- /dev/null +++ b/tools/Invoke-ScriptAnalyzerWorker.ps1 @@ -0,0 +1,57 @@ +<# +.SYNOPSIS + Runs PSScriptAnalyzer over one path in this process and writes findings and rule failures to a Clixml file. +.DESCRIPTION + Worker of the Analyze task (ModelContextProtocol.build.ps1). The build runs every analysis in a fresh pwsh + process with a timeout because PSScriptAnalyzer 1.25 runs its rules in parallel tasks that are not entirely + thread-safe: a rule occasionally fails on a file with a NullReferenceException or, after a lost command + lookup, with "The term 'Get-Command' is not recognized", and the process keeps that state until it exits. + The analyzer reports such a failure as a non-terminating error whose target is the affected file and still + returns the findings of every other rule, so this worker records both: the findings (Severity, RuleName, + ScriptPath, Line, Message) and the failures (File, Message). The build re-analyses the affected files in + fresh processes. +.PARAMETER Path + The file or folder (recursive) to analyse. +.PARAMETER Settings + The PSScriptAnalyzer settings file of the repository. +.PARAMETER CustomRulePath + The custom rule module of the repository. +.PARAMETER ResultPath + Where the Clixml result (a hashtable with Findings and Failures) is written. +.OUTPUTS + None. Exit code 0 when the analysis ran, 1 when it could not run at all. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [string] $Path, + + [Parameter(Mandatory)] + [string] $Settings, + + [Parameter(Mandatory)] + [string] $CustomRulePath, + + [Parameter(Mandatory)] + [string] $ResultPath +) + +$ErrorActionPreference = 'Stop' +Import-Module -Name PSScriptAnalyzer -MinimumVersion 1.25.0 + +$ruleErrors = @() +$parameters = @{ + Path = $Path + Settings = $Settings + CustomRulePath = $CustomRulePath + IncludeDefaultRules = $true + ErrorAction = 'SilentlyContinue' + ErrorVariable = 'ruleErrors' +} +if (Test-Path -Path $Path -PathType Container) { $parameters['Recurse'] = $true } +$findings = @(Invoke-ScriptAnalyzer @parameters | Select-Object -Property Severity, RuleName, ScriptPath, Line, Message) +$failures = @(foreach ($record in $ruleErrors) { + $file = if ($record.TargetObject -is [string] -and $record.TargetObject) { $record.TargetObject } else { $Path } + [pscustomobject]@{ File = $file; Message = $record.Exception.Message.Split("`n")[0].Trim() } + }) +@{ Findings = $findings; Failures = $failures } | Export-Clixml -Path $ResultPath -Depth 3 diff --git a/tools/README.md b/tools/README.md index fd534f8..de42883 100644 --- a/tools/README.md +++ b/tools/README.md @@ -4,6 +4,7 @@ |---|---| | `ScriptAnalyzerRules/McpAnalyzerRules.psm1` | Custom PSScriptAnalyzer rules (`Measure-McpStdoutPurity`, `Measure-McpNoInvokeExpression`), loaded by the `Analyze` task and tested in `tests/Unit/ScriptAnalyzerRules.Tests.ps1`. | | `Update-SpecSchemas.ps1` | Refreshes the vendored specification schemas in `tests/Spec/` from a pinned commit of the specification repository and regenerates the provenance manifest and the definition checklist. | +| `Invoke-ScriptAnalyzerWorker.ps1` | Worker of the `Analyze` task: analyses one path in a fresh `pwsh` process and records findings and rule failures, so that the build can retry and re-analyse files on which a PSScriptAnalyzer rule failed. | | `Get-ChangelogSection.ps1` | Extracts the section of `CHANGELOG.md` for a version (used by the release workflow for the release notes). | | `packages/` | Drop folder for offline dependency packages (`.nupkg`, ignored by git). |