diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0479a30..093d4bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,34 @@ support, dependency and breaking-change policy.
### Added
+- Milestone M4 (multi-round-trip requests and subscriptions): handlers ask for input with
+ `Request-McpElicitation` (form mode with the flat primitive schema subset, or URL mode),
+ `Request-McpSampling` and `Request-McpRoot`; the request is answered with an `InputRequiredResult`, and on
+ the retry the handler runs again and receives the answer. `-Defer` and `Wait-McpInput` ask for several
+ inputs in one round; answers of earlier rounds and `$Context.State` travel in a `requestState` signed with
+ HMAC-SHA256 and bound to method, target, argument digest and expiry (`New-McpServer -RequestStateKey`,
+ `-RequestStateTtlSeconds`). Tampered or foreign states, malformed `inputResponses` and answers that do not
+ match the request fail with `-32602`; input types the client did not declare fail with `-32021` and
+ `data.requiredCapabilities`. Works for `tools/call`, `prompts/get` and `resources/read`.
+- `subscriptions/listen` on the server: acknowledgement first with the honoured filter, every notification
+ tagged with the subscription id, a strictly honoured filter, `resources/updated` for subscribed URIs and
+ their sub-resources, a stream per listen request over Streamable HTTP (dropped when the client closes it),
+ cancellation by `notifications/cancelled` over stdio, and a graceful `complete` result for every open
+ subscription when the server stops. `Send-McpToolListChanged`, `Send-McpPromptListChanged`,
+ `Send-McpResourceListChanged` and `Send-McpResourceUpdated` announce changes from handlers or any runspace.
+- Dynamic registration: `Register-McpTool`, `Register-McpResource` and `Register-McpPrompt` on a running server
+ and the new `Unregister-McpTool`, `Unregister-McpResource` and `Unregister-McpPrompt` notify subscribers;
+ handlers registered after the start are callable at once. `listChanged` and `resources.subscribe` are
+ declared as `true`.
+- Client: `Connect-McpServer -OnElicitation`, `-OnSampling`, `-OnRoots` (which declare their capabilities)
+ and `-MaxInputRounds`; `Invoke-McpTool`, `Invoke-McpPrompt` and `Read-McpResource` run the input rounds
+ transparently and echo the `requestState` verbatim. `Register-McpSubscription`,
+ `Unregister-McpSubscription` and `Receive-McpNotification` read subscriptions in the background (a reader
+ runspace over stdio and in memory, one per stream over Streamable HTTP, with reconnects), invalidate the
+ result cache on list changes and resource updates, and run `-Action` callbacks in the caller's runspace.
+- Conformance: the fixture server implements the input-request and list-change fixtures, the fixture client
+ answers input requests; the server baseline is empty and the client baseline holds only the authorization
+ scenarios. `examples/elicitation-server.ps1` demonstrates input requests and list-change notifications.
- Milestone M3 (server primitives): `Register-McpResource` registers resources with fixed text or binary
content, files, handlers and RFC 6570 resource templates (levels 1 to 3; variables are bound to the
handler's parameters), and directories as `/{+path}` templates that reject `..`, absolute paths and
@@ -94,6 +122,10 @@ support, dependency and breaking-change policy.
### Fixed
+- A request id can be reused as soon as its response was sent; before, a request that arrived while the
+ previous request with the same id was still winding down in its worker was rejected with `-32600`.
+- `Connect-McpServer -Server` fails at once for a server object that is already running, instead of waiting
+ for the `server/discover` timeout.
- `build.ps1 -Bootstrap` reports why a dependency could not be installed instead of failing with a strict-mode
error about the missing `Optional` key.
- Script block tools whose names differ only in characters outside `A-Z`, `a-z`, `0-9` and `_` (for example
diff --git a/README.md b/README.md
index f339430..e7461f2 100644
--- a/README.md
+++ b/README.md
@@ -4,15 +4,17 @@ 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 M3 (server primitives).** Servers expose PowerShell functions, cmdlets, scripts and
-> script blocks as tools, resources (fixed content, files, directories, handlers, RFC 6570 templates) and
-> prompts, with argument completion and caching hints, over stdio and Streamable HTTP with the stateless
-> 2026-07-28 lifecycle (`server/discover`, per-request `_meta`, request metadata headers, progress,
-> cancellation, log notifications). The client side consumes all of them over both transports and caches
-> results for the `ttlMs` the server sends. The official conformance suite runs in CI: every 2026-07-28
-> scenario of the tools, resources, prompts, completion, caching, HTTP header validation and DNS rebinding
-> groups passes; the remaining scenarios (input requests, subscriptions, authorization) are listed in
-> [conformance-baseline.yml](conformance-baseline.yml) and follow in M4 to M7. The milestones are in
+> **Status: milestone M4 (input requests and subscriptions).** Servers expose PowerShell functions, cmdlets,
+> scripts and script blocks as tools, resources (fixed content, files, directories, handlers, RFC 6570
+> templates) and prompts, with argument completion and caching hints, over stdio and Streamable HTTP with the
+> stateless 2026-07-28 lifecycle (`server/discover`, per-request `_meta`, request metadata headers, progress,
+> cancellation, log notifications). Handlers ask the user for input (elicitation) or the client for sampling
+> and roots through multi-round-trip requests with a signed `requestState`; clients subscribe to list changes
+> and resource updates with `subscriptions/listen`, and tools, resources and prompts can be registered while
+> the server runs. The client side consumes all of it over both transports and caches results for the
+> `ttlMs` the server sends. The official conformance suite runs in CI: every 2026-07-28 server scenario
+> passes, and on the client side everything but authorization, which is listed in
+> [conformance-baseline.yml](conformance-baseline.yml) and follows in M6. The milestones are in
> [ROADMAP.md](ROADMAP.md); the design is in [docs/implementation-plan.md](docs/implementation-plan.md).
## Requirements
@@ -83,6 +85,22 @@ Get-McpResource | Read-McpResource # cached for the ttl
Disconnect-McpServer
```
+A handler that needs input asks for it; the client answers through a callback, and the request is retried
+with the answer (see [docs/concepts/mrtr.md](docs/concepts/mrtr.md)):
+
+```powershell
+Register-McpTool -Name 'delete-files' -ScriptBlock {
+ param([Parameter(Mandatory)] [string] $Pattern, $Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message "Delete '$Pattern'?" -Schema @{ ok = @{ type = 'boolean' } } -Required ok
+ if ($answer.Action -ne 'accept' -or -not $answer.Content.ok) { return 'Cancelled.' }
+ Remove-Item -Path $Pattern
+}
+
+$session = Connect-McpServer -Command pwsh -Arguments '-File', './server.ps1' -OnElicitation { param($Request) @{ ok = $true } }
+$subscription = Register-McpSubscription -ToolsListChanged -ResourceUri 'weather://stations'
+Receive-McpNotification -Subscription $subscription -TimeoutSeconds 30
+```
+
Over Streamable HTTP the same server listens on a URL, and the same client commands connect to it:
```powershell
@@ -101,7 +119,7 @@ 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/weather-server.ps1`
-(all server primitives), `examples/http-server.ps1`,
+(all server primitives), `examples/elicitation-server.ps1` (input requests), `examples/http-server.ps1`,
[docs/concepts/server-primitives.md](docs/concepts/server-primitives.md) and
[docs/development.md](docs/development.md) for the Inspector command line.
diff --git a/ROADMAP.md b/ROADMAP.md
index 44afa95..6329a53 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -19,9 +19,9 @@ against the requirement sets `2026-07-28` (37 server + 32 client scenarios) and
| **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` | Done |
-| **M4 MRTR and subscriptions** | Input-required machinery with signed `requestState`, capability gating, elicitation validator, sampling and roots as input requests, client retry loop; `subscriptions/listen` on server and client | All 14 `input-required-result-*`, `server-sse-multiple-streams`; client `sep-2322-client-request-state` | 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, list-changed and resource-updated fan-out, dynamic registration | All 14 `input-required-result-*`; the `subscriptions/listen` checks of `server-stateless` (acknowledgement, subscription id, filter, tools and prompts list changes); client `sep-2322-client-request-state` | Done |
| **M5 Dual era** | Legacy session (`initialize`, `ping`, `logging/setLevel`, `resources/subscribe`, server-initiated requests, HTTP sessions, GET SSE, DELETE), era-aware serialization, client legacy lifecycle | `--requirements 2025-11-25`: server 30/30, client 18/18; 2026-07-28 still green on the dual-era instance | Planned |
-| **M6 Authorization** | Client OAuth provider (discovery, PKCE, resource indicators, `iss`, CIMD/DCR/pre-registered clients, scope step-up, token store); server bearer middleware and protected-resource metadata | All client `auth/*` scenarios of the 2026-07-28 requirement set | Planned |
+| **M6 Authorization** | Client OAuth provider (discovery, PKCE, resource indicators, `iss`, CIMD/DCR/pre-registered clients, scope step-up, token store); server bearer middleware and protected-resource metadata; `requestState` encrypted (AES-GCM) and bound to the authenticated principal | All client `auth/*` scenarios of the 2026-07-28 requirement set | Planned |
| **M7 Extensions** | Tasks, Skills, Apps (server side), OAuth client credentials, enterprise-managed authorization | `tasks-*` (10), `auth/client-credentials-*`, `auth/enterprise-managed-authorization` | Planned |
| **M8 Developer experience and 1.0** | Discovery styles, launcher and client-configuration helpers, scaffolder, examples, PlatyPS help, concept documentation, performance pass | Empty baseline for both requirement sets; PowerShell Gallery release 1.0.0 | Planned |
diff --git a/conformance-baseline.yml b/conformance-baseline.yml
index 0ebd4ea..bf1ba76 100644
--- a/conformance-baseline.yml
+++ b/conformance-baseline.yml
@@ -7,23 +7,8 @@
# This file may only shrink. Version 1.0.0 requires empty lists for both requirement sets
# (2026-07-28 and 2025-11-25). The milestone that removes an entry is noted next to it (see ROADMAP.md);
# the 2025-11-25 requirement set is run from milestone M5 (dual era) on.
-server:
- # 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
+server: []
client:
- # M4: input requests
- - sep-2322-client-request-state
# M6: authorization
- auth/metadata-default
- auth/metadata-var1
diff --git a/docs/README.md b/docs/README.md
index 35d6c9f..fe20733 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -8,7 +8,8 @@
| [concepts/transports.md](concepts/transports.md) | stdio and Streamable HTTP: framing, stdout hygiene, header validation |
| [concepts/server-primitives.md](concepts/server-primitives.md) | Tools, resources, templates, prompts and completion: handler contract, errors, caching, pagination |
| [concepts/dual-era.md](concepts/dual-era.md) | Serving 2026-07-28 and the legacy revisions side by side |
-| [concepts/mrtr.md](concepts/mrtr.md) | Multi-round-trip requests: elicitation, sampling and roots as input requests |
+| [concepts/mrtr.md](concepts/mrtr.md) | Multi-round-trip requests: elicitation, sampling and roots as input requests, `requestState` |
+| [concepts/subscriptions.md](concepts/subscriptions.md) | `subscriptions/listen`: list-changed and resource-updated notifications, dynamic registration |
| [concepts/authorization.md](concepts/authorization.md) | OAuth client flows and server-side bearer validation |
| `help/` | Generated command reference (PlatyPS markdown; produced by `./build.ps1 -Task Help` from milestone M1) |
| [research/](research/README.md) | Secondary material the plan was written from (specification extractions, platform research) |
diff --git a/docs/concepts/mrtr.md b/docs/concepts/mrtr.md
index 5224e96..d33bd03 100644
--- a/docs/concepts/mrtr.md
+++ b/docs/concepts/mrtr.md
@@ -1,21 +1,144 @@
# Multi-round-trip requests (MRTR)
-Implemented in milestone M4. Revision 2026-07-28 removes server-initiated requests; a server that needs
-input from the client (elicitation, sampling, roots) answers with `resultType: input_required`, a list of
-`inputRequests` and an opaque `requestState`, and the client retries the original request with
-`inputResponses` and the echoed state.
-
-- **Handler API.** `Request-McpElicitation -Key -Message ... -Schema ...`, `Request-McpSampling`,
- `Request-McpRoots`, batched through `Request-McpInput -Batch`. Without a matching entry in
- `InputResponses` the cmdlet throws a control-flow exception; the dispatcher turns it into the
- `input_required` result. On the retry the handler runs again and the cmdlet returns the answer.
-- **Idempotency contract.** Handlers must be idempotent up to their first input request, because the retry
- re-executes them.
-- **`requestState`.** HMAC-SHA256 over principal hash, TTL, method, parameter digest and state payload
- (key configurable; random per process by default), optionally AES-GCM encrypted for confidential state.
- Verification failures answer `-32602`; missing responses yield another `input_required` result instead of
- an error.
-- **Capability gating.** Only input modes the client declared in `_meta.clientCapabilities` are requested;
- otherwise the server answers `-32021` with `requiredCapabilities`.
-- **Client.** `Connect-McpServer` accepts `-OnElicitation`, `-OnSampling` and `-OnRoots` callbacks; the retry
- loop is transparent to `Invoke-McpTool`, `Read-McpResource` and `Invoke-McpPrompt`.
+Revision 2026-07-28 removes server-initiated requests. A server that needs input from the client (a form
+the user fills in, a URL the user opens, a completion sampled by the client's model, the client's roots)
+answers the original request with an `InputRequiredResult`:
+
+```json
+{ "resultType": "input_required",
+ "inputRequests": { "confirm": { "method": "elicitation/create", "params": { "mode": "form", "message": "Delete 3 files?", "requestedSchema": { ... } } } },
+ "requestState": "eyJ2Ijox...Q.kC7x..." }
+```
+
+The client obtains the answers and sends the original request again, with a new JSON-RPC id, the answers in
+`inputResponses` (keyed like `inputRequests`) and the `requestState` echoed verbatim. Only `tools/call`,
+`prompts/get` and `resources/read` can be answered this way. Sampling and roots are deprecated in 2026-07-28
+but remain valid input requests.
+
+## Handler API
+
+A handler asks for input with one command per input type. Each takes the handler's `Context` parameter and
+a `-Key` that identifies the request within the handler:
+
+| Command | Input request | Returns |
+|---|---|---|
+| `Request-McpElicitation -Message -Schema [-Required]` | `elicitation/create`, form mode | `Mcp.ElicitResult` (`Action`, `Accepted`, `Content`) |
+| `Request-McpElicitation -Message -Url` | `elicitation/create`, URL mode | `Mcp.ElicitResult` |
+| `Request-McpSampling -Messages [-MaxTokens] [-SystemPrompt] [-Tools] ...` | `sampling/createMessage` | `Mcp.SamplingResult` (`Text`, `Content`, `Model`, `StopReason`) |
+| `Request-McpRoot` | `roots/list` | `Mcp.Root` objects (`Uri`, `Name`) |
+
+```powershell
+Register-McpTool -Name 'delete-files' -ScriptBlock {
+ param([Parameter(Mandatory)] [string] $Pattern, $Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message "Delete '$Pattern'?" -Schema @{
+ ok = @{ type = 'boolean'; title = 'Delete' }
+ } -Required ok
+ if ($answer.Action -ne 'accept' -or -not $answer.Content.ok) { return 'Cancelled.' }
+ Remove-Item -Path $Pattern
+ 'Deleted.'
+}
+```
+
+The first time the command runs, the answer is missing: it throws an internal control-flow exception
+(`McpInputRequiredException`), and the worker answers the request with the `InputRequiredResult`. On the
+retry the handler runs again **from the start**; this time the command finds the answer and returns it.
+
+**Several requests in one round.** With `-Defer` a command records its request and returns nothing instead
+of throwing; `Wait-McpInput -Context $Context` then throws once for all recorded requests. On the retry the
+same commands return their answers and `Wait-McpInput` returns without output:
+
+```powershell
+$name = Request-McpElicitation -Context $Context -Key 'name' -Message 'Name?' -Schema @{ name = @{ type = 'string' } } -Defer
+$roots = Request-McpRoot -Context $Context -Key 'roots' -Defer
+Wait-McpInput -Context $Context
+"Hello $($name.Content.name); roots: $(@($roots).Count)"
+```
+
+**Several rounds.** A handler may ask again after it got an answer (a second question that depends on the
+first answer). The answers of earlier rounds are kept in the signed `requestState`, so the client only sends
+the answers of the latest round.
+
+**Idempotency.** Because every round re-executes the handler, everything before the last input request
+must be free of side effects, or repeatable. Do the work after the last `Request-*` call.
+
+**Handler state.** `$Context.State` is a hashtable that survives the rounds: whatever the handler stores
+there before an input request is in the next round's `$Context.State`. It travels inside `requestState`
+(signed, not encrypted; see below), so it must be small and must not hold secrets.
+
+## Capability gating
+
+An input request is only sent when the client declared the matching capability in
+`_meta.clientCapabilities`: `elicitation` (an empty object means form mode) or `elicitation.form` for forms,
+`elicitation.url` for URL mode, `sampling` (`sampling.tools` with `-Tools`, `sampling.context` with
+`-IncludeContext` other than `none`) and `roots`. Otherwise the command fails the request with `-32021` and
+`data.requiredCapabilities` naming what is missing. A handler that can do without the input checks first:
+
+```powershell
+if (-not (Test-McpClientCapability -Context $Context -Path 'elicitation')) { return 'Cannot confirm; nothing done.' }
+```
+
+## Validation
+
+- **Requested schemas.** Form schemas are restricted to flat primitive properties: strings (formats `email`,
+ `uri`, `date`, `date-time`), numbers, integers, booleans, single-select enums (`enum`, `oneOf` with
+ `const`/`title`, the legacy `enumNames`) and multi-select enums (arrays with `enum` or `anyOf` items).
+ `Request-McpElicitation` throws an `ArgumentException` for anything else; a table of properties or a full
+ object schema are accepted.
+- **Answers.** `inputResponses` must be an object whose values are objects; an elicitation answer needs an
+ `action` of `accept`, `decline` or `cancel`, and accepted form content must match the requested schema; a
+ sampling answer needs `role`, `content` and `model`; a roots answer needs `roots` with a `uri` each. A
+ violation fails the request with `-32602`. Answers for keys the handler does not ask for are ignored.
+- **Missing answers.** A retry that lacks an answer is not an error: the handler asks again and the request
+ is answered with another `InputRequiredResult`.
+
+## `requestState`
+
+The state is a token of two base64url parts, `payload.signature`. The payload (JSON) holds a format
+version, the method, the target (tool or prompt name, resource URI), a SHA-256 digest of the request's
+salient parameters (the arguments, or the URI), an expiry, a nonce, the answers accepted so far, the keys
+requested in this round and the handler state. The signature is HMAC-SHA256 over the payload part.
+
+The server verifies the state before it looks at anything else in the request: format, signature (compared
+in constant time), expiry, method, target and parameter digest. Any failure answers `-32602 Invalid
+requestState`. A state therefore cannot be replayed against another tool, another resource or other
+arguments, and it cannot be altered.
+
+- **Key.** `New-McpServer -RequestStateKey` takes a string or `SecureString` of at least 16 characters
+ (hashed with SHA-256) or a `byte[]` of at least 32 bytes. Without it the server uses a random key per
+ process: a retry that reaches another process or a restarted server fails with `-32602` and the client has
+ to start over. Behind a load balancer, give every instance the same key. An HTTP server without an explicit
+ key logs a note to stderr at startup.
+- **Lifetime.** `-RequestStateTtlSeconds` (default 600) bounds how long the user may take to answer.
+- **Confidentiality.** The state is signed, not encrypted: the client can read it. It contains only what the
+ client sent or received anyway, plus `$Context.State`. Encryption (AES-GCM) and binding the state to the
+ authenticated principal follow with authorization in milestone M6.
+
+## Client
+
+`Connect-McpServer` takes one callback per input type. Each is invoked with an `Mcp.InputRequest` (`Key`,
+`Method`, `Mode`, `Message`, `RequestedSchema`, `Url`, `Messages`, `MaxTokens`, `SystemPrompt`, `Params`,
+and `RequestMethod`, the method being retried):
+
+| Parameter | Returns |
+|---|---|
+| `-OnElicitation` | the form content as a hashtable (meaning accept), an ElicitResult (`@{ action = 'decline' }`), the action as a string, or nothing (cancel) |
+| `-OnSampling` | the assistant's text as a string, or a CreateMessageResult (`role`, `content`, `model`, `stopReason`) |
+| `-OnRoots` | paths or URIs, hashtables with `uri` and `name`, or a ListRootsResult |
+
+A callback declares its capability unless `-Capabilities` says otherwise (elicitation in form and URL mode,
+sampling, roots). `Invoke-McpTool`, `Invoke-McpPrompt` and `Read-McpResource` run the rounds transparently:
+they call the callbacks, retry with a new id, the answers and the state exactly as received (and no state
+when the server sent none), and stop with an error after `-MaxInputRounds` rounds (default 10). A server
+asking for an input type without a callback fails the command with a message naming the missing parameter.
+Results that needed input rounds are not cached.
+
+```powershell
+$session = Connect-McpServer -Command pwsh -Arguments '-File', './examples/elicitation-server.ps1' -OnElicitation {
+ param($Request)
+ Write-Host $Request.Message
+ @{ confirm = (Read-Host 'yes/no') -eq 'yes' }
+}
+Invoke-McpTool -Name 'delete-files' -Arguments @{ Pattern = '*.tmp' }
+```
+
+`examples/elicitation-server.ps1` has a confirmation dialog and a two-round example.
diff --git a/docs/concepts/server-primitives.md b/docs/concepts/server-primitives.md
index 9a927c1..9ec9932 100644
--- a/docs/concepts/server-primitives.md
+++ b/docs/concepts/server-primitives.md
@@ -1,7 +1,8 @@
# Server primitives
-Tools (milestone M1), resources, prompts and completion (milestone M3) are implemented. This page records how
-they map onto PowerShell, the contract for their handlers, and the caching behaviour on both sides.
+Tools (milestone M1), resources, prompts and completion (milestone M3) are implemented; since milestone M4
+they can be registered and removed while the server runs. This page records how they map onto PowerShell,
+the contract for their handlers, and the caching behaviour on both sides.
## Registration and capabilities
@@ -14,8 +15,12 @@ they map onto PowerShell, the contract for their handlers, and the caching behav
| Completion | `-Completion` on prompts and templates, `ValidateSet` of prompt parameters | `completion/complete` | `completions` once a source exists |
A capability that is not declared has no methods: they answer `-32601`, as the specification requires (the
-`server-stateless` conformance scenario checks this for prompts). `listChanged` and `subscribe` are `false`
-until `subscriptions/listen` can deliver the notifications (milestone M4).
+`server-stateless` conformance scenario checks this for prompts). `listChanged` (and `resources.subscribe`)
+is `true`: `Register-McpTool`, `Register-McpResource` and `Register-McpPrompt` on a running server, and
+`Unregister-McpTool`, `Unregister-McpResource` and `Unregister-McpPrompt`, notify the clients subscribed with
+`subscriptions/listen`, and handlers registered after the start are callable at once (see
+[subscriptions.md](subscriptions.md)). Handlers that need input from the user or the client use
+multi-round-trip requests ([mrtr.md](mrtr.md)).
The list methods and everything without user code (fixed `-Content`, value-list completions) are answered by
the dispatcher itself. `tools/call`, `resources/read` of files, directories and handlers, `prompts/get` and
@@ -79,7 +84,8 @@ The client keeps a cache per session. `Get-McpServerInfo`, `Get-McpTool`, `Get-M
`Get-McpPrompt` and `Read-McpResource` (per URI) reuse a result until its `ttlMs` has elapsed; for a list
the shortest `ttlMs` of its pages applies. A `ttlMs` of 0 (immediately stale) is never cached. `-Refresh`
bypasses the cache. The cache is session-local, so private and public results are both reusable; the scope is
-kept with each entry. Invalidation by list-changed notifications follows with `subscriptions/listen` (M4).
+kept with each entry. On a session with subscriptions (`Register-McpSubscription`), list-changed and
+resource-updated notifications drop the affected entries.
## Pagination
diff --git a/docs/concepts/subscriptions.md b/docs/concepts/subscriptions.md
new file mode 100644
index 0000000..bafa63b
--- /dev/null
+++ b/docs/concepts/subscriptions.md
@@ -0,0 +1,97 @@
+# Subscriptions (`subscriptions/listen`)
+
+Revision 2026-07-28 replaces the GET SSE stream and `resources/subscribe` of earlier revisions with one
+long-lived request: `subscriptions/listen`. Its params name the notifications the client wants:
+
+```json
+{ "notifications": { "toolsListChanged": true, "promptsListChanged": true, "resourcesListChanged": true,
+ "resourceSubscriptions": ["file:///var/log/app.log"] } }
+```
+
+The server answers with a stream: first `notifications/subscriptions/acknowledged` with the subset it
+honours, then the requested notifications as they occur, every one of them (the acknowledgement included)
+tagged with `_meta["io.modelcontextprotocol/subscriptionId"]`, the id of the listen request. The request
+ends when the client cancels it, or with a result when the server shuts down.
+
+## Server
+
+**Capabilities.** A server declares `tools.listChanged: true`, and `listChanged: true` for prompts and
+resources plus `resources.subscribe: true` when it has prompts or resources; the acknowledgement honours
+exactly the requested types that are declared. `notifications/resources/updated` for a subscribed URI
+covers its sub-resources too (`/...`).
+
+**Announcing changes.** Registering or removing a tool, prompt or resource on a running server
+(`Register-McpTool`, `Unregister-McpTool`, and the prompt and resource counterparts) sends the matching
+`list_changed` notification. Handlers registered after the start are callable at once: workers define them
+on first use. For changes the server cannot see (a resource whose content changed, a list computed by a
+handler) there are explicit commands:
+
+| Command | Notification |
+|---|---|
+| `Send-McpToolListChanged` | `notifications/tools/list_changed` |
+| `Send-McpPromptListChanged` | `notifications/prompts/list_changed` |
+| `Send-McpResourceListChanged` | `notifications/resources/list_changed` |
+| `Send-McpResourceUpdated -Uri ` | `notifications/resources/updated` |
+
+They work from a handler (`-Context $Context`) and from any runspace that holds the server object
+(`-Server $server`, for example a thread job that watches a file; `Start-McpServer` itself blocks the host
+script's runspace); on a server that is not running they do nothing.
+
+```powershell
+Register-McpResource -Uri 'logs://app' -Name 'app-log' -ScriptBlock { Get-Content -Raw -Path /var/log/app.log }
+$null = Start-ThreadJob -ArgumentList $server -ScriptBlock {
+ param($server)
+ Import-Module ModelContextProtocol
+ $watcher = [System.IO.FileSystemWatcher]::new('/var/log', 'app.log')
+ while ($true) {
+ $null = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::Changed)
+ Send-McpResourceUpdated -Server $server -Uri 'logs://app'
+ }
+}
+Start-McpServer -Server $server
+```
+
+**Transports.** Listen requests never occupy a worker. Over stdio the notifications share the output stream
+with the responses; `notifications/cancelled` with the listen request's id ends the subscription without a
+response. Over Streamable HTTP every listen request gets its own SSE response stream, kept open with
+keep-alive comments; a client that closes the stream is detected by the next failed write and dropped.
+Request-scoped notifications (progress, log messages) never go to listen streams.
+
+**Shutdown.** `Stop-McpServer`, the end of stdin and the end of the HTTP listener close every open
+subscription gracefully: its request is answered with `{ "resultType": "complete" }` carrying the
+subscription id and the server info.
+
+## Client
+
+```powershell
+$subscription = Register-McpSubscription -ToolsListChanged -ResourceUri 'file:///var/log/app.log'
+$subscription.Honoured # what the server acknowledged
+Receive-McpNotification -Subscription $subscription -TimeoutSeconds 60
+Unregister-McpSubscription -Subscription $subscription
+```
+
+`Register-McpSubscription` sends the listen request, waits for the acknowledgement and returns an
+`Mcp.Subscription` (`Id`, `State` Open, Reconnecting, Closed or Failed, `Requested`, `Honoured`,
+`Reconnects`, `Error`). Received notifications (`Mcp.Notification`: `Method`, `Uri`, `SubscriptionId`,
+`Params`, `Received`) are queued for `Receive-McpNotification`, which returns what is queued and, with
+`-TimeoutSeconds`, waits for the first one. With `-Action { param($Notification) ... }` they are passed to the
+script block instead.
+
+Every notification also invalidates the session's result cache: a list change drops the cached list, a
+resource update drops the cached contents of the resource and its sub-resources. The next `Get-McpTool` or
+`Read-McpResource` then asks the server again.
+
+**Threading.** Notifications arrive while no command runs, so they are read in the background: over stdio
+and in memory, the first subscription switches the session to a reader runspace that moves every line of
+the server's output into an inbox, from which requests read their responses too; over Streamable HTTP each
+subscription's stream has its own reader runspace. `-Action` script blocks and cache invalidation run in
+the caller's runspace, whenever a client command of this module runs on the session;
+`Receive-McpNotification -TimeoutSeconds` is the way to wait for them.
+
+**Reconnects.** When an HTTP stream closes abruptly, the reader sends the listen request again with a new id,
+after 1, 2, 4, 8 and 16 seconds, then gives up (`State` Closed, `Error` with the reason);
+`-NoReconnect` turns this off. `CurrentId` is the id of the current listen request, with which the server
+tags its notifications; `Id` stays the same. A graceful close by the server ends the subscription without
+a reconnect. Over stdio a server that exits ends every subscription.
+
+`Disconnect-McpServer` ends all subscriptions of the session before it closes the transport.
diff --git a/docs/conformance.md b/docs/conformance.md
index 38997b5..071f428 100644
--- a/docs/conformance.md
+++ b/docs/conformance.md
@@ -4,8 +4,8 @@ The SDK is measured with the official suite `@modelcontextprotocol/conformance`.
(0.1.x) does not know revision 2026-07-28; the version pinned in `requirements.psd1` (alpha channel) does.
The fixtures live in `tests/Conformance/` (`everything-server.ps1`, a Streamable HTTP server with every tool,
resource, prompt and completion the server scenarios call; `everything-client.ps1`, a client that discovers,
-lists and calls tools, and reads resources and renders prompts when the server declares them, as the client
-scenarios expect), the build task `Conformance` runs both legs, and `.github/workflows/conformance.yml`
+lists and calls tools, answers input requests with fixed callbacks, and reads resources and renders prompts
+when the server declares them, as the client scenarios expect), the build task `Conformance` runs both legs, and `.github/workflows/conformance.yml`
runs them on every push and pull request.
## Running the suite
@@ -22,20 +22,28 @@ runs the server leg, stops the fixture, then runs the client leg with the fixtur
(`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 M3
-
-Requirement set `2026-07-28`, server leg: `server-stateless` (25 checks), `tools-list`, the seven
-`tools-call-*` scenarios, `resources-list`, `resources-read-text`, `resources-read-binary`,
-`resources-templates-read`, `sep-2164-resource-not-found` (the `-32602` error with `data.uri`), the five
-`prompts-*` scenarios, `completion-complete`, `caching` (hints on every list result and on
-`resources/read`), `dns-rebinding-protection` and `server-sse-multiple-streams` pass, each including the
-`wire-schema-valid` check of every message against the 2026-07-28 schema; the not-scored
-`json-schema-2020-12`, `http-header-validation` and `http-custom-header-server-validation` pass too. Client
-leg: `tools_call`, `request-metadata`, `auth/resource-mismatch`, `http-standard-headers` (now with the
-`Mcp-Method` and `Mcp-Name` checks of `resources/read` and `prompts/get`), `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.
+## State after milestone M4
+
+Requirement set `2026-07-28`, server leg: every scenario of the requirement set passes and the server
+baseline is empty. That covers `server-stateless` (30 checks, among them the `subscriptions/listen` checks:
+acknowledgement first, the subscription id on every notification, a strictly honoured filter, and tools and
+prompts list changes triggered by the fixture tools `test_trigger_tool_change` and
+`test_trigger_prompt_change`), the fourteen `input-required-result-*` scenarios (elicitation, sampling and
+roots input requests, answers accumulated over several rounds in the signed `requestState`, a tampered
+state rejected before any other validation, input requests gated by the client capabilities, prompts and
+resources as well as tools), `tools-list`, the seven `tools-call-*` scenarios, the `resources-*`,
+`prompts-*`, `completion-complete`, `caching`, `sep-2164-resource-not-found`, `dns-rebinding-protection`
+and `server-sse-multiple-streams` scenarios, each including the `wire-schema-valid` check of every message
+against the 2026-07-28 schema; the not-scored `json-schema-2020-12`, `http-header-validation` and
+`http-custom-header-server-validation` pass too. The `tasks-*` scenarios are extensions (milestone M7) and
+do not affect the score.
+
+Client leg: `tools_call`, `request-metadata`, `sep-2322-client-request-state` (the state echoed verbatim,
+a new request id per round, no state when the server sent none, no MRTR parameters on unrelated calls, a
+missing `resultType` read as `complete`), `auth/resource-mismatch`, `http-standard-headers`,
+`http-custom-headers`, `http-invalid-tool-headers`, `json-schema-ref-no-deref` and the not-scored
+`json-schema-2020-12-preservation` pass. The remaining entries of `conformance-baseline.yml` are the
+authorization scenarios of milestone M6.
## Requirement sets
diff --git a/docs/development.md b/docs/development.md
index a2ff486..8280de2 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -42,8 +42,8 @@ built manifest, vendored schema access, a child-process runner with UTF-8 stream
| Folder | Scope | Notes |
|---|---|---|
-| `tests/Unit` | manifest, import behaviour, type accelerators, enums against the schema, custom analyzer rules, JSON codec, JSON-RPC model, `_meta` validation, JSON Schema generation and validation (both engines), tool registry and in-process invocation, `server/discover` and the list shapes against the vendored schema, resources (content shaping, not-found errors, caching hints, file and directory resources including traversal and symbolic-link escapes), RFC 6570 template matching, prompts (argument derivation and validation, message shaping), completion (prefix filter, 100-value cap), icons, content annotations, kind-bound cursors, header value encoding and `x-mcp-header` validation, HTTP status mapping, Origin checks, SSE parsing | 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) and `examples/weather-server.ps1` (all server primitives); resources, prompts, completion, capability gating, log notifications from handler streams and the client cache over the in-memory transport; a Streamable HTTP server in a background runspace (client round trips, SSE progress, header mirroring, disconnect → cancel, and raw requests for every status and error code the specification assigns) | spawns processes, binds loopback ports |
+| `tests/Unit` | manifest, import behaviour, type accelerators, enums against the schema, custom analyzer rules, JSON codec, JSON-RPC model, `_meta` validation, JSON Schema generation and validation (both engines), tool registry and in-process invocation, `server/discover` and the list shapes against the vendored schema, resources (content shaping, not-found errors, caching hints, file and directory resources including traversal and symbolic-link escapes), RFC 6570 template matching, prompts (argument derivation and validation, message shaping), completion (prefix filter, 100-value cap), icons, content annotations, kind-bound cursors, header value encoding and `x-mcp-header` validation, HTTP status mapping, Origin checks, SSE parsing, `requestState` (signature, expiry, binding to method, target and arguments, key derivation), input requests (answers present and missing, `-Defer`, capability gating with `-32021`, answer validation, the elicitation schema subset) | in-process |
+| `tests/Integration` | fresh `pwsh` processes: import must be silent on stdout and stderr, also under `-File`; the client against a server in a background runspace (in-memory transport); `examples/echo-server.ps1` over stdio (encoding, 1 MB payloads, progress, timeouts, stderr capture, BOM-free stdout, EOF shutdown), `examples/weather-server.ps1` (all server primitives) and `examples/elicitation-server.ps1` (input requests and a subscription over stdio); resources, prompts, completion, capability gating, log notifications from handler streams and the client cache over the in-memory transport; multi-round-trip requests on the wire (state accumulation, tampering, invalid answers) and through the client callbacks, in memory and over HTTP; `subscriptions/listen` on the wire (acknowledgement, tagging, filter, dynamic registration, cancel, graceful close), through `Register-McpSubscription` (cache invalidation, `-Action`) and as SSE streams (parallel streams, client disconnect); a Streamable HTTP server in a background runspace (client round trips, SSE progress, header mirroring, disconnect → cancel, and raw requests for every status and error code the specification assigns) | spawns processes, binds loopback ports |
| `tests/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` |
diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md
index 8ca6a6c..92c760b 100644
--- a/docs/implementation-plan.md
+++ b/docs/implementation-plan.md
@@ -42,7 +42,7 @@ Normative Quelle: modelcontextprotocol.io, Revision **2026-07-28** (final; `late
| Typmodell | Drei Schichten: (1) **Engine-Klassen** (intern, `[NoRunspaceAffinity()]`, deterministisch geordnete Dateien, per TypeAccelerator exportiert und in `OnRemove` entfernt) nur für zustandsbehaftete Komponenten (Server, Client, Transports, Router, SubscriptionRegistry, TaskStore, LegacySession); (2) **Wire-Objekte** als geordnete Dictionaries (wire-treu, era-bewusst serialisiert); (3) **öffentliche Rückgaben** als `PSCustomObject` mit `PSTypeName` (`Mcp.Tool`, `Mcp.ToolResult`, `Mcp.Resource`, …) plus `ps1xml`-Formate. Konstruktoren `New-McpContent`, `New-McpToolResult` etc. erzeugen valide Wire-Objekte für alle 155 Schema-Definitionen. | Klassen lassen sich nicht neu laden, kreuzen Modulgrenzen nur per `using module` und serialisieren `null` für optionale Felder. | Alles als Klassen (Reload-/Scoping-Probleme), alles als Hashtables (keine Typprüfung). |
| HTTP-Hosting | **System.Net.HttpListener** (in-box) hinter einer Host-Abstraktion (`McpHttpHost`: Request-Kontext, `WriteJson`, `BeginSse` → SSE-Writer mit Keep-alive und Disconnect→Cancel). Default-Bindung `http://127.0.0.1:/mcp/`; Origin-Allowlist (403); TLS nur über Reverse Proxy (Linux/macOS-Listener kann kein HTTPS) oder http.sys-Zertifikatbindung auf Windows; `SendChunked` + `X-Accel-Buffering: no` + initiales `:`-Kommentar für SSE; JSON-only-Hostmodus als dokumentierter Fallback (keine Listen-Streams). | Einzige in-box, plattformübergreifende Option; Spec verlangt Loopback-Default und Origin-Check. | Kestrel (nicht in pwsh enthalten, ALC-Konflikte), Pode/PSU (optionale spätere Adapter). |
| HTTP-Client | `HttpClient` + `SocketsHttpHandler` (`AllowAutoRedirect=$false`, `Timeout = Infinite`, eigene CTS für Connect/Request/Idle), `SendAsync(ResponseHeadersRead)`, Branch auf Content-Type; eigener SSE-Parser (7.4) mit optionaler Nutzung von `System.Net.ServerSentEvents` ab 7.5; Proxy aus Umgebungsvariablen. `Invoke-WebRequest`/`Invoke-RestMethod` nur für One-Shot-OAuth-Metadaten. | Web-Cmdlets puffern Bodies, kein SSE; Redirect-Handler entfernt Authorization und macht aus POST GET. | — |
-| MRTR-Handler-API | Ein Cmdlet-Satz (`Request-McpElicitation`, `Request-McpSampling`, `Request-McpRoots`) mit **zwei Ausführungsstrategien**: modern → wirft eine Control-Flow-Exception, der Dispatcher antwortet mit `InputRequiredResult` (`inputRequests`, HMAC-signierter `requestState`), Retry führt den Handler erneut aus und die Cmdlets liefern die Antwort aus `inputResponses`; legacy → blockierender server-initiierter Request über die Session mit Response-Korrelation. Handler bleiben era-agnostisch. `requestState`: HMAC-SHA256 (Schlüssel konfigurierbar, Default zufällig pro Prozess) über Principal-Hash, TTL, Methode, Param-Digest, State-Payload; optional AES-GCM bei vertraulichem State; Verifikationsfehler → `-32602`. | MRTR verbietet server-initiierte Requests in 2026-07-28; Legacy braucht sie. | Callback-/Await-Modell (entspricht dem entfernten 2025-11-25-Muster). |
+| MRTR-Handler-API | Ein Cmdlet-Satz (`Request-McpElicitation`, `Request-McpSampling`, `Request-McpRoot`) mit **zwei Ausführungsstrategien**: modern → wirft eine Control-Flow-Exception, der Dispatcher antwortet mit `InputRequiredResult` (`inputRequests`, HMAC-signierter `requestState`), Retry führt den Handler erneut aus und die Cmdlets liefern die Antwort aus `inputResponses`; legacy → blockierender server-initiierter Request über die Session mit Response-Korrelation. Handler bleiben era-agnostisch. `requestState`: HMAC-SHA256 (Schlüssel konfigurierbar, Default zufällig pro Prozess) über Principal-Hash, TTL, Methode, Param-Digest, State-Payload; optional AES-GCM bei vertraulichem State; Verifikationsfehler → `-32602`. | MRTR verbietet server-initiierte Requests in 2026-07-28; Legacy braucht sie. | Callback-/Await-Modell (entspricht dem entfernten 2025-11-25-Muster). |
| Legacy-Schichtung | `Legacy/`-Komponente mit `McpLegacySession` (pro stdio-Prozess bzw. pro `Mcp-Session-Id`): initialize/initialized, Capability-Negotiation, ping, logging/setLevel, resources/subscribe/unsubscribe, server-initiierte Requests mit Pending-Tabelle, GET-SSE-Stream, DELETE, 404 bei abgelaufener Session, era-spezifische Fehlercodes (`-32002`, `-32042`), era-spezifische Serialisierung (kein `resultType`/`ttlMs`/`cacheScope` in Legacy-Antworten). Router wählt die Ära pro Nachricht: `_meta`-Pflichtfelder vorhanden → modern; `initialize` → Legacy-Session; Folge-Requests per Session zugeordnet. Resumability (`Last-Event-ID`) wird nicht implementiert (MAY). | Kern bleibt zustandslos; Legacy ist isoliert testbar und später entfernbar. | Legacy-Semantik im Kern (verletzt Statelessness-MUSTs). |
| Deprecated Features | Roots, Sampling, Logging werden implementiert (als MRTR-Input-Requests und in Legacy als server-initiierte Requests), in Hilfe und Discover-Dokumentation als deprecated markiert; Standard-Logging geht nach stderr. `includeContext` `thisServer`/`allServers` werden akzeptiert, nicht erzeugt. | 12-Monats-Fenster, Legacy-Clients brauchen sie, Conformance-Szenarien (`input-required-result-basic-sampling/list-roots`) verlangen sie. | Weglassen (Scope-Verstoß). |
| Extensions | Formale Registry (`Register-McpExtension`): Identifier, Settings-Objekt, zusätzliche Request-Handler, Capability-Advertising in `server/discover`, Pflichtprüfung der Client-Capability pro Request. Tasks, Skills, Apps (Server), Auth-Extensions setzen darauf auf; Extensions sind default-deaktiviert (Spec-Vorgabe). | Extension-Negotiation ist generisch spezifiziert. | Ad-hoc-Implementierung je Extension. |
@@ -98,7 +98,7 @@ Normative Quelle: modelcontextprotocol.io, Revision **2026-07-28** (final; `late
**Streamable HTTP (modern).** Dispatcher nimmt `HttpListenerContext` an → Origin-Check (403) → Methode POST (GET/DELETE → 405 im modern-only-Modus, sonst Legacy-Pfad) → Body-Limit und Content-Type → Header-Validierung (`MCP-Protocol-Version` gegen `_meta`, `Mcp-Method`, `Mcp-Name` für tools/call, resources/read, prompts/get, `Mcp-Param-*` gegen `x-mcp-header`-Pfade, Base64-Sentinel-Decoding, numerischer Vergleich für Integer) → Verstoß: 400 + `-32020`; unbekannte Methode: 404 + `-32601`; Version: 400 + `-32022`; Capability: 400 + `-32021` → Notification: 202 ohne Body → Request: Router wie oben; Antwortwahl JSON (kein `progressToken`, kein `logLevel`, kein Listen) oder SSE (`data: \n\n`, initiales `:`), Response schließt nach der finalen JSON-RPC-Antwort; `subscriptions/listen` bleibt offen mit Keep-alive; Write-Fehler → Cancel des Handlers.
-**MRTR.** Handler ruft `Request-McpElicitation -Key 'login' -Message … -Schema …`; ohne `InputResponses['login']` wirft es `McpInputRequiredException` (mehrere Requests sammelbar per `Request-McpInput -Batch`); Dispatcher antwortet `resultType: input_required` mit `inputRequests` (nur Modi/Capabilities, die der Client deklariert hat; sonst `-32021`) und `requestState`; Client-SDK ruft Callbacks, retried mit neuer `id`, `inputResponses` und exakt echo-tem `requestState`; Server verifiziert HMAC/TTL/Principal/Param-Digest, führt den Handler erneut aus. Fehlende Antworten → erneutes `input_required` statt Fehler.
+**MRTR.** Handler ruft `Request-McpElicitation -Key 'login' -Message … -Schema …`; ohne `InputResponses['login']` wirft es `McpInputRequiredException` (mehrere Requests sammelbar per `-Defer` und `Wait-McpInput`); Dispatcher antwortet `resultType: input_required` mit `inputRequests` (nur Modi/Capabilities, die der Client deklariert hat; sonst `-32021`) und `requestState`; Client-SDK ruft Callbacks, retried mit neuer `id`, `inputResponses` und exakt echo-tem `requestState`; Server verifiziert HMAC/TTL/Principal/Param-Digest, führt den Handler erneut aus. Fehlende Antworten → erneutes `input_required` statt Fehler.
**Subscriptions.** `subscriptions/listen` wird nie an den Pool gegeben: Filter validieren, honorierte Teilmenge aus Server-Capabilities bestimmen, unter Lock registrieren und Ack enqueuen; Fan-out-Cmdlets (`Send-McpToolListChanged` …) sind aus jedem Runspace aufrufbar und taggen jede Notification mit `io.modelcontextprotocol/subscriptionId`. Request-scoped Notifications gehen nie auf Listen-Streams.
@@ -157,7 +157,7 @@ Alle Funktionen: `[CmdletBinding()]`, `[OutputType()]`, kommentarbasierte Hilfe,
| Funktion | Zweck | Signatur-Skizze |
|---|---|---|
-| `New-McpServer` | Server-Objekt anlegen | `-Name -Version [-Title] [-Description] [-Instructions] [-Icons] [-SupportedVersions @('2026-07-28','2025-11-25','2025-06-18')] [-Era Dual\|Modern\|Legacy] [-MaxConcurrency] [-RequestTimeout] [-RequestStateKey ] [-DefaultTtlMs] [-PassThru] [-SetDefault]` |
+| `New-McpServer` | Server-Objekt anlegen | `-Name -Version [-Title] [-Description] [-Instructions] [-Icons] [-SupportedVersions @('2026-07-28','2025-11-25','2025-06-18')] [-Era Dual\|Modern\|Legacy] [-MaxConcurrency] [-RequestTimeout] [-RequestStateKey ] [-RequestStateTtlSeconds] [-DefaultTtlMs] [-PassThru] [-SetDefault]` |
| `Register-McpTool` | Tool aus Funktion/Cmdlet/Scriptblock | `-Name [-Command \|-ScriptBlock\|-FunctionName] [-Title] [-Description] [-InputSchema ] [-OutputSchema] [-Annotations @{ReadOnlyHint;DestructiveHint;IdempotentHint;OpenWorldHint}] [-Icons] [-Header @{Region='Region'}] [-ParameterSet] [-AdditionalProperties] [-TtlMs] [-CacheScope Public\|Private] [-Meta] [-Server]`; Schema-Generierung aus `ParameterMetadata` + AST-Hilfe (Mandatory→required, ValidateSet→enum, ValidateRange→min/max, ValidateLength/Count/Pattern, Defaults, `[switch]`→boolean, int→integer, DateTime→date-time, enum→enum, Arrays mit `items`, Common Parameters ausgeschlossen, SecureString/PSCredential/ScriptBlock abgelehnt) |
| `Register-McpResource` | Statische Resource oder Template | `-Uri\|-UriTemplate -Name [-Title] [-Description] [-MimeType] [-Size] [-Annotations] [-Icons] [-ScriptBlock {param($Uri,$Context)}\|-Path\|-Content] [-Subscribable] [-TtlMs] [-CacheScope] [-Completion {param($Argument,$Context)}]` |
| `Register-McpPrompt` | Prompt-Template | `-Name [-Title] [-Description] -Arguments @(@{Name;Description;Required}) -ScriptBlock {param($Arguments,$Context)} [-Icons] [-Completion {…}]` |
@@ -246,7 +246,7 @@ Legende: S = Server, C = Client, M = Meilenstein, Szenario = Conformance-Szenari
| `resources/list`, `resources/templates/list`, `resources/read` (text/blob, RFC 6570, Cacheable, MRTR, `-32602` not found) | ✓ | ✓ | M3 | `resources-list`, `resources-read-text`, `resources-read-binary`, `resources-templates-read`, `sep-2164-resource-not-found`, `caching` |
| `prompts/list`, `prompts/get` (Arguments, alle Content-Typen, MRTR) | ✓ | ✓ | M3 | `prompts-list`, `prompts-get-simple/-with-args/-embedded-resource/-with-image` |
| `completion/complete` (ref/prompt, ref/resource, context.arguments, max 100) | ✓ | ✓ | M3 | `completion-complete` |
-| `subscriptions/listen` + `notifications/subscriptions/acknowledged` + `notifications/tools/list_changed`, `notifications/prompts/list_changed`, `notifications/resources/list_changed`, `notifications/resources/updated` (Ack-first, subscriptionId, Graceful-Close, stdio-Cancel) | ✓ | ✓ | M4 | `server-sse-multiple-streams`, Pester Integration (stdio+HTTP) |
+| `subscriptions/listen` + `notifications/subscriptions/acknowledged` + `notifications/tools/list_changed`, `notifications/prompts/list_changed`, `notifications/resources/list_changed`, `notifications/resources/updated` (Ack-first, subscriptionId, Graceful-Close, stdio-Cancel) | ✓ | ✓ | M4 | `server-stateless` (Listen-Checks: Ack, subscriptionId, Filter, tools/prompts list_changed), Pester Integration (stdio+HTTP) |
| `notifications/progress` (progressToken, monoton, request-scoped) | ✓ | ✓ | M3 | `tools-call-with-progress` |
| `notifications/cancelled` (Client→Server auf stdio; Server→Client nur für Listen-Teardown) | ✓ | ✓ | M1/M4 | Pester Integration |
| `notifications/message` (nur bei `_meta.logLevel`, deprecated) | ✓ | ✓ | M3 | Pester; Legacy: `tools-call-with-logging` |
@@ -326,8 +326,8 @@ Jeder Meilenstein liefert einen nutzbaren, getesteten Zwischenstand; die Conform
- **Exit:** `tools-call-image/-audio/-embedded-resource/-mixed-content`, `json-schema-2020-12`, `resources-*` (4), `sep-2164-resource-not-found`, `prompts-*` (5), `completion-complete`, `caching`; Client `json-schema-2020-12-preservation`.
### M4 MRTR und Subscriptions
-- InputRequired-Maschinerie, `requestState`-HMAC/AES-GCM, Capability-Gating, Elicitation-Validator (Primitiv-Subset, LegacyTitledEnum akzeptieren), Sampling- und Roots-Requests, Client-Retry-Loop mit Callbacks; `subscriptions/listen` Server (Registry, Ack-first, Fan-out, stdio-Cancel, Graceful-Close) und Client (Hintergrund-Reader, Demux, Reconnect nach Neustart); `server-sse-multiple-streams`.
-- **Exit:** alle 14 `input-required-result-*`, `server-sse-multiple-streams`; Client `sep-2322-client-request-state`; Pester für Listen auf stdio und HTTP inkl. Interleaving.
+- InputRequired-Maschinerie, `requestState`-HMAC (AES-GCM und Principal-Bindung folgen mit M6), Capability-Gating, Elicitation-Validator (Primitiv-Subset, LegacyTitledEnum akzeptieren), Sampling- und Roots-Requests, Client-Retry-Loop mit Callbacks; `subscriptions/listen` Server (Registry, Ack-first, Fan-out, stdio-Cancel, Graceful-Close, dynamische Registrierung) und Client (Hintergrund-Reader, Demux, Reconnect über HTTP).
+- **Exit:** alle 14 `input-required-result-*`; die Listen-Checks von `server-stateless` (`server-sse-multiple-streams` prüft nur parallele Request-Streams und war bereits grün); Client `sep-2322-client-request-state`; Pester für Listen auf stdio und HTTP inkl. Interleaving.
### M5 Dual-Era
- `McpLegacySession` (Server), Router-Ära-Auswahl, era-bewusste Serialisierung, HTTP-Sessions/GET/DELETE, server-initiierte Requests, Legacy-Elicitation, `ping`, `logging/setLevel`, `resources/subscribe`; Client-Legacy-Lifecycle mit Probe-/400-Erkennung, Session-Header, GET-Stream-Handling, Beantwortung server-initiierter Requests, `-32002`-Akzeptanz, `resultType`-Absenz.
diff --git a/examples/elicitation-server.ps1 b/examples/elicitation-server.ps1
new file mode 100644
index 0000000..afb1dfd
--- /dev/null
+++ b/examples/elicitation-server.ps1
@@ -0,0 +1,91 @@
+#Requires -Version 7.4
+<#
+.SYNOPSIS
+ An MCP server over stdio whose tools ask the user for input (multi-round-trip requests) and announce changes
+ of their tool list to subscribers (subscriptions/listen).
+.DESCRIPTION
+ Start it from an MCP client with:
+ pwsh -NoLogo -NoProfile -NonInteractive -File ./examples/elicitation-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.
+
+ A tool that needs input calls Request-McpElicitation. The first time, the answer is not there: the server
+ answers with an InputRequiredResult, the client asks the user and sends the request again with the
+ answer, and the handler runs again from the start, this time getting the answer. Handlers therefore do
+ their side effects only after the last input request.
+
+ Try it from PowerShell:
+ $session = Connect-McpServer -Command pwsh -Arguments '-NoProfile', '-File', './examples/elicitation-server.ps1' -OnElicitation {
+ param($Request)
+ Write-Host $Request.Message
+ switch (@($Request.RequestedSchema.properties.Keys)[0]) {
+ 'confirm' { @{ confirm = $true } }
+ 'name' { @{ name = 'Ada' } }
+ 'color' { @{ color = 'green' } }
+ }
+ }
+ Invoke-McpTool -Name 'delete-files' -Arguments @{ Pattern = '*.tmp' }
+#>
+[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 'elicitation' -Version '0.1.0' -Title 'Elicitation example' -Instructions 'Tools that ask the user before they act.' -SetDefault
+
+Register-McpTool -Name 'delete-files' -ScriptBlock {
+ <#
+ .SYNOPSIS
+ Pretends to delete files, after the user confirmed it.
+ .PARAMETER Pattern
+ The file name pattern.
+ #>
+ param(
+ [Parameter(Mandatory)]
+ [string] $Pattern,
+
+ $Context
+ )
+ if (-not (Test-McpClientCapability -Context $Context -Path 'elicitation')) {
+ return "The client cannot ask for a confirmation; nothing deleted."
+ }
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message "Delete all files matching '$Pattern'?" -Schema @{
+ confirm = @{ type = 'boolean'; title = 'Delete'; description = 'Yes, delete the files.' }
+ } -Required confirm
+ if ($answer.Action -ne 'accept' -or -not $answer.Content.confirm) { return 'Cancelled; nothing deleted.' }
+ # The side effect happens only now, after the last input request.
+ "Deleted the files matching '$Pattern' (not really: this is an example)."
+}
+
+Register-McpTool -Name 'profile' -ScriptBlock {
+ <#
+ .SYNOPSIS
+ Asks two questions in two rounds and remembers the round count in the request state.
+ #>
+ param($Context)
+ $Context.State['rounds'] = 1 + [int] $Context.State['rounds']
+ $name = Request-McpElicitation -Context $Context -Key 'name' -Message 'What is your name?' -Schema @{ name = @{ type = 'string'; minLength = 1 } } -Required name
+ if ($name.Action -ne 'accept') { return 'No profile.' }
+ $color = Request-McpElicitation -Context $Context -Key 'color' -Message "Hello $($name.Content.name), what is your favourite color?" -Schema @{
+ color = @{ type = 'string'; enum = @('red', 'green', 'blue') }
+ } -Required color
+ "$($name.Content.name) likes $($color.Content.color) (asked in $($Context.State['rounds']) rounds)."
+}
+
+Register-McpTool -Name 'announce-tools' -ScriptBlock {
+ <#
+ .SYNOPSIS
+ Announces a change of the tool list to the clients subscribed with Register-McpSubscription -ToolsListChanged.
+ #>
+ param($Context)
+ # A handler announces changes through its context; Register-McpTool and Unregister-McpTool announce them
+ # automatically when they change a running server.
+ Send-McpToolListChanged -Context $Context
+ 'Announced.'
+}
+
+Start-McpServer -Server $server -Transport Stdio
diff --git a/src/Classes/010-McpProtocolException.ps1 b/src/Classes/010-McpProtocolException.ps1
index 3658473..5706c02 100644
--- a/src/Classes/010-McpProtocolException.ps1
+++ b/src/Classes/010-McpProtocolException.ps1
@@ -1,5 +1,5 @@
-# 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.
+# JSON-RPC errors as exceptions. The router and the handlers throw McpProtocolException; 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
@@ -14,3 +14,16 @@ class McpProtocolException : System.Exception {
$this.Data = $data
}
}
+
+# Control flow of multi-round-trip requests (MRTR): Request-McpElicitation, Request-McpSampling and
+# Request-McpRoot throw it when the answer to an input request is not there yet. It derives from
+# McpProtocolException so that the handler wrappers pass it through unchanged; the worker turns it into an
+# InputRequiredResult with the pending input requests and a signed requestState.
+[NoRunspaceAffinity()]
+class McpInputRequiredException : McpProtocolException {
+ [System.Collections.Specialized.OrderedDictionary] $InputRequests
+
+ McpInputRequiredException([System.Collections.Specialized.OrderedDictionary] $inputRequests) : base(-32603, 'The handler requires input from the client; input requests are only answered in tools/call, prompts/get and resources/read.') {
+ $this.InputRequests = $inputRequests
+ }
+}
diff --git a/src/Formats/ModelContextProtocol.Format.ps1xml b/src/Formats/ModelContextProtocol.Format.ps1xml
index d819716..8ff0b11 100644
--- a/src/Formats/ModelContextProtocol.Format.ps1xml
+++ b/src/Formats/ModelContextProtocol.Format.ps1xml
@@ -219,5 +219,51 @@
+
+ Mcp.Subscription
+
+ Mcp.Subscription
+
+
+
+
+
+
+
+
+
+
+
+ Id
+ State
+ if ($null -ne $_.Honoured) { @(foreach ($key in $_.Honoured.Keys) { if ($key -eq 'resourceSubscriptions') { @($_.Honoured[$key]) -join ', ' } else { $key } }) -join ', ' }
+ $_.Notifications.Count
+
+
+
+
+
+
+ Mcp.Notification
+
+ Mcp.Notification
+
+
+
+
+
+
+
+
+
+
+ $_.Received.ToLocalTime().ToString("HH:mm:ss")
+ Method
+ Uri
+
+
+
+
+
diff --git a/src/Private/Client.ps1 b/src/Private/Client.ps1
index f9a71a0..9084fde 100644
--- a/src/Private/Client.ps1
+++ b/src/Private/Client.ps1
@@ -41,12 +41,16 @@ function Resolve-McpSession {
if ($Session.Closed) {
throw [System.InvalidOperationException]::new('The session is closed.')
}
- return $Session
- }
- if ($null -eq $script:McpDefaultSession -or $script:McpDefaultSession.Closed) {
+ $resolved = $Session
+ } elseif ($null -eq $script:McpDefaultSession -or $script:McpDefaultSession.Closed) {
throw [System.InvalidOperationException]::new('No session given and no default session; connect with Connect-McpServer first.')
+ } else {
+ $resolved = $script:McpDefaultSession
}
- $script:McpDefaultSession
+ # Every client command starts here: process what the subscription readers received (cache invalidation,
+ # -Action callbacks) before the command looks at the cache.
+ $null = Invoke-McpClientEventPump -Session $resolved
+ $resolved
}
function New-McpClientRequestMeta {
@@ -171,7 +175,7 @@ function Invoke-McpClientRequest {
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'])."
+ Invoke-McpClientStrayMessage -Session $Session -Message $message
}
'ErrorResponse' {
if ($message.Contains('id') -and [string] $message['id'] -ceq [string] $id) {
@@ -179,7 +183,7 @@ function Invoke-McpClientRequest {
$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'])."
+ Invoke-McpClientStrayMessage -Session $Session -Message $message
}
'Notification' {
Invoke-McpClientNotificationHandler -Session $Session -Message $message -ProgressToken $progressToken -OnProgress $OnProgress
@@ -211,7 +215,25 @@ function Invoke-McpClientNotificationHandler {
$method = [string] $Message['method']
$params = if ($Message.Contains('params') -and $Message['params'] -is [System.Collections.IDictionary]) { $Message['params'] } else { [ordered]@{} }
+ if ($params['_meta'] -is [System.Collections.IDictionary] -and $params['_meta'].Contains($script:McpMetaKey.SubscriptionId)) {
+ $subscription = Get-McpClientSubscriptionById -Session $Session -Id $params['_meta'][$script:McpMetaKey.SubscriptionId]
+ if ($null -ne $subscription) {
+ Receive-McpSubscriptionNotification -Session $Session -Subscription $subscription -Message $Message
+ return
+ }
+ }
switch ($method) {
+ 'notifications/cancelled' {
+ # The server ended a subscription (servers do not cancel anything else in this revision).
+ $subscription = Get-McpClientSubscriptionById -Session $Session -Id $params['requestId']
+ if ($null -ne $subscription) {
+ $subscription.State = 'Closed'
+ $subscription.Error = if ($params.Contains('reason')) { [string] $params['reason'] } else { $null }
+ Remove-McpClientSubscriptionId -Session $Session -Subscription $subscription
+ } else {
+ $Session.Notifications.Enqueue($Message)
+ }
+ }
'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) {
@@ -748,3 +770,168 @@ function Stop-McpBackgroundServer {
try { $Background.Runspace.Dispose() } catch { Write-Debug 'Disposing the server runspace failed.' }
}
}
+
+function ConvertTo-McpWireValue {
+ <#
+ .SYNOPSIS
+ A value returned by a user callback (hashtables, PSCustomObjects, arrays) as wire objects: ordered dictionaries and arrays.
+ #>
+ [CmdletBinding()]
+ [OutputType([object], [System.Array])]
+ param(
+ [AllowNull()]
+ [object] $Value
+ )
+
+ if ($null -eq $Value) { return $null }
+ , (ConvertFrom-McpJson -Json (ConvertTo-McpJson -InputObject $Value))
+}
+
+function ConvertTo-McpInputRequestObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.InputRequest')]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Key,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Request,
+
+ [Parameter(Mandatory)]
+ [string] $RequestMethod
+ )
+
+ $params = if ($Request['params'] -is [System.Collections.IDictionary]) { $Request['params'] } else { [ordered]@{} }
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.InputRequest'
+ Key = $Key
+ Method = [string] $Request['method']
+ Params = $params
+ Mode = if ($Request['method'] -eq 'elicitation/create') { if ($params['mode'] -eq 'url') { 'url' } else { 'form' } } else { $null }
+ Message = Get-McpWireValue -Object $params -Key 'message'
+ RequestedSchema = Get-McpWireValue -Object $params -Key 'requestedSchema'
+ Url = Get-McpWireValue -Object $params -Key 'url'
+ Messages = Get-McpWireValue -Object $params -Key 'messages'
+ MaxTokens = Get-McpWireValue -Object $params -Key 'maxTokens'
+ SystemPrompt = Get-McpWireValue -Object $params -Key 'systemPrompt'
+ RequestMethod = $RequestMethod
+ }
+}
+
+function Invoke-McpClientInputCallback {
+ <#
+ .SYNOPSIS
+ Answers one input request of an InputRequiredResult with the session's callback and normalises the answer to its wire shape.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary], [System.Collections.IDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Request
+ )
+
+ $callback = switch ($Request.Method) {
+ 'elicitation/create' { $Session.OnElicitation }
+ 'sampling/createMessage' { $Session.OnSampling }
+ 'roots/list' { $Session.OnRoots }
+ default { throw [System.InvalidOperationException]::new("The server asked for the unknown input request '$($Request.Method)' (key '$($Request.Key)').") }
+ }
+ if ($null -eq $callback) {
+ $parameter = switch ($Request.Method) { 'elicitation/create' { '-OnElicitation' } 'sampling/createMessage' { '-OnSampling' } default { '-OnRoots' } }
+ throw [System.InvalidOperationException]::new("The server asked for input ($($Request.Method), key '$($Request.Key)'), but the session has no $parameter callback. Pass one to Connect-McpServer.")
+ }
+ $answer = @(& $callback $Request)
+ $value = if ($answer.Count -eq 1) { $answer[0] } elseif ($answer.Count -eq 0) { $null } else { , $answer }
+ switch ($Request.Method) {
+ 'elicitation/create' {
+ if ($null -eq $value) { return [ordered]@{ action = 'cancel' } }
+ if ($value -is [string] -and $value -in @('accept', 'decline', 'cancel')) { return [ordered]@{ action = $value } }
+ $wire = ConvertTo-McpWireValue -Value $value
+ if ($wire -isnot [System.Collections.IDictionary]) { throw [System.InvalidOperationException]::new('-OnElicitation must return a hashtable (the form content, or an ElicitResult with action and content).') }
+ if (-not $wire.Contains('action')) { return [ordered]@{ action = 'accept'; content = $wire } }
+ return $wire
+ }
+ 'sampling/createMessage' {
+ if ($value -is [string]) { return [ordered]@{ role = 'assistant'; content = [ordered]@{ type = 'text'; text = $value }; model = 'unknown' } }
+ $wire = ConvertTo-McpWireValue -Value $value
+ if ($wire -isnot [System.Collections.IDictionary]) { throw [System.InvalidOperationException]::new('-OnSampling must return a string or a CreateMessageResult (role, content, model).') }
+ return $wire
+ }
+ 'roots/list' {
+ $wire = ConvertTo-McpWireValue -Value $value
+ if ($wire -is [System.Collections.IDictionary] -and $wire.Contains('roots')) { return $wire }
+ $roots = foreach ($item in @($wire)) {
+ if ($null -eq $item) { continue }
+ if ($item -is [string]) {
+ $uri = $null
+ $text = if ([uri]::TryCreate($item, [System.UriKind]::Absolute, [ref] $uri) -and $uri.Scheme -ne 'file' -or $item -match '^file:') { $item } else { ([System.Uri]::new([System.IO.Path]::GetFullPath($item))).AbsoluteUri }
+ [ordered]@{ uri = $text }
+ } elseif ($item -is [System.Collections.IDictionary]) {
+ $item
+ }
+ }
+ return [ordered]@{ roots = @($roots) }
+ }
+ }
+}
+
+function Invoke-McpClientRequestWithInput {
+ <#
+ .SYNOPSIS
+ Sends a request that may be answered with an InputRequiredResult and runs the multi-round-trip loop: answers the input requests with the session's callbacks and retries with a new id, the answers and the requestState echoed verbatim.
+ .OUTPUTS
+ A hashtable with Result (the complete result) and Rounds (the number of retries).
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Params,
+
+ [scriptblock] $OnProgress,
+
+ [AllowNull()]
+ [object] $LogLevel,
+
+ [int] $TimeoutMs = 0,
+
+ [hashtable] $Headers
+ )
+
+ $current = $Params
+ for ($round = 0; ; $round++) {
+ $result = Invoke-McpClientRequest -Session $Session -Method $Method -Params $current -OnProgress $OnProgress -LogLevel $LogLevel -TimeoutMs $TimeoutMs -Headers $Headers
+ $resultType = if ($result -is [System.Collections.IDictionary] -and $result.Contains('resultType')) { $result['resultType'] } else { 'complete' }
+ if ($resultType -eq 'complete') { return @{ Result = $result; Rounds = $round } }
+ if ($resultType -ne 'input_required') {
+ throw [System.InvalidOperationException]::new("The server answered '$Method' with the unknown resultType '$resultType'.")
+ }
+ if ($round -ge $Session.MaxInputRounds) {
+ throw [System.InvalidOperationException]::new("The server still asks for input after $round rounds of '$Method' (the session allows $($Session.MaxInputRounds); see Connect-McpServer -MaxInputRounds).")
+ }
+ $retry = [ordered]@{}
+ foreach ($key in $Params.Keys) {
+ if ([string] $key -notin @('inputResponses', 'requestState')) { $retry[$key] = $Params[$key] }
+ }
+ if ($result['inputRequests'] -is [System.Collections.IDictionary] -and $result['inputRequests'].Count -gt 0) {
+ $responses = [ordered]@{}
+ foreach ($key in $result['inputRequests'].Keys) {
+ $request = ConvertTo-McpInputRequestObject -Key $key -Request $result['inputRequests'][$key] -RequestMethod $Method
+ $responses[$key] = Invoke-McpClientInputCallback -Session $Session -Request $request
+ }
+ $retry['inputResponses'] = $responses
+ }
+ # The state is opaque: it is echoed exactly as received, and only when the server sent one.
+ if ($result.Contains('requestState') -and $result['requestState'] -is [string]) { $retry['requestState'] = $result['requestState'] }
+ $current = $retry
+ }
+}
diff --git a/src/Private/ClientSubscriptions.ps1 b/src/Private/ClientSubscriptions.ps1
new file mode 100644
index 0000000..b11e441
--- /dev/null
+++ b/src/Private/ClientSubscriptions.ps1
@@ -0,0 +1,447 @@
+# Client side of subscriptions/listen. Notifications arrive while no request is in progress, so they are read
+# in the background: over stdio and in memory a pump runspace moves every line of the transport into an inbox
+# (the request path then reads from the inbox); over Streamable HTTP each subscription has its own POST whose
+# SSE stream a reader runspace reads, reconnecting after an abrupt close. User callbacks (-Action) and cache
+# invalidation run in the caller's runspace whenever a client command pumps the inbox.
+
+function New-McpClientBackgroundRunspace {
+ <#
+ .SYNOPSIS
+ Starts a module function in a new runspace (with this module imported); returns the handles.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')]
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $FunctionName,
+
+ [Parameter(Mandatory)]
+ [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
+ $null = $powershell.AddScript('param($Name, $Parameters) & (Get-Module -Name ModelContextProtocol) { param($n, $p) & $n @p } $Name $Parameters').AddArgument($FunctionName).AddArgument($Parameters)
+ @{
+ PowerShell = $powershell
+ Handle = $powershell.BeginInvoke()
+ Runspace = $runspace
+ }
+}
+
+function Stop-McpClientBackgroundRunspace {
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')]
+ [CmdletBinding()]
+ param(
+ [AllowNull()]
+ [hashtable] $Background,
+
+ [int] $TimeoutMs = 5000
+ )
+
+ if ($null -eq $Background) { return }
+ try {
+ if (-not $Background.Handle.AsyncWaitHandle.WaitOne($TimeoutMs)) { $null = $Background.PowerShell.BeginStop($null, $null) }
+ } catch {
+ Write-Debug 'Stopping a background reader failed.'
+ }
+ try { $Background.PowerShell.Dispose() } catch { Write-Debug 'Disposing a background reader failed.' }
+ try { $Background.Runspace.Dispose() } catch { Write-Debug 'Disposing a background runspace failed.' }
+}
+
+function Invoke-McpTransportPump {
+ <#
+ .SYNOPSIS
+ Background loop: moves every line of a line transport into its inbox until end of stream or stop.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Transport
+ )
+
+ $inbox = $Transport.LineInbox
+ try {
+ while (-not $Transport.PumpStop) {
+ $task = Read-McpTransportLineAsync -Transport $Transport
+ $done = $false
+ try { $done = $task.Wait(250) } catch [System.AggregateException] { $done = $true }
+ if (-not $done) { continue }
+ $line = $null
+ try { $line = Complete-McpTransportRead -Transport $Transport -Task $task } catch { $line = $null }
+ if ($null -eq $line) { break }
+ $inbox.Add($line)
+ }
+ } finally {
+ $inbox.CompleteAdding()
+ }
+}
+
+function Start-McpTransportPump {
+ <#
+ .SYNOPSIS
+ Switches a stdio or in-memory session to background reading: from now on requests read their responses from the inbox.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Transport
+ )
+
+ if ($Transport.ContainsKey('LineInbox') -and $null -ne $Transport.LineInbox) { return }
+ $Transport.PumpStop = $false
+ $Transport.LineInbox = [System.Collections.Concurrent.BlockingCollection[string]]::new()
+ $Transport.Pump = New-McpClientBackgroundRunspace -FunctionName 'Invoke-McpTransportPump' -Parameters @{ Transport = $Transport }
+}
+
+function Stop-McpTransportPump {
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal background reader.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Transport
+ )
+
+ if (-not $Transport.ContainsKey('Pump') -or $null -eq $Transport.Pump) { return }
+ $Transport.PumpStop = $true
+ Stop-McpClientBackgroundRunspace -Background $Transport.Pump -TimeoutMs 2000
+ $Transport.Pump = $null
+}
+
+function Invoke-McpHttpListenLoop {
+ <#
+ .SYNOPSIS
+ Background loop of one HTTP subscription: posts subscriptions/listen, reads the SSE stream into the session inbox and reconnects after an abrupt close.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Subscription
+ )
+
+ $inbox = $Session.Inbox
+ $push = { param($item) $item['Subscription'] = $Subscription.Id; $inbox.Enqueue($item) }
+ $attempt = 0
+ while (-not $Subscription.StopRequested) {
+ $id = $Subscription.CurrentId
+ $params = [ordered]@{ _meta = (New-McpClientRequestMeta -Session $Session); notifications = $Subscription.Requested }
+ $json = ConvertTo-McpJson -InputObject (New-McpRequest -Id $id -Method 'subscriptions/listen' -Params $params)
+ $message = New-McpHttpRequestMessage -Session $Session -Method 'subscriptions/listen' -Params $params -Json $json
+ $response = $null
+ $closed = $false
+ $failed = $null
+ try {
+ $sendTask = $Session.Transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $Subscription.Cts.Token)
+ while (-not $sendTask.IsCompleted -and -not $Subscription.StopRequested) { $null = $sendTask.Wait(250) }
+ if ($Subscription.StopRequested) { break }
+ $failure = Get-McpTaskFailure -Task $sendTask
+ if ($null -ne $failure) { throw $failure }
+ $response = $sendTask.Result
+ $mediaType = if ($null -ne $response.Content.Headers.ContentType) { $response.Content.Headers.ContentType.MediaType } else { $null }
+ if ($mediaType -ne 'text/event-stream') {
+ # A JSON answer ends the subscription: an error (for example -32601) or an immediate result.
+ & $push @{ Kind = 'Message'; Json = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() }
+ $closed = $true
+ } else {
+ $sse = New-McpSseReader -Stream ($response.Content.ReadAsStreamAsync().GetAwaiter().GetResult())
+ try {
+ while (-not $Subscription.StopRequested) {
+ $received = Receive-McpSseEvent -Sse $sse -TimeoutMs 250
+ if ($received.Status -eq 'Timeout') { continue }
+ if ($received.Status -eq 'Eof') { break }
+ if ($null -ne $received.Event -and $received.Event -ne 'message') { continue }
+ $attempt = 0
+ & $push @{ Kind = 'Message'; Json = $received.Data }
+ # The final response of the listen request is the graceful close.
+ if ($received.Data -match '"result"\s*:' -or $received.Data -match '"error"\s*:') {
+ $parsed = $null
+ try { $parsed = ConvertFrom-McpJson -Json $received.Data } catch { $parsed = $null }
+ if ($parsed -is [System.Collections.IDictionary] -and $parsed.Contains('id') -and [string] $parsed['id'] -ceq [string] $id) { $closed = $true; break }
+ }
+ }
+ } finally {
+ try { $sse.Reader.Dispose() } catch { Write-Debug 'Disposing the SSE reader failed.' }
+ }
+ }
+ } catch {
+ $failed = $_.Exception
+ } finally {
+ if ($null -ne $response) { try { $response.Dispose() } catch { Write-Debug 'Disposing the listen response failed.' } }
+ $message.Dispose()
+ }
+ if ($closed -or $Subscription.StopRequested) { break }
+ $attempt++
+ if ($Subscription.NoReconnect -or $attempt -gt 5) {
+ & $push @{ Kind = 'Closed'; Reason = if ($null -ne $failed) { $failed.Message } else { 'The server closed the stream.' } }
+ break
+ }
+ $delay = [math]::Min(16, [math]::Pow(2, $attempt - 1))
+ $until = [datetime]::UtcNow.AddSeconds($delay)
+ while ([datetime]::UtcNow -lt $until -and -not $Subscription.StopRequested) { Start-Sleep -Milliseconds 100 }
+ if ($Subscription.StopRequested) { break }
+ $newId = "$($Subscription.Id)-r$($Subscription.Reconnects + 1)"
+ & $push @{ Kind = 'Reconnect'; NewId = $newId }
+ $Subscription.CurrentId = $newId
+ }
+}
+
+function Receive-McpSubscriptionNotification {
+ <#
+ .SYNOPSIS
+ Handles a notification tagged with a subscription id: the acknowledgement opens the subscription; list-changed and resource-updated notifications invalidate the cache and are queued for the subscription.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Subscription,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Message
+ )
+
+ $method = [string] $Message['method']
+ $params = if ($Message['params'] -is [System.Collections.IDictionary]) { $Message['params'] } else { [ordered]@{} }
+ switch ($method) {
+ 'notifications/subscriptions/acknowledged' {
+ $Subscription.Honoured = if ($params['notifications'] -is [System.Collections.IDictionary]) { $params['notifications'] } else { [ordered]@{} }
+ $Subscription.State = 'Open'
+ return
+ }
+ 'notifications/tools/list_changed' { $Session.Cache.Remove('tools/list') }
+ 'notifications/prompts/list_changed' { $Session.Cache.Remove('prompts/list') }
+ 'notifications/resources/list_changed' { $Session.Cache.Remove('resources/list'); $Session.Cache.Remove('resources/templates/list') }
+ 'notifications/resources/updated' {
+ $uri = [string] $params['uri']
+ foreach ($key in @($Session.Cache.Keys)) {
+ if ($key -ceq "resources/read $uri" -or $key.StartsWith("resources/read $uri/", [System.StringComparison]::Ordinal)) { $Session.Cache.Remove($key) }
+ }
+ }
+ }
+ $notification = [pscustomobject]@{
+ PSTypeName = 'Mcp.Notification'
+ Method = $method
+ Uri = if ($method -eq 'notifications/resources/updated') { [string] $params['uri'] } else { $null }
+ SubscriptionId = $Subscription.Id
+ Params = $params
+ Received = [datetime]::UtcNow
+ }
+ if ($null -ne $Subscription.Action) {
+ $Session.PendingEvents.Add(@{ Subscription = $Subscription; Notification = $notification })
+ } else {
+ $Subscription.Notifications.Enqueue($notification)
+ }
+}
+
+function Get-McpClientSubscriptionById {
+ [CmdletBinding()]
+ [OutputType([pscustomobject])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [AllowNull()]
+ [object] $Id
+ )
+
+ if ($null -eq $Id -or -not $Session.PSObject.Properties['SubscriptionIds']) { return $null }
+ $key = [string] $Id
+ if ($Session.SubscriptionIds.ContainsKey($key)) { return $Session.SubscriptionIds[$key] }
+ $null
+}
+
+function Invoke-McpClientStrayMessage {
+ <#
+ .SYNOPSIS
+ Handles a message that answers no pending request: the final response (or error) of a listen request, or a notification.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Message
+ )
+
+ $kind = Get-McpMessageKind -Message $Message
+ if ($kind -eq 'Notification') {
+ Invoke-McpClientNotificationHandler -Session $Session -Message $Message
+ return
+ }
+ if ($kind -notin @('Response', 'ErrorResponse')) { return }
+ $subscription = Get-McpClientSubscriptionById -Session $Session -Id $(if ($Message.Contains('id')) { $Message['id'] } else { $null })
+ if ($null -eq $subscription) {
+ Write-Debug "Ignoring a response with id $($Message['id'])."
+ return
+ }
+ if ($kind -eq 'ErrorResponse') {
+ $errorObject = $Message['error']
+ $subscription.Error = [McpProtocolException]::new([int] $errorObject['code'], [string] $errorObject['message'], $(if ($errorObject.Contains('data')) { $errorObject['data'] } else { $null }))
+ $subscription.State = 'Failed'
+ } else {
+ $subscription.State = 'Closed'
+ }
+ Remove-McpClientSubscriptionId -Session $Session -Subscription $subscription
+}
+
+function Remove-McpClientSubscriptionId {
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal subscription bookkeeping.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Subscription
+ )
+
+ foreach ($key in @($Session.SubscriptionIds.Keys)) {
+ if ([object]::ReferenceEquals($Session.SubscriptionIds[$key], $Subscription)) { $Session.SubscriptionIds.Remove($key) }
+ }
+}
+
+function Invoke-McpClientEventPump {
+ <#
+ .SYNOPSIS
+ Processes what the background readers received and runs the -Action callbacks of subscriptions, in the caller's runspace.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session
+ )
+
+ if (-not $Session.PSObject.Properties['Inbox'] -or $Session.Closed) { return }
+ $transport = $Session.Transport
+ if ($transport.ContainsKey('LineInbox') -and $null -ne $transport.LineInbox) {
+ $line = $null
+ while ($transport.LineInbox.TryTake([ref] $line, 0)) {
+ $message = $null
+ try { $message = ConvertFrom-McpJson -Json $line } catch { continue }
+ if ($message -is [System.Collections.IDictionary]) { Invoke-McpClientStrayMessage -Session $Session -Message $message }
+ }
+ if ($transport.LineInbox.IsCompleted) {
+ foreach ($subscription in @($Session.Subscriptions.Values)) {
+ if ($subscription.State -in @('Opening', 'Open')) { $subscription.State = 'Closed' }
+ }
+ }
+ }
+ $item = $null
+ while ($Session.Inbox.TryDequeue([ref] $item)) {
+ $subscription = $Session.Subscriptions[[string] $item.Subscription]
+ if ($null -eq $subscription) { continue }
+ switch ($item.Kind) {
+ 'Message' {
+ $message = $null
+ try { $message = ConvertFrom-McpJson -Json $item.Json } catch { $message = $null }
+ if ($message -is [System.Collections.IDictionary]) { Invoke-McpClientStrayMessage -Session $Session -Message $message }
+ }
+ 'Reconnect' {
+ $subscription.Reconnects++
+ $subscription.State = 'Reconnecting'
+ $Session.SubscriptionIds[[string] $item.NewId] = $subscription
+ }
+ 'Closed' {
+ $subscription.State = 'Closed'
+ $subscription.Error = $item.Reason
+ Remove-McpClientSubscriptionId -Session $Session -Subscription $subscription
+ }
+ }
+ }
+ while ($Session.PendingEvents.Count -gt 0) {
+ $pending = $Session.PendingEvents[0]
+ $Session.PendingEvents.RemoveAt(0)
+ try {
+ $null = & $pending.Subscription.Action $pending.Notification
+ } catch {
+ Write-Warning "The subscription action failed: $($_.Exception.Message)"
+ }
+ }
+}
+
+function Close-McpClientSubscription {
+ <#
+ .SYNOPSIS
+ Ends a subscription: cancels the listen request on stdio, closes the stream over HTTP, and stops its reader.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The caller owns the ShouldProcess decision.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Subscription
+ )
+
+ $Subscription.StopRequested = $true
+ if ($Session.Kind -eq 'Http') {
+ try { $Subscription.Cts.Cancel() } catch { Write-Debug 'Cancelling the listen request failed.' }
+ Stop-McpClientBackgroundRunspace -Background $Subscription.Reader -TimeoutMs 5000
+ $Subscription.Reader = $null
+ try { $Subscription.Cts.Dispose() } catch { Write-Debug 'Disposing the token source failed.' }
+ } elseif ($Subscription.State -in @('Opening', 'Open') -and -not $Session.Closed) {
+ try {
+ Send-McpClientNotification -Session $Session -Method 'notifications/cancelled' -Params ([ordered]@{ requestId = $Subscription.CurrentId; reason = 'unsubscribed' })
+ } catch {
+ Write-Debug 'Cancelling the listen request failed.'
+ }
+ }
+ if ($Subscription.State -ne 'Failed') { $Subscription.State = 'Closed' }
+ Remove-McpClientSubscriptionId -Session $Session -Subscription $Subscription
+ $Session.Subscriptions.Remove([string] $Subscription.Id)
+}
+
+function Wait-McpClientEvent {
+ <#
+ .SYNOPSIS
+ Pumps the session's background input until a condition holds or a timeout passes; returns whether the condition holds.
+ #>
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [scriptblock] $Condition,
+
+ [int] $TimeoutMs = 0
+ )
+
+ $deadline = [datetime]::UtcNow.AddMilliseconds($TimeoutMs)
+ while ($true) {
+ Invoke-McpClientEventPump -Session $Session
+ if (& $Condition) { return $true }
+ $remaining = ($deadline - [datetime]::UtcNow).TotalMilliseconds
+ if ($remaining -le 0 -or $Session.Closed) { return $false }
+ $slice = [int] [math]::Max(1, [math]::Min(100, $remaining))
+ $transport = $Session.Transport
+ if ($transport.ContainsKey('LineInbox') -and $null -ne $transport.LineInbox) {
+ $received = Receive-McpTransportLine -Transport $transport -TimeoutMs $slice
+ if ($received.Status -eq 'Line') {
+ $message = $null
+ try { $message = ConvertFrom-McpJson -Json $received.Line } catch { $message = $null }
+ if ($message -is [System.Collections.IDictionary]) { Invoke-McpClientStrayMessage -Session $Session -Message $message }
+ } elseif ($received.Status -eq 'Eof') {
+ Invoke-McpClientEventPump -Session $Session
+ return [bool] (& $Condition)
+ }
+ } else {
+ Start-Sleep -Milliseconds $slice
+ }
+ }
+}
diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1
index 28da860..20fa8f4 100644
--- a/src/Private/Dispatcher.ps1
+++ b/src/Private/Dispatcher.ps1
@@ -84,6 +84,7 @@ function Invoke-McpDispatcher {
Outbound = [System.Collections.Concurrent.ConcurrentQueue[hashtable]]::new()
Signal = [System.Threading.AutoResetEvent]::new($false)
InFlight = @{}
+ Listeners = @{}
Pool = $null
EofReceived = $false
Stopping = $false
@@ -91,10 +92,17 @@ function Invoke-McpDispatcher {
LogLevel = $Server.Options.LogLevel
}
$Server.State.Signal = $state.Signal
+ # Fan-out cmdlets (Send-McpToolListChanged ...) queue notifications for the listeners here, from any runspace.
+ $Server.State.Sink = @{ Queue = $state.Outbound; Signal = $state.Signal }
+ # The open subscriptions, for diagnostics (a Hashtable: one writer, the dispatcher, and any number of readers).
+ $Server.State.Listeners = $state.Listeners
$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), $($Server.Resources.Count + $Server.ResourceTemplates.Count) resource(s) and template(s), $($Server.Prompts.Count) prompt(s)."
+ if (-not $Server.Options.RequestStateKeyGiven -and $Transport.Kind -eq 'Http') {
+ Write-McpStderr -Level Info -Threshold $state.LogLevel -Logger $Server.Name -Message 'requestState of input requests is signed with a random per-process key; pass New-McpServer -RequestStateKey to share it between instances.'
+ }
try {
$state.Pool = New-McpWorkerPool -Server $Server
if ($Transport.Kind -eq 'Http') {
@@ -103,6 +111,7 @@ function Invoke-McpDispatcher {
Invoke-McpLineDispatcherLoop -State $state -ShutdownGraceSeconds $ShutdownGraceSeconds
}
} finally {
+ Close-McpAllListener -State $state
Stop-McpAllInFlightRequest -State $state
Send-McpOutboundQueue -State $state
if ($null -ne $state.Pool) {
@@ -111,6 +120,8 @@ function Invoke-McpDispatcher {
Close-McpTransport -Transport $Transport
$Server.State.Started = $false
$Server.State.Signal = $null
+ $Server.State.Sink = $null
+ $Server.State.Listeners = $null
Write-McpStderr -Level Info -Threshold $state.LogLevel -Logger $Server.Name -Message 'Server stopped.'
}
}
@@ -149,6 +160,7 @@ function Invoke-McpLineDispatcherLoop {
Update-McpInFlightRequest -State $State
if ($State.Stopping) { break }
if ($State.EofReceived -or $server.State.StopRequested) {
+ if ($State.Listeners.Count -gt 0) { Close-McpAllListener -State $State }
if ($State.InFlight.Count -eq 0) { break }
if ($null -eq $stopDeadline) { $stopDeadline = [datetime]::UtcNow.AddSeconds($ShutdownGraceSeconds) }
if ([datetime]::UtcNow -ge $stopDeadline) { break }
@@ -200,6 +212,12 @@ function Send-McpOutboundQueue {
$item = $null
while ($State.Outbound.TryDequeue([ref] $item)) {
+ if ($item.Kind -eq 'Broadcast') {
+ $params = if ($item.ParamsJson) { ConvertFrom-McpJson -Json $item.ParamsJson } else { $null }
+ Send-McpListenerNotification -State $State -Method $item.Method -Params $params
+ if ($State.Stopping) { return }
+ continue
+ }
$entry = $null
if ($null -ne $item.RequestId) {
$key = Get-McpRequestKey -Id $item.RequestId
@@ -287,6 +305,10 @@ function Invoke-McpInboundNotification {
$params = if ($Message.Contains('params')) { $Message['params'] } else { $null }
if ($params -isnot [System.Collections.IDictionary] -or -not $params.Contains('requestId') -or -not (Test-McpRequestId -Id $params['requestId'])) { return }
$key = Get-McpRequestKey -Id $params['requestId']
+ if ($State.Listeners.ContainsKey($key)) {
+ Remove-McpListener -State $State -Key $key -Reason 'cancelled by the client'
+ return
+ }
if (-not $State.InFlight.ContainsKey($key)) { return }
$entry = $State.InFlight[$key]
if ($entry.Cancelled -or $entry.Responded) { return }
@@ -413,7 +435,13 @@ function Invoke-McpInboundRequest {
$method = [string] $Message['method']
$params = if ($Message.Contains('params')) { $Message['params'] } else { $null }
$key = Get-McpRequestKey -Id $id
- if ($State.InFlight.ContainsKey($key)) {
+ if ($State.InFlight.ContainsKey($key) -and ($State.InFlight[$key].Responded -or $State.InFlight[$key].Cancelled)) {
+ # Answered or cancelled, only its worker is still winding down: the client may reuse the id. The entry
+ # stays under a private key until Update-McpInFlightRequest disposes the worker.
+ $State.InFlight["$key#retired-" + [guid]::NewGuid().ToString('n')] = $State.InFlight[$key]
+ $State.InFlight.Remove($key)
+ }
+ if ($State.InFlight.ContainsKey($key) -or $State.Listeners.ContainsKey($key)) {
Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpErrorResponse -Id $id -ErrorObject (New-McpError -Code $script:McpErrorCode.InvalidRequest -Message "A request with id '$id' is already in flight."))
return
}
@@ -444,7 +472,12 @@ function Invoke-McpInboundRequest {
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 -Kind Tool -Method $method -Name $registration.Name -Registration $registration -Payload @{ Arguments = $arguments } -Meta $meta -Channel $Channel
+ $payload = New-McpInputPayload -Server $server -Method $method -Name $registration.Name -Params $params
+ $payload['Arguments'] = $arguments
+ Start-McpWorkerRequest -State $State -Id $id -Kind Tool -Method $method -Name $registration.Name -Registration $registration -Payload $payload -Meta $meta -Channel $Channel
+ }
+ 'subscriptions/listen' {
+ Start-McpListener -State $State -Id $id -Params $params -Channel $Channel
}
'resources/list' {
Assert-McpServerCapability -Server $server -Capability resources -Method $method
@@ -460,6 +493,7 @@ function Invoke-McpInboundRequest {
if (-not (Test-McpResourceUri -Uri $uri)) {
throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "resources/read requires a parameter 'uri' with an absolute URI.")
}
+ $payload = New-McpInputPayload -Server $server -Method $method -Name $uri -Params $params
$resolved = Resolve-McpResourceRequest -Server $server -Uri $uri
$registration = $resolved.Registration
$cacheHint = Get-McpResourceCacheHint -Server $server -Registration $registration
@@ -467,7 +501,9 @@ function Invoke-McpInboundRequest {
$result = Invoke-McpResourceHandler -Registration $registration -Uri $uri -CacheHint $cacheHint
Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result $result -Server $server))
} else {
- Start-McpWorkerRequest -State $State -Id $id -Kind Resource -Method $method -Name $uri -Registration $registration -Payload @{ Variables = $resolved.Variables; CacheHint = $cacheHint } -Meta $meta -Channel $Channel
+ $payload['Variables'] = $resolved.Variables
+ $payload['CacheHint'] = $cacheHint
+ Start-McpWorkerRequest -State $State -Id $id -Kind Resource -Method $method -Name $uri -Registration $registration -Payload $payload -Meta $meta -Channel $Channel
}
}
'prompts/list' {
@@ -477,8 +513,9 @@ function Invoke-McpInboundRequest {
'prompts/get' {
Assert-McpServerCapability -Server $server -Capability prompts -Method $method
$registration = Get-McpPromptRegistration -Server $server -Name $params['name']
- $arguments = Test-McpPromptArgument -Registration $registration -Arguments $(if ($params.Contains('arguments')) { $params['arguments'] } else { $null })
- Start-McpWorkerRequest -State $State -Id $id -Kind Prompt -Method $method -Name $registration.Name -Registration $registration -Payload @{ Arguments = $arguments } -Meta $meta -Channel $Channel
+ $payload = New-McpInputPayload -Server $server -Method $method -Name $registration.Name -Params $params
+ $payload['Arguments'] = Test-McpPromptArgument -Registration $registration -Arguments $(if ($params.Contains('arguments')) { $params['arguments'] } else { $null })
+ Start-McpWorkerRequest -State $State -Id $id -Kind Prompt -Method $method -Name $registration.Name -Registration $registration -Payload $payload -Meta $meta -Channel $Channel
}
'completion/complete' {
Assert-McpServerCapability -Server $server -Capability completions -Method $method
@@ -506,6 +543,38 @@ function Invoke-McpInboundRequest {
}
}
+function New-McpInputPayload {
+ <#
+ .SYNOPSIS
+ The envelope members of a request that may ask for input: the verified answers and handler state of earlier rounds and what the worker needs to sign the next requestState.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory table.')]
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [Parameter(Mandatory)]
+ [string] $Name,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Params
+ )
+
+ $requestInput = Get-McpRequestInput -Server $Server -Method $Method -Name $Name -Params $Params
+ @{
+ InputResponses = $requestInput.InputResponses
+ HandlerState = $requestInput.HandlerState
+ RequestDigest = $requestInput.Digest
+ RequestStateKey = $Server.Options.RequestStateKey
+ RequestStateTtlSeconds = $Server.Options.RequestStateTtlSeconds
+ }
+}
+
function Get-McpCursorParam {
[CmdletBinding()]
[OutputType([object])]
@@ -570,7 +639,7 @@ function Start-McpWorkerRequest {
[AllowNull()]
[pscustomobject] $Registration,
- # Kind-specific envelope members: Arguments, Variables, CacheHint or Completion.
+ # Kind-specific envelope members: Arguments, Variables, CacheHint or Completion, and the input members of New-McpInputPayload.
[hashtable] $Payload = @{},
[Parameter(Mandatory)]
diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1
index e253770..360a937 100644
--- a/src/Private/HttpServer.ps1
+++ b/src/Private/HttpServer.ps1
@@ -477,6 +477,10 @@ function Stop-McpHttpChannelRequest {
)
$key = Get-McpRequestKey -Id $Channel.RequestId
+ if ($State.Listeners.ContainsKey($key) -and $State.Listeners[$key].Channel -eq $Channel) {
+ Remove-McpListener -State $State -Key $key -Reason 'ended: the client closed the stream'
+ return
+ }
if (-not $State.InFlight.ContainsKey($key)) { return }
$entry = $State.InFlight[$key]
if ($entry.Cancelled -or $entry.Responded) { return }
@@ -735,6 +739,7 @@ function Invoke-McpHttpDispatcherLoop {
Update-McpHttpChannel -State $State
if ($State.Stopping) { break }
if ($server.State.StopRequested) {
+ if ($State.Listeners.Count -gt 0) { Close-McpAllListener -State $State }
if (-not $transport.Stopped) {
$transport.Stopped = $true
Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $server.Name -Message 'Stop requested; no longer accepting connections.'
diff --git a/src/Private/InputRequest.ps1 b/src/Private/InputRequest.ps1
new file mode 100644
index 0000000..50103c0
--- /dev/null
+++ b/src/Private/InputRequest.ps1
@@ -0,0 +1,295 @@
+# Input requests of multi-round-trip requests (MRTR): the shared flow behind Request-McpElicitation,
+# Request-McpSampling and Request-McpRoot (answer present -> validate and return it; otherwise check the
+# client capability, record the request and throw McpInputRequiredException), the validation of elicitation
+# schemas and of the client's answers, and the InputRequiredResult the worker builds from the exception.
+
+$script:McpElicitationStringFormats = @('email', 'uri', 'date', 'date-time')
+
+function Test-McpContextInput {
+ <#
+ .SYNOPSIS
+ Throws unless the context belongs to a request that can ask for input (a handler of tools/call, prompts/get or resources/read).
+ #>
+ [CmdletBinding()]
+ param(
+ [AllowNull()]
+ [object] $Context
+ )
+
+ if ($null -eq $Context -or -not $Context.PSObject.Properties['PendingInput'] -or $null -eq $Context.PendingInput) {
+ throw [System.InvalidOperationException]::new('Input requests need the request context of a tools/call, prompts/get or resources/read handler (its Context parameter).')
+ }
+}
+
+function Test-McpElicitationFormCapability {
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [AllowNull()]
+ [object] $Capabilities
+ )
+
+ if (-not (Test-McpCapabilityPath -Capabilities $Capabilities -Path 'elicitation')) { return $false }
+ $elicitation = $Capabilities['elicitation']
+ # An empty elicitation object means form mode only; with modes listed, form must be one of them.
+ if ($elicitation -isnot [System.Collections.IDictionary] -or $elicitation.Count -eq 0) { return $true }
+ $elicitation.Contains('form')
+}
+
+function Assert-McpInputCapability {
+ <#
+ .SYNOPSIS
+ Throws -32021 with data.requiredCapabilities when the client did not declare what an input request needs.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [ValidateSet('elicitation.form', 'elicitation.url', 'sampling', 'sampling.tools', 'sampling.context', 'roots')]
+ [string] $Capability
+ )
+
+ $capabilities = $Context.ClientCapabilities
+ $declared = switch ($Capability) {
+ 'elicitation.form' { Test-McpElicitationFormCapability -Capabilities $capabilities }
+ default { Test-McpCapabilityPath -Capabilities $capabilities -Path $Capability }
+ }
+ if ($declared) { return }
+ $required = [ordered]@{}
+ $node = $required
+ $segments = $Capability.Split('.')
+ for ($i = 0; $i -lt $segments.Count; $i++) {
+ $node[$segments[$i]] = [ordered]@{}
+ $node = $node[$segments[$i]]
+ }
+ throw [McpProtocolException]::new($script:McpErrorCode.MissingRequiredClientCapability, "This request needs the client capability '$Capability', which the client did not declare.", [ordered]@{ requiredCapabilities = $required })
+}
+
+function ConvertTo-McpElicitationSchema {
+ <#
+ .SYNOPSIS
+ Normalises and validates a requested schema of form elicitation: the restricted, flat subset of JSON Schema.
+ .DESCRIPTION
+ Accepts a full schema ({ type = 'object'; properties = ...; required = ... }) or a table of properties.
+ Properties must be primitive: string (optionally with format email, uri, date or date-time), number,
+ integer, boolean, single-select enums (enum, oneOf of const/title, or the legacy enum with enumNames)
+ and multi-select enums (arrays of enum or anyOf items).
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [object] $Schema,
+
+ [string[]] $Required
+ )
+
+ $source = ConvertTo-McpSchemaObject -Schema $Schema
+ if ($source -isnot [System.Collections.IDictionary]) { throw [System.ArgumentException]::new('The elicitation schema must be an object.') }
+ $isFull = $source.Contains('properties') -and ($source['type'] -eq 'object' -or -not $source.Contains('type')) -and $source['properties'] -is [System.Collections.IDictionary]
+ $properties = if ($isFull) { $source['properties'] } else { $source }
+ $schema = [ordered]@{ type = 'object'; properties = [ordered]@{} }
+ foreach ($name in $properties.Keys) {
+ $property = $properties[$name]
+ if ($property -isnot [System.Collections.IDictionary]) { throw [System.ArgumentException]::new("Elicitation property '$name' must be a schema object.") }
+ $type = $property['type']
+ switch ($type) {
+ 'string' {
+ if ($property.Contains('format') -and $property['format'] -notin $script:McpElicitationStringFormats) {
+ throw [System.ArgumentException]::new("Elicitation property '$name' has the format '$($property['format'])'; allowed are $($script:McpElicitationStringFormats -join ', ').")
+ }
+ }
+ { $_ -in @('number', 'integer', 'boolean') } { }
+ 'array' {
+ $items = $property['items']
+ if ($items -isnot [System.Collections.IDictionary] -or -not ($items.Contains('enum') -or $items.Contains('anyOf'))) {
+ throw [System.ArgumentException]::new("Elicitation property '$name' is an array; only multi-select enums (items with enum or anyOf) are allowed.")
+ }
+ }
+ default {
+ throw [System.ArgumentException]::new("Elicitation property '$name' has the type '$type'; only string, number, integer, boolean and enum arrays are allowed (no nesting).")
+ }
+ }
+ $schema['properties'][[string] $name] = $property
+ }
+ $requiredNames = if ($PSBoundParameters.ContainsKey('Required')) { $Required } elseif ($isFull -and $source.Contains('required')) { @($source['required']) } else { @() }
+ foreach ($name in $requiredNames) {
+ if (-not $schema['properties'].Contains([string] $name)) { throw [System.ArgumentException]::new("The required elicitation property '$name' is not defined.") }
+ }
+ if (@($requiredNames).Count -gt 0) { $schema['required'] = [string[]] @($requiredNames) }
+ $schema
+}
+
+function Test-McpInputResponse {
+ <#
+ .SYNOPSIS
+ Validates the client's answer to an input request against the request; -32602 when it does not fit.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.IDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Key,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Request,
+
+ [AllowNull()]
+ [object] $Response
+ )
+
+ $prefix = "Invalid input response '$Key'"
+ $errorData = [ordered]@{ key = $Key }
+ $invalid = { param($reason) [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "${prefix}: $reason", $errorData) }
+ if ($Response -isnot [System.Collections.IDictionary]) { throw (& $invalid 'it must be an object.') }
+ $params = $Request['params']
+ switch ($Request['method']) {
+ 'elicitation/create' {
+ if ($Response['action'] -notin @('accept', 'decline', 'cancel')) { throw (& $invalid "action must be accept, decline or cancel.") }
+ if ($Response['action'] -eq 'accept' -and $params['mode'] -ne 'url') {
+ $content = if ($Response.Contains('content')) { $Response['content'] } else { [ordered]@{} }
+ if ($content -isnot [System.Collections.IDictionary]) { throw (& $invalid 'content must be an object.') }
+ $validation = Test-McpJsonSchema -Schema $params['requestedSchema'] -Instance $content
+ if (-not $validation.IsValid) { throw (& $invalid ("the content does not match the requested schema: " + ($validation.Errors -join '; '))) }
+ }
+ }
+ 'sampling/createMessage' {
+ if ($Response['role'] -notin @('user', 'assistant')) { throw (& $invalid 'role must be user or assistant.') }
+ if ($Response['model'] -isnot [string]) { throw (& $invalid 'model must be a string.') }
+ $content = $Response['content']
+ if ($content -isnot [System.Collections.IDictionary] -and -not ($content -is [System.Collections.IList] -and @($content | Where-Object { $_ -isnot [System.Collections.IDictionary] }).Count -eq 0)) {
+ throw (& $invalid 'content must be a content block or an array of content blocks.')
+ }
+ }
+ 'roots/list' {
+ $roots = $Response['roots']
+ if ($roots -isnot [System.Collections.IList]) { throw (& $invalid 'roots must be an array.') }
+ foreach ($root in $roots) {
+ if ($root -isnot [System.Collections.IDictionary] -or $root['uri'] -isnot [string]) { throw (& $invalid 'every root needs a uri.') }
+ }
+ }
+ }
+ $Response
+}
+
+function Invoke-McpInputRequest {
+ <#
+ .SYNOPSIS
+ The answer to an input request when the client sent it; otherwise records the request and, unless deferred, throws McpInputRequiredException.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.IDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [string] $Key,
+
+ [Parameter(Mandatory)]
+ [System.Collections.Specialized.OrderedDictionary] $Request,
+
+ [Parameter(Mandatory)]
+ [string[]] $Capability,
+
+ [switch] $Defer
+ )
+
+ Test-McpContextInput -Context $Context
+ if ($Context.InputResponses.Contains($Key)) {
+ $response = Test-McpInputResponse -Key $Key -Request $Request -Response $Context.InputResponses[$Key]
+ $Context.ConsumedInput[$Key] = $response
+ return $response
+ }
+ foreach ($required in $Capability) { Assert-McpInputCapability -Context $Context -Capability $required }
+ $Context.PendingInput[$Key] = $Request
+ if (-not $Defer) {
+ throw [McpInputRequiredException]::new($Context.PendingInput)
+ }
+}
+
+function Get-McpInputRequiredResult {
+ <#
+ .SYNOPSIS
+ The InputRequiredResult for the pending input requests of a handler, with a signed requestState for the retry.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.Specialized.OrderedDictionary] $InputRequests,
+
+ [Parameter(Mandatory)]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [hashtable] $Envelope
+ )
+
+ $requested = [ordered]@{}
+ foreach ($key in $InputRequests.Keys) { $requested[$key] = $InputRequests[$key]['method'] }
+ $state = New-McpRequestState -Key $Envelope.RequestStateKey -Method $Envelope.Method -Name $Envelope.Name -Digest $Envelope.RequestDigest -Answers $Context.ConsumedInput -Requested $requested -HandlerState $Context.State -TtlSeconds $Envelope.RequestStateTtlSeconds
+ [ordered]@{
+ resultType = 'input_required'
+ inputRequests = $InputRequests
+ requestState = $state
+ }
+}
+
+function Get-McpRequestInput {
+ <#
+ .SYNOPSIS
+ Verifies requestState and inputResponses of a tools/call, prompts/get or resources/read request (in this order) and merges them.
+ .OUTPUTS
+ A hashtable with InputResponses (the answers of earlier rounds from the state, overlaid with the new ones),
+ HandlerState and Digest.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [Parameter(Mandatory)]
+ [string] $Name,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Params
+ )
+
+ $salient = [ordered]@{}
+ foreach ($key in $Params.Keys) { $salient[$key] = $Params[$key] }
+ if ($Method -ne 'resources/read' -and ($null -eq $salient['arguments'])) { $salient['arguments'] = [ordered]@{} }
+ $digest = Get-McpRequestDigest -Method $Method -Params $salient
+ $responses = [ordered]@{}
+ $handlerState = $null
+ if ($Params.Contains('requestState')) {
+ $payload = Read-McpRequestState -Key $Server.Options.RequestStateKey -Token $Params['requestState'] -Method $Method -Name $Name -Digest $digest
+ if ($payload['a'] -is [System.Collections.IDictionary]) {
+ foreach ($key in $payload['a'].Keys) { $responses[$key] = $payload['a'][$key] }
+ }
+ if ($payload.Contains('s') -and $payload['s'] -is [System.Collections.IDictionary]) { $handlerState = $payload['s'] }
+ }
+ if ($Params.Contains('inputResponses')) {
+ $given = $Params['inputResponses']
+ if ($given -isnot [System.Collections.IDictionary]) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "$Method 'inputResponses' must be an object.")
+ }
+ foreach ($key in $given.Keys) {
+ if ($given[$key] -isnot [System.Collections.IDictionary]) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Input response '$key' must be an object.", [ordered]@{ key = [string] $key })
+ }
+ $responses[[string] $key] = $given[$key]
+ }
+ }
+ @{
+ InputResponses = $responses
+ HandlerState = $handlerState
+ Digest = $digest
+ }
+}
diff --git a/src/Private/RequestState.ps1 b/src/Private/RequestState.ps1
new file mode 100644
index 0000000..0b2a873
--- /dev/null
+++ b/src/Private/RequestState.ps1
@@ -0,0 +1,204 @@
+# requestState of multi-round-trip requests: an opaque token the server hands to the client with an
+# InputRequiredResult and gets back verbatim on the retry. It carries the answers collected in earlier rounds
+# and the handler's own state, bound to the method, the target (tool or prompt name, resource URI), a digest
+# of the arguments and an expiry, and is signed with HMAC-SHA256. It is integrity-protected, not encrypted.
+#
+# Format: base64url(UTF-8 JSON payload) '.' base64url(HMAC-SHA256(key, first part)).
+
+function ConvertTo-McpBase64Url {
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [byte[]] $Bytes
+ )
+
+ [System.Convert]::ToBase64String($Bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_')
+}
+
+function ConvertFrom-McpBase64Url {
+ [CmdletBinding()]
+ [OutputType([byte[]], [System.Array])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Text
+ )
+
+ if ($Text -notmatch '^[A-Za-z0-9_-]*$') { throw [System.FormatException]::new('Not base64url.') }
+ $base64 = $Text.Replace('-', '+').Replace('_', '/')
+ switch ($base64.Length % 4) {
+ 2 { $base64 += '==' }
+ 3 { $base64 += '=' }
+ 1 { throw [System.FormatException]::new('Not base64url.') }
+ }
+ , [System.Convert]::FromBase64String($base64)
+}
+
+function ConvertTo-McpRequestStateKey {
+ <#
+ .SYNOPSIS
+ The 32-byte signing key of requestState: from a SecureString or string (hashed with SHA-256), a byte[] of at least 32 bytes, or random.
+ #>
+ [CmdletBinding()]
+ [OutputType([byte[]], [System.Object[]], [System.Array])]
+ param(
+ [AllowNull()]
+ [object] $Key
+ )
+
+ if ($null -eq $Key) { return , [System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32) }
+ if ($Key -is [byte[]]) {
+ if ($Key.Length -lt 32) { throw [System.ArgumentException]::new('-RequestStateKey must have at least 32 bytes.') }
+ return , [byte[]] $Key.Clone()
+ }
+ $text = if ($Key -is [System.Security.SecureString]) { [System.Net.NetworkCredential]::new('', $Key).Password } elseif ($Key -is [string]) { $Key } else { throw [System.ArgumentException]::new('-RequestStateKey must be a SecureString, a string or a byte[] of at least 32 bytes.') }
+ if ($text.Length -lt 16) { throw [System.ArgumentException]::new('-RequestStateKey must have at least 16 characters.') }
+ , [System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($text))
+}
+
+function ConvertTo-McpCanonicalValue {
+ <#
+ .SYNOPSIS
+ A copy of a JSON value with the members of every object sorted ordinally, for digests that do not depend on member order.
+ #>
+ [CmdletBinding()]
+ [OutputType([object], [System.Collections.Specialized.OrderedDictionary], [System.Array])]
+ param(
+ [AllowNull()]
+ [object] $Value,
+
+ [int] $Depth = 0
+ )
+
+ if ($Depth -gt 64) { throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'The arguments are nested too deeply.') }
+ if ($null -eq $Value) { return $null }
+ if ($Value -is [System.Collections.IDictionary]) {
+ $sorted = [ordered]@{}
+ foreach ($key in @($Value.Keys | ForEach-Object { [string] $_ } | Sort-Object -Culture ([cultureinfo]::InvariantCulture) -CaseSensitive)) {
+ $sorted[$key] = ConvertTo-McpCanonicalValue -Value $Value[$key] -Depth ($Depth + 1)
+ }
+ return $sorted
+ }
+ if ($Value -is [string] -or $Value -isnot [System.Collections.IEnumerable]) { return $Value }
+ , @(foreach ($item in $Value) { ConvertTo-McpCanonicalValue -Value $item -Depth ($Depth + 1) })
+}
+
+function Get-McpRequestDigest {
+ <#
+ .SYNOPSIS
+ A SHA-256 digest (base64url) of the salient params of a request: arguments of tools/call and prompts/get, the URI of resources/read.
+ #>
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Params
+ )
+
+ $salient = [ordered]@{ method = $Method }
+ foreach ($key in 'name', 'uri', 'arguments') {
+ if ($Params.Contains($key)) { $salient[$key] = $Params[$key] }
+ }
+ $json = ConvertTo-McpJson -InputObject (ConvertTo-McpCanonicalValue -Value $salient)
+ ConvertTo-McpBase64Url -Bytes ([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($json)))
+}
+
+function New-McpRequestState {
+ <#
+ .SYNOPSIS
+ Signs a requestState for the next round of a request.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds a token.')]
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [byte[]] $Key,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [Parameter(Mandatory)]
+ [string] $Name,
+
+ [Parameter(Mandatory)]
+ [string] $Digest,
+
+ # The input responses the handler accepted so far (key -> response).
+ [System.Collections.IDictionary] $Answers = [ordered]@{},
+
+ # The input requests of this round (key -> method).
+ [System.Collections.IDictionary] $Requested = [ordered]@{},
+
+ # The handler's own state (Context.State).
+ [AllowNull()]
+ [System.Collections.IDictionary] $HandlerState,
+
+ [int] $TtlSeconds = 600
+ )
+
+ $payload = [ordered]@{
+ v = 1
+ m = $Method
+ n = $Name
+ d = $Digest
+ exp = [System.DateTimeOffset]::UtcNow.AddSeconds($TtlSeconds).ToUnixTimeMilliseconds()
+ nonce = ConvertTo-McpBase64Url -Bytes ([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(12))
+ a = $Answers
+ r = $Requested
+ }
+ if ($null -ne $HandlerState -and $HandlerState.Count -gt 0) { $payload['s'] = $HandlerState }
+ $body = ConvertTo-McpBase64Url -Bytes ([System.Text.Encoding]::UTF8.GetBytes((ConvertTo-McpJson -InputObject $payload)))
+ $mac = [System.Security.Cryptography.HMACSHA256]::HashData($Key, [System.Text.Encoding]::ASCII.GetBytes($body))
+ $body + '.' + (ConvertTo-McpBase64Url -Bytes $mac)
+}
+
+function Read-McpRequestState {
+ <#
+ .SYNOPSIS
+ Verifies a requestState (signature, expiry, method, target, argument digest) and returns its payload; -32602 otherwise.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [byte[]] $Key,
+
+ [AllowNull()]
+ [object] $Token,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [Parameter(Mandatory)]
+ [string] $Name,
+
+ [Parameter(Mandatory)]
+ [string] $Digest
+ )
+
+ $invalid = { param($reason) [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Invalid requestState: $reason.") }
+ if ($Token -isnot [string] -or $Token.Length -gt 1MB) { throw (& $invalid 'not a string of acceptable length') }
+ $parts = $Token.Split('.')
+ if ($parts.Count -ne 2) { throw (& $invalid 'malformed') }
+ $expected = [System.Security.Cryptography.HMACSHA256]::HashData($Key, [System.Text.Encoding]::ASCII.GetBytes($parts[0]))
+ $given = $null
+ try { $given = ConvertFrom-McpBase64Url -Text $parts[1] } catch { $given = $null }
+ if ($null -eq $given -or -not [System.Security.Cryptography.CryptographicOperations]::FixedTimeEquals($expected, $given)) {
+ throw (& $invalid 'the signature does not match')
+ }
+ $payload = $null
+ try {
+ $payload = ConvertFrom-McpJson -Json ([System.Text.Encoding]::UTF8.GetString((ConvertFrom-McpBase64Url -Text $parts[0])))
+ } catch {
+ $payload = $null
+ }
+ if ($payload -isnot [System.Collections.IDictionary] -or $payload['v'] -ne 1) { throw (& $invalid 'unknown format') }
+ if ([long] $payload['exp'] -lt [System.DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()) { throw (& $invalid 'it has expired') }
+ if ($payload['m'] -cne $Method -or $payload['n'] -cne $Name) { throw (& $invalid 'it belongs to another request') }
+ if ($payload['d'] -cne $Digest) { throw (& $invalid 'the arguments differ from the original request') }
+ $payload
+}
diff --git a/src/Private/Server.ps1 b/src/Private/Server.ps1
index 7c6dc03..e8d1396 100644
--- a/src/Private/Server.ps1
+++ b/src/Private/Server.ps1
@@ -73,7 +73,7 @@ function Get-McpServerCapability {
if (Test-McpCompletionCapability -Server $Server) { $capabilities['completions'] = [ordered]@{} }
if ($Server.Prompts.Count -gt 0) { $capabilities['prompts'] = [ordered]@{ listChanged = [bool] $Server.Options.ListChanged } }
if (Test-McpResourceCapability -Server $Server) {
- $capabilities['resources'] = [ordered]@{ subscribe = $false; listChanged = [bool] $Server.Options.ListChanged }
+ $capabilities['resources'] = [ordered]@{ subscribe = [bool] $Server.Options.ListChanged; listChanged = [bool] $Server.Options.ListChanged }
}
$capabilities['tools'] = [ordered]@{ listChanged = [bool] $Server.Options.ListChanged }
$capabilities
diff --git a/src/Private/Subscriptions.ps1 b/src/Private/Subscriptions.ps1
new file mode 100644
index 0000000..22020da
--- /dev/null
+++ b/src/Private/Subscriptions.ps1
@@ -0,0 +1,257 @@
+# subscriptions/listen on the server: listeners (one per open listen request), the acknowledgement that opens
+# every stream, the fan-out of list-changed and resource-updated notifications to the listeners whose filter
+# asked for them (tagged with the subscription id), and the teardown (client cancel, disconnect, graceful
+# close on shutdown). Listen requests never reach the worker pool.
+
+$script:McpListenFilterFlags = [ordered]@{
+ toolsListChanged = 'notifications/tools/list_changed'
+ promptsListChanged = 'notifications/prompts/list_changed'
+ resourcesListChanged = 'notifications/resources/list_changed'
+}
+
+function Get-McpHonouredSubscription {
+ <#
+ .SYNOPSIS
+ Validates a SubscriptionFilter and returns the subset of it the server honours (the types it can deliver).
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [AllowNull()]
+ [object] $Filter
+ )
+
+ if ($Filter -isnot [System.Collections.IDictionary]) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "subscriptions/listen requires an object parameter 'notifications'.")
+ }
+ $capabilities = Get-McpServerCapability -Server $Server
+ $honoured = [ordered]@{}
+ foreach ($flag in $script:McpListenFilterFlags.Keys) {
+ if (-not $Filter.Contains($flag)) { continue }
+ if ($Filter[$flag] -isnot [bool]) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The subscription filter member '$flag' must be a boolean.")
+ }
+ $capability = $capabilities[$flag.Substring(0, $flag.Length - 'ListChanged'.Length)]
+ if ($Filter[$flag] -and $capability -is [System.Collections.IDictionary] -and $capability['listChanged']) { $honoured[$flag] = $true }
+ }
+ if ($Filter.Contains('resourceSubscriptions')) {
+ $uris = $Filter['resourceSubscriptions']
+ if ($uris -isnot [System.Collections.IList] -or @($uris | Where-Object { $_ -isnot [string] }).Count -gt 0) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The subscription filter member 'resourceSubscriptions' must be an array of URIs.")
+ }
+ $resources = $capabilities['resources']
+ if ($uris.Count -gt 0 -and $resources -is [System.Collections.IDictionary] -and $resources['subscribe']) {
+ $honoured['resourceSubscriptions'] = [string[]] @($uris)
+ }
+ }
+ $honoured
+}
+
+function Test-McpListenerMatch {
+ <#
+ .SYNOPSIS
+ Whether a listener's honoured filter asks for a notification.
+ #>
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Honoured,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [AllowNull()]
+ [System.Collections.IDictionary] $Params
+ )
+
+ foreach ($flag in $script:McpListenFilterFlags.Keys) {
+ if ($script:McpListenFilterFlags[$flag] -ceq $Method) { return [bool] $Honoured[$flag] }
+ }
+ if ($Method -ceq 'notifications/resources/updated' -and $Honoured.Contains('resourceSubscriptions') -and $null -ne $Params) {
+ $uri = [string] $Params['uri']
+ foreach ($subscribed in $Honoured['resourceSubscriptions']) {
+ # A sub-resource of a subscribed URI (subscribed/...) is delivered too.
+ if ($uri -ceq $subscribed -or $uri.StartsWith($subscribed.TrimEnd('/') + '/', [System.StringComparison]::Ordinal)) { return $true }
+ }
+ }
+ $false
+}
+
+function Start-McpListener {
+ <#
+ .SYNOPSIS
+ Opens a subscriptions/listen stream: sends the acknowledgement as its first message and registers the listener.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal subscription bookkeeping.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $State,
+
+ [Parameter(Mandatory)]
+ [object] $Id,
+
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Params,
+
+ [AllowNull()]
+ [hashtable] $Channel
+ )
+
+ $honoured = Get-McpHonouredSubscription -Server $State.Server -Filter $(if ($Params.Contains('notifications')) { $Params['notifications'] } else { $null })
+ $meta = [ordered]@{}
+ $meta[$script:McpMetaKey.SubscriptionId] = $Id
+ $notification = New-McpNotification -Method 'notifications/subscriptions/acknowledged' -Params ([ordered]@{ notifications = $honoured; _meta = $meta })
+ $json = ConvertTo-McpJson -InputObject $notification
+ if ($null -ne $Channel -and $Channel.Kind -eq 'Http') {
+ if (-not (Start-McpHttpSse -State $State -Channel $Channel)) { return }
+ if (-not (Write-McpSseChunk -State $State -Channel $Channel -Text "event: message`ndata: $json`n`n")) { return }
+ } else {
+ Send-McpTransportLine -Transport $State.Transport -Line $json
+ }
+ $key = Get-McpRequestKey -Id $Id
+ $State.Listeners[$key] = @{
+ Id = $Id
+ Key = $key
+ Honoured = $honoured
+ Channel = $Channel
+ Opened = [datetime]::UtcNow
+ }
+ Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Subscription $Id opened ($(if ($honoured.Count -gt 0) { @($honoured.Keys) -join ', ' } else { 'nothing honoured' }))."
+}
+
+function Remove-McpListener {
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal subscription bookkeeping.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $State,
+
+ [Parameter(Mandatory)]
+ [string] $Key,
+
+ [string] $Reason = 'closed'
+ )
+
+ if (-not $State.Listeners.ContainsKey($Key)) { return }
+ $listener = $State.Listeners[$Key]
+ $State.Listeners.Remove($Key)
+ if ($null -ne $listener.Channel -and $listener.Channel.Kind -eq 'Http') {
+ Close-McpHttpChannel -State $State -Channel $listener.Channel -Abort
+ }
+ Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Subscription $($listener.Id) $Reason."
+}
+
+function Send-McpListenerNotification {
+ <#
+ .SYNOPSIS
+ Delivers a notification to every listener whose filter asks for it, tagged with the listener's subscription id.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $State,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [AllowNull()]
+ [System.Collections.IDictionary] $Params
+ )
+
+ foreach ($listener in @($State.Listeners.Values)) {
+ if (-not (Test-McpListenerMatch -Honoured $listener.Honoured -Method $Method -Params $Params)) { continue }
+ $tagged = [ordered]@{}
+ if ($null -ne $Params) {
+ foreach ($key in $Params.Keys) { if ([string] $key -ne '_meta') { $tagged[$key] = $Params[$key] } }
+ }
+ $meta = [ordered]@{}
+ if ($null -ne $Params -and $Params['_meta'] -is [System.Collections.IDictionary]) {
+ foreach ($key in $Params['_meta'].Keys) { $meta[$key] = $Params['_meta'][$key] }
+ }
+ $meta[$script:McpMetaKey.SubscriptionId] = $listener.Id
+ $tagged['_meta'] = $meta
+ $json = ConvertTo-McpJson -InputObject (New-McpNotification -Method $Method -Params $tagged)
+ Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "-> $Method on subscription $($listener.Id)"
+ if ($null -ne $listener.Channel -and $listener.Channel.Kind -eq 'Http') {
+ if (-not (Write-McpSseChunk -State $State -Channel $listener.Channel -Text "event: message`ndata: $json`n`n")) {
+ Remove-McpListener -State $State -Key $listener.Key -Reason 'ended: the client closed the stream'
+ }
+ continue
+ }
+ try {
+ Send-McpTransportLine -Transport $State.Transport -Line $json
+ } catch [System.IO.IOException] {
+ Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing to the transport failed: $($_.Exception.Message)"
+ $State.Stopping = $true
+ return
+ }
+ }
+}
+
+function Close-McpAllListener {
+ <#
+ .SYNOPSIS
+ Ends every subscription gracefully: the SubscriptionsListenResult with the subscription id answers each listen request.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal subscription bookkeeping.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $State
+ )
+
+ foreach ($listener in @($State.Listeners.Values)) {
+ $State.Listeners.Remove($listener.Key)
+ $meta = [ordered]@{}
+ $meta[$script:McpMetaKey.SubscriptionId] = $listener.Id
+ $result = Add-McpResultMeta -Result ([ordered]@{ resultType = 'complete'; _meta = $meta }) -Server $State.Server
+ try {
+ Send-McpDispatcherMessage -State $State -Channel $listener.Channel -Message (New-McpResultResponse -Id $listener.Id -Result $result)
+ } catch {
+ Write-Debug "Closing subscription $($listener.Id) failed: $($_.Exception.Message)"
+ }
+ Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Subscription $($listener.Id) closed by the server."
+ }
+}
+
+function Send-McpServerNotification {
+ <#
+ .SYNOPSIS
+ Queues a notification for the listeners of a running server, from a handler (its context) or from any runspace (the server object).
+ #>
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ [System.Collections.IDictionary] $Params,
+
+ [AllowNull()]
+ [object] $Context,
+
+ [AllowNull()]
+ [object] $Server
+ )
+
+ $sink = $null
+ if ($null -ne $Context -and $Context.PSObject.Properties['Sink'] -and $null -ne $Context.Sink) {
+ $sink = $Context.Sink
+ } else {
+ $target = Resolve-McpServer -Server $Server
+ if ($target.State.ContainsKey('Sink')) { $sink = $target.State.Sink }
+ }
+ if ($null -eq $sink) {
+ Write-Verbose "The server is not running; '$Method' is not sent."
+ return $false
+ }
+ $paramsJson = if ($null -ne $Params) { ConvertTo-McpJson -InputObject $Params } else { $null }
+ $sink.Queue.Enqueue(@{ Kind = 'Broadcast'; RequestId = $null; Method = $Method; ParamsJson = $paramsJson })
+ $null = $sink.Signal.Set()
+ $true
+}
diff --git a/src/Private/Transport.ps1 b/src/Private/Transport.ps1
index 4715db4..4c67ff7 100644
--- a/src/Private/Transport.ps1
+++ b/src/Private/Transport.ps1
@@ -193,6 +193,17 @@ function Receive-McpTransportLine {
[int] $TimeoutMs
)
+ if ($Transport.ContainsKey('LineInbox') -and $null -ne $Transport.LineInbox) {
+ # A background pump reads the transport (client subscriptions, ClientSubscriptions.ps1).
+ $inboxLine = $null
+ try {
+ if ($Transport.LineInbox.TryTake([ref] $inboxLine, $TimeoutMs)) { return @{ Status = 'Line'; Line = $inboxLine } }
+ } catch [System.InvalidOperationException] {
+ return @{ Status = 'Eof'; Line = $null }
+ }
+ if ($Transport.LineInbox.IsCompleted) { return @{ Status = 'Eof'; Line = $null } }
+ return @{ Status = 'Timeout'; Line = $null }
+ }
$task = Read-McpTransportLineAsync -Transport $Transport
$completed = $false
try {
diff --git a/src/Private/Worker.ps1 b/src/Private/Worker.ps1
index b20edfc..7409753 100644
--- a/src/Private/Worker.ps1
+++ b/src/Private/Worker.ps1
@@ -1,6 +1,7 @@
# Worker side of a request that runs user code (tools/call, resources/read, prompts/get, completion/complete):
# runs in a runspace of the server's pool, builds the request context, invokes the handler and enqueues the
-# response for the dispatcher.
+# response for the dispatcher; a handler that asks for input (McpInputRequiredException) is answered with an
+# InputRequiredResult.
$script:McpModuleManifestPath = Join-Path $PSScriptRoot 'ModelContextProtocol.psd1'
@@ -39,6 +40,16 @@ function New-McpRequestContext {
ServerName = $Envelope.ServerName
ServerLogLevel = $Envelope.ServerLogLevel
ProgressState = @{ Last = $null }
+ # Multi-round-trip requests: the answers of this and earlier rounds, the requests of this round, the
+ # answers the handler accepted, and handler state that survives the rounds (in the signed requestState).
+ InputResponses = if ($null -ne $Envelope.InputResponses) { $Envelope.InputResponses } else { [ordered]@{} }
+ PendingInput = if ($Envelope.Kind -in @('Tool', 'Resource', 'Prompt')) { [ordered]@{} } else { $null }
+ ConsumedInput = [ordered]@{}
+ State = $(
+ $table = @{}
+ if ($Envelope.HandlerState -is [System.Collections.IDictionary]) { foreach ($key in $Envelope.HandlerState.Keys) { $table[[string] $key] = $Envelope.HandlerState[$key] } }
+ $table
+ )
}
}
@@ -71,6 +82,41 @@ function Send-McpSinkMessage {
$null = $Sink.Signal.Set()
}
+$script:McpWorkerDefinitions = @{}
+
+function Initialize-McpWorkerHandler {
+ <#
+ .SYNOPSIS
+ Makes a handler callable by name in this worker runspace: defines (or redefines) its function and imports its module.
+ .DESCRIPTION
+ The pool defines the handlers registered before the start. Handlers registered, or replaced with -Force,
+ while the server runs are defined here on first use, so that they can be called too.
+ #>
+ [CmdletBinding()]
+ param(
+ [AllowNull()]
+ [hashtable] $Handler
+ )
+
+ if ($null -eq $Handler) { return }
+ if ($Handler.Definition -and $Handler.Kind -in @('ScriptBlock', 'Function')) {
+ $name = $Handler.CommandName
+ if ($script:McpWorkerDefinitions[$name] -cne $Handler.Definition) {
+ if (-not $script:McpWorkerDefinitions.ContainsKey($name) -and (Test-Path -Path "function:global:$name")) {
+ # Defined by the pool: remember its definition instead of replacing it.
+ $script:McpWorkerDefinitions[$name] = (Get-Item -Path "function:global:$name").Definition
+ }
+ if ($script:McpWorkerDefinitions[$name] -cne $Handler.Definition) {
+ # A string value is compiled by the function provider, exactly like the pool's function entries.
+ Set-Item -Path "function:global:$name" -Value $Handler.Definition
+ $script:McpWorkerDefinitions[$name] = $Handler.Definition
+ }
+ }
+ } elseif ($Handler.ModulePath -and -not (Get-Module -Name $Handler.ModuleName)) {
+ Import-Module -Name $Handler.ModulePath -Global
+ }
+}
+
function Invoke-McpWorkerRequest {
<#
.SYNOPSIS
@@ -86,6 +132,10 @@ function Invoke-McpWorkerRequest {
$response = $null
$errorCode = $null
try {
+ switch ($Envelope.Kind) {
+ 'Completion' { if ($null -ne $Envelope.Completion.Source) { Initialize-McpWorkerHandler -Handler $Envelope.Completion.Source.Handler } }
+ default { Initialize-McpWorkerHandler -Handler $Envelope.Registration.Handler }
+ }
$result = switch ($Envelope.Kind) {
'Tool' { Invoke-McpToolHandler -Registration $Envelope.Registration -Arguments $Envelope.Arguments -Context $context -UseCommandName }
'Resource' { Invoke-McpResourceHandler -Registration $Envelope.Registration -Uri $Envelope.Name -Variables $Envelope.Variables -Context $context -CacheHint $Envelope.CacheHint -UseCommandName }
@@ -102,6 +152,17 @@ function Invoke-McpWorkerRequest {
throw
} catch {
$exception = Get-McpHandlerException -Exception $_.Exception
+ if ($exception -is [McpInputRequiredException] -and $null -ne $context.PendingInput) {
+ $result = Get-McpInputRequiredResult -InputRequests $exception.InputRequests -Context $context -Envelope $Envelope
+ if ($Envelope.IncludeServerInfo -and $null -ne $Envelope.ServerInfo) {
+ $meta = [ordered]@{}
+ $meta[$script:McpMetaKey.ServerInfo] = $Envelope.ServerInfo
+ $result['_meta'] = $meta
+ }
+ if ($Envelope.CancellationToken.IsCancellationRequested) { return }
+ Send-McpSinkMessage -Sink $Envelope.Sink -Kind Response -RequestId $Envelope.RequestId -Json (ConvertTo-McpJson -InputObject (New-McpResultResponse -Id $Envelope.RequestId -Result $result))
+ return
+ }
$errorObject = ConvertTo-McpErrorObject -Exception $exception
$errorCode = $errorObject['code']
$response = New-McpErrorResponse -Id $Envelope.RequestId -ErrorObject $errorObject
diff --git a/src/Public/Connect-McpServer.ps1 b/src/Public/Connect-McpServer.ps1
index c2630c3..974a063 100644
--- a/src/Public/Connect-McpServer.ps1
+++ b/src/Public/Connect-McpServer.ps1
@@ -37,7 +37,21 @@ function Connect-McpServer {
.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).
+ The client capabilities declared with every request (default: none, plus what the callbacks imply).
+ .PARAMETER OnElicitation
+ Answers elicitation input requests of multi-round-trip requests: invoked with an Mcp.InputRequest
+ (Key, Mode form or url, Message, RequestedSchema, Url); returns the form content as a hashtable (meaning
+ accept), an ElicitResult (@{ action = 'accept' | 'decline' | 'cancel'; content = @{...} }), or nothing
+ (cancel). Declares the elicitation capability (form and URL mode) unless -Capabilities has one.
+ .PARAMETER OnSampling
+ Answers sampling input requests (deprecated): invoked with an Mcp.InputRequest (Messages, MaxTokens,
+ SystemPrompt, Params); returns a string (the assistant text) or a CreateMessageResult (role, content,
+ model, stopReason). Declares the sampling capability unless -Capabilities has one.
+ .PARAMETER OnRoots
+ Answers roots input requests (deprecated): returns paths or URIs, or hashtables with uri and name.
+ Declares the roots capability unless -Capabilities has one.
+ .PARAMETER MaxInputRounds
+ The maximum number of input rounds of one request before it fails (default: 10).
.PARAMETER ProtocolVersion
The preferred protocol version (default: 2026-07-28).
.PARAMETER RequestTimeoutSeconds
@@ -97,6 +111,15 @@ function Connect-McpServer {
[hashtable] $Capabilities,
+ [scriptblock] $OnElicitation,
+
+ [scriptblock] $OnSampling,
+
+ [scriptblock] $OnRoots,
+
+ [ValidateRange(1, 100)]
+ [int] $MaxInputRounds = 10,
+
[ValidateNotNullOrEmpty()]
[string] $ProtocolVersion = '2026-07-28',
@@ -128,12 +151,16 @@ function Connect-McpServer {
throw [System.ArgumentException]::new('-ClientInfo needs name and version.')
}
$capabilityObject = if ($Capabilities) { ConvertFrom-McpJson -Json (ConvertTo-McpJson -InputObject $Capabilities) } else { [ordered]@{} }
+ if ($OnElicitation -and -not $capabilityObject.Contains('elicitation')) { $capabilityObject['elicitation'] = [ordered]@{ form = [ordered]@{}; url = [ordered]@{} } }
+ if ($OnSampling -and -not $capabilityObject.Contains('sampling')) { $capabilityObject['sampling'] = [ordered]@{} }
+ if ($OnRoots -and -not $capabilityObject.Contains('roots')) { $capabilityObject['roots'] = [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.') }
+ if ($Server.State.Started) { throw [System.InvalidOperationException]::new("Server '$($Server.Name)' is already running; a server object serves one in-memory session at a time.") }
$pair = New-McpInMemoryTransportPair
$background = Start-McpBackgroundServer -Server $Server -Endpoint $pair.Server
$transport = $pair.Client
@@ -163,8 +190,16 @@ function Connect-McpServer {
RequestTimeoutMs = $RequestTimeoutSeconds * 1000
LogLevel = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $null }
OnLog = $OnLog
+ OnElicitation = $OnElicitation
+ OnSampling = $OnSampling
+ OnRoots = $OnRoots
+ MaxInputRounds = $MaxInputRounds
Log = [System.Collections.Generic.List[object]]::new()
Notifications = [System.Collections.Generic.Queue[object]]::new()
+ Subscriptions = [ordered]@{}
+ SubscriptionIds = @{}
+ Inbox = [System.Collections.Concurrent.ConcurrentQueue[hashtable]]::new()
+ PendingEvents = [System.Collections.Generic.List[object]]::new()
StandardErrorPath = $stderrPath
Closed = $false
}
diff --git a/src/Public/Disconnect-McpServer.ps1 b/src/Public/Disconnect-McpServer.ps1
index 03f2e32..5325bf2 100644
--- a/src/Public/Disconnect-McpServer.ps1
+++ b/src/Public/Disconnect-McpServer.ps1
@@ -3,6 +3,7 @@ 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
+ Open subscriptions (Register-McpSubscription) are ended first.
For an in-memory session the background server runspace is stopped as well. Closing the default session
clears the default.
.PARAMETER Session
@@ -27,7 +28,11 @@ function Disconnect-McpServer {
}
if ($target.Closed) { return }
if (-not $PSCmdlet.ShouldProcess("session '$($target.Name)'", 'Disconnect')) { return }
+ foreach ($subscription in @($target.Subscriptions.Values)) {
+ try { Close-McpClientSubscription -Session $target -Subscription $subscription } catch { Write-Debug "Closing subscription $($subscription.Id) failed." }
+ }
$target.Closed = $true
+ Stop-McpTransportPump -Transport $target.Transport
Close-McpTransport -Transport $target.Transport -ExitTimeoutSeconds $ExitTimeoutSeconds
if ($null -ne $target.Background) {
Stop-McpBackgroundServer -Background $target.Background
diff --git a/src/Public/Invoke-McpPrompt.ps1 b/src/Public/Invoke-McpPrompt.ps1
index dba61e2..4156acd 100644
--- a/src/Public/Invoke-McpPrompt.ps1
+++ b/src/Public/Invoke-McpPrompt.ps1
@@ -52,7 +52,7 @@ function Invoke-McpPrompt {
$params['arguments'] = $values
}
$level = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $target.LogLevel }
- $result = Invoke-McpClientRequest -Session $target -Method 'prompts/get' -Params $params -LogLevel $level -TimeoutMs ($TimeoutSeconds * 1000)
+ $result = (Invoke-McpClientRequestWithInput -Session $target -Method 'prompts/get' -Params $params -LogLevel $level -TimeoutMs ($TimeoutSeconds * 1000)).Result
if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains('messages')) {
throw [System.InvalidOperationException]::new('The prompts/get result has no messages member.')
}
diff --git a/src/Public/Invoke-McpTool.ps1 b/src/Public/Invoke-McpTool.ps1
index a1e6c43..e5049ca 100644
--- a/src/Public/Invoke-McpTool.ps1
+++ b/src/Public/Invoke-McpTool.ps1
@@ -50,20 +50,20 @@ function Invoke-McpTool {
$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
+ $result = (Invoke-McpClientRequestWithInput -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs).Result
} else {
# Streamable HTTP mirrors x-mcp-header parameters into Mcp-Param-* headers; the annotations come from the
# 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
+ $result = (Invoke-McpClientRequestWithInput -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs -Headers $headers).Result
} 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
+ $result = (Invoke-McpClientRequestWithInput -Session $target -Method 'tools/call' -Params $params -OnProgress $OnProgress -LogLevel $level -TimeoutMs $timeoutMs -Headers $headers).Result
}
}
if ($result -isnot [System.Collections.IDictionary]) {
diff --git a/src/Public/New-McpServer.ps1 b/src/Public/New-McpServer.ps1
index 2316198..8770ea4 100644
--- a/src/Public/New-McpServer.ps1
+++ b/src/Public/New-McpServer.ps1
@@ -35,6 +35,13 @@ function New-McpServer {
The cacheScope caching hint (public or private) sent with the same results.
.PARAMETER PageSize
The number of items per page of tools/list, resources/list, resources/templates/list and prompts/list.
+ .PARAMETER RequestStateKey
+ The key that signs requestState of multi-round-trip requests (HMAC-SHA256): a SecureString or string of
+ at least 16 characters, or a byte[] of at least 32 bytes. Without it a random key is created per server
+ object; a retry then only succeeds against the same process. Give the same key to every instance behind
+ a load balancer.
+ .PARAMETER RequestStateTtlSeconds
+ How long a requestState stays valid (default 600 seconds).
.PARAMETER LogLevel
The minimum level of diagnostics written to stderr (default: warning).
.PARAMETER NoServerInfo
@@ -86,6 +93,11 @@ function New-McpServer {
[ValidateRange(1, 1000)]
[int] $PageSize = 100,
+ [object] $RequestStateKey,
+
+ [ValidateRange(1, 86400)]
+ [int] $RequestStateTtlSeconds = 600,
+
[McpLoggingLevel] $LogLevel = [McpLoggingLevel]::Warning,
[switch] $NoServerInfo,
@@ -114,16 +126,18 @@ function New-McpServer {
ResourceTemplates = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
Prompts = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
Options = @{
- MaxConcurrency = $MaxConcurrency
- RequestTimeoutSeconds = $RequestTimeoutSeconds
- DefaultTtlMs = $DefaultTtlMs
- DefaultCacheScope = $DefaultCacheScope
- PageSize = $PageSize
- LogLevel = $LogLevel
- IncludeServerInfo = -not $NoServerInfo
- # listChanged (tools, prompts, resources) is advertised once subscriptions/listen can deliver the
- # notifications (milestone M4).
- ListChanged = $false
+ MaxConcurrency = $MaxConcurrency
+ RequestTimeoutSeconds = $RequestTimeoutSeconds
+ DefaultTtlMs = $DefaultTtlMs
+ DefaultCacheScope = $DefaultCacheScope
+ PageSize = $PageSize
+ LogLevel = $LogLevel
+ IncludeServerInfo = -not $NoServerInfo
+ # listChanged (tools, prompts, resources) and resources.subscribe: delivered on subscriptions/listen streams.
+ ListChanged = $true
+ RequestStateKey = ConvertTo-McpRequestStateKey -Key $RequestStateKey
+ RequestStateKeyGiven = $PSBoundParameters.ContainsKey('RequestStateKey')
+ RequestStateTtlSeconds = $RequestStateTtlSeconds
}
State = @{
Started = $false
diff --git a/src/Public/Read-McpResource.ps1 b/src/Public/Read-McpResource.ps1
index 0922e9d..83d9b76 100644
--- a/src/Public/Read-McpResource.ps1
+++ b/src/Public/Read-McpResource.ps1
@@ -54,7 +54,8 @@ function Read-McpResource {
continue
}
try {
- $result = Invoke-McpClientRequest -Session $target -Method 'resources/read' -Params ([ordered]@{ uri = $item }) -LogLevel $level -TimeoutMs ($TimeoutSeconds * 1000)
+ $exchange = Invoke-McpClientRequestWithInput -Session $target -Method 'resources/read' -Params ([ordered]@{ uri = $item }) -LogLevel $level -TimeoutMs ($TimeoutSeconds * 1000)
+ $result = $exchange.Result
} catch [McpProtocolException] {
if (-not (Test-McpResourceNotFoundError -Exception $_.Exception)) { throw }
$record = [System.Management.Automation.ErrorRecord]::new(
@@ -69,7 +70,8 @@ function Read-McpResource {
throw [System.InvalidOperationException]::new('The resources/read result has no contents member.')
}
$contents = @(@($result['contents']) | Where-Object { $_ -is [System.Collections.IDictionary] } | ForEach-Object { ConvertTo-McpResourceContentObject -Content $_ })
- Set-McpClientCacheEntry -Session $target -Key $key -Value $contents -CacheHint (Get-McpResultCacheHint -Result $result)
+ # Results that needed input rounds are not cached (the specification forbids caching them).
+ if ($exchange.Rounds -eq 0) { Set-McpClientCacheEntry -Session $target -Key $key -Value $contents -CacheHint (Get-McpResultCacheHint -Result $result) }
foreach ($content in $contents) { $content }
}
}
diff --git a/src/Public/Receive-McpNotification.ps1 b/src/Public/Receive-McpNotification.ps1
new file mode 100644
index 0000000..30fedc1
--- /dev/null
+++ b/src/Public/Receive-McpNotification.ps1
@@ -0,0 +1,60 @@
+function Receive-McpNotification {
+ <#
+ .SYNOPSIS
+ Returns the notifications received on subscriptions, waiting up to a timeout for the first one.
+ .DESCRIPTION
+ Returns and removes the queued notifications (Mcp.Notification) of the given subscriptions, or of all
+ subscriptions of the session. With -TimeoutSeconds it waits until at least one notification has arrived
+ or the timeout has passed; without, it returns what is queued. Notifications of subscriptions with an
+ -Action are passed to the script block instead (while this command waits, too) and are not returned.
+ .PARAMETER Subscription
+ The subscriptions to read; defaults to all subscriptions of the session.
+ .PARAMETER TimeoutSeconds
+ How long to wait for a notification (default: 0, do not wait).
+ .PARAMETER Session
+ Without -Subscription, the session; defaults to the default session.
+ .EXAMPLE
+ Receive-McpNotification -Subscription $subscription -TimeoutSeconds 30
+ .OUTPUTS
+ Mcp.Notification
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.Notification')]
+ param(
+ [Parameter(Position = 0, ValueFromPipeline)]
+ [object[]] $Subscription,
+
+ [ValidateRange(0, 86400)]
+ [double] $TimeoutSeconds = 0,
+
+ [object] $Session
+ )
+
+ begin {
+ $selected = [System.Collections.Generic.List[object]]::new()
+ }
+ process {
+ foreach ($item in $Subscription) {
+ if ($item.PSObject.TypeNames -notcontains 'Mcp.Subscription') {
+ throw [System.ArgumentException]::new('-Subscription takes subscriptions returned by Register-McpSubscription.')
+ }
+ $selected.Add($item)
+ }
+ }
+ end {
+ $target = if ($selected.Count -gt 0) { $selected[0].Session } else { Resolve-McpSession -Session $Session }
+ if ($target.Closed) {
+ # A closed session keeps what was queued before it closed.
+ $sources = @($selected)
+ } else {
+ $null = Resolve-McpSession -Session $target
+ $sources = if ($selected.Count -gt 0) { @($selected) } else { @($target.Subscriptions.Values) }
+ $hasQueued = { foreach ($source in $sources) { if (-not $source.Notifications.IsEmpty) { return $true } }; $false }
+ $null = Wait-McpClientEvent -Session $target -Condition $hasQueued -TimeoutMs ([int] ($TimeoutSeconds * 1000))
+ }
+ foreach ($source in $sources) {
+ $notification = $null
+ while ($source.Notifications.TryDequeue([ref] $notification)) { $notification }
+ }
+ }
+}
diff --git a/src/Public/Register-McpPrompt.ps1 b/src/Public/Register-McpPrompt.ps1
index 219c993..16f8859 100644
--- a/src/Public/Register-McpPrompt.ps1
+++ b/src/Public/Register-McpPrompt.ps1
@@ -142,5 +142,6 @@ function Register-McpPrompt {
Completion = ConvertTo-McpCompletionSource -Completion $derivedCompletion -ArgumentNames $argumentNames -Key $Name
}
$target.Prompts[$Name] = $registration
+ if ($target.State.Started) { $null = Send-McpServerNotification -Method 'notifications/prompts/list_changed' -Server $target }
if ($PassThru) { $registration }
}
diff --git a/src/Public/Register-McpResource.ps1 b/src/Public/Register-McpResource.ps1
index b1a49cd..603b7ff 100644
--- a/src/Public/Register-McpResource.ps1
+++ b/src/Public/Register-McpResource.ps1
@@ -244,5 +244,6 @@ function Register-McpResource {
# Assigned separately: an if expression would enumerate a byte[] into an object[].
if ($source -eq 'Content') { $registration.Content = $Content }
if ($kind -eq 'Resource') { $target.Resources[$Uri] = $registration } else { $target.ResourceTemplates[$UriTemplate] = $registration }
+ if ($target.State.Started) { $null = Send-McpServerNotification -Method 'notifications/resources/list_changed' -Server $target }
if ($PassThru) { $registration }
}
diff --git a/src/Public/Register-McpSubscription.ps1 b/src/Public/Register-McpSubscription.ps1
new file mode 100644
index 0000000..4319a7d
--- /dev/null
+++ b/src/Public/Register-McpSubscription.ps1
@@ -0,0 +1,124 @@
+function Register-McpSubscription {
+ <#
+ .SYNOPSIS
+ Opens a subscriptions/listen stream: list-changed notifications of tools, prompts and resources and updates of resources.
+ .DESCRIPTION
+ The server acknowledges the subscription with the subset of the requested notification types it honours
+ (the Honoured property); requested types the server does not support are dropped silently. Received
+ notifications invalidate the session's result cache (a list-changed notification the cached list,
+ a resource update the cached contents of the resource and its sub-resources) and are either queued for
+ Receive-McpNotification or, with -Action, passed to the script block.
+
+ Notifications are read in the background; the script block runs in the caller's runspace whenever a
+ client command of this module runs on the session (Receive-McpNotification waits for them). Over
+ Streamable HTTP each subscription is its own long-lived POST with an SSE response; an abruptly closed
+ stream is reopened with a new request id (backoff 1, 2, 4, 8, 16 seconds; see -NoReconnect). Over stdio
+ the subscription shares the server's output stream with the requests.
+
+ The subscription ends with Unregister-McpSubscription, Disconnect-McpServer or when the server closes it
+ (State Closed).
+ .PARAMETER ToolsListChanged
+ Subscribe to notifications/tools/list_changed.
+ .PARAMETER PromptsListChanged
+ Subscribe to notifications/prompts/list_changed.
+ .PARAMETER ResourcesListChanged
+ Subscribe to notifications/resources/list_changed.
+ .PARAMETER ResourceUri
+ Subscribe to notifications/resources/updated of these resources (and their sub-resources).
+ .PARAMETER Action
+ A script block invoked with each notification (Mcp.Notification: Method, Uri, SubscriptionId, Params,
+ Received) instead of queueing it for Receive-McpNotification.
+ .PARAMETER NoReconnect
+ Over Streamable HTTP, do not reopen a stream that closed abruptly; the subscription ends instead.
+ .PARAMETER TimeoutSeconds
+ How long to wait for the server's acknowledgement (default: 30).
+ .PARAMETER Session
+ The session; defaults to the default session.
+ .EXAMPLE
+ $subscription = Register-McpSubscription -ToolsListChanged -ResourceUri 'file:///var/log/app.log'
+ Receive-McpNotification -Subscription $subscription -TimeoutSeconds 60
+ .EXAMPLE
+ Register-McpSubscription -ToolsListChanged -Action { param($Notification) Write-Host "Tools changed: $($Notification.Method)" }
+ .OUTPUTS
+ Mcp.Subscription
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.Subscription')]
+ param(
+ [switch] $ToolsListChanged,
+
+ [switch] $PromptsListChanged,
+
+ [switch] $ResourcesListChanged,
+
+ [ValidateNotNullOrEmpty()]
+ [string[]] $ResourceUri,
+
+ [scriptblock] $Action,
+
+ [switch] $NoReconnect,
+
+ [ValidateRange(1, 3600)]
+ [int] $TimeoutSeconds = 30,
+
+ [object] $Session
+ )
+
+ $target = Resolve-McpSession -Session $Session
+ $filter = [ordered]@{}
+ if ($ToolsListChanged) { $filter['toolsListChanged'] = $true }
+ if ($PromptsListChanged) { $filter['promptsListChanged'] = $true }
+ if ($ResourcesListChanged) { $filter['resourcesListChanged'] = $true }
+ if ($ResourceUri) { $filter['resourceSubscriptions'] = [string[]] @($ResourceUri) }
+ if ($filter.Count -eq 0) {
+ throw [System.ArgumentException]::new('Subscribe to at least one notification type: -ToolsListChanged, -PromptsListChanged, -ResourcesListChanged or -ResourceUri.')
+ }
+
+ $id = [int] $target.NextId
+ $target.NextId = $id + 1
+ $subscription = [pscustomobject]@{
+ PSTypeName = 'Mcp.Subscription'
+ Id = $id
+ CurrentId = $id
+ State = 'Opening'
+ Requested = $filter
+ Honoured = $null
+ Reconnects = 0
+ Error = $null
+ Action = $Action
+ Notifications = [System.Collections.Concurrent.ConcurrentQueue[object]]::new()
+ NoReconnect = [bool] $NoReconnect
+ StopRequested = $false
+ Cts = $null
+ Reader = $null
+ Session = $target
+ }
+ $target.Subscriptions[[string] $id] = $subscription
+ $target.SubscriptionIds[[string] $id] = $subscription
+
+ try {
+ if ($target.Kind -eq 'Http') {
+ $subscription.Cts = [System.Threading.CancellationTokenSource]::new()
+ $subscription.Reader = New-McpClientBackgroundRunspace -FunctionName 'Invoke-McpHttpListenLoop' -Parameters @{ Session = $target; Subscription = $subscription }
+ } else {
+ Start-McpTransportPump -Transport $target.Transport
+ $params = [ordered]@{ _meta = (New-McpClientRequestMeta -Session $target); notifications = $filter }
+ Send-McpTransportLine -Transport $target.Transport -Line (ConvertTo-McpJson -InputObject (New-McpRequest -Id $id -Method 'subscriptions/listen' -Params $params))
+ }
+ $acknowledged = Wait-McpClientEvent -Session $target -Condition { $subscription.State -ne 'Opening' } -TimeoutMs ($TimeoutSeconds * 1000)
+ } catch {
+ Close-McpClientSubscription -Session $target -Subscription $subscription
+ throw
+ }
+ if (-not $acknowledged) {
+ Close-McpClientSubscription -Session $target -Subscription $subscription
+ throw [System.TimeoutException]::new("The server did not acknowledge the subscription (id $id) within $TimeoutSeconds s.")
+ }
+ if ($subscription.State -ne 'Open') {
+ Close-McpClientSubscription -Session $target -Subscription $subscription
+ if ($subscription.Error -is [System.Exception]) { throw $subscription.Error }
+ $reason = if ($subscription.Error) { ": $($subscription.Error)" } else { '.' }
+ throw [System.InvalidOperationException]::new("The server ended the subscription (id $id) before acknowledging it$reason")
+ }
+ $subscription
+}
diff --git a/src/Public/Register-McpTool.ps1 b/src/Public/Register-McpTool.ps1
index 250bebf..e45f66d 100644
--- a/src/Public/Register-McpTool.ps1
+++ b/src/Public/Register-McpTool.ps1
@@ -164,5 +164,6 @@ function Register-McpTool {
Handler = $handler
}
$target.Tools[$Name] = $registration
+ if ($target.State.Started) { $null = Send-McpServerNotification -Method 'notifications/tools/list_changed' -Server $target }
if ($PassThru) { $registration }
}
diff --git a/src/Public/Request-McpElicitation.ps1 b/src/Public/Request-McpElicitation.ps1
new file mode 100644
index 0000000..30933b9
--- /dev/null
+++ b/src/Public/Request-McpElicitation.ps1
@@ -0,0 +1,93 @@
+function Request-McpElicitation {
+ <#
+ .SYNOPSIS
+ Asks the user, through the client, for input: a form (elicitation/create in form mode) or a URL to visit (URL mode).
+ .DESCRIPTION
+ Multi-round-trip request (MRTR): the first time a handler calls this command, the answer is not there
+ yet; the command throws, the server answers the request with an InputRequiredResult carrying this
+ elicitation, and the client retries the request with the user's answer. The handler then runs again
+ from the start and this command returns the answer (Mcp.ElicitResult: Action accept, decline or cancel,
+ and Content with the form values). A handler must therefore be idempotent up to its last input request;
+ answers of earlier rounds are kept in the signed requestState.
+
+ The client must have declared the elicitation capability (form mode) or elicitation.url (URL mode);
+ otherwise the request fails with -32021 and the required capability. Check with
+ Test-McpClientCapability first to offer a fallback. Accepted form content is validated against -Schema.
+ .PARAMETER Context
+ The request context (the handler's Context parameter).
+ .PARAMETER Key
+ The identifier of this input request within the handler; the answer is looked up by it.
+ .PARAMETER Message
+ The message shown to the user.
+ .PARAMETER Schema
+ The form: a table of properties (name = @{ type = 'string'; title = ...; ... }) or a full schema
+ (@{ type = 'object'; properties = @{ ... }; required = @(...) }). Only flat primitive properties are
+ allowed: string (format email, uri, date, date-time), number, integer, boolean and enums.
+ .PARAMETER Required
+ The names of required form properties (overrides required of a full schema).
+ .PARAMETER Url
+ The URL the user should open (URL mode), for interactions that must not pass through the client.
+ .PARAMETER Defer
+ Record the request without throwing and return nothing when the answer is missing; call Wait-McpInput
+ after deferring several requests to ask for all of them in one round.
+ .EXAMPLE
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message 'Delete 3 files?' -Schema @{ ok = @{ type = 'boolean' } } -Required ok
+ if ($answer.Action -ne 'accept' -or -not $answer.Content.ok) { return 'Cancelled.' }
+ .OUTPUTS
+ Mcp.ElicitResult
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Form')]
+ [OutputType('Mcp.ElicitResult')]
+ param(
+ [Parameter(Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Key,
+
+ [Parameter(Mandatory)]
+ [string] $Message,
+
+ [Parameter(ParameterSetName = 'Form', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Schema,
+
+ [Parameter(ParameterSetName = 'Form')]
+ [string[]] $Required,
+
+ [Parameter(ParameterSetName = 'Url', Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Url,
+
+ [switch] $Defer
+ )
+
+ $params = [ordered]@{}
+ if ($PSCmdlet.ParameterSetName -eq 'Url') {
+ $parsed = $null
+ if (-not [uri]::TryCreate($Url, [System.UriKind]::Absolute, [ref] $parsed)) { throw [System.ArgumentException]::new("'$Url' is not an absolute URL.") }
+ $params['mode'] = 'url'
+ $params['message'] = $Message
+ $params['url'] = $Url
+ $capability = 'elicitation.url'
+ } else {
+ $schemaParameters = @{ Schema = $Schema }
+ if ($PSBoundParameters.ContainsKey('Required')) { $schemaParameters['Required'] = $Required }
+ $params['mode'] = 'form'
+ $params['message'] = $Message
+ $params['requestedSchema'] = ConvertTo-McpElicitationSchema @schemaParameters
+ $capability = 'elicitation.form'
+ }
+ $request = [ordered]@{ method = 'elicitation/create'; params = $params }
+ $response = Invoke-McpInputRequest -Context $Context -Key $Key -Request $request -Capability $capability -Defer:$Defer
+ if ($null -eq $response) { return }
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.ElicitResult'
+ Key = $Key
+ Action = [string] $response['action']
+ Accepted = $response['action'] -eq 'accept'
+ Content = if ($response.Contains('content')) { $response['content'] } else { $null }
+ }
+}
diff --git a/src/Public/Request-McpRoot.ps1 b/src/Public/Request-McpRoot.ps1
new file mode 100644
index 0000000..0586e01
--- /dev/null
+++ b/src/Public/Request-McpRoot.ps1
@@ -0,0 +1,46 @@
+function Request-McpRoot {
+ <#
+ .SYNOPSIS
+ Asks the client for its roots (roots/list as an input request): the directories or files the server may work in.
+ .DESCRIPTION
+ Multi-round-trip request (MRTR), deprecated in revision 2026-07-28 but supported: the first call throws
+ and the server answers with an InputRequiredResult; when the client retries with its roots, the handler
+ runs again and this command returns them (Mcp.Root: Uri, Name). The client must have declared the roots
+ capability; otherwise -32021.
+ .PARAMETER Context
+ The request context (the handler's Context parameter).
+ .PARAMETER Key
+ The identifier of this input request within the handler.
+ .PARAMETER Defer
+ Record the request without throwing when the answer is missing (see Wait-McpInput).
+ .EXAMPLE
+ Request-McpRoot -Context $Context -Key 'roots' | Select-Object -ExpandProperty Uri
+ .OUTPUTS
+ Mcp.Root
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.Root')]
+ param(
+ [Parameter(Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Key,
+
+ [switch] $Defer
+ )
+
+ $request = [ordered]@{ method = 'roots/list'; params = [ordered]@{} }
+ $response = Invoke-McpInputRequest -Context $Context -Key $Key -Request $request -Capability 'roots' -Defer:$Defer
+ if ($null -eq $response) { return }
+ foreach ($root in @($response['roots'])) {
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.Root'
+ Uri = [string] $root['uri']
+ Name = if ($root.Contains('name')) { [string] $root['name'] } else { $null }
+ Meta = if ($root.Contains('_meta')) { $root['_meta'] } else { $null }
+ }
+ }
+}
diff --git a/src/Public/Request-McpSampling.ps1 b/src/Public/Request-McpSampling.ps1
new file mode 100644
index 0000000..f5697f1
--- /dev/null
+++ b/src/Public/Request-McpSampling.ps1
@@ -0,0 +1,126 @@
+function Request-McpSampling {
+ <#
+ .SYNOPSIS
+ Asks the client's language model for a completion (sampling/createMessage as an input request).
+ .DESCRIPTION
+ Multi-round-trip request (MRTR), deprecated in revision 2026-07-28 but supported: the first call throws
+ and the server answers with an InputRequiredResult; when the client retries with the model's answer,
+ the handler runs again and this command returns it (Mcp.SamplingResult: Role, Content, Model,
+ StopReason and the Text of text blocks). The client must have declared the sampling capability
+ (sampling.tools for -Tools, sampling.context for -IncludeContext other than none); otherwise -32021.
+ .PARAMETER Context
+ The request context (the handler's Context parameter).
+ .PARAMETER Key
+ The identifier of this input request within the handler.
+ .PARAMETER Messages
+ The conversation: strings (user text), content blocks (New-McpContent, user messages) or hashtables
+ with role and content.
+ .PARAMETER MaxTokens
+ The maximum number of tokens to sample.
+ .PARAMETER SystemPrompt
+ An optional system prompt.
+ .PARAMETER Temperature
+ The sampling temperature.
+ .PARAMETER StopSequences
+ Sequences that stop sampling.
+ .PARAMETER ModelPreferences
+ Model preferences: hints (@(@{ name = '...' })), costPriority, speedPriority, intelligencePriority.
+ .PARAMETER Tools
+ Tool definitions the model may call (hashtables with name, description and inputSchema).
+ .PARAMETER ToolChoice
+ How the model uses the tools: auto, none or required.
+ .PARAMETER IncludeContext
+ Context from MCP servers to include: none, thisServer or allServers (deprecated values).
+ .PARAMETER Metadata
+ Provider-specific metadata.
+ .PARAMETER Defer
+ Record the request without throwing when the answer is missing (see Wait-McpInput).
+ .EXAMPLE
+ (Request-McpSampling -Context $Context -Key 'summary' -Messages "Summarise: $text" -MaxTokens 200).Text
+ .OUTPUTS
+ Mcp.SamplingResult
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.SamplingResult')]
+ param(
+ [Parameter(Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Key,
+
+ [Parameter(Mandatory)]
+ [object[]] $Messages,
+
+ [ValidateRange(1, [int]::MaxValue)]
+ [int] $MaxTokens = 1000,
+
+ [string] $SystemPrompt,
+
+ [double] $Temperature,
+
+ [string[]] $StopSequences,
+
+ [hashtable] $ModelPreferences,
+
+ [object[]] $Tools,
+
+ [ValidateSet('auto', 'none', 'required')]
+ [string] $ToolChoice,
+
+ [ValidateSet('none', 'thisServer', 'allServers')]
+ [string] $IncludeContext,
+
+ [hashtable] $Metadata,
+
+ [switch] $Defer
+ )
+
+ $wireMessages = foreach ($message in $Messages) {
+ if ($null -eq $message) { continue }
+ if ($message -is [string]) {
+ [ordered]@{ role = 'user'; content = [ordered]@{ type = 'text'; text = $message } }
+ } elseif (Test-McpContentObject -Value $message) {
+ [ordered]@{ role = 'user'; content = $message }
+ } elseif ($message -is [System.Collections.IDictionary] -and $message.Contains('role') -and $message.Contains('content')) {
+ $content = $message['content']
+ if ($content -is [string]) { $content = [ordered]@{ type = 'text'; text = $content } }
+ [ordered]@{ role = [string] $message['role']; content = $content }
+ } else {
+ throw [System.ArgumentException]::new('-Messages accepts strings, content blocks and hashtables with role and content.')
+ }
+ }
+ $params = [ordered]@{ messages = @($wireMessages); maxTokens = $MaxTokens }
+ if ($SystemPrompt) { $params['systemPrompt'] = $SystemPrompt }
+ if ($PSBoundParameters.ContainsKey('Temperature')) { $params['temperature'] = $Temperature }
+ if ($StopSequences) { $params['stopSequences'] = $StopSequences }
+ if ($ModelPreferences) { $params['modelPreferences'] = $ModelPreferences }
+ if ($Metadata) { $params['metadata'] = $Metadata }
+ $capabilities = [System.Collections.Generic.List[string]]::new()
+ $capabilities.Add('sampling')
+ if ($Tools) {
+ $params['tools'] = @($Tools)
+ $capabilities.Add('sampling.tools')
+ }
+ if ($ToolChoice) { $params['toolChoice'] = [ordered]@{ mode = $ToolChoice } }
+ if ($IncludeContext) {
+ $params['includeContext'] = $IncludeContext
+ if ($IncludeContext -ne 'none') { $capabilities.Add('sampling.context') }
+ }
+ $request = [ordered]@{ method = 'sampling/createMessage'; params = $params }
+ $response = Invoke-McpInputRequest -Context $Context -Key $Key -Request $request -Capability $capabilities.ToArray() -Defer:$Defer
+ if ($null -eq $response) { return }
+ $blocks = @($response['content'])
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.SamplingResult'
+ Key = $Key
+ Role = [string] $response['role']
+ Content = $response['content']
+ Model = [string] $response['model']
+ StopReason = if ($response.Contains('stopReason')) { $response['stopReason'] } else { $null }
+ Text = (@($blocks | Where-Object { $_ -is [System.Collections.IDictionary] -and $_['type'] -eq 'text' } | ForEach-Object { [string] $_['text'] })) -join "`n"
+ Raw = $response
+ }
+}
diff --git a/src/Public/Send-McpPromptListChanged.ps1 b/src/Public/Send-McpPromptListChanged.ps1
new file mode 100644
index 0000000..312f73a
--- /dev/null
+++ b/src/Public/Send-McpPromptListChanged.ps1
@@ -0,0 +1,29 @@
+function Send-McpPromptListChanged {
+ <#
+ .SYNOPSIS
+ Sends notifications/prompts/list_changed to the clients listening for prompt list changes.
+ .DESCRIPTION
+ The notification goes to every open subscriptions/listen stream whose filter asked for
+ promptsListChanged, tagged with the stream's subscription id. Register-McpPrompt and Unregister-McpPrompt
+ send it automatically while the server runs; call this command when the list changes otherwise. It
+ works from a handler (-Context) and from any runspace that holds the server object (-Server); when the
+ server is not running, nothing is sent.
+ .PARAMETER Context
+ The request context of a handler (its Context parameter).
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Send-McpPromptListChanged -Server $server
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Server')]
+ param(
+ [Parameter(ParameterSetName = 'Context', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(ParameterSetName = 'Server')]
+ [object] $Server
+ )
+
+ $null = Send-McpServerNotification -Method 'notifications/prompts/list_changed' -Context $Context -Server $Server
+}
diff --git a/src/Public/Send-McpResourceListChanged.ps1 b/src/Public/Send-McpResourceListChanged.ps1
new file mode 100644
index 0000000..0bf62a3
--- /dev/null
+++ b/src/Public/Send-McpResourceListChanged.ps1
@@ -0,0 +1,29 @@
+function Send-McpResourceListChanged {
+ <#
+ .SYNOPSIS
+ Sends notifications/resources/list_changed to the clients listening for resource list changes.
+ .DESCRIPTION
+ The notification goes to every open subscriptions/listen stream whose filter asked for
+ resourcesListChanged, tagged with the stream's subscription id. Register-McpResource and Unregister-McpResource
+ send it automatically while the server runs; call this command when the list changes otherwise. It
+ works from a handler (-Context) and from any runspace that holds the server object (-Server); when the
+ server is not running, nothing is sent.
+ .PARAMETER Context
+ The request context of a handler (its Context parameter).
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Send-McpResourceListChanged -Server $server
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Server')]
+ param(
+ [Parameter(ParameterSetName = 'Context', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(ParameterSetName = 'Server')]
+ [object] $Server
+ )
+
+ $null = Send-McpServerNotification -Method 'notifications/resources/list_changed' -Context $Context -Server $Server
+}
diff --git a/src/Public/Send-McpResourceUpdated.ps1 b/src/Public/Send-McpResourceUpdated.ps1
new file mode 100644
index 0000000..26ea107
--- /dev/null
+++ b/src/Public/Send-McpResourceUpdated.ps1
@@ -0,0 +1,39 @@
+function Send-McpResourceUpdated {
+ <#
+ .SYNOPSIS
+ Sends notifications/resources/updated for a resource to the clients that subscribed to it.
+ .DESCRIPTION
+ The notification goes to every open subscriptions/listen stream whose resourceSubscriptions contain the
+ URI, or a URI it lies below (a subscription to 'docs://guide' also receives 'docs://guide/intro.md'),
+ tagged with the stream's subscription id. It works from a handler (-Context) and from any runspace that
+ holds the server object (-Server); when the server is not running, nothing is sent.
+ .PARAMETER Uri
+ The URI of the resource that changed.
+ .PARAMETER Context
+ The request context of a handler (its Context parameter).
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Send-McpResourceUpdated -Uri 'config://app' -Server $server
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Server')]
+ param(
+ [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
+ [ValidateNotNullOrEmpty()]
+ [string[]] $Uri,
+
+ [Parameter(ParameterSetName = 'Context', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(ParameterSetName = 'Server')]
+ [object] $Server
+ )
+
+ process {
+ foreach ($item in $Uri) {
+ if (-not (Test-McpResourceUri -Uri $item)) { throw [System.ArgumentException]::new("'$item' is not an absolute URI.") }
+ $null = Send-McpServerNotification -Method 'notifications/resources/updated' -Params ([ordered]@{ uri = $item }) -Context $Context -Server $Server
+ }
+ }
+}
diff --git a/src/Public/Send-McpToolListChanged.ps1 b/src/Public/Send-McpToolListChanged.ps1
new file mode 100644
index 0000000..a29fc78
--- /dev/null
+++ b/src/Public/Send-McpToolListChanged.ps1
@@ -0,0 +1,29 @@
+function Send-McpToolListChanged {
+ <#
+ .SYNOPSIS
+ Sends notifications/tools/list_changed to the clients listening for tool list changes.
+ .DESCRIPTION
+ The notification goes to every open subscriptions/listen stream whose filter asked for
+ toolsListChanged, tagged with the stream's subscription id. Register-McpTool and Unregister-McpTool
+ send it automatically while the server runs; call this command when the list changes otherwise. It
+ works from a handler (-Context) and from any runspace that holds the server object (-Server); when the
+ server is not running, nothing is sent.
+ .PARAMETER Context
+ The request context of a handler (its Context parameter).
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Send-McpToolListChanged -Server $server
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Server')]
+ param(
+ [Parameter(ParameterSetName = 'Context', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context,
+
+ [Parameter(ParameterSetName = 'Server')]
+ [object] $Server
+ )
+
+ $null = Send-McpServerNotification -Method 'notifications/tools/list_changed' -Context $Context -Server $Server
+}
diff --git a/src/Public/Unregister-McpPrompt.ps1 b/src/Public/Unregister-McpPrompt.ps1
new file mode 100644
index 0000000..f5feb03
--- /dev/null
+++ b/src/Public/Unregister-McpPrompt.ps1
@@ -0,0 +1,31 @@
+function Unregister-McpPrompt {
+ <#
+ .SYNOPSIS
+ Removes a prompt from a server; while the server runs, listening clients are told that the prompt list changed.
+ .PARAMETER Name
+ The prompt name.
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Unregister-McpPrompt -Name 'summarize'
+ #>
+ [CmdletBinding(SupportsShouldProcess)]
+ param(
+ [Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
+ [ValidateNotNullOrEmpty()]
+ [string[]] $Name,
+
+ [object] $Server
+ )
+
+ process {
+ $target = Resolve-McpServer -Server $Server
+ foreach ($item in $Name) {
+ if (-not $target.Prompts.Contains($item)) { throw [System.ArgumentException]::new("No prompt named '$item' is registered.") }
+ if ($PSCmdlet.ShouldProcess($item, 'Unregister MCP prompt')) {
+ $target.Prompts.Remove($item)
+ $null = Send-McpServerNotification -Method 'notifications/prompts/list_changed' -Server $target
+ }
+ }
+ }
+}
diff --git a/src/Public/Unregister-McpResource.ps1 b/src/Public/Unregister-McpResource.ps1
new file mode 100644
index 0000000..1c795d4
--- /dev/null
+++ b/src/Public/Unregister-McpResource.ps1
@@ -0,0 +1,38 @@
+function Unregister-McpResource {
+ <#
+ .SYNOPSIS
+ Removes a resource or resource template from a server; while the server runs, listening clients are told that the resource list changed.
+ .PARAMETER Uri
+ The URI of a resource.
+ .PARAMETER UriTemplate
+ The URI template of a resource template.
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Unregister-McpResource -Uri 'config://app'
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Uri', SupportsShouldProcess)]
+ param(
+ [Parameter(ParameterSetName = 'Uri', Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
+ [ValidateNotNullOrEmpty()]
+ [string[]] $Uri,
+
+ [Parameter(ParameterSetName = 'UriTemplate', Mandatory, ValueFromPipelineByPropertyName)]
+ [ValidateNotNullOrEmpty()]
+ [string[]] $UriTemplate,
+
+ [object] $Server
+ )
+
+ process {
+ $target = Resolve-McpServer -Server $Server
+ $registry = if ($PSCmdlet.ParameterSetName -eq 'Uri') { $target.Resources } else { $target.ResourceTemplates }
+ foreach ($item in $(if ($PSCmdlet.ParameterSetName -eq 'Uri') { $Uri } else { $UriTemplate })) {
+ if (-not $registry.Contains($item)) { throw [System.ArgumentException]::new("No resource or template '$item' is registered.") }
+ if ($PSCmdlet.ShouldProcess($item, 'Unregister MCP resource')) {
+ $registry.Remove($item)
+ $null = Send-McpServerNotification -Method 'notifications/resources/list_changed' -Server $target
+ }
+ }
+ }
+}
diff --git a/src/Public/Unregister-McpSubscription.ps1 b/src/Public/Unregister-McpSubscription.ps1
new file mode 100644
index 0000000..143c26c
--- /dev/null
+++ b/src/Public/Unregister-McpSubscription.ps1
@@ -0,0 +1,51 @@
+function Unregister-McpSubscription {
+ <#
+ .SYNOPSIS
+ Ends subscriptions opened with Register-McpSubscription.
+ .DESCRIPTION
+ Over stdio the listen request is cancelled with notifications/cancelled; over Streamable HTTP its
+ stream is closed. Notifications still queued on the subscription stay readable with
+ Receive-McpNotification -Subscription.
+ .PARAMETER Subscription
+ The subscriptions to end (Mcp.Subscription); accepts pipeline input.
+ .PARAMETER All
+ End all subscriptions of the session.
+ .PARAMETER Session
+ With -All, the session; defaults to the default session.
+ .EXAMPLE
+ Unregister-McpSubscription -Subscription $subscription
+ .EXAMPLE
+ Unregister-McpSubscription -All
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Subscription', SupportsShouldProcess)]
+ param(
+ [Parameter(ParameterSetName = 'Subscription', Mandatory, Position = 0, ValueFromPipeline)]
+ [ValidateNotNull()]
+ [object[]] $Subscription,
+
+ [Parameter(ParameterSetName = 'All', Mandatory)]
+ [switch] $All,
+
+ [Parameter(ParameterSetName = 'All')]
+ [object] $Session
+ )
+
+ process {
+ $targets = if ($All) {
+ $resolved = Resolve-McpSession -Session $Session
+ @($resolved.Subscriptions.Values)
+ } else {
+ foreach ($item in $Subscription) {
+ if ($item.PSObject.TypeNames -notcontains 'Mcp.Subscription') {
+ throw [System.ArgumentException]::new('-Subscription takes subscriptions returned by Register-McpSubscription.')
+ }
+ $item
+ }
+ }
+ foreach ($item in $targets) {
+ if ($item.State -in @('Closed', 'Failed') -and -not $item.Session.Subscriptions.Contains([string] $item.Id)) { continue }
+ if (-not $PSCmdlet.ShouldProcess("subscription $($item.Id)", 'Unregister')) { continue }
+ Close-McpClientSubscription -Session $item.Session -Subscription $item
+ }
+ }
+}
diff --git a/src/Public/Unregister-McpTool.ps1 b/src/Public/Unregister-McpTool.ps1
new file mode 100644
index 0000000..1285f68
--- /dev/null
+++ b/src/Public/Unregister-McpTool.ps1
@@ -0,0 +1,31 @@
+function Unregister-McpTool {
+ <#
+ .SYNOPSIS
+ Removes a tool from a server; while the server runs, listening clients are told that the tool list changed.
+ .PARAMETER Name
+ The tool name.
+ .PARAMETER Server
+ The server; defaults to the server set with New-McpServer -SetDefault.
+ .EXAMPLE
+ Unregister-McpTool -Name 'echo'
+ #>
+ [CmdletBinding(SupportsShouldProcess)]
+ param(
+ [Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
+ [ValidateNotNullOrEmpty()]
+ [string[]] $Name,
+
+ [object] $Server
+ )
+
+ process {
+ $target = Resolve-McpServer -Server $Server
+ foreach ($item in $Name) {
+ if (-not $target.Tools.Contains($item)) { throw [System.ArgumentException]::new("No tool named '$item' is registered.") }
+ if ($PSCmdlet.ShouldProcess($item, 'Unregister MCP tool')) {
+ $target.Tools.Remove($item)
+ $null = Send-McpServerNotification -Method 'notifications/tools/list_changed' -Server $target
+ }
+ }
+ }
+}
diff --git a/src/Public/Wait-McpInput.ps1 b/src/Public/Wait-McpInput.ps1
new file mode 100644
index 0000000..cc80b79
--- /dev/null
+++ b/src/Public/Wait-McpInput.ps1
@@ -0,0 +1,28 @@
+function Wait-McpInput {
+ <#
+ .SYNOPSIS
+ Asks the client for all input requests deferred with -Defer in one round, when any answer is missing.
+ .DESCRIPTION
+ Request-McpElicitation, Request-McpSampling and Request-McpRoot with -Defer record a missing input
+ request instead of throwing. Wait-McpInput then throws once for all of them, so the client receives
+ them together in one InputRequiredResult; when every answer is there, it returns without output and
+ the deferred commands, called again on the retry, return their answers.
+ .PARAMETER Context
+ The request context (the handler's Context parameter).
+ .EXAMPLE
+ $name = Request-McpElicitation -Context $Context -Key 'name' -Message 'Name?' -Schema @{ name = @{ type = 'string' } } -Defer
+ $roots = Request-McpRoot -Context $Context -Key 'roots' -Defer
+ Wait-McpInput -Context $Context
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [ValidateNotNull()]
+ [object] $Context
+ )
+
+ Test-McpContextInput -Context $Context
+ if ($Context.PendingInput.Count -gt 0) {
+ throw [McpInputRequiredException]::new($Context.PendingInput)
+ }
+}
diff --git a/src/Suffix.ps1 b/src/Suffix.ps1
index 9b11d3e..4c00ea5 100644
--- a/src/Suffix.ps1
+++ b/src/Suffix.ps1
@@ -9,6 +9,7 @@ $script:McpTypeAccelerators = @(
@{ Name = 'McpEra'; Type = [McpEra] }
@{ Name = 'McpLoggingLevel'; Type = [McpLoggingLevel] }
@{ Name = 'McpProtocolException'; Type = [McpProtocolException] }
+ @{ Name = 'McpInputRequiredException'; Type = [McpInputRequiredException] }
)
$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 c14646f..46e8a41 100644
--- a/src/en-US/about_ModelContextProtocol.help.txt
+++ b/src/en-US/about_ModelContextProtocol.help.txt
@@ -17,27 +17,35 @@ LONG DESCRIPTION
Supported transports are stdio and Streamable HTTP.
CURRENT STATUS
- Milestone M3 (server primitives): servers expose PowerShell commands and
- script blocks as tools, resources (fixed content, files, directories,
- handlers, RFC 6570 templates) and prompts, with argument completion and
- caching hints, over stdio and over Streamable HTTP with the stateless
- 2026-07-28 lifecycle (server/discover, per-request _meta, request metadata
- headers, progress, cancellation, log notifications). Clients consume all
- of them over both transports and cache results for the ttlMs the server
- sends. The official conformance suite runs in CI. Input requests,
- subscriptions, the legacy revisions, authorization and the extensions
+ Milestone M4 (input requests and subscriptions): servers expose PowerShell
+ commands and script blocks as tools, resources (fixed content, files,
+ directories, handlers, RFC 6570 templates) and prompts, with argument
+ completion and caching hints, over stdio and over Streamable HTTP with the
+ stateless 2026-07-28 lifecycle (server/discover, per-request _meta, request
+ metadata headers, progress, cancellation, log notifications). Handlers ask
+ for user input (elicitation), sampling and roots through multi-round-trip
+ requests; clients subscribe to list changes and resource updates with
+ subscriptions/listen. Clients consume all of it over both transports and
+ cache results for the ttlMs the server sends. The official conformance
+ suite runs in CI. The legacy revisions, authorization and the extensions
follow in later milestones (ROADMAP.md).
COMMANDS
Server: New-McpServer, Register-McpTool, Register-McpResource,
- Register-McpPrompt, Start-McpServer, Stop-McpServer,
+ Register-McpPrompt, Unregister-McpTool, Unregister-McpResource,
+ Unregister-McpPrompt, Start-McpServer, Stop-McpServer,
+ Send-McpToolListChanged, Send-McpPromptListChanged,
+ Send-McpResourceListChanged, Send-McpResourceUpdated,
Invoke-McpToolHandler
Handlers: New-McpContent, New-McpToolResult, New-McpPromptMessage,
New-McpResourceContent, Write-McpProgress, Write-McpLog,
- Test-McpClientCapability
+ Test-McpClientCapability, Request-McpElicitation,
+ Request-McpSampling, Request-McpRoot, Wait-McpInput
Client: Connect-McpServer, Disconnect-McpServer, Get-McpServerInfo,
Get-McpTool, Invoke-McpTool, Get-McpResource, Read-McpResource,
- Get-McpPrompt, Invoke-McpPrompt, Get-McpCompletion
+ Get-McpPrompt, Invoke-McpPrompt, Get-McpCompletion,
+ Register-McpSubscription, Unregister-McpSubscription,
+ Receive-McpNotification
Start-McpServer serves stdio by default; -Transport Http -Url serves a
Streamable HTTP endpoint (POST-only, JSON or SSE responses, request
@@ -56,9 +64,25 @@ COMMANDS
completions are declared in server/discover only when something is
registered.
+ A handler that needs input calls Request-McpElicitation (a form or a URL
+ for the user), Request-McpSampling or Request-McpRoot. The first call
+ answers the request with an InputRequiredResult; the client obtains the
+ answer (Connect-McpServer -OnElicitation, -OnSampling, -OnRoots) and
+ retries, and the handler runs again and gets the answer. Answers of earlier
+ rounds and $Context.State travel in a signed requestState (New-McpServer
+ -RequestStateKey). Handlers must be free of side effects before their last
+ input request.
+
+ Register-McpSubscription opens a subscriptions/listen stream for tool,
+ prompt and resource list changes and resource updates; the notifications
+ invalidate the client's cache and are read with Receive-McpNotification or
+ handled by an -Action script block. Registering or removing a primitive
+ on a running server notifies the subscribers; Send-McpResourceUpdated and
+ the Send-*ListChanged commands announce other changes.
+
A handler receives the request context through a parameter named Context
(request id, method, name, protocol version, client info and capabilities,
- log level, progress token, cancellation token). Handlers run in a worker
+ log level, progress token, cancellation token, input responses, state). Handlers run in a worker
runspace pool: pass everything they need as parameters; nothing they write
to the host reaches the client. Their warnings, information and verbose
records are logged to stderr and, when the request asks for it, sent as
diff --git a/tests/Conformance/everything-client.ps1 b/tests/Conformance/everything-client.ps1
index 171fb60..758a212 100644
--- a/tests/Conformance/everything-client.ps1
+++ b/tests/Conformance/everything-client.ps1
@@ -10,8 +10,8 @@
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.
+ connection fails. Input requests of multi-round-trip requests are answered by fixed callbacks. Scenarios
+ of later milestones (authorization) are listed in conformance-baseline.yml.
#>
[CmdletBinding()]
param(
@@ -74,7 +74,31 @@ if ($protocolVersion -ne '2026-07-28') {
exit 0
}
+# Answers to the input requests of multi-round-trip requests: form content derived from the requested schema,
+# a fixed sampling reply and one root.
+$onElicitation = {
+ param($Request)
+ $content = [ordered]@{}
+ $schema = $Request.RequestedSchema
+ if ($schema -is [System.Collections.IDictionary] -and $schema['properties'] -is [System.Collections.IDictionary]) {
+ foreach ($name in $schema['properties'].Keys) {
+ $property = $schema['properties'][$name]
+ $content[[string] $name] = switch ([string] $property['type']) {
+ 'boolean' { $true }
+ 'number' { 1 }
+ 'integer' { 1 }
+ 'array' { @() }
+ default { if ($property.Contains('enum')) { @($property['enum'])[0] } else { 'value' } }
+ }
+ }
+ }
+ @{ action = 'accept'; content = $content }
+}
+
$connectParameters = @{
+ OnElicitation = $onElicitation
+ OnSampling = { param($Request) $null = $Request; 'Paris' }
+ OnRoots = { param($Request) $null = $Request; @{ uri = 'file:///tmp/conformance'; name = 'conformance' } }
Url = $url
ClientInfo = @{ name = 'ModelContextProtocol-everything-client'; version = '0.1.0' }
Capabilities = @{ elicitation = @{ form = @{} }; sampling = @{}; roots = @{ listChanged = $true } }
diff --git a/tests/Conformance/everything-server.ps1 b/tests/Conformance/everything-server.ps1
index 3bc16e3..a06ae7a 100644
--- a/tests/Conformance/everything-server.ps1
+++ b/tests/Conformance/everything-server.ps1
@@ -8,8 +8,7 @@
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 (subscriptions, input requests) are listed in conformance-baseline.yml until
- their milestone lands.
+ Scenarios of later milestones are listed in conformance-baseline.yml until their milestone lands.
.PARAMETER Port
The TCP port on the loopback interface.
.PARAMETER Hostname
@@ -93,8 +92,91 @@ Register-McpTool -Name 'test_missing_capability' -Description 'Requires the samp
'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_streaming_elicitation' -Description 'Asks the client for a confirmation: an InputRequiredResult, never an independent request on the response stream.' -ScriptBlock {
+ param($Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message 'Continue?' -Schema @{ ok = @{ type = 'boolean' } } -Required ok
+ "Confirmation: $($answer.Action)"
+}
+
+# Multi-round-trip requests (SEP-2322): the keys, messages and schemas are the ones the input-required-result-*
+# scenarios send and expect.
+
+Register-McpTool -Name 'test_input_required_result_elicitation' -Description 'Asks for the user name with an elicitation input request.' -ScriptBlock {
+ param($Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'user_name' -Message 'What is your name?' -Schema @{ name = @{ type = 'string'; description = 'Your name' } } -Required name
+ if ($answer.Action -ne 'accept') { return "Elicitation $($answer.Action)." }
+ "Hello, $($answer.Content.name)!"
+}
+
+Register-McpTool -Name 'test_input_required_result_sampling' -Description 'Asks the client to sample a completion.' -ScriptBlock {
+ param($Context)
+ $answer = Request-McpSampling -Context $Context -Key 'capital_question' -Messages 'What is the capital of France?' -MaxTokens 100
+ "Sampling result: $($answer.Text)"
+}
+
+Register-McpTool -Name 'test_input_required_result_list_roots' -Description 'Asks the client for its roots.' -ScriptBlock {
+ param($Context)
+ $roots = @(Request-McpRoot -Context $Context -Key 'client_roots')
+ "Roots: $(@($roots | ForEach-Object Uri) -join ', ')"
+}
+
+Register-McpTool -Name 'test_input_required_result_request_state' -Description 'Keeps handler state across rounds in the requestState.' -ScriptBlock {
+ param($Context)
+ if (-not $Context.State.ContainsKey('started')) { $Context.State['started'] = 'round-1' }
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message 'Please confirm' -Schema @{ ok = @{ type = 'boolean' } } -Required ok
+ $marker = if ($Context.State['started'] -eq 'round-1') { 'state-ok' } else { 'state-missing' }
+ "Confirmed: $($answer.Content.ok) ($marker)"
+}
+
+Register-McpTool -Name 'test_input_required_result_multiple_inputs' -Description 'Asks for an elicitation, a sampling and the roots in one round.' -ScriptBlock {
+ param($Context)
+ $name = Request-McpElicitation -Context $Context -Key 'user_name' -Message 'What is your name?' -Schema @{ name = @{ type = 'string' } } -Required name -Defer
+ $greeting = Request-McpSampling -Context $Context -Key 'greeting' -Messages 'Generate a greeting' -MaxTokens 50 -Defer
+ $roots = Request-McpRoot -Context $Context -Key 'client_roots' -Defer
+ Wait-McpInput -Context $Context
+ "Name: $($name.Content.name); greeting: $($greeting.Text); roots: $(@($roots).Count)"
+}
+
+Register-McpTool -Name 'test_input_required_result_multi_round' -Description 'Asks two questions in two consecutive rounds.' -ScriptBlock {
+ param($Context)
+ $first = Request-McpElicitation -Context $Context -Key 'step1' -Message 'Step 1: What is your name?' -Schema @{ name = @{ type = 'string' } } -Required name
+ $second = Request-McpElicitation -Context $Context -Key 'step2' -Message 'Step 2: What is your favorite color?' -Schema @{ color = @{ type = 'string' } } -Required color
+ "$($first.Content.name) likes $($second.Content.color)."
+}
+
+Register-McpTool -Name 'test_input_required_result_tampered_state' -Description 'Asks for a confirmation; a modified requestState is rejected.' -ScriptBlock {
+ param($Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message 'Please confirm' -Schema @{ ok = @{ type = 'boolean' } } -Required ok
+ "Confirmed: $($answer.Content.ok)"
+}
+
+Register-McpTool -Name 'test_input_required_result_capabilities' -Description 'Asks only for the input types the client declared.' -ScriptBlock {
+ param($Context)
+ $asked = $false
+ if (Test-McpClientCapability -Context $Context -Path 'elicitation') {
+ $null = Request-McpElicitation -Context $Context -Key 'user_name' -Message 'What is your name?' -Schema @{ name = @{ type = 'string' } } -Required name -Defer
+ $asked = $true
+ }
+ if (Test-McpClientCapability -Context $Context -Path 'sampling') {
+ $null = Request-McpSampling -Context $Context -Key 'capital_question' -Messages 'What is the capital of France?' -MaxTokens 100 -Defer
+ $asked = $true
+ }
+ Wait-McpInput -Context $Context
+ if ($asked) { 'All declared input types answered.' } else { 'The client declared no input capability.' }
+}
+
+# subscriptions/listen: these tools make the server announce list changes to the open listen streams.
+
+Register-McpTool -Name 'test_trigger_tool_change' -Description 'Announces a change of the tool list to subscribers.' -ScriptBlock {
+ param($Context)
+ Send-McpToolListChanged -Context $Context
+ 'Tool list change announced.'
+}
+
+Register-McpTool -Name 'test_trigger_prompt_change' -Description 'Announces a change of the prompt list to subscribers.' -ScriptBlock {
+ param($Context)
+ Send-McpPromptListChanged -Context $Context
+ 'Prompt list change announced.'
}
Register-McpTool -Name 'test_custom_headers' -Description 'Mirrors region and priority into Mcp-Param headers.' -ScriptBlock {
@@ -167,6 +249,12 @@ Register-McpPrompt -Name 'test_prompt_with_embedded_resource' -Description 'A pr
'Please process the embedded resource above.'
}
+Register-McpPrompt -Name 'test_input_required_result_prompt' -Description 'A prompt that asks the user for context first.' -ScriptBlock {
+ param($Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'user_context' -Message 'What context should the prompt use?' -Schema @{ context = @{ type = 'string' } } -Required context
+ "Use this context: $($answer.Content.context)"
+}
+
Register-McpPrompt -Name 'test_prompt_with_image' -Description 'A prompt with an image.' -ScriptBlock {
New-McpContent -Image 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==' -MimeType 'image/png'
'Please analyze the image above.'
diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1
index e2aa2fa..de98648 100644
--- a/tests/Integration/HttpServer.Tests.ps1
+++ b/tests/Integration/HttpServer.Tests.ps1
@@ -270,6 +270,13 @@ Describe 'Raw Streamable HTTP behaviour' -Tag 'Integration' {
if ($Status -eq 400) { $response.Json['error']['code'] | Should -Be -32020 } else { $response.Json['result']['content'][0]['text'] | Should -Be 'Hello/42/q' }
}
+ It 'accepts a request id again as soon as its response was sent' {
+ # The worker of an answered request may still be winding down; its id must be free nonetheless.
+ $headers = @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = 'echo' }
+ $statuses = @(1..50 | ForEach-Object { (Send-Raw -Body $script:echoCall -Headers $headers).Status })
+ @($statuses | Where-Object { $_ -ne 200 }).Count | Should -Be 0
+ }
+
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'
diff --git a/tests/Integration/InMemoryClient.Tests.ps1 b/tests/Integration/InMemoryClient.Tests.ps1
index a84d7c2..821dd92 100644
--- a/tests/Integration/InMemoryClient.Tests.ps1
+++ b/tests/Integration/InMemoryClient.Tests.ps1
@@ -42,7 +42,7 @@ Describe 'Connect-McpServer over the in-memory transport' {
$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
+ $info.Capabilities['tools']['listChanged'] | Should -BeTrue
(Get-McpServerInfo -Session $script:session -Refresh).Name | Should -Be 'memory'
}
diff --git a/tests/Integration/InputRequests.Tests.ps1 b/tests/Integration/InputRequests.Tests.ps1
new file mode 100644
index 0000000..ee49738
--- /dev/null
+++ b/tests/Integration/InputRequests.Tests.ps1
@@ -0,0 +1,242 @@
+[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:New-InputServer {
+ param([string] $Name = 'input')
+ $server = New-McpServer -Name $Name -Version '1.0.0' -RequestTimeoutSeconds 10 -RequestStateKey 'a test key of sufficient length'
+ Register-McpTool -Name 'two-rounds' -Description 'Asks two questions in two rounds.' -ScriptBlock {
+ param([string] $Topic = 'x', $Context)
+ $Context.State['rounds'] = 1 + [int] $Context.State['rounds']
+ $first = Request-McpElicitation -Context $Context -Key 'step1' -Message "Name ($Topic)?" -Schema @{ name = @{ type = 'string' } } -Required name
+ $second = Request-McpElicitation -Context $Context -Key 'step2' -Message 'Color?' -Schema @{ color = @{ type = 'string'; enum = @('red', 'green') } } -Required color
+ "$($first.Content.name)/$($second.Content.color)/rounds=$($Context.State['rounds'])"
+ } -Server $server
+ Register-McpTool -Name 'all-at-once' -Description 'Asks for three inputs in one round.' -ScriptBlock {
+ param($Context)
+ $name = Request-McpElicitation -Context $Context -Key 'user_name' -Message 'Name?' -Schema @{ name = @{ type = 'string' } } -Defer
+ $sample = Request-McpSampling -Context $Context -Key 'greeting' -Messages 'Greet' -MaxTokens 20 -Defer
+ $roots = Request-McpRoot -Context $Context -Key 'client_roots' -Defer
+ Wait-McpInput -Context $Context
+ "$($name.Content.name)|$($sample.Text)|$(@($roots | ForEach-Object Uri) -join ',')"
+ } -Server $server
+ Register-McpTool -Name 'decline' -Description 'Reports the elicitation action.' -ScriptBlock {
+ param($Context)
+ (Request-McpElicitation -Context $Context -Key 'k' -Message 'Sure?' -Schema @{ ok = @{ type = 'boolean' } }).Action
+ } -Server $server
+ Register-McpPrompt -Name 'ask-prompt' -Description 'Asks for context first.' -ScriptBlock {
+ param($Context)
+ "Context: $((Request-McpElicitation -Context $Context -Key 'user_context' -Message 'Context?' -Schema @{ context = @{ type = 'string' } } -Required context).Content.context)"
+ } -Server $server
+ Register-McpResource -UriTemplate 'ask://{item}' -Name 'ask-resource' -Description 'Asks before it reads.' -ScriptBlock {
+ param([string] $item, $Context)
+ $answer = Request-McpElicitation -Context $Context -Key 'confirm' -Message "Read $item?" -Schema @{ ok = @{ type = 'boolean' } } -Required ok
+ "read $item ok=$($answer.Content.ok)"
+ } -Server $server
+ $server
+ }
+
+ $script:elicitation = {
+ param($Request)
+ switch (@($Request.RequestedSchema['properties'].Keys)[0]) {
+ 'name' { @{ name = 'Ada' } }
+ 'color' { @{ color = 'green' } }
+ 'context' { @{ context = 'tests' } }
+ 'ok' { @{ ok = $true } }
+ }
+ }
+}
+
+Describe 'Multi-round-trip requests on the wire' -Tag 'Integration' {
+ BeforeAll {
+ $script:rawServer = New-InputServer -Name 'raw'
+ $script:pair = Invoke-McpInModule { New-McpInMemoryTransportPair }
+ $script:background = Invoke-McpInModule { param($s, $e) Start-McpBackgroundServer -Server $s -Endpoint $e } -Parameters @{ s = $script:rawServer; e = $script:pair.Server }
+ $script:nextId = 100
+ function script:Invoke-Raw {
+ param([string] $Method = 'tools/call', [hashtable] $Params, [hashtable] $Capabilities = @{ elicitation = @{}; sampling = @{}; roots = @{} })
+ $script:nextId++
+ $all = [ordered]@{ _meta = [ordered]@{ 'io.modelcontextprotocol/protocolVersion' = '2026-07-28'; 'io.modelcontextprotocol/clientCapabilities' = $Capabilities } }
+ foreach ($key in $Params.Keys) { $all[$key] = $Params[$key] }
+ $line = Invoke-McpInModule { param($r) ConvertTo-McpJson -InputObject $r } -Parameters @{ r = [ordered]@{ jsonrpc = '2.0'; id = $script:nextId; method = $Method; params = $all } }
+ Invoke-McpInModule { param($t, $l) Send-McpTransportLine -Transport $t -Line $l } -Parameters @{ t = $script:pair.Client; l = $line }
+ while ($true) {
+ $received = Invoke-McpInModule { param($t) Receive-McpTransportLine -Transport $t -TimeoutMs 10000 } -Parameters @{ t = $script:pair.Client }
+ if ($received.Status -ne 'Line') { throw "No response: $($received.Status)" }
+ $message = Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } -Parameters @{ l = $received.Line }
+ if ($message['id'] -eq $script:nextId) { return $message }
+ }
+ }
+ }
+
+ AfterAll {
+ Stop-McpServer -Server $script:rawServer
+ Invoke-McpInModule { param($t) Close-McpTransport -Transport $t } -Parameters @{ t = $script:pair.Client }
+ Invoke-McpInModule { param($b) Stop-McpBackgroundServer -Background $b } -Parameters @{ b = $script:background }
+ }
+
+ It 'answers with an InputRequiredResult and accumulates the answers in the requestState' {
+ $round1 = Invoke-Raw -Params @{ name = 'two-rounds'; arguments = @{ Topic = 't' } }
+ $result = $round1['result']
+ (Test-McpSpecShape -Definition 'InputRequiredResult' -Instance $result).IsValid | Should -BeTrue
+ $result['resultType'] | Should -Be 'input_required'
+ @($result['inputRequests'].Keys) | Should -Be @('step1')
+ $result['_meta']['io.modelcontextprotocol/serverInfo']['name'] | Should -Be 'raw'
+
+ $round2 = Invoke-Raw -Params @{ name = 'two-rounds'; arguments = @{ Topic = 't' }; requestState = $result['requestState']; inputResponses = @{ step1 = @{ action = 'accept'; content = @{ name = 'Ada' } } } }
+ @($round2['result']['inputRequests'].Keys) | Should -Be @('step2')
+
+ # Round 3 carries only the new answer; the first one comes back from the state.
+ $round3 = Invoke-Raw -Params @{ name = 'two-rounds'; arguments = @{ Topic = 't' }; requestState = $round2['result']['requestState']; inputResponses = @{ step2 = @{ action = 'accept'; content = @{ color = 'green' } } } }
+ $round3['result']['resultType'] | Should -Be 'complete'
+ $round3['result']['content'][0]['text'] | Should -Be 'Ada/green/rounds=3'
+ }
+
+ It 'works without requestState when the client sends every answer' {
+ $response = Invoke-Raw -Params @{ name = 'two-rounds'; arguments = @{}; inputResponses = @{ step1 = @{ action = 'accept'; content = @{ name = 'Bo' } }; step2 = @{ action = 'accept'; content = @{ color = 'red' } }; unrelated = @{ x = 1 } } }
+ $response['result']['content'][0]['text'] | Should -Be 'Bo/red/rounds=1'
+ }
+
+ It 'asks for all deferred inputs in one round' {
+ $response = Invoke-Raw -Params @{ name = 'all-at-once'; arguments = @{} }
+ @($response['result']['inputRequests'].Keys) | Should -Be @('user_name', 'greeting', 'client_roots')
+ }
+
+ It 'rejects with -32602' -TestCases @(
+ @{ Case = 'a tampered requestState'; Mutate = { param($p) $p['requestState'] = $p['requestState'] + 'x'; $p } }
+ @{ Case = 'a requestState of other arguments'; Mutate = { param($p) $p['arguments'] = @{ Topic = 'other' }; $p } }
+ @{ Case = 'inputResponses that are not an object'; Mutate = { param($p) $p['inputResponses'] = 5; $p } }
+ @{ Case = 'null inputResponses'; Mutate = { param($p) $p['inputResponses'] = $null; $p } }
+ @{ Case = 'an input response that is not an object'; Mutate = { param($p) $p['inputResponses'] = @{ step1 = 12345 }; $p } }
+ @{ Case = 'an answer that does not match the schema'; Mutate = { param($p) $p['inputResponses'] = @{ step1 = @{ action = 'accept'; content = @{ name = 12345 } } }; $p } }
+ ) {
+ param($Case, $Mutate)
+ $null = $Case
+ $round1 = Invoke-Raw -Params @{ name = 'two-rounds'; arguments = @{ Topic = 't' } }
+ $params = & $Mutate @{ name = 'two-rounds'; arguments = @{ Topic = 't' }; requestState = $round1['result']['requestState']; inputResponses = @{ step1 = @{ action = 'accept'; content = @{ name = 'Ada' } } } }
+ $response = Invoke-Raw -Params $params
+ $response.Contains('result') | Should -BeFalse
+ $response['error']['code'] | Should -Be -32602
+ }
+
+ It 'fails with -32021 when the client did not declare the capability' {
+ $response = Invoke-Raw -Params @{ name = 'two-rounds'; arguments = @{} } -Capabilities @{ sampling = @{} }
+ $response['error']['code'] | Should -Be -32021
+ $response['error']['data']['requiredCapabilities']['elicitation'].Contains('form') | Should -BeTrue
+ }
+
+ It 'asks for input in prompts/get and resources/read' {
+ (Invoke-Raw -Method 'prompts/get' -Params @{ name = 'ask-prompt' })['result']['inputRequests'].Contains('user_context') | Should -BeTrue
+ $read = Invoke-Raw -Method 'resources/read' -Params @{ uri = 'ask://one' }
+ $read['result']['resultType'] | Should -Be 'input_required'
+ $done = Invoke-Raw -Method 'resources/read' -Params @{ uri = 'ask://one'; requestState = $read['result']['requestState']; inputResponses = @{ confirm = @{ action = 'accept'; content = @{ ok = $true } } } }
+ $done['result']['contents'][0]['text'] | Should -Be 'read one ok=True'
+ }
+}
+
+Describe 'Input callbacks of Connect-McpServer' -Tag 'Integration' {
+ BeforeAll {
+ $script:memoryServer = New-InputServer -Name 'memory-input'
+ $script:requests = [System.Collections.Generic.List[object]]::new()
+ $script:session = Connect-McpServer -Server $script:memoryServer -OnElicitation {
+ param($Request)
+ $script:requests.Add($Request)
+ & $script:elicitation $Request
+ } -OnSampling { param($Request) "hello ($($Request.MaxTokens))" } -OnRoots { param($Request) $null = $Request; '/work', @{ uri = 'file:///data'; name = 'data' } }
+ }
+
+ AfterAll {
+ if ($script:session) { Disconnect-McpServer -Session $script:session }
+ }
+
+ It 'declares the capabilities of the callbacks' {
+ $capabilities = $script:session.ClientCapabilities
+ $capabilities['elicitation'].Contains('form') | Should -BeTrue
+ $capabilities['elicitation'].Contains('url') | Should -BeTrue
+ $capabilities.Contains('sampling') | Should -BeTrue
+ $capabilities.Contains('roots') | Should -BeTrue
+ }
+
+ It 'answers input requests over several rounds' {
+ $script:requests.Clear()
+ (Invoke-McpTool -Name 'two-rounds' -Arguments @{ Topic = 'z' } -Session $script:session).Text | Should -Be 'Ada/green/rounds=3'
+ @($script:requests | ForEach-Object Key) | Should -Be @('step1', 'step2')
+ $script:requests[0].PSObject.TypeNames | Should -Contain 'Mcp.InputRequest'
+ $script:requests[0].Mode | Should -Be 'form'
+ $script:requests[0].Message | Should -Be 'Name (z)?'
+ $script:requests[0].RequestMethod | Should -Be 'tools/call'
+ }
+
+ It 'answers elicitation, sampling and roots in one round' {
+ $expectedRoot = [System.Uri]::new((Join-Path ([System.IO.Path]::GetPathRoot((Get-Location).Path)) 'work'), [System.UriKind]::Absolute).AbsoluteUri
+ (Invoke-McpTool -Name 'all-at-once' -Session $script:session).Text | Should -Be "Ada|hello (20)|$expectedRoot,file:///data"
+ }
+
+ It 'renders prompts and reads resources that ask for input' {
+ (Invoke-McpPrompt -Name 'ask-prompt' -Session $script:session).Messages[0].Content.Text | Should -Be 'Context: tests'
+ (Read-McpResource -Uri 'ask://two' -Session $script:session).Text | Should -Be 'read two ok=True'
+ # A result that needed input rounds is not cached.
+ $script:session.Cache.ContainsKey('resources/read ask://two') | Should -BeFalse
+ }
+
+ It 'passes on a declined elicitation' {
+ $session = Connect-McpServer -Server (New-InputServer) -OnElicitation { param($Request) $null = $Request; 'decline' }
+ try {
+ (Invoke-McpTool -Name 'decline' -Session $session).Text | Should -Be 'decline'
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+
+ It 'fails with -32021 without the callback and capability' {
+ $session = Connect-McpServer -Server (New-InputServer)
+ try {
+ $exception = $null
+ try { Invoke-McpTool -Name 'two-rounds' -Session $session } catch { $exception = $_.Exception }
+ $exception | Should -BeOfType [McpProtocolException]
+ $exception.Code | Should -Be -32021
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+
+ It 'fails when the server keeps asking beyond -MaxInputRounds' {
+ $session = Connect-McpServer -Server (New-InputServer) -OnElicitation $script:elicitation -MaxInputRounds 1
+ try {
+ { Invoke-McpTool -Name 'two-rounds' -Session $session } | Should -Throw -ExpectedMessage '*-MaxInputRounds*'
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+
+ It 'fails when a declared capability has no callback' {
+ $session = Connect-McpServer -Server (New-InputServer) -Capabilities @{ elicitation = @{} }
+ try {
+ { Invoke-McpTool -Name 'two-rounds' -Session $session } | Should -Throw -ExpectedMessage '*-OnElicitation*'
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+}
+
+Describe 'Multi-round-trip requests over Streamable HTTP' -Tag 'Integration' {
+ BeforeAll {
+ $script:httpServer = New-InputServer -Name 'http-input'
+ $script:handle = Start-McpTestHttpServer -Server $script:httpServer
+ $script:httpSession = Connect-McpServer -Url $script:handle.Url -OnElicitation $script:elicitation -OnSampling { param($Request) $null = $Request; 'hi' } -OnRoots { param($Request) $null = $Request; @{ uri = 'file:///r' } }
+ }
+
+ AfterAll {
+ if ($script:httpSession) { Disconnect-McpServer -Session $script:httpSession }
+ if ($script:handle) { Stop-McpTestHttpServer -Handle $script:handle }
+ }
+
+ It 'runs the rounds as separate POSTs' {
+ (Invoke-McpTool -Name 'two-rounds' -Arguments @{ Topic = 'h' } -Session $script:httpSession).Text | Should -Be 'Ada/green/rounds=3'
+ (Invoke-McpTool -Name 'all-at-once' -Session $script:httpSession).Text | Should -Be 'Ada|hi|file:///r'
+ (Read-McpResource -Uri 'ask://three' -Session $script:httpSession).Text | Should -Be 'read three ok=True'
+ }
+}
diff --git a/tests/Integration/ServerPrimitives.Tests.ps1 b/tests/Integration/ServerPrimitives.Tests.ps1
index 29d2dfc..914b27d 100644
--- a/tests/Integration/ServerPrimitives.Tests.ps1
+++ b/tests/Integration/ServerPrimitives.Tests.ps1
@@ -47,8 +47,8 @@ Describe 'Resources through the client' -Tag 'Integration' {
It 'declares the capabilities of what is registered' {
$capabilities = (Get-McpServerInfo -Session $script:session).Capabilities
@($capabilities.Keys) | Should -Be @('completions', 'prompts', 'resources', 'tools')
- $capabilities['resources']['subscribe'] | Should -BeFalse
- $capabilities['resources']['listChanged'] | Should -BeFalse
+ $capabilities['resources']['subscribe'] | Should -BeTrue
+ $capabilities['resources']['listChanged'] | Should -BeTrue
}
It 'lists resources and templates across pages' {
diff --git a/tests/Integration/StdioServer.Tests.ps1 b/tests/Integration/StdioServer.Tests.ps1
index f4b5306..cc92ec5 100644
--- a/tests/Integration/StdioServer.Tests.ps1
+++ b/tests/Integration/StdioServer.Tests.ps1
@@ -156,3 +156,40 @@ Describe 'The weather example over stdio' -Tag 'Integration' {
(Invoke-McpTool -Name 'forecast' -Arguments @{ City = 'Berlin'; Days = 2 } -Session $script:weather).StructuredContent['days'].Count | Should -Be 2
}
}
+
+Describe 'The elicitation example over stdio' -Tag 'Integration' {
+ BeforeAll {
+ $elicitationArguments = @('-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path (Get-McpRepositoryRoot) 'examples' 'elicitation-server.ps1'))
+ $script:asked = [System.Collections.Generic.List[string]]::new()
+ $script:elicitation = Connect-McpServer -Command $script:pwsh -Arguments $elicitationArguments -ConnectTimeoutSeconds 60 -OnElicitation {
+ param($Request)
+ $script:asked.Add($Request.Message)
+ switch (@($Request.RequestedSchema['properties'].Keys)[0]) {
+ 'confirm' { @{ confirm = $true } }
+ 'name' { @{ name = 'Ada' } }
+ 'color' { @{ color = 'green' } }
+ }
+ }
+ }
+
+ AfterAll {
+ if ($script:elicitation) { Disconnect-McpServer -Session $script:elicitation }
+ }
+
+ It 'asks the user through the client in one and in several rounds' {
+ (Invoke-McpTool -Name 'delete-files' -Arguments @{ Pattern = '*.tmp' } -Session $script:elicitation).Text | Should -BeLike "Deleted the files matching '*.tmp'*"
+ (Invoke-McpTool -Name 'profile' -Session $script:elicitation).Text | Should -Be 'Ada likes green (asked in 3 rounds).'
+ @($script:asked) | Should -Be @("Delete all files matching '*.tmp'?", 'What is your name?', 'Hello Ada, what is your favourite color?')
+ }
+
+ It 'delivers subscription notifications on the shared output stream' {
+ $subscription = Register-McpSubscription -ToolsListChanged -Session $script:elicitation
+ $subscription.State | Should -Be 'Open'
+ (Invoke-McpTool -Name 'announce-tools' -Session $script:elicitation).Text | Should -Be 'Announced.'
+ @(Receive-McpNotification -Subscription $subscription -TimeoutSeconds 10 | ForEach-Object Method) | Should -Be @('notifications/tools/list_changed')
+ # Requests keep working while the background reader owns the output stream.
+ @(Get-McpTool -Session $script:elicitation -Refresh | ForEach-Object Name) | Should -Contain 'profile'
+ Unregister-McpSubscription -Subscription $subscription
+ $subscription.State | Should -Be 'Closed'
+ }
+}
diff --git a/tests/Integration/Subscriptions.Tests.ps1 b/tests/Integration/Subscriptions.Tests.ps1
new file mode 100644
index 0000000..505a97c
--- /dev/null
+++ b/tests/Integration/Subscriptions.Tests.ps1
@@ -0,0 +1,269 @@
+[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:New-ListenServer {
+ param([string] $Name = 'listen')
+ $server = New-McpServer -Name $Name -Version '1.0.0' -RequestTimeoutSeconds 10
+ Register-McpTool -Name 'trigger-tools' -Description 'Announces a tool list change.' -ScriptBlock { param($Context) Send-McpToolListChanged -Context $Context; 'ok' } -Server $server
+ Register-McpTool -Name 'touch' -Description 'Announces a resource update.' -ScriptBlock { param([string] $Uri, $Context) Send-McpResourceUpdated -Context $Context -Uri $Uri; 'touched' } -Server $server
+ Register-McpResource -Uri 'test://doc' -Name 'doc' -Description 'A document.' -Content 'v1' -TtlMs 60000 -Server $server
+ Register-McpPrompt -Name 'p' -Description 'A prompt.' -ScriptBlock { 'hi' } -Server $server
+ $server
+ }
+ $script:meta = [ordered]@{ 'io.modelcontextprotocol/protocolVersion' = '2026-07-28'; 'io.modelcontextprotocol/clientCapabilities' = [ordered]@{} }
+ $script:subscriptionKey = 'io.modelcontextprotocol/subscriptionId'
+}
+
+Describe 'subscriptions/listen on the wire' -Tag 'Integration' {
+ BeforeAll {
+ $script:rawServer = New-ListenServer -Name 'raw-listen'
+ $script:pair = Invoke-McpInModule { New-McpInMemoryTransportPair }
+ $script:background = Invoke-McpInModule { param($s, $e) Start-McpBackgroundServer -Server $s -Endpoint $e } -Parameters @{ s = $script:rawServer; e = $script:pair.Server }
+ function script:Send-Raw {
+ param([object] $Id, [string] $Method, [System.Collections.IDictionary] $Params = [ordered]@{})
+ $all = [ordered]@{ _meta = $script:meta }
+ foreach ($key in $Params.Keys) { $all[$key] = $Params[$key] }
+ $message = [ordered]@{ jsonrpc = '2.0' }
+ if ($null -ne $Id) { $message['id'] = $Id }
+ $message['method'] = $Method
+ $message['params'] = $all
+ $line = Invoke-McpInModule { param($m) ConvertTo-McpJson -InputObject $m } -Parameters @{ m = $message }
+ Invoke-McpInModule { param($t, $l) Send-McpTransportLine -Transport $t -Line $l } -Parameters @{ t = $script:pair.Client; l = $line }
+ }
+ function script:Receive-Raw {
+ param([int] $TimeoutMs = 5000)
+ $received = Invoke-McpInModule { param($t, $ms) Receive-McpTransportLine -Transport $t -TimeoutMs $ms } -Parameters @{ t = $script:pair.Client; ms = $TimeoutMs }
+ if ($received.Status -ne 'Line') { return $null }
+ Invoke-McpInModule { param($l) ConvertFrom-McpJson $l } -Parameters @{ l = $received.Line }
+ }
+ }
+
+ AfterAll {
+ Invoke-McpInModule { param($t) Close-McpTransport -Transport $t } -Parameters @{ t = $script:pair.Client }
+ Invoke-McpInModule { param($b) Stop-McpBackgroundServer -Background $b } -Parameters @{ b = $script:background }
+ }
+
+ It 'acknowledges first, with the honoured filter and the subscription id' {
+ Send-Raw -Id 'L1' -Method 'subscriptions/listen' -Params ([ordered]@{ notifications = [ordered]@{ toolsListChanged = $true; resourceSubscriptions = @('test://doc') } })
+ $ack = Receive-Raw
+ (Test-McpSpecShape -Definition 'SubscriptionsAcknowledgedNotification' -Instance $ack).IsValid | Should -BeTrue
+ $ack['method'] | Should -Be 'notifications/subscriptions/acknowledged'
+ $ack['params']['_meta'][$script:subscriptionKey] | Should -Be 'L1'
+ $ack['params']['notifications']['toolsListChanged'] | Should -BeTrue
+ $ack['params']['notifications']['resourceSubscriptions'] | Should -Be @('test://doc')
+ }
+
+ It 'delivers only what the filter asked for, tagged with the subscription id' {
+ Send-Raw -Id 1 -Method 'tools/call' -Params ([ordered]@{ name = 'trigger-tools'; arguments = @{} })
+ Send-Raw -Id 2 -Method 'tools/call' -Params ([ordered]@{ name = 'touch'; arguments = @{ Uri = 'test://doc/part' } })
+ Send-Raw -Id 3 -Method 'tools/call' -Params ([ordered]@{ name = 'touch'; arguments = @{ Uri = 'test://other' } })
+ $null = Send-McpPromptListChanged -Server $script:rawServer
+ $messages = @(for ($i = 0; $i -lt 5; $i++) { Receive-Raw })
+ $notifications = @($messages | Where-Object { $_.Contains('method') })
+ @($notifications | ForEach-Object { $_['method'] }) | Should -Be @('notifications/tools/list_changed', 'notifications/resources/updated')
+ foreach ($notification in $notifications) { $notification['params']['_meta'][$script:subscriptionKey] | Should -Be 'L1' }
+ $notifications[1]['params']['uri'] | Should -Be 'test://doc/part'
+ @($messages | Where-Object { $_.Contains('result') }).Count | Should -Be 3
+ Receive-Raw -TimeoutMs 300 | Should -BeNullOrEmpty
+ }
+
+ It 'announces tools registered while the server runs, which are callable at once' {
+ Register-McpTool -Name 'late' -Description 'Registered late.' -ScriptBlock { 'late ok' } -Server $script:rawServer
+ (Receive-Raw)['method'] | Should -Be 'notifications/tools/list_changed'
+ Send-Raw -Id 4 -Method 'tools/call' -Params ([ordered]@{ name = 'late'; arguments = @{} })
+ (Receive-Raw)['result']['content'][0]['text'] | Should -Be 'late ok'
+ Unregister-McpTool -Name 'late' -Server $script:rawServer -Confirm:$false
+ (Receive-Raw)['method'] | Should -Be 'notifications/tools/list_changed'
+ }
+
+ It 'rejects a filter that is not an object and duplicate request ids' {
+ Send-Raw -Id 'bad' -Method 'subscriptions/listen' -Params ([ordered]@{ notifications = 'all' })
+ (Receive-Raw)['error']['code'] | Should -Be -32602
+ Send-Raw -Id 'L1' -Method 'subscriptions/listen' -Params ([ordered]@{ notifications = [ordered]@{ toolsListChanged = $true } })
+ (Receive-Raw)['error']['code'] | Should -Be -32600
+ }
+
+ It 'ends a subscription on notifications/cancelled without a response' {
+ Send-Raw -Method 'notifications/cancelled' -Params ([ordered]@{ requestId = 'L1' })
+ Start-Sleep -Milliseconds 200
+ $null = Send-McpToolListChanged -Server $script:rawServer
+ Receive-Raw -TimeoutMs 500 | Should -BeNullOrEmpty
+ }
+
+ It 'closes open subscriptions gracefully when the server stops' {
+ Send-Raw -Id 'L2' -Method 'subscriptions/listen' -Params ([ordered]@{ notifications = [ordered]@{ promptsListChanged = $true } })
+ (Receive-Raw)['params']['notifications']['promptsListChanged'] | Should -BeTrue
+ Stop-McpServer -Server $script:rawServer
+ $final = Receive-Raw
+ (Test-McpSpecShape -Definition 'SubscriptionsListenResultResponse' -Instance $final).IsValid | Should -BeTrue
+ $final['id'] | Should -Be 'L2'
+ $final['result']['resultType'] | Should -Be 'complete'
+ $final['result']['_meta'][$script:subscriptionKey] | Should -Be 'L2'
+ $final['result']['_meta']['io.modelcontextprotocol/serverInfo']['name'] | Should -Be 'raw-listen'
+ }
+}
+
+Describe 'Register-McpSubscription in memory' -Tag 'Integration' {
+ BeforeAll {
+ $script:memoryServer = New-ListenServer -Name 'memory-listen'
+ $script:session = Connect-McpServer -Server $script:memoryServer
+ }
+
+ AfterAll {
+ if ($script:session) { Disconnect-McpServer -Session $script:session }
+ }
+
+ It 'opens a subscription with the honoured subset' {
+ $script:subscription = Register-McpSubscription -ToolsListChanged -ResourceUri 'test://doc' -Session $script:session
+ $script:subscription.PSObject.TypeNames | Should -Contain 'Mcp.Subscription'
+ $script:subscription.State | Should -Be 'Open'
+ @($script:subscription.Honoured.Keys) | Should -Be @('toolsListChanged', 'resourceSubscriptions')
+ }
+
+ It 'receives notifications and invalidates the cache' {
+ (Read-McpResource -Uri 'test://doc' -Session $script:session).Text | Should -Be 'v1'
+ $script:session.Cache.ContainsKey('resources/read test://doc') | Should -BeTrue
+ $null = Invoke-McpTool -Name 'touch' -Arguments @{ Uri = 'test://doc' } -Session $script:session
+ $notifications = @(Receive-McpNotification -Subscription $script:subscription -TimeoutSeconds 5)
+ $notifications.Count | Should -Be 1
+ $notifications[0].PSObject.TypeNames | Should -Contain 'Mcp.Notification'
+ $notifications[0].Method | Should -Be 'notifications/resources/updated'
+ $notifications[0].Uri | Should -Be 'test://doc'
+ $notifications[0].SubscriptionId | Should -Be $script:subscription.Id
+ $script:session.Cache.ContainsKey('resources/read test://doc') | Should -BeFalse
+ }
+
+ It 'returns nothing when nothing arrived' {
+ @(Receive-McpNotification -Session $script:session).Count | Should -Be 0
+ }
+
+ It 'runs -Action for each notification in the caller''s runspace' {
+ $seen = [System.Collections.Generic.List[string]]::new()
+ $withAction = Register-McpSubscription -ToolsListChanged -Action { param($Notification) $seen.Add($Notification.Method) } -Session $script:session
+ Register-McpTool -Name 'dynamic' -Description 'Registered while subscribed.' -ScriptBlock { 'dynamic ok' } -Server $script:memoryServer
+ $null = Receive-McpNotification -Subscription $withAction -TimeoutSeconds 2
+ @($seen) | Should -Be @('notifications/tools/list_changed')
+ (Invoke-McpTool -Name 'dynamic' -Session $script:session).Text | Should -Be 'dynamic ok'
+ @(Get-McpTool -Session $script:session | ForEach-Object Name) | Should -Contain 'dynamic'
+ Unregister-McpSubscription -Subscription $withAction
+ $withAction.State | Should -Be 'Closed'
+ # The other subscription got the change as well.
+ @(Receive-McpNotification -Subscription $script:subscription -TimeoutSeconds 2 | ForEach-Object Method) | Should -Be @('notifications/tools/list_changed')
+ }
+
+ It 'ends subscriptions with Unregister-McpSubscription and on Disconnect-McpServer' {
+ $other = Register-McpSubscription -PromptsListChanged -Session $script:session
+ Unregister-McpSubscription -Subscription $script:subscription
+ $script:subscription.State | Should -Be 'Closed'
+ $null = Invoke-McpTool -Name 'trigger-tools' -Session $script:session
+ @(Receive-McpNotification -Subscription $script:subscription -TimeoutSeconds 1).Count | Should -Be 0
+ Disconnect-McpServer -Session $script:session
+ $other.State | Should -Be 'Closed'
+ $script:session = $null
+ }
+
+ It 'requires at least one notification type' {
+ $session = Connect-McpServer -Server (New-ListenServer)
+ try {
+ { Register-McpSubscription -Session $session } | Should -Throw -ExpectedMessage '*at least one*'
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+}
+
+Describe 'subscriptions/listen over Streamable HTTP' -Tag 'Integration' {
+ BeforeAll {
+ $script:httpServer = New-ListenServer -Name 'http-listen'
+ $script:handle = Start-McpTestHttpServer -Server $script:httpServer -Parameters @{ KeepAliveSeconds = 1 }
+ function script:Open-RawListen {
+ param([object] $Id, [System.Collections.IDictionary] $Filter)
+ $handler = [System.Net.Http.SocketsHttpHandler]::new()
+ $handler.UseProxy = $false
+ $client = [System.Net.Http.HttpClient]::new($handler)
+ $body = Invoke-McpInModule { param($m) ConvertTo-McpJson -InputObject $m } -Parameters @{ m = [ordered]@{ jsonrpc = '2.0'; id = $Id; method = 'subscriptions/listen'; params = [ordered]@{ _meta = $script:meta; notifications = $Filter } } }
+ $request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $script:handle.Url)
+ $request.Content = [System.Net.Http.StringContent]::new($body, [System.Text.Encoding]::UTF8, 'application/json')
+ $null = $request.Headers.TryAddWithoutValidation('Accept', 'application/json, text/event-stream')
+ $null = $request.Headers.TryAddWithoutValidation('MCP-Protocol-Version', '2026-07-28')
+ $null = $request.Headers.TryAddWithoutValidation('Mcp-Method', 'subscriptions/listen')
+ $response = $client.SendAsync($request, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
+ $sse = Invoke-McpInModule { param($s) New-McpSseReader -Stream $s } -Parameters @{ s = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult() }
+ @{ Client = $client; Response = $response; Sse = $sse }
+ }
+ function script:Receive-RawEvent {
+ param([hashtable] $Stream, [int] $TimeoutMs = 5000)
+ $deadline = [datetime]::UtcNow.AddMilliseconds($TimeoutMs)
+ while ([datetime]::UtcNow -lt $deadline) {
+ $received = Invoke-McpInModule { param($s) Receive-McpSseEvent -Sse $s -TimeoutMs 250 } -Parameters @{ s = $Stream.Sse }
+ if ($received.Status -eq 'Eof') { return $null }
+ if ($received.Status -eq 'Event' -and $received.Data) { return Invoke-McpInModule { param($d) ConvertFrom-McpJson $d } -Parameters @{ d = $received.Data } }
+ }
+ $null
+ }
+ function script:Close-RawListen {
+ param([hashtable] $Stream)
+ $Stream.Response.Dispose()
+ $Stream.Client.Dispose()
+ }
+ }
+
+ AfterAll {
+ if ($script:handle) { Stop-McpTestHttpServer -Handle $script:handle }
+ }
+
+ It 'answers with an SSE stream whose first event is the acknowledgement' {
+ $stream = Open-RawListen -Id 7 -Filter ([ordered]@{ toolsListChanged = $true })
+ try {
+ $stream.Response.StatusCode | Should -Be 200
+ $stream.Response.Content.Headers.ContentType.MediaType | Should -Be 'text/event-stream'
+ $ack = Receive-RawEvent -Stream $stream
+ $ack['method'] | Should -Be 'notifications/subscriptions/acknowledged'
+ $ack['params']['_meta'][$script:subscriptionKey] | Should -Be 7
+ } finally {
+ Close-RawListen -Stream $stream
+ }
+ }
+
+ It 'serves several parallel streams and drops the ones the client closed' {
+ $first = Open-RawListen -Id 'a' -Filter ([ordered]@{ toolsListChanged = $true })
+ $second = Open-RawListen -Id 'b' -Filter ([ordered]@{ toolsListChanged = $true })
+ try {
+ $null = Receive-RawEvent -Stream $first
+ $null = Receive-RawEvent -Stream $second
+ Close-RawListen -Stream $first
+ $null = Send-McpToolListChanged -Server $script:httpServer
+ $notification = Receive-RawEvent -Stream $second
+ $notification['method'] | Should -Be 'notifications/tools/list_changed'
+ $notification['params']['_meta'][$script:subscriptionKey] | Should -Be 'b'
+ # The keep-alive (1 s) notices the closed stream.
+ $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
+ while ($script:httpServer.State.Listeners.ContainsKey('s:a') -and $stopwatch.Elapsed.TotalSeconds -lt 5) { Start-Sleep -Milliseconds 100 }
+ $script:httpServer.State.Listeners.ContainsKey('s:a') | Should -BeFalse
+ } finally {
+ Close-RawListen -Stream $second
+ }
+ }
+
+ It 'works through the client and ends gracefully when the server stops' {
+ $session = Connect-McpServer -Url $script:handle.Url
+ try {
+ $subscription = Register-McpSubscription -ToolsListChanged -PromptsListChanged -Session $session
+ $subscription.State | Should -Be 'Open'
+ $null = Invoke-McpTool -Name 'trigger-tools' -Session $session
+ @(Receive-McpNotification -Subscription $subscription -TimeoutSeconds 5 | ForEach-Object Method) | Should -Be @('notifications/tools/list_changed')
+ Stop-McpTestHttpServer -Handle $script:handle
+ $script:handle = $null
+ $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
+ while ($subscription.State -eq 'Open' -and $stopwatch.Elapsed.TotalSeconds -lt 5) { $null = Receive-McpNotification -Session $session -TimeoutSeconds 0.2 }
+ $subscription.State | Should -Be 'Closed'
+ $subscription.Reconnects | Should -Be 0
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+}
diff --git a/tests/Unit/InputRequest.Tests.ps1 b/tests/Unit/InputRequest.Tests.ps1
new file mode 100644
index 0000000..768c62c
--- /dev/null
+++ b/tests/Unit/InputRequest.Tests.ps1
@@ -0,0 +1,204 @@
+[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 Get-TestContext {
+ param(
+ [System.Collections.IDictionary] $Capabilities = @{ elicitation = @{ form = @{}; url = @{} }; sampling = @{ tools = @{} }; roots = @{} },
+ [System.Collections.IDictionary] $Responses = [ordered]@{},
+ [string] $Kind = 'Tool'
+ )
+ $wire = Invoke-McpInModule { param($c, $r) @{ c = (ConvertFrom-McpJson (ConvertTo-McpJson -InputObject $c)); r = (ConvertFrom-McpJson (ConvertTo-McpJson -InputObject $r)) } } -Parameters @{ c = $Capabilities; r = $Responses }
+ Invoke-McpInModule { param($e) New-McpRequestContext -Envelope $e } -Parameters @{ e = @{ Kind = $Kind; Method = 'tools/call'; Name = 't'; Meta = @{ ClientCapabilities = $wire.c }; InputResponses = $wire.r } }
+ }
+ function Get-ThrownException {
+ # (Not named $Action: a script block that calls $Action would resolve it to this parameter.)
+ param([scriptblock] $Code)
+ try { & $Code; $null } catch { $_.Exception }
+ }
+ function ConvertTo-Wire {
+ param($InputObject)
+ Invoke-McpInModule { param($o) ConvertFrom-McpJson (ConvertTo-McpJson -InputObject $o) } -Parameters @{ o = $InputObject }
+ }
+}
+
+Describe 'Request-McpElicitation' {
+ It 'throws McpInputRequiredException with a form elicitation when the answer is missing' {
+ $context = Get-TestContext
+ $exception = Get-ThrownException { Request-McpElicitation -Context $context -Key 'user_name' -Message 'What is your name?' -Schema @{ name = @{ type = 'string' } } -Required name }
+ $exception | Should -BeOfType [McpInputRequiredException]
+ $request = $exception.InputRequests['user_name']
+ $request['method'] | Should -Be 'elicitation/create'
+ $request['params']['mode'] | Should -Be 'form'
+ $request['params']['message'] | Should -Be 'What is your name?'
+ $request['params']['requestedSchema']['type'] | Should -Be 'object'
+ $request['params']['requestedSchema']['required'] | Should -Be @('name')
+ (Test-McpSpecShape -Definition 'InputRequests' -Instance (ConvertTo-Wire $exception.InputRequests)).IsValid | Should -BeTrue
+ }
+
+ It 'returns the accepted answer as Mcp.ElicitResult' {
+ $context = Get-TestContext -Responses ([ordered]@{ user_name = @{ action = 'accept'; content = @{ name = 'Ada' } } })
+ $answer = Request-McpElicitation -Context $context -Key 'user_name' -Message 'Name?' -Schema @{ name = @{ type = 'string' } } -Required name
+ $answer.PSObject.TypeNames | Should -Contain 'Mcp.ElicitResult'
+ $answer.Action | Should -Be 'accept'
+ $answer.Accepted | Should -BeTrue
+ $answer.Content.name | Should -Be 'Ada'
+ $context.ConsumedInput.Contains('user_name') | Should -BeTrue
+ }
+
+ It 'returns declined and cancelled answers without content' {
+ $context = Get-TestContext -Responses ([ordered]@{ a = @{ action = 'decline' }; b = @{ action = 'cancel' } })
+ (Request-McpElicitation -Context $context -Key 'a' -Message 'm' -Schema @{ x = @{ type = 'string' } }).Accepted | Should -BeFalse
+ (Request-McpElicitation -Context $context -Key 'b' -Message 'm' -Schema @{ x = @{ type = 'string' } }).Action | Should -Be 'cancel'
+ }
+
+ It 'rejects with -32602' -TestCases @(
+ @{ Case = 'a response that is not an object'; Response = 'yes' }
+ @{ Case = 'an unknown action'; Response = @{ action = 'maybe' } }
+ @{ Case = 'content of the wrong type'; Response = @{ action = 'accept'; content = @{ name = 12345 } } }
+ @{ Case = 'content without a required property'; Response = @{ action = 'accept'; content = @{} } }
+ ) {
+ param($Case, $Response)
+ $null = $Case
+ $context = Get-TestContext -Responses ([ordered]@{ user_name = $Response })
+ $exception = Get-ThrownException { Request-McpElicitation -Context $context -Key 'user_name' -Message 'Name?' -Schema @{ name = @{ type = 'string' } } -Required name }
+ $exception | Should -BeOfType [McpProtocolException]
+ $exception.Code | Should -Be -32602
+ }
+
+ It 'asks for a URL in URL mode' {
+ $exception = Get-ThrownException { Request-McpElicitation -Context (Get-TestContext) -Key 'login' -Message 'Sign in' -Url 'https://example.com/login' }
+ $params = $exception.InputRequests['login']['params']
+ $params['mode'] | Should -Be 'url'
+ $params['url'] | Should -Be 'https://example.com/login'
+ (Test-McpSpecShape -Definition 'ElicitRequestURLParams' -Instance (ConvertTo-Wire $params)).IsValid | Should -BeTrue
+ }
+
+ It 'fails with -32021 and the required capability when the client did not declare ' -TestCases @(
+ @{ Case = 'elicitation'; Capabilities = @{ sampling = @{} }; Action = { param($c) Request-McpElicitation -Context $c -Key 'k' -Message 'm' -Schema @{ x = @{ type = 'string' } } }; Path = 'elicitation', 'form' }
+ @{ Case = 'URL mode'; Capabilities = @{ elicitation = @{ form = @{} } }; Action = { param($c) Request-McpElicitation -Context $c -Key 'k' -Message 'm' -Url 'https://example.com' }; Path = 'elicitation', 'url' }
+ @{ Case = 'sampling'; Capabilities = @{ elicitation = @{} }; Action = { param($c) Request-McpSampling -Context $c -Key 'k' -Messages 'hi' }; Path = @('sampling') }
+ @{ Case = 'sampling with tools'; Capabilities = @{ sampling = @{} }; Action = { param($c) Request-McpSampling -Context $c -Key 'k' -Messages 'hi' -Tools @(@{ name = 'x'; inputSchema = @{ type = 'object' } }) }; Path = 'sampling', 'tools' }
+ @{ Case = 'roots'; Capabilities = @{}; Action = { param($c) Request-McpRoot -Context $c -Key 'k' }; Path = @('roots') }
+ ) {
+ param($Case, $Capabilities, $Action, $Path)
+ $null = $Case
+ $context = Get-TestContext -Capabilities $Capabilities
+ $request = $Action
+ $exception = Get-ThrownException { & $request $context }
+ $exception | Should -BeOfType [McpProtocolException]
+ $exception | Should -Not -BeOfType [McpInputRequiredException]
+ $exception.Code | Should -Be -32021
+ $node = $exception.Data['requiredCapabilities']
+ foreach ($segment in $Path) { $node.Contains($segment) | Should -BeTrue; $node = $node[$segment] }
+ $context.PendingInput.Count | Should -Be 0
+ }
+
+ It 'treats an empty elicitation capability as form mode' {
+ $exception = Get-ThrownException { Request-McpElicitation -Context (Get-TestContext -Capabilities @{ elicitation = @{} }) -Key 'k' -Message 'm' -Schema @{ x = @{ type = 'boolean' } } }
+ $exception | Should -BeOfType [McpInputRequiredException]
+ }
+
+ It 'throws outside of a tools/call, prompts/get or resources/read handler' {
+ { Request-McpElicitation -Context (Get-TestContext -Kind 'Completion') -Key 'k' -Message 'm' -Schema @{ x = @{ type = 'string' } } } | Should -Throw -ExpectedMessage '*request context*'
+ }
+}
+
+Describe 'Deferred input requests' {
+ It 'collects several requests into one round with Wait-McpInput' {
+ $context = Get-TestContext
+ $name = Request-McpElicitation -Context $context -Key 'user_name' -Message 'Name?' -Schema @{ name = @{ type = 'string' } } -Defer
+ $greeting = Request-McpSampling -Context $context -Key 'greeting' -Messages 'Generate a greeting' -MaxTokens 50 -Defer
+ $roots = Request-McpRoot -Context $context -Key 'client_roots' -Defer
+ $name | Should -BeNullOrEmpty
+ $greeting | Should -BeNullOrEmpty
+ $roots | Should -BeNullOrEmpty
+ $exception = Get-ThrownException { Wait-McpInput -Context $context }
+ $exception | Should -BeOfType [McpInputRequiredException]
+ @($exception.InputRequests.Keys) | Should -Be @('user_name', 'greeting', 'client_roots')
+ @($exception.InputRequests.Values | ForEach-Object { $_['method'] }) | Should -Be @('elicitation/create', 'sampling/createMessage', 'roots/list')
+ (Test-McpSpecShape -Definition 'InputRequests' -Instance (ConvertTo-Wire $exception.InputRequests)).IsValid | Should -BeTrue
+ }
+
+ It 'returns the answers and passes Wait-McpInput when all are there' {
+ $context = Get-TestContext -Responses ([ordered]@{
+ greeting = @{ role = 'assistant'; content = @{ type = 'text'; text = 'Hi!' }; model = 'm1'; stopReason = 'endTurn' }
+ client_roots = @{ roots = @(@{ uri = 'file:///work'; name = 'work' }) }
+ })
+ $greeting = Request-McpSampling -Context $context -Key 'greeting' -Messages 'Generate a greeting' -Defer
+ $roots = @(Request-McpRoot -Context $context -Key 'client_roots' -Defer)
+ { Wait-McpInput -Context $context } | Should -Not -Throw
+ $greeting.PSObject.TypeNames | Should -Contain 'Mcp.SamplingResult'
+ $greeting.Text | Should -Be 'Hi!'
+ $greeting.Model | Should -Be 'm1'
+ $roots.Count | Should -Be 1
+ $roots[0].PSObject.TypeNames | Should -Contain 'Mcp.Root'
+ $roots[0].Uri | Should -Be 'file:///work'
+ }
+
+ It 'rejects malformed answers with -32602' -TestCases @(
+ @{ Case = 'sampling'; Response = @{ role = 'robot'; content = @{ type = 'text'; text = 'x' }; model = 'm' }; Action = { param($c) Request-McpSampling -Context $c -Key 'k' -Messages 'hi' } }
+ @{ Case = 'roots'; Response = @{ roots = @(@{ name = 'no uri' }) }; Action = { param($c) Request-McpRoot -Context $c -Key 'k' } }
+ ) {
+ param($Case, $Response, $Action)
+ $null = $Case
+ $context = Get-TestContext -Responses ([ordered]@{ k = $Response })
+ $request = $Action
+ (Get-ThrownException { & $request $context }).Code | Should -Be -32602
+ }
+}
+
+Describe 'Elicitation schemas' {
+ It 'accepts the primitive schema ' -TestCases @(
+ @{ Case = 'string with format'; Property = @{ type = 'string'; format = 'email'; minLength = 3 } }
+ @{ Case = 'number'; Property = @{ type = 'number'; minimum = 0 } }
+ @{ Case = 'integer'; Property = @{ type = 'integer' } }
+ @{ Case = 'boolean'; Property = @{ type = 'boolean'; default = $true } }
+ @{ Case = 'untitled single-select enum'; Property = @{ type = 'string'; enum = @('a', 'b') } }
+ @{ Case = 'titled single-select enum'; Property = @{ type = 'string'; oneOf = @(@{ const = 'a'; title = 'A' }) } }
+ @{ Case = 'legacy titled enum'; Property = @{ type = 'string'; enum = @('a'); enumNames = @('A') } }
+ @{ Case = 'untitled multi-select enum'; Property = @{ type = 'array'; items = @{ type = 'string'; enum = @('a', 'b') } } }
+ @{ Case = 'titled multi-select enum'; Property = @{ type = 'array'; items = @{ anyOf = @(@{ const = 'a'; title = 'A' }) } } }
+ ) {
+ param($Case, $Property)
+ $null = $Case
+ $schema = Invoke-McpInModule { param($p) ConvertTo-McpElicitationSchema -Schema @{ field = $p } } -Parameters @{ p = $Property }
+ (Test-McpSpecShape -Definition 'PrimitiveSchemaDefinition' -Instance (ConvertTo-Wire $schema['properties']['field'])).IsValid | Should -BeTrue
+ }
+
+ It 'accepts a full schema with its required list' {
+ $schema = Invoke-McpInModule { ConvertTo-McpElicitationSchema -Schema @{ type = 'object'; properties = @{ ok = @{ type = 'boolean' } }; required = @('ok') } }
+ $schema['required'] | Should -Be @('ok')
+ }
+
+ It 'rejects ' -TestCases @(
+ @{ Case = 'nested objects'; Schema = @{ address = @{ type = 'object'; properties = @{ city = @{ type = 'string' } } } }; Message = '*only string*' }
+ @{ Case = 'arrays of free values'; Schema = @{ tags = @{ type = 'array'; items = @{ type = 'string' } } }; Message = '*multi-select*' }
+ @{ Case = 'unknown string formats'; Schema = @{ ip = @{ type = 'string'; format = 'ipv4' } }; Message = '*format*' }
+ @{ Case = 'a required property that is not defined'; Schema = @{ type = 'object'; properties = @{ a = @{ type = 'string' } }; required = @('b') }; Message = '*not defined*' }
+ ) {
+ param($Case, $Schema, $Message)
+ $null = $Case
+ $schemaUnderTest = $Schema
+ { Invoke-McpInModule { param($s) ConvertTo-McpElicitationSchema -Schema $s } -Parameters @{ s = $schemaUnderTest } } | Should -Throw -ExpectedMessage $Message
+ }
+}
+
+Describe 'InputRequiredResult' {
+ It 'matches the specification schema and signs the answers accepted so far' {
+ $context = Get-TestContext -Responses ([ordered]@{ step1 = @{ action = 'accept'; content = @{ name = 'Ada' } } })
+ $null = Request-McpElicitation -Context $context -Key 'step1' -Message 'Step 1' -Schema @{ name = @{ type = 'string' } }
+ $exception = Get-ThrownException { Request-McpElicitation -Context $context -Key 'step2' -Message 'Step 2' -Schema @{ color = @{ type = 'string' } } }
+ $key = [byte[]] (1..32)
+ $envelope = @{ RequestStateKey = $key; Method = 'tools/call'; Name = 't'; RequestDigest = 'd'; RequestStateTtlSeconds = 60 }
+ $result = Invoke-McpInModule { param($r, $c, $e) Get-McpInputRequiredResult -InputRequests $r -Context $c -Envelope $e } -Parameters @{ r = $exception.InputRequests; c = $context; e = $envelope }
+ (Test-McpSpecShape -Definition 'InputRequiredResult' -Instance (ConvertTo-Wire $result)).IsValid | Should -BeTrue
+ @($result['inputRequests'].Keys) | Should -Be @('step2')
+ $payload = Invoke-McpInModule { param($k, $t) Read-McpRequestState -Key $k -Token $t -Method 'tools/call' -Name 't' -Digest 'd' } -Parameters @{ k = $key; t = $result['requestState'] }
+ $payload['a']['step1']['content']['name'] | Should -Be 'Ada'
+ $payload['r']['step2'] | Should -Be 'elicitation/create'
+ }
+}
diff --git a/tests/Unit/Module.Tests.ps1 b/tests/Unit/Module.Tests.ps1
index b4465e1..e2493d5 100644
--- a/tests/Unit/Module.Tests.ps1
+++ b/tests/Unit/Module.Tests.ps1
@@ -3,7 +3,7 @@ BeforeAll {
$script:manifestPath = Get-McpBuiltModuleManifest
$script:manifestData = Import-PowerShellDataFile -Path $script:manifestPath
$script:accelerators = [psobject].Assembly.GetType('System.Management.Automation.TypeAccelerators')
- $script:engineTypeNames = @('McpEra', 'McpLoggingLevel')
+ $script:engineTypeNames = @('McpEra', 'McpLoggingLevel', 'McpProtocolException', 'McpInputRequiredException')
Remove-Module -Name ModelContextProtocol -Force -ErrorAction SilentlyContinue
}
diff --git a/tests/Unit/RequestState.Tests.ps1 b/tests/Unit/RequestState.Tests.ps1
new file mode 100644
index 0000000..77c1cc4
--- /dev/null
+++ b/tests/Unit/RequestState.Tests.ps1
@@ -0,0 +1,128 @@
+[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:key = [byte[]] (1..32)
+ function Get-TestState {
+ param([hashtable] $Overrides = @{})
+ $parameters = @{
+ Key = $script:key
+ Method = 'tools/call'
+ Name = 'confirm'
+ Digest = 'digest-1'
+ Answers = [ordered]@{ step1 = [ordered]@{ action = 'accept'; content = [ordered]@{ name = 'Ada' } } }
+ Requested = [ordered]@{ step2 = 'elicitation/create' }
+ HandlerState = @{ phase = 2 }
+ }
+ foreach ($name in $Overrides.Keys) { $parameters[$name] = $Overrides[$name] }
+ Invoke-McpInModule { param($p) New-McpRequestState @p } -Parameters @{ p = $parameters }
+ }
+ function Read-TestState {
+ param([object] $Token, [hashtable] $Overrides = @{})
+ $parameters = @{ Key = $script:key; Token = $Token; Method = 'tools/call'; Name = 'confirm'; Digest = 'digest-1' }
+ foreach ($name in $Overrides.Keys) { $parameters[$name] = $Overrides[$name] }
+ Invoke-McpInModule { param($p) Read-McpRequestState @p } -Parameters @{ p = $parameters }
+ }
+ function ConvertTo-TestSecureString {
+ param([string] $Text)
+ $secure = [System.Security.SecureString]::new()
+ foreach ($character in $Text.ToCharArray()) { $secure.AppendChar($character) }
+ $secure
+ }
+ function Get-StateError {
+ param([scriptblock] $Action)
+ try { & $Action; $null } catch { $_.Exception }
+ }
+}
+
+Describe 'requestState' {
+ It 'round-trips the accumulated answers, the requested keys and the handler state' {
+ $token = Get-TestState
+ $token | Should -Match '^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$'
+ $payload = Read-TestState -Token $token
+ $payload['v'] | Should -Be 1
+ $payload['a']['step1']['content']['name'] | Should -Be 'Ada'
+ $payload['r']['step2'] | Should -Be 'elicitation/create'
+ $payload['s']['phase'] | Should -Be 2
+ }
+
+ It 'differs on every call (nonce) and leaves out an empty handler state' {
+ $first = Get-TestState -Overrides @{ HandlerState = @{} }
+ $second = Get-TestState -Overrides @{ HandlerState = @{} }
+ $first | Should -Not -Be $second
+ (Read-TestState -Token $first).Contains('s') | Should -BeFalse
+ }
+
+ It 'rejects with -32602' -TestCases @(
+ @{ Case = 'a modified payload'; Mutate = { param($t) $parts = $t.Split('.'); $body = $parts[0].ToCharArray(); $body[5] = if ($body[5] -eq 'A') { 'B' } else { 'A' }; (-join $body) + '.' + $parts[1] }; Reason = 'signature' }
+ @{ Case = 'a modified signature'; Mutate = { param($t) $t.Substring(0, $t.Length - 2) + $(if ($t.EndsWith('AA')) { 'BB' } else { 'AA' }) }; Reason = 'signature' }
+ @{ Case = 'a token without signature'; Mutate = { param($t) $t.Split('.')[0] }; Reason = 'malformed' }
+ @{ Case = 'garbage'; Mutate = { param($t) $null = $t; 'not-a-token' }; Reason = 'malformed' }
+ @{ Case = 'a non-string token'; Mutate = { param($t) $null = $t; 42 }; Reason = 'not a string' }
+ ) {
+ param($Case, $Mutate, $Reason)
+ $null = $Case
+ $token = & $Mutate (Get-TestState)
+ $exception = Get-StateError { Read-TestState -Token $token }
+ $exception | Should -BeOfType [McpProtocolException]
+ $exception.Code | Should -Be -32602
+ $exception.Message | Should -BeLike "*$Reason*"
+ }
+
+ It 'rejects a state signed with another key' {
+ $token = Get-TestState -Overrides @{ Key = [byte[]] (101..132) }
+ (Get-StateError { Read-TestState -Token $token }).Message | Should -BeLike '*signature*'
+ }
+
+ It 'rejects an expired state' {
+ $token = Get-TestState -Overrides @{ TtlSeconds = -1 }
+ (Get-StateError { Read-TestState -Token $token }).Message | Should -BeLike '*expired*'
+ }
+
+ It 'rejects a state of another ' -TestCases @(
+ @{ Case = 'method'; Overrides = @{ Method = 'prompts/get' }; Reason = 'another request' }
+ @{ Case = 'target'; Overrides = @{ Name = 'other' }; Reason = 'another request' }
+ @{ Case = 'argument digest'; Overrides = @{ Digest = 'digest-2' }; Reason = 'arguments differ' }
+ ) {
+ param($Case, $Overrides, $Reason)
+ $null = $Case
+ $stateOverrides = $Overrides
+ (Get-StateError { Read-TestState -Token (Get-TestState) -Overrides $stateOverrides }).Message | Should -BeLike "*$Reason*"
+ }
+}
+
+Describe 'Request digests and signing keys' {
+ It 'digests the salient params independently of member order' {
+ $a = Invoke-McpInModule { Get-McpRequestDigest -Method 'tools/call' -Params ([ordered]@{ name = 't'; arguments = [ordered]@{ x = 1; y = [ordered]@{ b = 2; a = 1 } } }) }
+ $b = Invoke-McpInModule { Get-McpRequestDigest -Method 'tools/call' -Params ([ordered]@{ arguments = [ordered]@{ y = [ordered]@{ a = 1; b = 2 }; x = 1 }; name = 't'; inputResponses = @{}; requestState = 'x' }) }
+ $c = Invoke-McpInModule { Get-McpRequestDigest -Method 'tools/call' -Params ([ordered]@{ name = 't'; arguments = [ordered]@{ x = 2 } }) }
+ $a | Should -Be $b
+ $a | Should -Not -Be $c
+ }
+
+ It 'derives a 32-byte key from ' -TestCases @(
+ @{ Case = 'nothing (random)'; Key = $null }
+ @{ Case = 'a string'; Key = 'a sufficiently long secret' }
+ @{ Case = 'a byte array'; Key = [byte[]] (1..40) }
+ ) {
+ param($Case, $Key)
+ $null = $Case
+ $bytes = Invoke-McpInModule { param($k) ConvertTo-McpRequestStateKey -Key $k } -Parameters @{ k = $Key }
+ $bytes.Length | Should -BeGreaterOrEqual 32
+ }
+
+ It 'derives the same key from a string and the equal SecureString' {
+ $fromString = Invoke-McpInModule { ConvertTo-McpRequestStateKey -Key 'a sufficiently long secret' }
+ $fromSecure = Invoke-McpInModule { param($k) ConvertTo-McpRequestStateKey -Key $k } -Parameters @{ k = (ConvertTo-TestSecureString -Text 'a sufficiently long secret') }
+ [System.Convert]::ToBase64String($fromString) | Should -Be ([System.Convert]::ToBase64String($fromSecure))
+ }
+
+ It 'rejects weak keys' {
+ { Invoke-McpInModule { ConvertTo-McpRequestStateKey -Key 'short' } } | Should -Throw -ExpectedMessage '*16 characters*'
+ { Invoke-McpInModule { ConvertTo-McpRequestStateKey -Key ([byte[]] (1..16)) } } | Should -Throw -ExpectedMessage '*32 bytes*'
+ { New-McpServer -Name 'weak' -Version '1.0.0' -RequestStateKey 'short' } | Should -Throw -ExpectedMessage '*16 characters*'
+ }
+}
diff --git a/tests/Unit/Server.Tests.ps1 b/tests/Unit/Server.Tests.ps1
index 8704590..532432c 100644
--- a/tests/Unit/Server.Tests.ps1
+++ b/tests/Unit/Server.Tests.ps1
@@ -37,7 +37,7 @@ Describe 'server/discover' {
@($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['capabilities']['tools']['listChanged'] | Should -BeTrue
$result['ttlMs'] | Should -Be 5000
$result['cacheScope'] | Should -Be 'private'
$result['_meta']['io.modelcontextprotocol/serverInfo']['name'] | Should -Be 'demo'