diff --git a/CHANGELOG.md b/CHANGELOG.md
index 990dfba..0479a30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,34 @@ support, dependency and breaking-change policy.
### Added
+- 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
+ symbolic links leading outside; `resources/list`, `resources/templates/list` and `resources/read` with
+ `-32602` and `data.uri` for unknown resources (SEP-2164) and per-resource caching hints (`-TtlMs`,
+ `-CacheScope`).
+- `Register-McpPrompt` registers prompts whose arguments are derived from the handler's parameters (or given
+ with `-Arguments`); `prompts/list` and `prompts/get` with argument validation and message shaping (strings,
+ content blocks, `New-McpPromptMessage`). `completion/complete` for prompt arguments and template variables
+ from `-Completion` value lists or handlers and from `ValidateSet`, capped at 100 values with `total` and
+ `hasMore`.
+- The `resources`, `prompts` and `completions` capabilities are declared when something is registered; their
+ methods answer `-32601` otherwise. All list methods page with cursors bound to their list.
+- `New-McpContent` validates annotations (`audience`, `priority`, `lastModified`) and takes `-Icons` for
+ resource links and `-ResourceMeta` for embedded resources; icons of servers, tools, resources and prompts are
+ validated; `New-McpPromptMessage` and `New-McpResourceContent` build prompt messages and resource contents.
+- Warning, information, verbose and debug records of handlers are sent as `notifications/message` when the
+ request asks for log notifications (besides stderr); the request context has a `Name` for every kind of
+ handler.
+- Client: `Get-McpResource [-Template]`, `Read-McpResource` (pipeline input, non-terminating `ObjectNotFound`
+ errors for `-32602` with `data.uri` and the legacy `-32002`), `Get-McpPrompt`, `Invoke-McpPrompt` and
+ `Get-McpCompletion`; a per-session cache that reuses `server/discover`, list and `resources/read` results
+ for their `ttlMs`; content blocks and resource contents are typed objects with `GetBytes()`; format views
+ for the new objects.
+- Conformance: the fixture server registers the resources, template, prompts and completions of the
+ resource, prompt, completion and caching scenarios, whose baseline entries are removed; the fixture client
+ also reads resources and renders prompts when the server declares them. `examples/weather-server.ps1`
+ demonstrates every server primitive.
- Milestone M2 (Streamable HTTP): `Start-McpServer -Transport Http -Url ...` serves the MCP endpoint on
`System.Net.HttpListener`: one JSON-RPC request or notification per POST, responses as a single JSON
object or as a request-scoped SSE stream (progress and log notifications, keep-alive comments, a closed
@@ -66,6 +94,10 @@ support, dependency and breaking-change policy.
### Fixed
+- `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
+ `a-b` and `a_b`) no longer share one worker function.
- The `Analyze` build task no longer fails or hangs on PSScriptAnalyzer's sporadic rule failures: every path is
analysed in a fresh process with a timeout, and files on which a rule failed are re-analysed in further fresh
processes.
diff --git a/README.md b/README.md
index ab0c7b7..f339430 100644
--- a/README.md
+++ b/README.md
@@ -4,14 +4,16 @@ 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 M2 (Streamable HTTP).** Servers expose PowerShell functions, cmdlets, scripts and
-> script blocks as tools over stdio and over Streamable HTTP with the stateless 2026-07-28 lifecycle
-> (`server/discover`, per-request `_meta`, request metadata headers, progress, cancellation), and the client
-> side connects to such servers over both transports. The official conformance suite runs in CI: every
-> 2026-07-28 scenario of the tools, HTTP header validation and DNS rebinding groups passes on both legs;
-> the remaining scenarios (resources, prompts, completion, input requests, subscriptions, authorization)
-> are listed in [conformance-baseline.yml](conformance-baseline.yml) and follow in M3 to M7. The milestones
-> are in [ROADMAP.md](ROADMAP.md); the design is in [docs/implementation-plan.md](docs/implementation-plan.md).
+> **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
+> [ROADMAP.md](ROADMAP.md); the design is in [docs/implementation-plan.md](docs/implementation-plan.md).
## Requirements
@@ -54,6 +56,19 @@ validated against the generated JSON Schema and bound to the parameters; objects
`Write-McpProgress`/`Write-McpLog` reach the client through a `Context` parameter. Handlers run in a worker
runspace pool, so nothing they write to the host can reach stdout.
+Resources and prompts are registered the same way; resource templates bind their variables to parameters,
+prompt arguments come from the `param()` block, and a `ValidateSet` doubles as argument completion:
+
+```powershell
+Register-McpResource -Uri 'weather://stations' -MimeType application/json -Content '["Berlin","Vienna"]'
+Register-McpResource -UriTemplate 'weather://{city}/current' -ScriptBlock { param($city) Get-Weather -Location $city } -TtlMs 10000
+Register-McpResource -Path ./docs -Uri 'docs://' # every file below ./docs, as docs://{+path}
+Register-McpPrompt -Name 'weather-report' -Description 'Asks for a weather report.' -ScriptBlock {
+ param([Parameter(Mandatory)] [ValidateSet('Berlin', 'Vienna')] [string] $City)
+ "Write a three-sentence weather report for $City."
+}
+```
+
The client side:
```powershell
@@ -62,6 +77,9 @@ Get-McpServerInfo | Format-List
Get-McpTool | Select-Object Name, Description
$result = Invoke-McpTool -Name Get-Weather -Arguments @{ Location = 'Berlin' }
$result.StructuredContent.temperature
+Get-McpResource | Read-McpResource # cached for the ttlMs of each result
+(Invoke-McpPrompt -Name weather-report -Arguments @{ City = 'Vienna' }).Messages
+(Get-McpCompletion -PromptName weather-report -Argument City -Value 'Vi').Values
Disconnect-McpServer
```
@@ -82,8 +100,10 @@ SSE responses. See [docs/concepts/transports.md](docs/concepts/transports.md).
`Connect-McpServer -Server $serverObject` runs a server in a background runspace over an in-memory transport,
which is how the tests exercise servers without child processes. `Invoke-McpToolHandler` calls a registered
-tool directly for unit tests of the tool itself. See `examples/echo-server.ps1`, `examples/http-server.ps1`
-and [docs/development.md](docs/development.md) for the Inspector command line.
+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`,
+[docs/concepts/server-primitives.md](docs/concepts/server-primitives.md) and
+[docs/development.md](docs/development.md) for the Inspector command line.
## Building from source
diff --git a/ROADMAP.md b/ROADMAP.md
index 6a2dddc..44afa95 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -18,7 +18,7 @@ against the requirement sets `2026-07-28` (37 server + 32 client scenarios) and
| **M0 Foundation** | Toolchain, module skeleton, ModuleBuilder build, analyzer rules, Pester skeleton, vendored schemas, CI matrix, release dry run, governance documents | CI green on all matrix cells with the empty module; side-effect-free import; publishing to a local repository works | Done |
| **M1 Protocol core, stdio, tools (modern)** | System.Text.Json codec, JSON-RPC model, `_meta` validation, error codes, router, `server/discover`, capabilities, extension registry, in-memory transport, dispatcher and runspace pool, stdio server and client transports, `tools/list`, `tools/call` (text), schema generator and validator, progress, cancellation | Unit and integration tests green; Inspector CLI `tools/list` against `examples/echo-server.ps1`; startup and per-request overhead measured | Done |
| **M2 Streamable HTTP (modern)** | HttpListener host, header validation, Origin allowlist, JSON/SSE selection, keep-alive, disconnect → cancel; client HTTP transport with SSE parser; conformance fixtures and workflow | Conformance 2026-07-28: `server-stateless`, `tools-list`, `tools-call-simple-text/-error/-with-progress`, `dns-rebinding-protection`, `http-header-validation`, `http-custom-header-server-validation`; client `tools_call`, `request-metadata`, `http-*`, `json-schema-ref-no-deref`; first `0.1.0-preview` on the PowerShell Gallery | Done (the Gallery preview is published from the release workflow by tagging `v0.1.0-preview1`) |
-| **M3 Server primitives** | Resources (static, file, templates, blob), prompts, completion, pagination, caching fields, all content types, `structuredContent`/`outputSchema`, icons, annotations, `notifications/message`; client counterparts with TTL cache | `tools-call-image/-audio/-embedded-resource/-mixed-content`, `json-schema-2020-12`, `resources-*`, `sep-2164-resource-not-found`, `prompts-*`, `completion-complete`, `caching`; client `json-schema-2020-12-preservation` | Planned |
+| **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 |
| **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 |
@@ -34,7 +34,7 @@ against the requirement sets `2026-07-28` (37 server + 32 client scenarios) and
| stdio transport (server and client) | M1 |
| Streamable HTTP (server and client), header validation, Origin protection | M2 |
| `resources/*`, `prompts/*`, `completion/complete`, caching (`ttlMs`, `cacheScope`), pagination | M3 |
-| `notifications/progress`, `notifications/cancelled`, `notifications/message` | M1 / M3 |
+| `notifications/progress`, `notifications/cancelled`, `notifications/message` (including handler streams) | M1 / M3 |
| MRTR: `elicitation/create`, `sampling/createMessage`, `roots/list` as input requests | M4 |
| `subscriptions/listen`, list-changed and resource-updated notifications | M4 |
| Legacy revisions 2025-11-25 and 2025-06-18 (both roles) | M5 |
diff --git a/build.ps1 b/build.ps1
index 10f0248..d2b9db1 100644
--- a/build.ps1
+++ b/build.ps1
@@ -328,7 +328,7 @@ function Install-BuildDependency {
}
}
$message = "Could not install '$Name' $range.`n " + ($errors -join "`n ")
- if ($Requirement.Optional) {
+ if ($Requirement.ContainsKey('Optional') -and $Requirement.Optional) {
Write-Warning "$message`n '$Name' is optional; tasks that need it will be skipped."
return $false
}
@@ -348,7 +348,7 @@ foreach ($entry in ($script:Requirements.Modules.GetEnumerator() | Sort-Object -
if ($Bootstrap) {
Write-Host (" {0,-32} {1,-14} installing..." -f $name, $requirement.Version)
$null = Install-BuildDependency -Name $name -Requirement $requirement -Source $DependencySource -OfflinePath $OfflinePackagePath
- } elseif ($requirement.Optional) {
+ } elseif ($requirement.ContainsKey('Optional') -and $requirement.Optional) {
Write-Host (" {0,-32} {1,-14} missing (optional)" -f $name, $requirement.Version) -ForegroundColor Yellow
} else {
Write-Host (" {0,-32} {1,-14} missing" -f $name, $requirement.Version) -ForegroundColor Red
diff --git a/conformance-baseline.yml b/conformance-baseline.yml
index b8fdbf4..0ebd4ea 100644
--- a/conformance-baseline.yml
+++ b/conformance-baseline.yml
@@ -8,19 +8,6 @@
# (2026-07-28 and 2025-11-25). The milestone that removes an entry is noted next to it (see ROADMAP.md);
# the 2025-11-25 requirement set is run from milestone M5 (dual era) on.
server:
- # M3: resources, prompts, completion and caching hints on their results
- - completion-complete
- - resources-list
- - resources-read-text
- - resources-read-binary
- - resources-templates-read
- - sep-2164-resource-not-found
- - prompts-list
- - prompts-get-simple
- - prompts-get-with-args
- - prompts-get-embedded-resource
- - prompts-get-with-image
- - caching
# M4: input requests (MRTR); the two scenarios that only warn today (SHOULD checks) are listed as well
- input-required-result-basic-elicitation
- input-required-result-basic-sampling
diff --git a/docs/README.md b/docs/README.md
index bbf84b3..35d6c9f 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -6,6 +6,7 @@
| [development.md](development.md) | Build, analysis, tests, packaging, CI and release mechanics |
| [conformance.md](conformance.md) | How the MCP conformance suite is run and how the baseline works |
| [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/authorization.md](concepts/authorization.md) | OAuth client flows and server-side bearer validation |
diff --git a/docs/concepts/server-primitives.md b/docs/concepts/server-primitives.md
new file mode 100644
index 0000000..9a927c1
--- /dev/null
+++ b/docs/concepts/server-primitives.md
@@ -0,0 +1,88 @@
+# 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.
+
+## Registration and capabilities
+
+| Primitive | Server command | Methods | Capability in `server/discover` |
+|---|---|---|---|
+| Tool | `Register-McpTool` | `tools/list`, `tools/call` | `tools` (always) |
+| Resource | `Register-McpResource -Uri` or `-Path ` | `resources/list`, `resources/read` | `resources` once a resource or template exists |
+| Resource template | `Register-McpResource -UriTemplate` or `-Path ` | `resources/templates/list`, `resources/read` | `resources` |
+| Prompt | `Register-McpPrompt` | `prompts/list`, `prompts/get` | `prompts` once a prompt exists |
+| 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).
+
+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
+completion handlers run in the worker runspace pool, with the request's cancellation token and timeout.
+
+## Handler contract
+
+Handlers run in a hostless runspace pool. They see only their parameters, so pass all data through them. The
+request context arrives in a parameter named `Context` (`Mcp.RequestContext`: `RequestId`, `Method`, `Name`,
+`ProtocolVersion`, `ClientInfo`, `ClientCapabilities`, `LogLevel`, `ProgressToken`, `CancellationToken`).
+Warnings, information, verbose and debug records go to stderr and, when the request carried
+`io.modelcontextprotocol/logLevel`, to the client as `notifications/message` (warning, info, debug). Resource,
+prompt and completion handlers also report non-terminating errors as `error`.
+
+| Handler | Parameters it may declare | Output |
+|---|---|---|
+| Resource | `Uri`, `Variables` (all template variables), each template variable by name, `Context` | strings (joined into one text content), `byte[]` (a blob; `return $bytes` works too), `FileInfo` (the file), objects (JSON text), `New-McpResourceContent` (several contents, own URI, MIME type, `_meta`). No output or `ItemNotFoundException` means not found. |
+| Prompt | each argument by name (converted to the parameter type), or `Arguments` (all values) with explicit `-Arguments`; `Context` | strings (joined into one user text message), content blocks (`New-McpContent`, one user message each), `New-McpPromptMessage` (role and content), objects (JSON text) |
+| Completion | `Value` (typed so far), `Argument` (its name), `Arguments` (`context.arguments`), `Context` | candidate strings, returned as given (the handler filters) |
+
+Prompt arguments are strings on the wire. Without `-Arguments` they are derived from the handler's parameters:
+a mandatory parameter is a required argument, the comment-based help describes it, and a `ValidateSet`
+becomes a completion source. Every prompt should have a description (`-Description` or `.SYNOPSIS`); the
+registration warns otherwise, because clients show descriptions in their prompt lists.
+
+## URIs and templates
+
+Resource URIs must be absolute (RFC 3986). `resources/read` serves an exact resource URI first and otherwise
+the first template, in registration order, whose RFC 6570 template matches. Levels 1 to 3 are supported: the
+operators none, `+`, `#`, `.`, `/`, `;`, `?` and `&`. Values are percent-decoded before they reach the
+handler. The level 4 modifiers (prefix `:n` and explode `*`) are rejected at registration, because matching
+them in reverse is ambiguous.
+
+`Register-McpResource -Path ` registers the template `/{+path}` (the base defaults to the
+`file://` URI of the directory). The path is combined with the directory and normalised; `..` segments,
+absolute paths and symbolic links whose target lies outside the directory are answered as not found, which
+satisfies the specification's requirement to sanitise file resources against directory traversal.
+
+## Errors
+
+| Situation | Error |
+|---|---|
+| Unknown resource URI, a handler without output or throwing `ItemNotFoundException`, a missing file | `-32602` `Resource not found` with `data.uri` (SEP-2164; never an empty `contents`) |
+| `uri` missing or not an absolute URI, unknown prompt, missing required argument, non-string argument value | `-32602` |
+| Unknown completion reference, argument or template variable | `-32602` |
+| A resource, prompt or completion handler throws | `-32603` with the message |
+| A tool handler throws | a tool result with `isError` (the model sees it), as for every tool execution error |
+
+Over Streamable HTTP these map to the HTTP statuses of the transport (400 for `-32602`), and the `Mcp-Name`
+header of `resources/read` (`params.uri`) and `prompts/get` (`params.name`) is validated against the body.
+
+## Caching
+
+Every `complete` result that the specification makes cacheable carries `ttlMs` and `cacheScope`:
+`server/discover`, the four list methods (the server defaults, `New-McpServer -DefaultTtlMs
+-DefaultCacheScope`, on every page so that all pages share one scope) and `resources/read` (the resource's own
+`-TtlMs`/`-CacheScope`, else the server defaults). `prompts/get`, `completion/complete` and `tools/call`
+results are not cacheable.
+
+The client keeps a cache per session. `Get-McpServerInfo`, `Get-McpTool`, `Get-McpResource`,
+`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).
+
+## Pagination
+
+The list methods page with `New-McpServer -PageSize`. Cursors are opaque base64 strings that name their list
+and the offset of the next page; a cursor of one list is rejected by another (`-32602 Invalid cursor.`). The
+client follows `nextCursor` through all pages.
diff --git a/docs/conformance.md b/docs/conformance.md
index 92b0455..38997b5 100644
--- a/docs/conformance.md
+++ b/docs/conformance.md
@@ -2,9 +2,10 @@
The SDK is measured with the official suite `@modelcontextprotocol/conformance`. The npm `latest` dist-tag
(0.1.x) does not know revision 2026-07-28; the version pinned in `requirements.psd1` (alpha channel) does.
-The fixtures live in `tests/Conformance/` (`everything-server.ps1`, a Streamable HTTP server with every tool
-the server scenarios call; `everything-client.ps1`, a client that discovers, lists and calls tools as the
-client scenarios expect), the build task `Conformance` runs both legs, and `.github/workflows/conformance.yml`
+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`
runs them on every push and pull request.
## Running the suite
@@ -21,15 +22,20 @@ 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 M2
+## State after milestone M3
Requirement set `2026-07-28`, server leg: `server-stateless` (25 checks), `tools-list`, the seven
-`tools-call-*` scenarios, `sep-2164-resource-not-found`, `dns-rebinding-protection` and
-`server-sse-multiple-streams` pass; the not-scored `json-schema-2020-12`, `http-header-validation` and
-`http-custom-header-server-validation` pass too. Client leg: `tools_call`, `request-metadata`,
-`auth/resource-mismatch`, `http-standard-headers`, `http-custom-headers`, `http-invalid-tool-headers`,
-`json-schema-ref-no-deref` and the not-scored `json-schema-2020-12-preservation` pass. Everything else is in
-`conformance-baseline.yml`, grouped by the milestone that removes it.
+`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.
## Requirement sets
diff --git a/docs/development.md b/docs/development.md
index b2d9e2d..a2ff486 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 `tools/list` shapes against the vendored schema, header value encoding and `x-mcp-header` validation, HTTP status mapping, Origin checks, SSE parsing | in-process |
-| `tests/Integration` | fresh `pwsh` processes: import must be silent on stdout and stderr, also under `-File`; the client against a server in a background runspace (in-memory transport); `examples/echo-server.ps1` over stdio (encoding, 1 MB payloads, progress, timeouts, stderr capture, BOM-free stdout, EOF shutdown); a Streamable HTTP server in a background runspace (client round trips, SSE progress, header mirroring, disconnect → cancel, and raw requests for every status and error code the specification assigns) | spawns processes, binds loopback ports |
+| `tests/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/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/examples/weather-server.ps1 b/examples/weather-server.ps1
new file mode 100644
index 0000000..49a5d2e
--- /dev/null
+++ b/examples/weather-server.ps1
@@ -0,0 +1,86 @@
+#Requires -Version 7.4
+<#
+.SYNOPSIS
+ An MCP server over stdio with all server primitives: a tool, resources, a resource template, prompts and
+ argument completion, around made-up weather data.
+.DESCRIPTION
+ Start it from an MCP client with:
+ pwsh -NoLogo -NoProfile -NonInteractive -File ./examples/weather-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. The data is generated from the city
+ name, so the example needs no network access.
+#>
+[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 'weather' -Version '0.1.0' -Title 'Weather example' -Instructions 'Made-up weather data: read weather://stations for the known cities, weather://{city}/current for current conditions, or use the forecast tool and the weather-report prompt.' -DefaultTtlMs 60000 -SetDefault
+
+# Handlers run in worker runspaces and see nothing but their parameters, so each handler derives its data from
+# the city name itself.
+Register-McpTool -Name 'forecast' -Description 'A made-up forecast for the next days.' -ScriptBlock {
+ param(
+ [Parameter(Mandatory)]
+ [ValidateSet('Berlin', 'Hamburg', 'Munich', 'Vienna', 'Zurich')]
+ [string] $City,
+
+ [ValidateRange(1, 7)]
+ [int] $Days = 3
+ )
+ $seed = [int] ($City.ToCharArray() | Measure-Object -Sum { [int] $_ }).Sum
+ [pscustomobject]@{
+ city = $City
+ days = @(for ($day = 1; $day -le $Days; $day++) {
+ [ordered]@{ day = $day; high = 12 + ($seed + $day * 7) % 15; low = 2 + ($seed + $day * 3) % 8 }
+ })
+ }
+} -OutputSchema @{ type = 'object'; properties = @{ city = @{ type = 'string' }; days = @{ type = 'array' } }; required = @('city', 'days') } -Annotations @{ ReadOnlyHint = $true; OpenWorldHint = $false }
+
+Register-McpResource -Uri 'weather://stations' -Name 'stations' -Title 'Weather stations' -Description 'The cities with weather data.' -MimeType 'application/json' -Content '["Berlin","Hamburg","Munich","Vienna","Zurich"]' -Annotations @{ Audience = 'assistant'; Priority = 0.8 }
+
+Register-McpResource -UriTemplate 'weather://{city}/current' -Name 'current-weather' -Title 'Current weather' -Description 'Current conditions in a city.' -MimeType 'application/json' -TtlMs 10000 -ScriptBlock {
+ param([string] $city)
+ if ($city -notin @('Berlin', 'Hamburg', 'Munich', 'Vienna', 'Zurich')) { return }
+ $seed = [int] ($city.ToCharArray() | Measure-Object -Sum { [int] $_ }).Sum
+ [ordered]@{ city = $city; temperature = 5 + $seed % 20; conditions = @('clear', 'cloudy', 'rain', 'snow')[$seed % 4] }
+} -Completion @{
+ city = { param($Value) @('Berlin', 'Hamburg', 'Munich', 'Vienna', 'Zurich') | Where-Object { $_ -like "$Value*" } }
+}
+
+Register-McpPrompt -Name 'weather-report' -ScriptBlock {
+ <#
+ .SYNOPSIS
+ Asks the model for a short weather report for a city.
+ .PARAMETER City
+ The city of the report.
+ .PARAMETER Tone
+ The tone of the report.
+ #>
+ param(
+ [Parameter(Mandatory)]
+ [ValidateSet('Berlin', 'Hamburg', 'Munich', 'Vienna', 'Zurich')]
+ [string] $City,
+
+ [ValidateSet('neutral', 'cheerful', 'dramatic')]
+ [string] $Tone = 'neutral'
+ )
+ New-McpContent -EmbeddedResource "weather://$City/current" -MimeType 'text/plain' -ResourceText "Current weather data for $City is available as weather://$City/current."
+ "Write a $Tone three-sentence weather report for $City. Use the forecast tool for the coming days."
+}
+
+Register-McpPrompt -Name 'packing-list' -Description 'Asks the model what to pack for a trip.' -Arguments @(
+ @{ Name = 'destination'; Description = 'Where the trip goes.'; Required = $true }
+ @{ Name = 'days'; Description = 'The length of the trip in days.' }
+) -ScriptBlock {
+ param($Arguments)
+ $days = if ($Arguments['days']) { $Arguments['days'] } else { 'a few' }
+ New-McpPromptMessage -Role user -Text "I am travelling to $($Arguments['destination']) for $days days. What should I pack?"
+ New-McpPromptMessage -Role assistant -Text 'Let me check the forecast first.'
+}
+
+Start-McpServer -Server $server
diff --git a/src/Formats/ModelContextProtocol.Format.ps1xml b/src/Formats/ModelContextProtocol.Format.ps1xml
index ac534d4..d819716 100644
--- a/src/Formats/ModelContextProtocol.Format.ps1xml
+++ b/src/Formats/ModelContextProtocol.Format.ps1xml
@@ -93,5 +93,131 @@
+
+ Mcp.Resource
+
+ Mcp.Resource
+
+
+
+
+
+ 24
+
+
+
+
+
+ Name
+ Uri
+ MimeType
+ Description
+
+
+
+
+
+
+ Mcp.ResourceTemplate
+
+ Mcp.ResourceTemplate
+
+
+
+
+
+ 24
+
+
+
+
+
+ Name
+ UriTemplate
+ MimeType
+ Description
+
+
+
+
+
+
+ Mcp.ResourceContent
+
+ Mcp.ResourceContent
+
+
+
+
+ 24
+
+
+
+
+
+ Uri
+ MimeType
+ if ($null -ne $_.Text) { $_.Text } elseif ($null -ne $_.Blob) { "(" + [System.Convert]::FromBase64String([string] $_.Blob).Length + " bytes)" }
+
+
+
+
+
+
+ Mcp.Prompt
+
+ Mcp.Prompt
+
+
+
+
+
+
+
+
+
+
+ Name
+ @($_.Arguments | ForEach-Object { if ($_.Required) { $_.Name } else { "[" + $_.Name + "]" } }) -join ", "
+ Description
+
+
+
+
+
+
+ Mcp.PromptResult
+
+ Mcp.PromptResult
+
+
+
+
+
+ Name
+ Description
+ @($_.Messages | ForEach-Object { $_.Role + ": " + $(if ($_.Content.type -eq "text") { $_.Content.text } else { "(" + $_.Content.type + ")" }) }) -join [System.Environment]::NewLine
+
+
+
+
+
+
+ Mcp.Completion
+
+ Mcp.Completion
+
+
+
+
+
+ $_.Values -join ", "
+ Total
+ HasMore
+
+
+
+
+
diff --git a/src/Private/Client.ps1 b/src/Private/Client.ps1
index fd1d34b..f9a71a0 100644
--- a/src/Private/Client.ps1
+++ b/src/Private/Client.ps1
@@ -1,6 +1,7 @@
# Client side: the session object (PSTypeName Mcp.Session), request/response over a transport with progress
-# and log notifications dispatched on the way, and the public object shapes (Mcp.ServerInfo, Mcp.Tool,
-# Mcp.ToolResult).
+# and log notifications dispatched on the way, the result cache that honours the servers' caching hints, list
+# pagination, and the public object shapes (Mcp.ServerInfo, Mcp.Tool, Mcp.ToolResult, Mcp.Content,
+# Mcp.Resource, Mcp.ResourceTemplate, Mcp.ResourceContent, Mcp.Prompt, Mcp.PromptResult, Mcp.Completion).
$script:McpDefaultSession = $null
@@ -319,14 +320,13 @@ function ConvertTo-McpToolResultObject {
$content = @()
if ($Result.Contains('content') -and $null -ne $Result['content']) {
- $content = @($Result['content'] | ForEach-Object { if ($_ -is [System.Collections.IDictionary]) { [pscustomobject] $_ } else { $_ } })
+ $content = @($Result['content'] | ForEach-Object { ConvertTo-McpClientContentObject -Block $_ })
}
- $text = ($content | Where-Object { $_.PSObject.Properties['type'] -and $_.type -eq 'text' } | ForEach-Object { [string] $_.text }) -join "`n"
[pscustomobject]@{
PSTypeName = 'Mcp.ToolResult'
ToolName = $ToolName
IsError = [bool] ($Result.Contains('isError') -and $Result['isError'])
- Text = $text
+ Text = Get-McpContentText -Content $content
Content = $content
StructuredContent = if ($Result.Contains('structuredContent')) { $Result['structuredContent'] } else { $null }
ResultType = if ($Result.Contains('resultType')) { [string] $Result['resultType'] } else { 'complete' }
@@ -335,6 +335,352 @@ function ConvertTo-McpToolResultObject {
}
}
+function Get-McpWireValue {
+ <#
+ .SYNOPSIS
+ A member of a wire object, or $null when it is absent.
+ #>
+ [CmdletBinding()]
+ [OutputType([object], [object[]])]
+ param(
+ [AllowNull()]
+ [object] $Object,
+
+ [Parameter(Mandatory)]
+ [string] $Key
+ )
+
+ if ($Object -is [System.Collections.IDictionary] -and $Object.Contains($Key)) { return , $Object[$Key] }
+ $null
+}
+
+function ConvertTo-McpClientContentObject {
+ <#
+ .SYNOPSIS
+ A content block received from a server as Mcp.Content (its wire members as properties; GetBytes() decodes binary data).
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.Content')]
+ param(
+ [AllowNull()]
+ [object] $Block
+ )
+
+ if ($Block -isnot [System.Collections.IDictionary]) { return $Block }
+ $object = [pscustomobject] $Block
+ $object.PSObject.TypeNames.Insert(0, 'Mcp.Content')
+ $object
+}
+
+function Get-McpContentText {
+ <#
+ .SYNOPSIS
+ The text of the text blocks of a content list, joined with newlines.
+ #>
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [object[]] $Content
+ )
+
+ (@($Content) | Where-Object { $null -ne $_ -and $_.PSObject.Properties['type'] -and $_.type -eq 'text' } | ForEach-Object { [string] $_.text }) -join "`n"
+}
+
+function ConvertTo-McpResourceObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.Resource')]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Resource
+ )
+
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.Resource'
+ Uri = Get-McpWireValue -Object $Resource -Key 'uri'
+ Name = Get-McpWireValue -Object $Resource -Key 'name'
+ Title = Get-McpWireValue -Object $Resource -Key 'title'
+ Description = Get-McpWireValue -Object $Resource -Key 'description'
+ MimeType = Get-McpWireValue -Object $Resource -Key 'mimeType'
+ Size = Get-McpWireValue -Object $Resource -Key 'size'
+ Annotations = Get-McpWireValue -Object $Resource -Key 'annotations'
+ Icons = Get-McpWireValue -Object $Resource -Key 'icons'
+ Meta = Get-McpWireValue -Object $Resource -Key '_meta'
+ Raw = $Resource
+ }
+}
+
+function ConvertTo-McpResourceTemplateObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.ResourceTemplate')]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Template
+ )
+
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.ResourceTemplate'
+ UriTemplate = Get-McpWireValue -Object $Template -Key 'uriTemplate'
+ Name = Get-McpWireValue -Object $Template -Key 'name'
+ Title = Get-McpWireValue -Object $Template -Key 'title'
+ Description = Get-McpWireValue -Object $Template -Key 'description'
+ MimeType = Get-McpWireValue -Object $Template -Key 'mimeType'
+ Annotations = Get-McpWireValue -Object $Template -Key 'annotations'
+ Icons = Get-McpWireValue -Object $Template -Key 'icons'
+ Meta = Get-McpWireValue -Object $Template -Key '_meta'
+ Raw = $Template
+ }
+}
+
+function ConvertTo-McpResourceContentObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.ResourceContent')]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Content
+ )
+
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.ResourceContent'
+ Uri = Get-McpWireValue -Object $Content -Key 'uri'
+ MimeType = Get-McpWireValue -Object $Content -Key 'mimeType'
+ Text = Get-McpWireValue -Object $Content -Key 'text'
+ Blob = Get-McpWireValue -Object $Content -Key 'blob'
+ Meta = Get-McpWireValue -Object $Content -Key '_meta'
+ Raw = $Content
+ }
+}
+
+function ConvertTo-McpPromptObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.Prompt')]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Prompt
+ )
+
+ $wireArguments = Get-McpWireValue -Object $Prompt -Key 'arguments'
+ $arguments = @(@($wireArguments) | Where-Object { $_ -is [System.Collections.IDictionary] } | ForEach-Object {
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.PromptArgument'
+ Name = Get-McpWireValue -Object $_ -Key 'name'
+ Title = Get-McpWireValue -Object $_ -Key 'title'
+ Description = Get-McpWireValue -Object $_ -Key 'description'
+ Required = [bool] (Get-McpWireValue -Object $_ -Key 'required')
+ }
+ })
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.Prompt'
+ Name = Get-McpWireValue -Object $Prompt -Key 'name'
+ Title = Get-McpWireValue -Object $Prompt -Key 'title'
+ Description = Get-McpWireValue -Object $Prompt -Key 'description'
+ Arguments = $arguments
+ Icons = Get-McpWireValue -Object $Prompt -Key 'icons'
+ Meta = Get-McpWireValue -Object $Prompt -Key '_meta'
+ Raw = $Prompt
+ }
+}
+
+function ConvertTo-McpPromptResultObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.PromptResult')]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Result,
+
+ [Parameter(Mandatory)]
+ [string] $Name
+ )
+
+ $wireMessages = Get-McpWireValue -Object $Result -Key 'messages'
+ $messages = @(@($wireMessages) | Where-Object { $_ -is [System.Collections.IDictionary] } | ForEach-Object {
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.PromptMessage'
+ Role = Get-McpWireValue -Object $_ -Key 'role'
+ Content = ConvertTo-McpClientContentObject -Block (Get-McpWireValue -Object $_ -Key 'content')
+ }
+ })
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.PromptResult'
+ Name = $Name
+ Description = Get-McpWireValue -Object $Result -Key 'description'
+ Messages = $messages
+ Text = Get-McpContentText -Content @($messages | ForEach-Object { $_.Content })
+ Meta = Get-McpWireValue -Object $Result -Key '_meta'
+ Raw = $Result
+ }
+}
+
+function ConvertTo-McpCompletionObject {
+ [CmdletBinding()]
+ [OutputType('Mcp.Completion')]
+ param(
+ [Parameter(Mandatory)]
+ [System.Collections.IDictionary] $Result
+ )
+
+ $completion = Get-McpWireValue -Object $Result -Key 'completion'
+ $values = Get-McpWireValue -Object $completion -Key 'values'
+ [pscustomobject]@{
+ PSTypeName = 'Mcp.Completion'
+ Values = [string[]] @(@($values) | Where-Object { $null -ne $_ } | ForEach-Object { [string] $_ })
+ Total = Get-McpWireValue -Object $completion -Key 'total'
+ HasMore = [bool] (Get-McpWireValue -Object $completion -Key 'hasMore')
+ Raw = $Result
+ }
+}
+
+function Get-McpResultCacheHint {
+ <#
+ .SYNOPSIS
+ The ttlMs and cacheScope of a result; a result without a valid ttlMs is not cached.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [AllowNull()]
+ [object] $Result
+ )
+
+ $ttl = Get-McpWireValue -Object $Result -Key 'ttlMs'
+ $scope = Get-McpWireValue -Object $Result -Key 'cacheScope'
+ @{
+ TtlMs = if (($ttl -is [long] -or $ttl -is [int]) -and $ttl -ge 0) { [long] $ttl } else { [long] 0 }
+ CacheScope = if ($scope -in @('public', 'private')) { [string] $scope } else { 'private' }
+ }
+}
+
+function Get-McpClientCacheEntry {
+ <#
+ .SYNOPSIS
+ A fresh entry of the session's result cache, or $null when there is none or it has expired.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [string] $Key
+ )
+
+ $entry = $Session.Cache[$Key]
+ if ($null -eq $entry) { return $null }
+ if ([datetime]::UtcNow -ge $entry.ExpiresAt) {
+ $Session.Cache.Remove($Key)
+ return $null
+ }
+ $entry
+}
+
+function Set-McpClientCacheEntry {
+ <#
+ .SYNOPSIS
+ Caches a value for the result's ttlMs; a ttlMs of 0 (immediately stale) removes the entry instead.
+ .DESCRIPTION
+ The cache belongs to one session, so private and public results are both reusable; the scope is kept
+ with the entry.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Changes an in-memory cache.')]
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [string] $Key,
+
+ [AllowNull()]
+ [object] $Value,
+
+ [Parameter(Mandatory)]
+ [hashtable] $CacheHint
+ )
+
+ if ($CacheHint.TtlMs -le 0) {
+ $Session.Cache.Remove($Key)
+ return
+ }
+ $Session.Cache[$Key] = @{
+ Value = $Value
+ ExpiresAt = [datetime]::UtcNow.AddMilliseconds([double] $CacheHint.TtlMs)
+ CacheScope = $CacheHint.CacheScope
+ }
+}
+
+function Invoke-McpClientListRequest {
+ <#
+ .SYNOPSIS
+ Calls a list method and follows nextCursor through all pages.
+ .OUTPUTS
+ A hashtable with Items (the wire items), and the CacheHint of the whole list: the shortest ttlMs of
+ its pages and private when any page is private.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Session,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ # The member of the result that holds the items (tools, resources, resourceTemplates, prompts).
+ [Parameter(Mandatory)]
+ [string] $ItemKey
+ )
+
+ $items = [System.Collections.Generic.List[object]]::new()
+ $hint = $null
+ $cursor = $null
+ $pages = 0
+ do {
+ $params = [ordered]@{}
+ if ($null -ne $cursor) { $params['cursor'] = $cursor }
+ $result = Invoke-McpClientRequest -Session $Session -Method $Method -Params $params
+ if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains($ItemKey)) {
+ throw [System.InvalidOperationException]::new("The $Method result has no $ItemKey member.")
+ }
+ foreach ($item in @($result[$ItemKey])) {
+ if ($item -is [System.Collections.IDictionary]) { $items.Add($item) }
+ }
+ $pageHint = Get-McpResultCacheHint -Result $result
+ if ($null -eq $hint) {
+ $hint = $pageHint
+ } else {
+ $hint = @{
+ TtlMs = [math]::Min($hint.TtlMs, $pageHint.TtlMs)
+ CacheScope = if ($hint.CacheScope -eq 'private' -or $pageHint.CacheScope -eq 'private') { 'private' } else { 'public' }
+ }
+ }
+ $cursor = if ($result.Contains('nextCursor') -and $null -ne $result['nextCursor']) { [string] $result['nextCursor'] } else { $null }
+ $pages++
+ if ($pages -gt 10000) { throw [System.InvalidOperationException]::new("$Method paged more than 10000 times.") }
+ } while ($null -ne $cursor)
+ @{
+ Items = $items.ToArray()
+ CacheHint = $hint
+ }
+}
+
+function Test-McpResourceNotFoundError {
+ <#
+ .SYNOPSIS
+ Whether an error response reports an unknown resource: -32602 with data.uri (2026-07-28) or -32002 (earlier revisions).
+ #>
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [McpProtocolException] $Exception
+ )
+
+ if ($Exception.Code -eq -32002) { return $true }
+ $Exception.Code -eq $script:McpErrorCode.InvalidParams -and $Exception.Data -is [System.Collections.IDictionary] -and $Exception.Data.Contains('uri')
+}
+
function Start-McpBackgroundServer {
<#
.SYNOPSIS
diff --git a/src/Private/Completion.ps1 b/src/Private/Completion.ps1
new file mode 100644
index 0000000..e1ab361
--- /dev/null
+++ b/src/Private/Completion.ps1
@@ -0,0 +1,219 @@
+# Argument completion (completion/complete) for prompt arguments and resource template variables: completion
+# sources registered with -Completion (value lists filtered by prefix, or handlers), request validation and
+# the CompleteResult with its 100-value cap.
+
+$script:McpCompletionMaxValues = 100
+
+function ConvertTo-McpCompletionSource {
+ <#
+ .SYNOPSIS
+ Normalises a -Completion table (argument name -> value list or script block) to completion sources.
+ .OUTPUTS
+ An ordinal ordered dictionary of argument name -> @{ Values } or @{ Handler }.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [AllowNull()]
+ [System.Collections.IDictionary] $Completion,
+
+ # The argument (or template variable) names that may be completed.
+ [Parameter(Mandatory)]
+ [AllowEmptyCollection()]
+ [string[]] $ArgumentNames,
+
+ # Identifies the owner (prompt name or URI template) in the worker function names of handlers.
+ [Parameter(Mandatory)]
+ [string] $Key
+ )
+
+ $sources = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
+ if ($null -eq $Completion) { return $sources }
+ foreach ($name in $Completion.Keys) {
+ $argumentName = [string] $name
+ if ($ArgumentNames -cnotcontains $argumentName) {
+ throw [System.ArgumentException]::new("Completion given for '$argumentName', which is not one of the arguments ($($ArgumentNames -join ', ')).")
+ }
+ $value = $Completion[$name]
+ if ($value -is [scriptblock]) {
+ $sources[$argumentName] = @{ Values = $null; Handler = (New-McpHandlerDescriptor -Prefix 'McpCompletion' -Key "$Key|$argumentName" -ScriptBlock $value).Handler }
+ } elseif ($value -is [System.Management.Automation.CommandInfo]) {
+ $sources[$argumentName] = @{ Values = $null; Handler = (New-McpHandlerDescriptor -Prefix 'McpCompletion' -Key "$Key|$argumentName" -CommandInfo $value).Handler }
+ } else {
+ $sources[$argumentName] = @{ Values = [string[]] @($value | Where-Object { $null -ne $_ } | ForEach-Object { [string] $_ }); Handler = $null }
+ }
+ }
+ $sources
+}
+
+function Test-McpCompletionCapability {
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server
+ )
+
+ foreach ($registration in @($Server.Prompts.Values) + @($Server.ResourceTemplates.Values)) {
+ if ($null -ne $registration.Completion -and $registration.Completion.Count -gt 0) { return $true }
+ }
+ $false
+}
+
+function Resolve-McpCompletionRequest {
+ <#
+ .SYNOPSIS
+ Validates completion/complete params and finds the completion source of the referenced argument.
+ .OUTPUTS
+ A hashtable with Name (the argument), Value, Arguments (context.arguments), Source (or $null) and Label.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [AllowNull()]
+ [System.Collections.IDictionary] $Params
+ )
+
+ $invalid = { param($message) [McpProtocolException]::new($script:McpErrorCode.InvalidParams, $message) }
+ if ($null -eq $Params -or $Params['ref'] -isnot [System.Collections.IDictionary]) { throw (& $invalid "completion/complete requires an object parameter 'ref'.") }
+ $argument = $Params['argument']
+ if ($argument -isnot [System.Collections.IDictionary] -or $argument['name'] -isnot [string] -or $argument['value'] -isnot [string]) {
+ throw (& $invalid "completion/complete requires 'argument' with string members 'name' and 'value'.")
+ }
+ $contextArguments = [ordered]@{}
+ if ($Params.Contains('context') -and $null -ne $Params['context']) {
+ $context = $Params['context']
+ if ($context -isnot [System.Collections.IDictionary]) { throw (& $invalid "completion/complete 'context' must be an object.") }
+ if ($context.Contains('arguments') -and $null -ne $context['arguments']) {
+ if ($context['arguments'] -isnot [System.Collections.IDictionary]) { throw (& $invalid "completion/complete 'context.arguments' must be an object.") }
+ foreach ($key in $context['arguments'].Keys) {
+ if ($context['arguments'][$key] -isnot [string]) { throw (& $invalid "The value of context argument '$key' must be a string.") }
+ $contextArguments[[string] $key] = $context['arguments'][$key]
+ }
+ }
+ }
+
+ $reference = $Params['ref']
+ $name = $argument['name']
+ switch ($reference['type']) {
+ 'ref/prompt' {
+ $registration = Get-McpPromptRegistration -Server $Server -Name $reference['name']
+ if (@($registration.Arguments | ForEach-Object { $_['name'] }) -cnotcontains $name) {
+ throw (& $invalid "Prompt '$($registration.Name)' has no argument '$name'.")
+ }
+ $label = "prompt $($registration.Name)"
+ }
+ 'ref/resource' {
+ $uri = $reference['uri']
+ $registration = $null
+ if ($uri -is [string]) {
+ $registration = @($Server.ResourceTemplates.Values | Where-Object { $_.UriTemplate -ceq $uri }) | Select-Object -First 1
+ }
+ if ($null -eq $registration) { throw (& $invalid "Unknown resource template '$uri'.") }
+ if ($registration.Template.Variables -cnotcontains $name) {
+ throw (& $invalid "Resource template '$uri' has no variable '$name'.")
+ }
+ $label = "template $uri"
+ }
+ default {
+ throw (& $invalid "Unknown completion reference type '$($reference['type'])'; expected ref/prompt or ref/resource.")
+ }
+ }
+ $source = $null
+ if ($null -ne $registration.Completion -and $registration.Completion.Contains($name)) { $source = $registration.Completion[$name] }
+ @{
+ Name = $name
+ Value = $argument['value']
+ Arguments = $contextArguments
+ Source = $source
+ Label = "$label/$name"
+ }
+}
+
+function Get-McpCompleteResult {
+ <#
+ .SYNOPSIS
+ The CompleteResult for a list of candidate values: at most 100 values, the total and hasMore.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [string[]] $Values
+ )
+
+ $all = @($Values | Where-Object { $null -ne $_ })
+ $page = if ($all.Count -gt $script:McpCompletionMaxValues) { $all[0..($script:McpCompletionMaxValues - 1)] } else { $all }
+ [ordered]@{
+ completion = [ordered]@{
+ values = [string[]] @($page)
+ total = [long] $all.Count
+ hasMore = $all.Count -gt $script:McpCompletionMaxValues
+ }
+ resultType = 'complete'
+ }
+}
+
+function Get-McpStaticCompletion {
+ <#
+ .SYNOPSIS
+ The values of a value list that start with the typed value (case-insensitive).
+ #>
+ [CmdletBinding()]
+ [OutputType([string[]], [System.Array])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [string[]] $Values,
+
+ [AllowEmptyString()]
+ [string] $Value = ''
+ )
+
+ , [string[]] @($Values | Where-Object { $_.StartsWith($Value, [System.StringComparison]::OrdinalIgnoreCase) })
+}
+
+function Invoke-McpCompletionHandler {
+ <#
+ .SYNOPSIS
+ Runs a completion handler and returns its CompleteResult.
+ .DESCRIPTION
+ The handler receives the parameters it declares of: Value (the typed text), Argument (the argument
+ name), Arguments (the already resolved arguments of context.arguments) and Context. Its string output
+ is the candidate list, returned as is (the handler filters).
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Request,
+
+ [AllowNull()]
+ [object] $Context,
+
+ [switch] $UseCommandName
+ )
+
+ $source = $Request.Source
+ if ($null -eq $source) { return Get-McpCompleteResult -Values @() }
+ if ($null -eq $source.Handler) { return Get-McpCompleteResult -Values (Get-McpStaticCompletion -Values $source.Values -Value $Request.Value) }
+ $values = [ordered]@{ Value = $Request.Value; Argument = $Request.Name; Arguments = $Request.Arguments }
+ $splat = New-McpHandlerSplat -Handler $source.Handler -Values $values -Context $Context
+ $threshold = if ($null -ne $Context -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel }
+ try {
+ $merged = @(Invoke-McpHandlerCommand -Handler $source.Handler -Splat $splat -UseCommandName:$UseCommandName)
+ } catch [System.Management.Automation.PipelineStoppedException] {
+ throw
+ } catch {
+ $exception = Get-McpHandlerException -Exception $_.Exception
+ if ($exception -is [McpProtocolException]) { throw $exception }
+ throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "Completion of $($Request.Label) failed: $($exception.Message)")
+ }
+ $parts = Split-McpHandlerOutput -Merged $merged
+ Write-McpHandlerDiagnostic -Diagnostics $parts.Diagnostics -Name $Request.Label -Threshold $threshold -Context $Context -ErrorRecords $parts.Errors
+ Get-McpCompleteResult -Values @($parts.Output | ForEach-Object { [string] $_ })
+}
diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1
index 977d551..28da860 100644
--- a/src/Private/Dispatcher.ps1
+++ b/src/Private/Dispatcher.ps1
@@ -1,5 +1,6 @@
-# The dispatcher: the loop that owns a transport, decodes inbound messages, answers server/discover and
-# tools/list itself, hands tools/call to the worker runspace pool, forwards the workers' responses and
+# The dispatcher: the loop that owns a transport, decodes inbound messages, answers server/discover, the list
+# methods and everything that runs no user code itself, hands tools/call, resources/read, prompts/get and
+# completion/complete with a handler to the worker runspace pool, forwards the workers' responses and
# notifications, honours notifications/cancelled and shuts down on end of stream or Stop-McpServer.
#
# Over stdio and in memory all messages share one line writer. Over Streamable HTTP every request owns a
@@ -22,7 +23,7 @@ function Get-McpRequestKey {
function New-McpWorkerPool {
<#
.SYNOPSIS
- The hostless runspace pool that runs tool handlers: the module, the registered handlers and preferences.
+ The hostless runspace pool that runs handlers: the module, the registered handlers and preferences.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates a runspace pool for the caller (Start-McpServer), which owns the ShouldProcess decision.')]
[CmdletBinding()]
@@ -38,8 +39,7 @@ function New-McpWorkerPool {
}
$modules = [System.Collections.Generic.List[string]]::new()
$modules.Add($script:McpModuleManifestPath)
- foreach ($registration in $Server.Tools.Values) {
- $handler = $registration.Handler
+ foreach ($handler in Get-McpServerHandler -Server $Server) {
if ($handler.ModulePath -and -not $modules.Contains($handler.ModulePath)) {
$modules.Add($handler.ModulePath)
} elseif (-not $handler.ModulePath -and $handler.ModuleName -and -not $modules.Contains($handler.ModuleName)) {
@@ -94,7 +94,7 @@ function Invoke-McpDispatcher {
$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)."
+ 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)."
try {
$state.Pool = New-McpWorkerPool -Server $Server
if ($Transport.Kind -eq 'Http') {
@@ -219,7 +219,7 @@ function Send-McpOutboundQueue {
Send-McpHttpResponse -State $State -Channel $entry.Channel -Json $item.Json -ErrorCode $item.ErrorCode
}
if (-not $delivered -and -not $entry.Cancelled) {
- Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)): the client disconnected; cancelling."
+ Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)): the client disconnected; cancelling."
Stop-McpInFlightRequest -Entry $entry
$entry.Responded = $true
}
@@ -372,7 +372,7 @@ function Update-McpInFlightRequest {
$finished = $invocationState -in @([System.Management.Automation.PSInvocationState]::Completed, [System.Management.Automation.PSInvocationState]::Failed, [System.Management.Automation.PSInvocationState]::Stopped)
if (-not $finished) {
if ($timeout -gt 0 -and -not $entry.Cancelled -and -not $entry.Responded -and ([datetime]::UtcNow - $entry.StartedAt).TotalSeconds -gt $timeout) {
- Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)) timed out after $timeout s."
+ Write-McpStderr -Level Warning -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)) timed out after $timeout s."
Stop-McpInFlightRequest -Entry $entry
$entry.Responded = $true
Send-McpDispatcherMessage -State $State -Channel $entry.Channel -Message (New-McpErrorResponse -Id $entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message "The request timed out after $timeout seconds."))
@@ -384,7 +384,7 @@ function Update-McpInFlightRequest {
if ($invocationState -eq [System.Management.Automation.PSInvocationState]::Failed -and -not $entry.Cancelled -and -not $entry.Responded) {
$reason = $entry.PowerShell.InvocationStateInfo.Reason
$text = if ($reason) { $reason.Message } else { 'The worker failed.' }
- Write-McpStderr -Level Error -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)) failed in the worker: $text"
+ Write-McpStderr -Level Error -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)) failed in the worker: $text"
$entry.Responded = $true
Send-McpDispatcherMessage -State $State -Channel $entry.Channel -Message (New-McpErrorResponse -Id $entry.Id -ErrorObject (New-McpError -Code $script:McpErrorCode.InternalError -Message $text))
}
@@ -427,8 +427,7 @@ function Invoke-McpInboundRequest {
Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpDiscoverResult -Server $server))
}
'tools/list' {
- $cursor = if ($params.Contains('cursor')) { $params['cursor'] } else { $null }
- Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpToolListResult -Server $server -Cursor $cursor))
+ Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpToolListResult -Server $server -Cursor (Get-McpCursorParam -Params $params)))
}
'tools/call' {
if (-not $params.Contains('name') -or $params['name'] -isnot [string]) {
@@ -445,7 +444,50 @@ 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 -Registration $registration -Arguments $arguments -Meta $meta -Channel $Channel
+ Start-McpWorkerRequest -State $State -Id $id -Kind Tool -Method $method -Name $registration.Name -Registration $registration -Payload @{ Arguments = $arguments } -Meta $meta -Channel $Channel
+ }
+ 'resources/list' {
+ Assert-McpServerCapability -Server $server -Capability resources -Method $method
+ Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpResourceListResult -Server $server -Cursor (Get-McpCursorParam -Params $params)))
+ }
+ 'resources/templates/list' {
+ Assert-McpServerCapability -Server $server -Capability resources -Method $method
+ Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpResourceTemplateListResult -Server $server -Cursor (Get-McpCursorParam -Params $params)))
+ }
+ 'resources/read' {
+ Assert-McpServerCapability -Server $server -Capability resources -Method $method
+ $uri = $params['uri']
+ if (-not (Test-McpResourceUri -Uri $uri)) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "resources/read requires a parameter 'uri' with an absolute URI.")
+ }
+ $resolved = Resolve-McpResourceRequest -Server $server -Uri $uri
+ $registration = $resolved.Registration
+ $cacheHint = Get-McpResourceCacheHint -Server $server -Registration $registration
+ if ($registration.Source -eq 'Content') {
+ $result = Invoke-McpResourceHandler -Registration $registration -Uri $uri -CacheHint $cacheHint
+ Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result $result -Server $server))
+ } 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
+ }
+ }
+ 'prompts/list' {
+ Assert-McpServerCapability -Server $server -Capability prompts -Method $method
+ Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Get-McpPromptListResult -Server $server -Cursor (Get-McpCursorParam -Params $params)))
+ }
+ '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
+ }
+ 'completion/complete' {
+ Assert-McpServerCapability -Server $server -Capability completions -Method $method
+ $request = Resolve-McpCompletionRequest -Server $server -Params $params
+ if ($null -eq $request.Source -or $null -eq $request.Source.Handler) {
+ Send-McpDispatcherMessage -State $State -Channel $Channel -Message (New-McpResultResponse -Id $id -Result (Add-McpResultMeta -Result (Invoke-McpCompletionHandler -Request $request) -Server $server))
+ } else {
+ Start-McpWorkerRequest -State $State -Id $id -Kind Completion -Method $method -Name $request.Label -Registration $null -Payload @{ Completion = $request } -Meta $meta -Channel $Channel
+ }
}
default {
throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "Method not found: $method")
@@ -464,6 +506,46 @@ function Invoke-McpInboundRequest {
}
}
+function Get-McpCursorParam {
+ [CmdletBinding()]
+ [OutputType([object])]
+ param(
+ [AllowNull()]
+ [System.Collections.IDictionary] $Params
+ )
+
+ if ($null -ne $Params -and $Params.Contains('cursor')) { return $Params['cursor'] }
+ $null
+}
+
+function Assert-McpServerCapability {
+ <#
+ .SYNOPSIS
+ Answers methods of a capability the server does not declare (no registrations) with -32601.
+ #>
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [ValidateSet('resources', 'prompts', 'completions')]
+ [string] $Capability,
+
+ [Parameter(Mandatory)]
+ [string] $Method
+ )
+
+ $declared = switch ($Capability) {
+ 'resources' { Test-McpResourceCapability -Server $Server }
+ 'prompts' { $Server.Prompts.Count -gt 0 }
+ 'completions' { Test-McpCompletionCapability -Server $Server }
+ }
+ if (-not $declared) {
+ throw [McpProtocolException]::new($script:McpErrorCode.MethodNotFound, "Method not found: $Method (the server does not declare the $Capability capability).")
+ }
+}
+
function Start-McpWorkerRequest {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')]
[CmdletBinding()]
@@ -475,10 +557,21 @@ function Start-McpWorkerRequest {
[object] $Id,
[Parameter(Mandatory)]
- [pscustomobject] $Registration,
+ [ValidateSet('Tool', 'Resource', 'Prompt', 'Completion')]
+ [string] $Kind,
+
+ [Parameter(Mandatory)]
+ [string] $Method,
+
+ # The tool or prompt name, the resource URI or the completion target.
+ [Parameter(Mandatory)]
+ [string] $Name,
[AllowNull()]
- [System.Collections.IDictionary] $Arguments,
+ [pscustomobject] $Registration,
+
+ # Kind-specific envelope members: Arguments, Variables, CacheHint or Completion.
+ [hashtable] $Payload = @{},
[Parameter(Mandatory)]
[hashtable] $Meta,
@@ -491,10 +584,10 @@ function Start-McpWorkerRequest {
$cts = [System.Threading.CancellationTokenSource]::new()
$envelope = @{
RequestId = $Id
- Method = 'tools/call'
- ToolName = $Registration.Name
+ Kind = $Kind
+ Method = $Method
+ Name = $Name
Registration = $Registration
- Arguments = $Arguments
Meta = $Meta
Sink = @{ Queue = $State.Outbound; Signal = $State.Signal }
CancellationToken = $cts.Token
@@ -503,13 +596,14 @@ function Start-McpWorkerRequest {
ServerInfo = $State.ServerInfo
IncludeServerInfo = [bool] $server.Options.IncludeServerInfo
}
+ foreach ($key in $Payload.Keys) { $envelope[$key] = $Payload[$key] }
$worker = [powershell]::Create()
$worker.RunspacePool = $State.Pool
$null = $worker.AddScript($script:McpWorkerScript).AddArgument($envelope)
$handle = $worker.BeginInvoke()
$State.InFlight[(Get-McpRequestKey -Id $Id)] = @{
Id = $Id
- ToolName = $Registration.Name
+ Label = "$Method $Name"
PowerShell = $worker
Handle = $handle
Cts = $cts
diff --git a/src/Private/Handler.ps1 b/src/Private/Handler.ps1
new file mode 100644
index 0000000..41ff1d1
--- /dev/null
+++ b/src/Private/Handler.ps1
@@ -0,0 +1,301 @@
+# Handlers of tools, resources, prompts and completions: resolving the command or script block given at
+# registration, the descriptor that lets the worker runspaces invoke it by name, parameter binding and the
+# invocation itself with all streams merged.
+
+function Resolve-McpHandlerCommand {
+ <#
+ .SYNOPSIS
+ The CommandInfo of a command given by name (resolved in the caller's scope first) or as CommandInfo.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Management.Automation.CommandInfo])]
+ param(
+ [Parameter(Mandatory)]
+ [object] $Command,
+
+ # The PSCmdlet of the public registration command; names resolve in its caller's scope first so that
+ # functions of the calling script are found.
+ [Parameter(Mandatory)]
+ [System.Management.Automation.PSCmdlet] $Cmdlet
+ )
+
+ $commandInfo = $Command
+ if ($Command -is [string]) {
+ $commandInfo = $Cmdlet.SessionState.InvokeCommand.GetCommand($Command, [System.Management.Automation.CommandTypes]::All)
+ if ($null -eq $commandInfo) {
+ $commandInfo = Get-Command -Name $Command -ErrorAction SilentlyContinue | Select-Object -First 1
+ }
+ if ($null -eq $commandInfo) {
+ throw [System.Management.Automation.CommandNotFoundException]::new("The command '$Command' was not found. Pass the result of Get-Command for functions defined in a nested scope.")
+ }
+ }
+ if ($commandInfo -isnot [System.Management.Automation.CommandInfo]) {
+ throw [System.ArgumentException]::new('-Command must be a command name or a CommandInfo object.')
+ }
+ if ($commandInfo -is [System.Management.Automation.AliasInfo]) {
+ $commandInfo = $commandInfo.ResolvedCommand
+ }
+ $commandInfo
+}
+
+function Get-McpHandlerFunctionName {
+ <#
+ .SYNOPSIS
+ The function name under which a script block handler exists in the worker runspaces.
+ .DESCRIPTION
+ Characters outside A-Z, a-z, 0-9 and '_' are replaced; a name that needed replacing gets a hash suffix
+ so that, for example, the tools 'a-b' and 'a_b' do not share a function.
+ #>
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Prefix,
+
+ [Parameter(Mandatory)]
+ [string] $Key
+ )
+
+ $sanitised = $Key -replace '[^A-Za-z0-9_]', '_'
+ if ($sanitised.Length -gt 64) { $sanitised = $sanitised.Substring(0, 64) }
+ $name = $Prefix + '_' + $sanitised
+ if ($sanitised -cne $Key) {
+ $hash = [System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($Key))
+ $name += '_' + [System.Convert]::ToHexString($hash, 0, 4).ToLowerInvariant()
+ }
+ $name
+}
+
+function New-McpHandlerDescriptor {
+ <#
+ .SYNOPSIS
+ Describes a handler given as script block or CommandInfo: how workers invoke it and which parameters it has.
+ .OUTPUTS
+ A hashtable with Handler (the descriptor stored on the registration), Ast, Parameters and CommandName.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory descriptor.')]
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ # The function-name prefix of script block handlers: McpTool, McpResource, McpPrompt or McpCompletion.
+ [Parameter(Mandatory)]
+ [string] $Prefix,
+
+ [Parameter(Mandatory)]
+ [string] $Key,
+
+ [scriptblock] $ScriptBlock,
+
+ [System.Management.Automation.CommandInfo] $CommandInfo
+ )
+
+ $handler = @{
+ Kind = $null
+ CommandName = $null
+ Definition = $null
+ ModuleName = $null
+ ModulePath = $null
+ CommandInfo = $null
+ ScriptBlock = $null
+ ArgumentStyle = 'Splat'
+ ContextParameter = $null
+ ParameterTypes = @{}
+ ParameterNames = @()
+ }
+ $ast = $null
+ $parameters = $null
+
+ if ($null -ne $ScriptBlock) {
+ $handler.Kind = 'ScriptBlock'
+ $handler.ScriptBlock = $ScriptBlock
+ $handler.Definition = $ScriptBlock.ToString()
+ $handler.CommandName = Get-McpHandlerFunctionName -Prefix $Prefix -Key $Key
+ $ast = $ScriptBlock.Ast
+ $temporaryName = 'McpTemporaryHandler_' + [guid]::NewGuid().ToString('n')
+ Set-Item -Path "function:script:$temporaryName" -Value $ScriptBlock
+ try {
+ $parameters = (Get-Command -Name $temporaryName -CommandType Function).Parameters
+ } finally {
+ Remove-Item -Path "function:script:$temporaryName" -ErrorAction SilentlyContinue
+ }
+ } elseif ($null -ne $CommandInfo) {
+ $handler.CommandInfo = $CommandInfo
+ switch ($CommandInfo.GetType().Name) {
+ 'FunctionInfo' {
+ $handler.Kind = 'Function'
+ $handler.CommandName = $CommandInfo.Name
+ $ast = $CommandInfo.ScriptBlock.Ast
+ if ($CommandInfo.Module -and $CommandInfo.Module.Path) {
+ $handler.ModuleName = $CommandInfo.Module.Name
+ $handler.ModulePath = $CommandInfo.Module.Path
+ } else {
+ $handler.Definition = $CommandInfo.Definition
+ }
+ }
+ 'CmdletInfo' {
+ $handler.Kind = 'Cmdlet'
+ $handler.CommandName = $CommandInfo.Name
+ if ($CommandInfo.Module) {
+ $handler.ModuleName = $CommandInfo.Module.Name
+ $handler.ModulePath = $CommandInfo.Module.Path
+ } elseif ($CommandInfo.ModuleName) {
+ $handler.ModuleName = $CommandInfo.ModuleName
+ }
+ }
+ 'ExternalScriptInfo' {
+ $handler.Kind = 'Script'
+ $handler.CommandName = $CommandInfo.Path
+ $ast = $CommandInfo.ScriptBlock.Ast
+ }
+ default {
+ throw [System.ArgumentException]::new("Commands of type $($CommandInfo.CommandType) cannot be registered as handlers.")
+ }
+ }
+ $parameters = $CommandInfo.Parameters
+ } else {
+ throw [System.ArgumentException]::new('A handler needs a script block or a command.')
+ }
+
+ $names = [System.Collections.Generic.List[string]]::new()
+ if ($null -ne $parameters) {
+ $common = [System.Management.Automation.PSCmdlet]::CommonParameters + [System.Management.Automation.PSCmdlet]::OptionalCommonParameters
+ foreach ($entry in $parameters.GetEnumerator()) {
+ $name = [string] $entry.Value.Name
+ if ($name -in $common) { continue }
+ if ($name -ieq 'Context') { $handler.ContextParameter = $name; continue }
+ $names.Add($name)
+ $handler.ParameterTypes[$name] = $entry.Value.ParameterType
+ }
+ }
+ $handler.ParameterNames = $names.ToArray()
+ @{
+ Handler = $handler
+ Ast = $ast
+ Parameters = $parameters
+ CommandName = if ($null -ne $CommandInfo) { $CommandInfo.Name } else { $null }
+ }
+}
+
+function Get-McpHandlerParameterName {
+ <#
+ .SYNOPSIS
+ The declared parameter name matching a name exactly, then case-insensitively; $null when there is none.
+ #>
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Handler,
+
+ [Parameter(Mandatory)]
+ [string] $Name
+ )
+
+ if ($Handler.ParameterNames -ccontains $Name) { return $Name }
+ foreach ($candidate in $Handler.ParameterNames) {
+ if ($candidate -ieq $Name) { return $candidate }
+ }
+ $null
+}
+
+function New-McpHandlerSplat {
+ <#
+ .SYNOPSIS
+ A splatting table with the values whose names the handler declares, converted to the declared types.
+ .DESCRIPTION
+ Used for resource, prompt and completion handlers: a handler declares only the parameters it wants
+ (for example a template variable, Uri, Arguments or Context); values without a matching parameter are
+ not passed.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory table.')]
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Handler,
+
+ [System.Collections.IDictionary] $Values = @{},
+
+ [AllowNull()]
+ [object] $Context
+ )
+
+ $splat = @{}
+ foreach ($key in $Values.Keys) {
+ $parameterName = Get-McpHandlerParameterName -Handler $Handler -Name ([string] $key)
+ if ($null -eq $parameterName -or $splat.ContainsKey($parameterName)) { continue }
+ $splat[$parameterName] = ConvertTo-McpParameterValue -Value $Values[$key] -Type $Handler.ParameterTypes[$parameterName] -Name $parameterName
+ }
+ if ($Handler.ContextParameter -and $null -ne $Context) {
+ $splat[$Handler.ContextParameter] = $Context
+ }
+ $splat
+}
+
+function Invoke-McpHandlerCommand {
+ <#
+ .SYNOPSIS
+ Invokes a handler with all streams merged into the output (split them with Split-McpHandlerOutput).
+ #>
+ [CmdletBinding()]
+ [OutputType([object[]])]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Handler,
+
+ [hashtable] $Splat = @{},
+
+ # Invoke by command name in the current runspace (the worker runspaces, where handlers exist as
+ # functions) instead of the script block or command object captured at registration.
+ [switch] $UseCommandName
+ )
+
+ if ($UseCommandName) {
+ & $Handler.CommandName @Splat *>&1
+ } elseif ($Handler.Kind -eq 'ScriptBlock') {
+ & $Handler.ScriptBlock @Splat *>&1
+ } else {
+ & $Handler.CommandInfo @Splat *>&1
+ }
+}
+
+function Get-McpHandlerException {
+ <#
+ .SYNOPSIS
+ The exception a handler failed with, unwrapped from the RuntimeException PowerShell adds around it.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Exception])]
+ param(
+ [Parameter(Mandatory)]
+ [System.Exception] $Exception
+ )
+
+ if ($Exception -is [System.Management.Automation.RuntimeException] -and $null -ne $Exception.InnerException -and $Exception.GetType() -eq [System.Management.Automation.RuntimeException]) {
+ return $Exception.InnerException
+ }
+ $Exception
+}
+
+function Get-McpServerHandler {
+ <#
+ .SYNOPSIS
+ All handler descriptors registered on a server (tools, resources, templates, prompts, completions).
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server
+ )
+
+ foreach ($registration in $Server.Tools.Values) { $registration.Handler }
+ foreach ($registration in @($Server.Resources.Values) + @($Server.ResourceTemplates.Values) + @($Server.Prompts.Values)) {
+ if ($null -ne $registration.Handler) { $registration.Handler }
+ if ($null -ne $registration.Completion) {
+ foreach ($source in $registration.Completion.Values) {
+ if ($null -ne $source.Handler) { $source.Handler }
+ }
+ }
+ }
+}
diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1
index afe5823..e253770 100644
--- a/src/Private/HttpServer.ps1
+++ b/src/Private/HttpServer.ps1
@@ -480,7 +480,7 @@ function Stop-McpHttpChannelRequest {
if (-not $State.InFlight.ContainsKey($key)) { return }
$entry = $State.InFlight[$key]
if ($entry.Cancelled -or $entry.Responded) { return }
- Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.ToolName)): the client closed the connection; cancelling."
+ Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)): the client closed the connection; cancelling."
Stop-McpInFlightRequest -Entry $entry
$entry.Responded = $true
}
diff --git a/src/Private/Metadata.ps1 b/src/Private/Metadata.ps1
new file mode 100644
index 0000000..e017623
--- /dev/null
+++ b/src/Private/Metadata.ps1
@@ -0,0 +1,149 @@
+# Metadata shared by the primitives: icons (Icon) and the annotations of content blocks and resources
+# (Annotations: audience, priority, lastModified), normalised to wire objects and validated at registration.
+
+function Get-McpDictionaryValue {
+ <#
+ .SYNOPSIS
+ The entries of a hashtable, ordered dictionary or PSCustomObject as (key, value) pairs.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.DictionaryEntry])]
+ param(
+ [Parameter(Mandatory)]
+ [object] $InputObject
+ )
+
+ if ($InputObject -is [System.Collections.IDictionary]) {
+ foreach ($key in $InputObject.Keys) { [System.Collections.DictionaryEntry]::new($key, $InputObject[$key]) }
+ } elseif ($InputObject -is [System.Management.Automation.PSCustomObject]) {
+ foreach ($property in $InputObject.PSObject.Properties) { [System.Collections.DictionaryEntry]::new($property.Name, $property.Value) }
+ } else {
+ throw [System.ArgumentException]::new("Expected a hashtable or object, got $($InputObject.GetType().Name).")
+ }
+}
+
+function ConvertTo-McpIconList {
+ <#
+ .SYNOPSIS
+ Validates icons (hashtables or objects with src, mimeType, sizes, theme; or plain src strings) and returns wire Icon objects.
+ #>
+ [CmdletBinding()]
+ [OutputType([object[]], [System.Array])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [object[]] $Icons
+ )
+
+ if ($null -eq $Icons -or $Icons.Count -eq 0) { return $null }
+ $known = @{ src = 'src'; mimetype = 'mimeType'; sizes = 'sizes'; theme = 'theme' }
+ $list = foreach ($icon in $Icons) {
+ if ($null -eq $icon) { continue }
+ $entries = if ($icon -is [string]) { @([System.Collections.DictionaryEntry]::new('src', $icon)) } else { @(Get-McpDictionaryValue -InputObject $icon) }
+ $wire = [ordered]@{}
+ foreach ($entry in $entries) {
+ $lower = ([string] $entry.Key).ToLowerInvariant()
+ if (-not $known.ContainsKey($lower)) {
+ throw [System.ArgumentException]::new("Unknown icon member '$($entry.Key)'; icons have src, mimeType, sizes and theme.")
+ }
+ $wire[$known[$lower]] = $entry.Value
+ }
+ $source = [string] $wire['src']
+ $uri = $null
+ if (-not $source -or -not [uri]::TryCreate($source, [System.UriKind]::Absolute, [ref] $uri) -or $uri.Scheme -notin @('http', 'https', 'data')) {
+ throw [System.ArgumentException]::new("Icon src '$source' must be an absolute http, https or data URI.")
+ }
+ $wire['src'] = $source
+ if ($wire.Contains('mimeType')) { $wire['mimeType'] = [string] $wire['mimeType'] }
+ if ($wire.Contains('sizes')) {
+ $sizes = @($wire['sizes'] | ForEach-Object { [string] $_ })
+ foreach ($size in $sizes) {
+ if ($size -notmatch '^(\d+x\d+|any)$') {
+ throw [System.ArgumentException]::new("Icon size '$size' must be 'WIDTHxHEIGHT' (for example 48x48) or 'any'.")
+ }
+ }
+ $wire['sizes'] = $sizes
+ }
+ if ($wire.Contains('theme')) {
+ $theme = ([string] $wire['theme']).ToLowerInvariant()
+ if ($theme -notin @('light', 'dark')) { throw [System.ArgumentException]::new("Icon theme '$($wire['theme'])' must be light or dark.") }
+ $wire['theme'] = $theme
+ }
+ $wire
+ }
+ , @($list)
+}
+
+function ConvertTo-McpContentAnnotation {
+ <#
+ .SYNOPSIS
+ Validates annotations of a content block, resource or template and returns the wire Annotations object.
+ .DESCRIPTION
+ audience is user and/or assistant, priority a number from 0 (least) to 1 (most important), and
+ lastModified an ISO 8601 timestamp (a DateTime or DateTimeOffset is converted to UTC).
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [AllowNull()]
+ [object] $Annotations
+ )
+
+ if ($null -eq $Annotations) { return $null }
+ $wire = [ordered]@{}
+ foreach ($entry in Get-McpDictionaryValue -InputObject $Annotations) {
+ switch (([string] $entry.Key).ToLowerInvariant()) {
+ 'audience' {
+ $roles = @($entry.Value | ForEach-Object { ([string] $_).ToLowerInvariant() })
+ foreach ($role in $roles) {
+ if ($role -notin @('user', 'assistant')) { throw [System.ArgumentException]::new("Annotation audience '$role' must be user or assistant.") }
+ }
+ $wire['audience'] = $roles
+ }
+ 'priority' {
+ $priority = 0.0
+ if (-not [double]::TryParse([string] $entry.Value, [System.Globalization.NumberStyles]::Float, [cultureinfo]::InvariantCulture, [ref] $priority) -or $priority -lt 0 -or $priority -gt 1) {
+ throw [System.ArgumentException]::new("Annotation priority '$($entry.Value)' must be a number from 0 to 1.")
+ }
+ $wire['priority'] = $priority
+ }
+ 'lastmodified' {
+ $value = $entry.Value
+ if ($value -is [datetime]) { $value = [datetimeoffset] $value.ToUniversalTime() }
+ if ($value -is [datetimeoffset]) {
+ $wire['lastModified'] = $value.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", [cultureinfo]::InvariantCulture)
+ } else {
+ $parsed = [datetimeoffset]::MinValue
+ if (-not [datetimeoffset]::TryParse([string] $value, [cultureinfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref] $parsed)) {
+ throw [System.ArgumentException]::new("Annotation lastModified '$value' must be an ISO 8601 timestamp.")
+ }
+ $wire['lastModified'] = [string] $value
+ }
+ }
+ default {
+ throw [System.ArgumentException]::new("Unknown annotation '$($entry.Key)'; content annotations are audience, priority and lastModified.")
+ }
+ }
+ }
+ if ($wire.Count -eq 0) { return $null }
+ $wire
+}
+
+function ConvertTo-McpMetaObject {
+ <#
+ .SYNOPSIS
+ A _meta dictionary given as hashtable or object, as an ordered dictionary; $null when empty.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [AllowNull()]
+ [object] $Meta
+ )
+
+ if ($null -eq $Meta) { return $null }
+ $wire = [ordered]@{}
+ foreach ($entry in Get-McpDictionaryValue -InputObject $Meta) { $wire[[string] $entry.Key] = $entry.Value }
+ if ($wire.Count -eq 0) { return $null }
+ $wire
+}
diff --git a/src/Private/Pagination.ps1 b/src/Private/Pagination.ps1
new file mode 100644
index 0000000..d7f776c
--- /dev/null
+++ b/src/Private/Pagination.ps1
@@ -0,0 +1,96 @@
+# Cursor pagination of the list methods (tools/list, resources/list, resources/templates/list, prompts/list)
+# with the caching hints every page carries. A cursor is opaque to clients; it encodes the list it belongs to
+# and the offset of the next page, so a cursor of one list is rejected by another.
+
+function New-McpCursor {
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Encodes a value.')]
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Kind,
+
+ [Parameter(Mandatory)]
+ [int] $Offset
+ )
+
+ [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("mcp-cursor:${Kind}:offset=$Offset"))
+}
+
+function Read-McpCursor {
+ <#
+ .SYNOPSIS
+ The offset encoded in a cursor of the given list; -32602 for anything else.
+ #>
+ [CmdletBinding()]
+ [OutputType([int])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Kind,
+
+ [AllowNull()]
+ [object] $Cursor
+ )
+
+ if ($null -eq $Cursor) { return 0 }
+ if ($Cursor -is [string]) {
+ $text = $null
+ try {
+ $text = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Cursor))
+ } catch {
+ $text = $null
+ }
+ if ($null -ne $text -and $text -match '^mcp-cursor:([A-Za-z]+):offset=(\d{1,9})$' -and $Matches[1] -ceq $Kind) { return [int] $Matches[2] }
+ }
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Invalid cursor.')
+}
+
+function Get-McpPagedListResult {
+ <#
+ .SYNOPSIS
+ One page of a list result: resultType, the converted items, nextCursor, ttlMs, cacheScope and _meta.
+ .DESCRIPTION
+ Every page carries the server's default caching hints, so all pages of one list share the same
+ cacheScope, as the specification requires. The item member is named after the list kind (tools,
+ resources, resourceTemplates, prompts).
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [ValidateSet('tools', 'resources', 'resourceTemplates', 'prompts')]
+ [string] $Kind,
+
+ [Parameter(Mandatory)]
+ [AllowEmptyCollection()]
+ [object[]] $Items,
+
+ [Parameter(Mandatory)]
+ [scriptblock] $Converter,
+
+ [AllowNull()]
+ [object] $Cursor
+ )
+
+ $offset = Read-McpCursor -Kind $Kind -Cursor $Cursor
+ if ($offset -gt $Items.Count) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Invalid cursor.')
+ }
+ $pageSize = [int] $Server.Options.PageSize
+ $page = @()
+ if ($offset -lt $Items.Count) {
+ $end = [math]::Min($offset + $pageSize, $Items.Count) - 1
+ $page = @($Items[$offset..$end] | ForEach-Object { & $Converter $_ })
+ }
+ $result = [ordered]@{ resultType = 'complete' }
+ $result[$Kind] = $page
+ if ($offset + $pageSize -lt $Items.Count) {
+ $result['nextCursor'] = New-McpCursor -Kind $Kind -Offset ($offset + $pageSize)
+ }
+ $result['ttlMs'] = [long] $Server.Options.DefaultTtlMs
+ $result['cacheScope'] = $Server.Options.DefaultCacheScope
+ Add-McpResultMeta -Result $result -Server $Server
+}
diff --git a/src/Private/Prompts.ps1 b/src/Private/Prompts.ps1
new file mode 100644
index 0000000..0a95557
--- /dev/null
+++ b/src/Private/Prompts.ps1
@@ -0,0 +1,227 @@
+# Prompt registry: registrations (PSTypeName Mcp.PromptRegistration), the Prompt definitions of prompts/list,
+# argument validation of prompts/get and the shaping of handler output into GetPromptResult.
+
+function Get-McpPromptRegistration {
+ [CmdletBinding()]
+ [OutputType([pscustomobject])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [AllowNull()]
+ [object] $Name
+ )
+
+ if ($Name -isnot [string] -or -not $Server.Prompts.Contains([string] $Name)) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Unknown prompt '$Name'.")
+ }
+ $Server.Prompts[[string] $Name]
+}
+
+function ConvertTo-McpPromptDefinition {
+ <#
+ .SYNOPSIS
+ The Prompt object (as sent in prompts/list) of a registration.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration
+ )
+
+ $prompt = [ordered]@{ name = $Registration.Name }
+ if ($Registration.Title) { $prompt['title'] = $Registration.Title }
+ if ($Registration.Description) { $prompt['description'] = $Registration.Description }
+ if (@($Registration.Arguments).Count -gt 0) { $prompt['arguments'] = @($Registration.Arguments) }
+ if ($null -ne $Registration.Icons) { $prompt['icons'] = @($Registration.Icons) }
+ if ($null -ne $Registration.Meta) { $prompt['_meta'] = $Registration.Meta }
+ $prompt
+}
+
+function Get-McpPromptListResult {
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [AllowNull()]
+ [object] $Cursor
+ )
+
+ Get-McpPagedListResult -Server $Server -Kind 'prompts' -Items @($Server.Prompts.Values) -Cursor $Cursor -Converter { param($registration) ConvertTo-McpPromptDefinition -Registration $registration }
+}
+
+function ConvertTo-McpPromptArgumentList {
+ <#
+ .SYNOPSIS
+ Normalises prompt arguments given as hashtables (Name, Title, Description, Required) to PromptArgument wire objects.
+ #>
+ [CmdletBinding()]
+ [OutputType([object[]], [System.Array])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [object[]] $Arguments
+ )
+
+ $names = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
+ $list = foreach ($argument in @($Arguments)) {
+ if ($null -eq $argument) { continue }
+ if ($argument -is [string]) { $argument = @{ name = $argument } }
+ $wire = [ordered]@{}
+ foreach ($entry in Get-McpDictionaryValue -InputObject $argument) {
+ switch (([string] $entry.Key).ToLowerInvariant()) {
+ 'name' { $wire['name'] = [string] $entry.Value }
+ 'title' { if ($entry.Value) { $wire['title'] = [string] $entry.Value } }
+ 'description' { if ($entry.Value) { $wire['description'] = [string] $entry.Value } }
+ 'required' { $wire['required'] = [bool] $entry.Value }
+ default { throw [System.ArgumentException]::new("Unknown prompt argument member '$($entry.Key)'; arguments have Name, Title, Description and Required.") }
+ }
+ }
+ if (-not $wire['name']) { throw [System.ArgumentException]::new('Every prompt argument needs a Name.') }
+ if (-not $names.Add($wire['name'])) { throw [System.ArgumentException]::new("The prompt argument '$($wire['name'])' is declared more than once.") }
+ $ordered = [ordered]@{ name = $wire['name'] }
+ foreach ($key in 'title', 'description', 'required') {
+ if ($wire.Contains($key)) { $ordered[$key] = $wire[$key] }
+ }
+ $ordered
+ }
+ , @($list)
+}
+
+function Test-McpPromptArgument {
+ <#
+ .SYNOPSIS
+ Validates the arguments of a prompts/get request: an object of strings with every required argument.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration,
+
+ [AllowNull()]
+ [object] $Arguments
+ )
+
+ $values = [ordered]@{}
+ if ($null -ne $Arguments) {
+ if ($Arguments -isnot [System.Collections.IDictionary]) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "prompts/get 'arguments' must be an object.")
+ }
+ foreach ($key in $Arguments.Keys) {
+ $value = $Arguments[$key]
+ if ($value -isnot [string]) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "The value of prompt argument '$key' must be a string.")
+ }
+ $values[[string] $key] = $value
+ }
+ }
+ $missing = @($Registration.Arguments | Where-Object { $_.Contains('required') -and $_['required'] -and -not $values.Contains($_['name']) } | ForEach-Object { $_['name'] })
+ if ($missing.Count -gt 0) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Missing required argument(s) of prompt '$($Registration.Name)': $($missing -join ', ').", [ordered]@{ missing = $missing })
+ }
+ $values
+}
+
+function ConvertTo-McpGetPromptResult {
+ <#
+ .SYNOPSIS
+ Shapes the output of a prompt handler into a GetPromptResult.
+ .DESCRIPTION
+ New-McpPromptMessage objects pass through; content blocks (New-McpContent) become user messages;
+ consecutive strings become one user text message; other objects become a user message with their JSON.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [object[]] $Output,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration
+ )
+
+ $messages = [System.Collections.Generic.List[object]]::new()
+ $texts = [System.Collections.Generic.List[string]]::new()
+ $flush = {
+ if ($texts.Count -gt 0) {
+ $messages.Add([ordered]@{ role = 'user'; content = (ConvertTo-McpTextBlock -Text ($texts -join "`n")) })
+ $texts.Clear()
+ }
+ }
+ foreach ($item in @($Output | Where-Object { $null -ne $_ })) {
+ if ($item.PSObject.TypeNames -contains 'Mcp.PromptMessage') {
+ . $flush
+ $messages.Add($item)
+ } elseif ($item -is [System.Collections.IDictionary] -and $item.Contains('role') -and $item.Contains('content')) {
+ . $flush
+ $messages.Add($item)
+ } elseif (Test-McpContentObject -Value $item) {
+ . $flush
+ $messages.Add([ordered]@{ role = 'user'; content = $item })
+ } elseif ($item -is [string]) {
+ $texts.Add($item)
+ } elseif ($item -is [valuetype] -or $item -is [enum] -or $item -is [uri] -or $item -is [version]) {
+ $texts.Add([System.Management.Automation.LanguagePrimitives]::ConvertTo($item, [string]))
+ } else {
+ . $flush
+ $messages.Add([ordered]@{ role = 'user'; content = (ConvertTo-McpTextBlock -Text (ConvertTo-McpJson -InputObject $item)) })
+ }
+ }
+ . $flush
+ $result = [ordered]@{}
+ if ($Registration.Description) { $result['description'] = $Registration.Description }
+ $result['messages'] = $messages.ToArray()
+ $result['resultType'] = 'complete'
+ $result
+}
+
+function Invoke-McpPromptHandler {
+ <#
+ .SYNOPSIS
+ Runs a prompt handler with validated string arguments and returns its GetPromptResult.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration,
+
+ [System.Collections.IDictionary] $Arguments = [ordered]@{},
+
+ [AllowNull()]
+ [object] $Context,
+
+ [switch] $UseCommandName
+ )
+
+ $handler = $Registration.Handler
+ if ($handler.ArgumentStyle -eq 'Arguments') {
+ $splat = @{ Arguments = $Arguments }
+ if ($handler.ContextParameter -and $null -ne $Context) { $splat[$handler.ContextParameter] = $Context }
+ } else {
+ $splat = New-McpHandlerSplat -Handler $handler -Values $Arguments -Context $Context
+ }
+ $threshold = if ($null -ne $Context -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel }
+ try {
+ $merged = @(Invoke-McpHandlerCommand -Handler $handler -Splat $splat -UseCommandName:$UseCommandName)
+ } catch [System.Management.Automation.PipelineStoppedException] {
+ throw
+ } catch {
+ $exception = Get-McpHandlerException -Exception $_.Exception
+ if ($exception -is [McpProtocolException]) { throw $exception }
+ throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "Prompt '$($Registration.Name)' failed: $($exception.Message)")
+ }
+ $parts = Split-McpHandlerOutput -Merged $merged
+ Write-McpHandlerDiagnostic -Diagnostics $parts.Diagnostics -Name $Registration.Name -Threshold $threshold -Context $Context -ErrorRecords $parts.Errors
+ $result = ConvertTo-McpGetPromptResult -Output $parts.Output -Registration $Registration
+ if ($result['messages'].Count -eq 0 -and $parts.Errors.Count -gt 0) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "Prompt '$($Registration.Name)' failed: $($parts.Errors[0].ToString())")
+ }
+ $result
+}
diff --git a/src/Private/Resources.ps1 b/src/Private/Resources.ps1
new file mode 100644
index 0000000..2f4e16a
--- /dev/null
+++ b/src/Private/Resources.ps1
@@ -0,0 +1,557 @@
+# Resource registry: static resources (fixed content, files, handlers) and resource templates (RFC 6570,
+# handlers or directories), the Resource and ResourceTemplate definitions of the list methods, the resolution
+# of a URI to a registration, and the shaping of content into ReadResourceResult.
+
+$script:McpMimeTypes = @{
+ '.txt' = 'text/plain'; '.log' = 'text/plain'; '.md' = 'text/markdown'; '.markdown' = 'text/markdown'
+ '.csv' = 'text/csv'; '.tsv' = 'text/tab-separated-values'; '.html' = 'text/html'; '.htm' = 'text/html'
+ '.css' = 'text/css'; '.js' = 'text/javascript'; '.mjs' = 'text/javascript'; '.ts' = 'text/plain'
+ '.ps1' = 'text/plain'; '.psm1' = 'text/plain'; '.psd1' = 'text/plain'; '.ps1xml' = 'application/xml'
+ '.py' = 'text/x-python'; '.cs' = 'text/plain'; '.sh' = 'text/x-shellscript'; '.ini' = 'text/plain'
+ '.json' = 'application/json'; '.xml' = 'application/xml'; '.yaml' = 'application/yaml'; '.yml' = 'application/yaml'
+ '.toml' = 'application/toml'; '.svg' = 'image/svg+xml'; '.png' = 'image/png'; '.jpg' = 'image/jpeg'
+ '.jpeg' = 'image/jpeg'; '.gif' = 'image/gif'; '.webp' = 'image/webp'; '.ico' = 'image/x-icon'
+ '.bmp' = 'image/bmp'; '.pdf' = 'application/pdf'; '.zip' = 'application/zip'; '.gz' = 'application/gzip'
+ '.wav' = 'audio/wav'; '.mp3' = 'audio/mpeg'; '.ogg' = 'audio/ogg'; '.mp4' = 'video/mp4'
+}
+$script:McpTextMimeTypes = @('application/json', 'application/xml', 'application/yaml', 'application/toml', 'application/javascript', 'image/svg+xml')
+
+function Get-McpMimeType {
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Path
+ )
+
+ $extension = [System.IO.Path]::GetExtension($Path).ToLowerInvariant()
+ if ($script:McpMimeTypes.ContainsKey($extension)) { return $script:McpMimeTypes[$extension] }
+ 'application/octet-stream'
+}
+
+function Test-McpTextMimeType {
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [AllowNull()]
+ [string] $MimeType
+ )
+
+ if (-not $MimeType) { return $false }
+ $essence = $MimeType.Split(';')[0].Trim().ToLowerInvariant()
+ $essence.StartsWith('text/') -or $essence -in $script:McpTextMimeTypes -or $essence.EndsWith('+json') -or $essence.EndsWith('+xml')
+}
+
+function Test-McpResourceUri {
+ <#
+ .SYNOPSIS
+ Whether a string is an absolute URI (RFC 3986) as the uri members of resources require.
+ #>
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [AllowNull()]
+ [object] $Uri
+ )
+
+ if ($Uri -isnot [string] -or $Uri.Length -eq 0 -or $Uri -match '\s') { return $false }
+ $parsed = $null
+ [uri]::TryCreate($Uri, [System.UriKind]::Absolute, [ref] $parsed) -and $Uri -match '^[A-Za-z][A-Za-z0-9+.-]*:'
+}
+
+function Test-McpResourceCapability {
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server
+ )
+
+ ($Server.Resources.Count + $Server.ResourceTemplates.Count) -gt 0
+}
+
+function Get-McpResourceSize {
+ [CmdletBinding()]
+ [OutputType([long])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration
+ )
+
+ if ($null -ne $Registration.Size) { return [long] $Registration.Size }
+ switch ($Registration.Source) {
+ 'Content' {
+ if ($Registration.Content -is [byte[]]) { return [long] $Registration.Content.Length }
+ return [long] [System.Text.Encoding]::UTF8.GetByteCount([string] $Registration.Content)
+ }
+ 'File' {
+ $info = [System.IO.FileInfo]::new($Registration.Path)
+ if ($info.Exists) { return [long] $info.Length }
+ }
+ }
+ [long] -1
+}
+
+function ConvertTo-McpResourceDefinition {
+ <#
+ .SYNOPSIS
+ The Resource object (as sent in resources/list) of a static resource registration.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration
+ )
+
+ $resource = [ordered]@{
+ uri = $Registration.Uri
+ name = $Registration.Name
+ }
+ if ($Registration.Title) { $resource['title'] = $Registration.Title }
+ if ($Registration.Description) { $resource['description'] = $Registration.Description }
+ if ($Registration.MimeType) { $resource['mimeType'] = $Registration.MimeType }
+ $size = Get-McpResourceSize -Registration $Registration
+ if ($size -ge 0) { $resource['size'] = $size }
+ if ($null -ne $Registration.Icons) { $resource['icons'] = @($Registration.Icons) }
+ if ($null -ne $Registration.Annotations) { $resource['annotations'] = $Registration.Annotations }
+ if ($null -ne $Registration.Meta) { $resource['_meta'] = $Registration.Meta }
+ $resource
+}
+
+function ConvertTo-McpResourceTemplateDefinition {
+ <#
+ .SYNOPSIS
+ The ResourceTemplate object (as sent in resources/templates/list) of a template registration.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration
+ )
+
+ $template = [ordered]@{
+ uriTemplate = $Registration.UriTemplate
+ name = $Registration.Name
+ }
+ if ($Registration.Title) { $template['title'] = $Registration.Title }
+ if ($Registration.Description) { $template['description'] = $Registration.Description }
+ if ($Registration.MimeType) { $template['mimeType'] = $Registration.MimeType }
+ if ($null -ne $Registration.Icons) { $template['icons'] = @($Registration.Icons) }
+ if ($null -ne $Registration.Annotations) { $template['annotations'] = $Registration.Annotations }
+ if ($null -ne $Registration.Meta) { $template['_meta'] = $Registration.Meta }
+ $template
+}
+
+function Get-McpResourceListResult {
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [AllowNull()]
+ [object] $Cursor
+ )
+
+ Get-McpPagedListResult -Server $Server -Kind 'resources' -Items @($Server.Resources.Values) -Cursor $Cursor -Converter { param($registration) ConvertTo-McpResourceDefinition -Registration $registration }
+}
+
+function Get-McpResourceTemplateListResult {
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [AllowNull()]
+ [object] $Cursor
+ )
+
+ Get-McpPagedListResult -Server $Server -Kind 'resourceTemplates' -Items @($Server.ResourceTemplates.Values) -Cursor $Cursor -Converter { param($registration) ConvertTo-McpResourceTemplateDefinition -Registration $registration }
+}
+
+function New-McpResourceNotFoundException {
+ <#
+ .SYNOPSIS
+ The error for a URI that names no resource: -32602 with the URI in data (SEP-2164).
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an exception object.')]
+ [CmdletBinding()]
+ [OutputType([McpProtocolException])]
+ param(
+ [Parameter(Mandatory)]
+ [AllowEmptyString()]
+ [string] $Uri
+ )
+
+ [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Resource not found', [ordered]@{ uri = $Uri })
+}
+
+function Resolve-McpResourceRequest {
+ <#
+ .SYNOPSIS
+ The registration serving a URI (exact static match first, then templates in registration order) and the template variables.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [string] $Uri
+ )
+
+ if ($Server.Resources.Contains($Uri)) {
+ return @{ Registration = $Server.Resources[$Uri]; Variables = [ordered]@{} }
+ }
+ foreach ($registration in $Server.ResourceTemplates.Values) {
+ $variables = Test-McpUriTemplateMatch -Template $registration.Template -Uri $Uri
+ if ($null -ne $variables) {
+ return @{ Registration = $registration; Variables = $variables }
+ }
+ }
+ throw (New-McpResourceNotFoundException -Uri $Uri)
+}
+
+function Get-McpResourceCacheHint {
+ <#
+ .SYNOPSIS
+ The ttlMs and cacheScope of a resources/read result: the registration's, else the server defaults.
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Server,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration
+ )
+
+ @{
+ TtlMs = if ($null -ne $Registration.TtlMs) { [long] $Registration.TtlMs } else { [long] $Server.Options.DefaultTtlMs }
+ CacheScope = if ($Registration.CacheScope) { $Registration.CacheScope } else { $Server.Options.DefaultCacheScope }
+ }
+}
+
+function New-McpResourceContentObject {
+ <#
+ .SYNOPSIS
+ A TextResourceContents or BlobResourceContents wire object.
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory wire object.')]
+ [CmdletBinding(DefaultParameterSetName = 'Text')]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Uri,
+
+ [Parameter(ParameterSetName = 'Text', Mandatory)]
+ [AllowEmptyString()]
+ [string] $Text,
+
+ [Parameter(ParameterSetName = 'Blob', Mandatory)]
+ [object] $Blob,
+
+ [AllowNull()]
+ [string] $MimeType,
+
+ [AllowNull()]
+ [System.Collections.IDictionary] $Meta
+ )
+
+ $content = [ordered]@{ uri = $Uri }
+ if ($MimeType) { $content['mimeType'] = $MimeType }
+ if ($PSCmdlet.ParameterSetName -eq 'Text') { $content['text'] = $Text } else { $content['blob'] = ConvertTo-McpBase64 -Data $Blob }
+ if ($null -ne $Meta -and $Meta.Count -gt 0) { $content['_meta'] = $Meta }
+ $content
+}
+
+function Read-McpFileResourceContent {
+ <#
+ .SYNOPSIS
+ The contents of a file as text (text MIME types, UTF-8) or blob; $null when the file does not exist.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Path,
+
+ [Parameter(Mandatory)]
+ [string] $Uri,
+
+ [AllowNull()]
+ [string] $MimeType
+ )
+
+ if (-not [System.IO.File]::Exists($Path)) { return $null }
+ if (-not $MimeType) { $MimeType = Get-McpMimeType -Path $Path }
+ if (Test-McpTextMimeType -MimeType $MimeType) {
+ return New-McpResourceContentObject -Uri $Uri -Text ([System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)) -MimeType $MimeType
+ }
+ New-McpResourceContentObject -Uri $Uri -Blob ([System.IO.File]::ReadAllBytes($Path)) -MimeType $MimeType
+}
+
+function Get-McpRealPath {
+ <#
+ .SYNOPSIS
+ The path with every symbolic link along it resolved.
+ #>
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Path,
+
+ [int] $Depth = 0
+ )
+
+ if ($Depth -gt 32) { throw [System.IO.IOException]::new('Too many levels of symbolic links.') }
+ $full = [System.IO.Path]::GetFullPath($Path)
+ $root = [System.IO.Path]::GetPathRoot($full)
+ $current = $root
+ $separators = [char[]] @([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar)
+ foreach ($part in $full.Substring($root.Length).Split($separators, [System.StringSplitOptions]::RemoveEmptyEntries)) {
+ $next = [System.IO.Path]::Combine($current, $part)
+ $item = if ([System.IO.Directory]::Exists($next)) { [System.IO.DirectoryInfo]::new($next) } else { [System.IO.FileInfo]::new($next) }
+ if ($null -ne $item.LinkTarget) {
+ $target = $item.ResolveLinkTarget($true)
+ if ($null -ne $target) { $next = Get-McpRealPath -Path $target.FullName -Depth ($Depth + 1) }
+ }
+ $current = $next
+ }
+ $current
+}
+
+function Test-McpPathWithin {
+ [CmdletBinding()]
+ [OutputType([bool])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Path,
+
+ [Parameter(Mandatory)]
+ [string] $Root
+ )
+
+ $comparison = if ($IsLinux) { [System.StringComparison]::Ordinal } else { [System.StringComparison]::OrdinalIgnoreCase }
+ $prefix = if ([System.IO.Path]::EndsInDirectorySeparator($Root)) { $Root } else { $Root + [System.IO.Path]::DirectorySeparatorChar }
+ $Path.StartsWith($prefix, $comparison)
+}
+
+function Resolve-McpDirectoryResourcePath {
+ <#
+ .SYNOPSIS
+ The file a relative path names below a directory resource root; $null when it escapes the root or does not exist.
+ .DESCRIPTION
+ The path is combined with the root and normalised; '..' segments, absolute paths and symbolic links
+ that lead outside the root are rejected, as the specification requires for file resources.
+ #>
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Root,
+
+ [AllowNull()]
+ [AllowEmptyString()]
+ [string] $RelativePath
+ )
+
+ if (-not $RelativePath -or $RelativePath.Contains([char] 0)) { return $null }
+ try {
+ $rootFull = [System.IO.Path]::GetFullPath($Root)
+ $candidate = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($rootFull, $RelativePath.TrimStart('/')))
+ if ([System.IO.Path]::IsPathRooted($RelativePath.TrimStart('/')) -or -not (Test-McpPathWithin -Path $candidate -Root $rootFull)) { return $null }
+ if (-not [System.IO.File]::Exists($candidate)) { return $null }
+ $real = Get-McpRealPath -Path $candidate
+ if (-not (Test-McpPathWithin -Path $real -Root (Get-McpRealPath -Path $rootFull))) { return $null }
+ $candidate
+ } catch [System.IO.IOException] {
+ $null
+ } catch [System.ArgumentException] {
+ $null
+ } catch [System.UnauthorizedAccessException] {
+ $null
+ }
+}
+
+function ConvertTo-McpResourceContentList {
+ <#
+ .SYNOPSIS
+ Shapes the output of a resource handler into resource contents.
+ .DESCRIPTION
+ New-McpResourceContent objects (Mcp.ResourceContents) pass through; their uri defaults to the
+ requested URI. Consecutive strings become one text content, byte arrays (or a stream of bytes) a blob content, FileInfo objects
+ the contents of the file, and other objects JSON text. Without an explicit MIME type text is
+ text/plain, JSON application/json and binary application/octet-stream.
+ #>
+ [CmdletBinding()]
+ [OutputType([object[]], [System.Array])]
+ param(
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [object[]] $Output,
+
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration,
+
+ [Parameter(Mandatory)]
+ [string] $Uri
+ )
+
+ # A loop instead of the pipeline keeps byte[] items whole; a handler that wrote a byte[] to the pipeline
+ # (return $bytes) produced single bytes, which are joined again.
+ $items = [System.Collections.Generic.List[object]]::new()
+ foreach ($item in @($Output)) {
+ if ($null -ne $item) { $items.Add($item) }
+ }
+ if ($items.Count -gt 0 -and @($items | Where-Object { $_ -isnot [byte] }).Count -eq 0) {
+ $items = @(, [byte[]] $items.ToArray())
+ }
+ $contents = [System.Collections.Generic.List[object]]::new()
+ $texts = [System.Collections.Generic.List[string]]::new()
+ $objects = [System.Collections.Generic.List[object]]::new()
+ $mimeType = $Registration.MimeType
+ $flush = {
+ if ($texts.Count -gt 0) {
+ $contents.Add((New-McpResourceContentObject -Uri $Uri -Text ($texts -join "`n") -MimeType $(if ($mimeType) { $mimeType } else { 'text/plain' })))
+ $texts.Clear()
+ }
+ if ($objects.Count -gt 0) {
+ $value = if ($objects.Count -eq 1) { $objects[0] } else { , $objects.ToArray() }
+ $contents.Add((New-McpResourceContentObject -Uri $Uri -Text (ConvertTo-McpJson -InputObject $value) -MimeType $(if ($mimeType) { $mimeType } else { 'application/json' })))
+ $objects.Clear()
+ }
+ }
+ foreach ($item in $items) {
+ if ($item.PSObject.TypeNames -contains 'Mcp.ResourceContents') {
+ . $flush
+ $content = [ordered]@{}
+ foreach ($property in $item.PSObject.Properties) {
+ if ($null -ne $property.Value) { $content[$property.Name] = $property.Value }
+ }
+ if (-not $content.Contains('uri')) {
+ $ordered = [ordered]@{ uri = $Uri }
+ foreach ($key in $content.Keys) { $ordered[$key] = $content[$key] }
+ $content = $ordered
+ }
+ $contents.Add($content)
+ } elseif ($item -is [byte[]]) {
+ . $flush
+ $contents.Add((New-McpResourceContentObject -Uri $Uri -Blob $item -MimeType $(if ($mimeType) { $mimeType } else { 'application/octet-stream' })))
+ } elseif ($item -is [System.IO.FileInfo]) {
+ . $flush
+ $fileContent = Read-McpFileResourceContent -Path $item.FullName -Uri $Uri -MimeType $mimeType
+ if ($null -ne $fileContent) { $contents.Add($fileContent) }
+ } elseif ($item -is [string]) {
+ if ($objects.Count -gt 0) { . $flush }
+ $texts.Add($item)
+ } elseif ($item -is [valuetype] -or $item -is [enum] -or $item -is [uri] -or $item -is [version]) {
+ if ($objects.Count -gt 0) { . $flush }
+ $texts.Add([System.Management.Automation.LanguagePrimitives]::ConvertTo($item, [string]))
+ } else {
+ if ($texts.Count -gt 0) { . $flush }
+ $objects.Add($item)
+ }
+ }
+ . $flush
+ , $contents.ToArray()
+}
+
+function ConvertTo-McpReadResourceResult {
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [AllowEmptyCollection()]
+ [object[]] $Contents,
+
+ [Parameter(Mandatory)]
+ [hashtable] $CacheHint
+ )
+
+ [ordered]@{
+ resultType = 'complete'
+ contents = $Contents
+ ttlMs = [long] $CacheHint.TtlMs
+ cacheScope = $CacheHint.CacheScope
+ }
+}
+
+function Invoke-McpResourceHandler {
+ <#
+ .SYNOPSIS
+ Reads a resource: fixed content, a file, a file below a directory root or the output of a handler.
+ .DESCRIPTION
+ Returns the ReadResourceResult. A resource that yields no contents, a missing file and a handler that
+ throws ItemNotFoundException are reported as resource not found (-32602 with the URI); other handler
+ failures become internal errors (-32603).
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [pscustomobject] $Registration,
+
+ [Parameter(Mandatory)]
+ [string] $Uri,
+
+ [System.Collections.IDictionary] $Variables = [ordered]@{},
+
+ [AllowNull()]
+ [object] $Context,
+
+ [Parameter(Mandatory)]
+ [hashtable] $CacheHint,
+
+ [switch] $UseCommandName
+ )
+
+ $contents = @()
+ switch ($Registration.Source) {
+ 'Content' {
+ $contents = ConvertTo-McpResourceContentList -Output @(, $Registration.Content) -Registration $Registration -Uri $Uri
+ }
+ 'File' {
+ $content = Read-McpFileResourceContent -Path $Registration.Path -Uri $Uri -MimeType $Registration.MimeType
+ if ($null -ne $content) { $contents = @($content) }
+ }
+ 'Directory' {
+ $path = Resolve-McpDirectoryResourcePath -Root $Registration.Path -RelativePath $Variables['path']
+ if ($null -ne $path) {
+ $contents = @(Read-McpFileResourceContent -Path $path -Uri $Uri -MimeType $null)
+ }
+ }
+ 'Handler' {
+ $values = [ordered]@{ Uri = $Uri; Variables = $Variables }
+ foreach ($key in $Variables.Keys) {
+ if (-not $values.Contains($key)) { $values[$key] = $Variables[$key] }
+ }
+ $splat = New-McpHandlerSplat -Handler $Registration.Handler -Values $values -Context $Context
+ $threshold = if ($null -ne $Context -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel }
+ try {
+ $merged = @(Invoke-McpHandlerCommand -Handler $Registration.Handler -Splat $splat -UseCommandName:$UseCommandName)
+ } catch [System.Management.Automation.PipelineStoppedException] {
+ throw
+ } catch {
+ $exception = Get-McpHandlerException -Exception $_.Exception
+ if ($exception -is [McpProtocolException]) { throw $exception }
+ if ($exception -is [System.Management.Automation.ItemNotFoundException] -or $exception -is [System.IO.FileNotFoundException]) { throw (New-McpResourceNotFoundException -Uri $Uri) }
+ throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "Reading resource '$Uri' failed: $($exception.Message)")
+ }
+ $parts = Split-McpHandlerOutput -Merged $merged
+ Write-McpHandlerDiagnostic -Diagnostics $parts.Diagnostics -Name $Uri -Threshold $threshold -Context $Context -ErrorRecords $parts.Errors
+ $contents = ConvertTo-McpResourceContentList -Output $parts.Output -Registration $Registration -Uri $Uri
+ if ($contents.Count -eq 0 -and $parts.Errors.Count -gt 0) {
+ throw [McpProtocolException]::new($script:McpErrorCode.InternalError, "Reading resource '$Uri' failed: $($parts.Errors[0].ToString())")
+ }
+ }
+ }
+ if (@($contents).Count -eq 0) { throw (New-McpResourceNotFoundException -Uri $Uri) }
+ ConvertTo-McpReadResourceResult -Contents @($contents) -CacheHint $CacheHint
+}
diff --git a/src/Private/Server.ps1 b/src/Private/Server.ps1
index 8c30a4e..7c6dc03 100644
--- a/src/Private/Server.ps1
+++ b/src/Private/Server.ps1
@@ -67,9 +67,15 @@ function Get-McpServerCapability {
[pscustomobject] $Server
)
- $capabilities = [ordered]@{
- tools = [ordered]@{ listChanged = [bool] $Server.Options.ListChanged }
+ # Resources, prompts and completions are declared only when something is registered: their methods answer
+ # -32601 otherwise, and a declared capability must be backed by working methods.
+ $capabilities = [ordered]@{}
+ 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['tools'] = [ordered]@{ listChanged = [bool] $Server.Options.ListChanged }
$capabilities
}
diff --git a/src/Private/Tools.ps1 b/src/Private/Tools.ps1
index 5603723..b8f9fbc 100644
--- a/src/Private/Tools.ps1
+++ b/src/Private/Tools.ps1
@@ -1,5 +1,5 @@
-# Tool registry: registrations (PSTypeName Mcp.ToolRegistration), the Tool definitions of tools/list, cursor
-# pagination, typed argument binding and the shaping of handler output into CallToolResult.
+# Tool registry: registrations (PSTypeName Mcp.ToolRegistration), the Tool definitions of tools/list, typed
+# argument binding and the shaping of handler output into CallToolResult.
$script:McpToolNamePattern = '^[A-Za-z0-9_.-]{1,128}$'
$script:McpContentTypes = @('text', 'image', 'audio', 'resource_link', 'resource')
@@ -70,39 +70,6 @@ function ConvertTo-McpAnnotationObject {
$result
}
-function New-McpCursor {
- [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Encodes a value.')]
- [CmdletBinding()]
- [OutputType([string])]
- param(
- [Parameter(Mandatory)]
- [int] $Offset
- )
-
- [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("mcp-cursor:offset=$Offset"))
-}
-
-function Read-McpCursor {
- [CmdletBinding()]
- [OutputType([int])]
- param(
- [AllowNull()]
- [object] $Cursor
- )
-
- if ($null -eq $Cursor) { return 0 }
- if ($Cursor -is [string]) {
- $text = $null
- try {
- $text = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Cursor))
- } catch {
- $text = $null
- }
- if ($null -ne $text -and $text -match '^mcp-cursor:offset=(\d{1,9})$') { return [int] $Matches[1] }
- }
- throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Invalid cursor.')
-}
-
function Get-McpToolListResult {
[CmdletBinding()]
[OutputType([System.Collections.Specialized.OrderedDictionary])]
@@ -114,27 +81,7 @@ function Get-McpToolListResult {
[object] $Cursor
)
- $offset = Read-McpCursor -Cursor $Cursor
- $registrations = @($Server.Tools.Values)
- if ($offset -gt $registrations.Count) {
- throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, 'Invalid cursor.')
- }
- $pageSize = [int] $Server.Options.PageSize
- $page = @()
- if ($offset -lt $registrations.Count) {
- $end = [math]::Min($offset + $pageSize, $registrations.Count) - 1
- $page = @($registrations[$offset..$end] | ForEach-Object { ConvertTo-McpToolDefinition -Registration $_ })
- }
- $result = [ordered]@{
- resultType = 'complete'
- tools = $page
- }
- if ($offset + $pageSize -lt $registrations.Count) {
- $result['nextCursor'] = New-McpCursor -Offset ($offset + $pageSize)
- }
- $result['ttlMs'] = [long] $Server.Options.DefaultTtlMs
- $result['cacheScope'] = $Server.Options.DefaultCacheScope
- Add-McpResultMeta -Result $result -Server $Server
+ Get-McpPagedListResult -Server $Server -Kind 'tools' -Items @($Server.Tools.Values) -Cursor $Cursor -Converter { param($registration) ConvertTo-McpToolDefinition -Registration $registration }
}
function ConvertTo-McpToolArgument {
@@ -360,26 +307,50 @@ function Split-McpHandlerOutput {
}
function Write-McpHandlerDiagnostic {
+ <#
+ .SYNOPSIS
+ Routes a handler's warning, verbose, debug and information records (and optionally its non-terminating
+ errors) to stderr and, when the request asked for log notifications, to the client.
+ .DESCRIPTION
+ Warnings map to the level warning, information to info, verbose and debug to debug and errors to
+ error. With a request context whose request carried io.modelcontextprotocol/logLevel, the records at
+ or above that level are also sent as notifications/message (see Write-McpLog).
+ #>
[CmdletBinding()]
param(
[AllowNull()]
[AllowEmptyCollection()]
[object[]] $Diagnostics,
+ # The logger name: the tool or prompt name or the resource URI.
[Parameter(Mandatory)]
- [string] $ToolName,
+ [string] $Name,
- [object] $Threshold = $script:McpDefaultLogLevel
+ [object] $Threshold = $script:McpDefaultLogLevel,
+
+ [AllowNull()]
+ [object] $Context,
+
+ [AllowNull()]
+ [AllowEmptyCollection()]
+ [System.Management.Automation.ErrorRecord[]] $ErrorRecords
)
- foreach ($record in @($Diagnostics)) {
+ $records = @($Diagnostics) + @($ErrorRecords)
+ foreach ($record in $records) {
+ if ($null -eq $record) { continue }
$level = switch ($record) {
+ { $_ -is [System.Management.Automation.ErrorRecord] } { [McpLoggingLevel]::Error }
{ $_ -is [System.Management.Automation.WarningRecord] } { [McpLoggingLevel]::Warning }
{ $_ -is [System.Management.Automation.VerboseRecord] } { [McpLoggingLevel]::Debug }
{ $_ -is [System.Management.Automation.DebugRecord] } { [McpLoggingLevel]::Debug }
default { [McpLoggingLevel]::Info }
}
- $text = if ($record -is [System.Management.Automation.InformationRecord]) { [string] $record.MessageData } else { $record.Message }
- Write-McpStderr -Level $level -Threshold $Threshold -Logger $ToolName -Message $text
+ $text = if ($record -is [System.Management.Automation.InformationRecord]) { [string] $record.MessageData } elseif ($record -is [System.Management.Automation.ErrorRecord]) { $record.ToString() } else { $record.Message }
+ if ($null -ne $Context -and $Context.PSObject.Properties['Sink']) {
+ Write-McpLog -Message $text -Level $level -Context $Context -Logger $Name
+ } else {
+ Write-McpStderr -Level $level -Threshold $Threshold -Logger $Name -Message $text
+ }
}
}
diff --git a/src/Private/UriTemplate.ps1 b/src/Private/UriTemplate.ps1
new file mode 100644
index 0000000..713e469
--- /dev/null
+++ b/src/Private/UriTemplate.ps1
@@ -0,0 +1,146 @@
+# RFC 6570 URI templates of resource templates: parsing and matching a concrete URI against a template to
+# extract its variables. Levels 1 to 3 are supported (the operators none, +, #, ., /, ;, ? and &); the level 4
+# modifiers (prefix :n and explode *) are rejected at registration, because matching them in reverse is
+# ambiguous.
+
+$script:McpUriTemplateOperators = @('', '+', '#', '.', '/', ';', '?', '&')
+$script:McpUriTemplateVariablePattern = '^(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*$'
+# Unreserved characters and percent-encoded octets; the reserved expansions (+, #) also allow reserved characters.
+$script:McpUriTemplateUnreserved = '(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})'
+$script:McpUriTemplateReserved = '(?:[A-Za-z0-9\-._~:/?#\[\]@!$&''()*+,;=]|%[0-9A-Fa-f]{2})'
+
+function ConvertFrom-McpUriTemplate {
+ <#
+ .SYNOPSIS
+ Parses a URI template into literal and expression parts and compiles the regular expression that matches it.
+ .OUTPUTS
+ A hashtable with Template, Variables (names in order), Regex and Groups (group name -> variable and operator).
+ #>
+ [CmdletBinding()]
+ [OutputType([hashtable])]
+ param(
+ [Parameter(Mandatory)]
+ [string] $Template
+ )
+
+ $pattern = [System.Text.StringBuilder]::new('^')
+ $variables = [System.Collections.Generic.List[string]]::new()
+ $groups = [ordered]@{}
+ $position = 0
+ $groupIndex = 0
+ while ($position -lt $Template.Length) {
+ $open = $Template.IndexOf('{', $position)
+ $closeBefore = $Template.IndexOf('}', $position)
+ if ($closeBefore -ge 0 -and ($open -lt 0 -or $closeBefore -lt $open)) {
+ throw [System.ArgumentException]::new("URI template '$Template' has an unmatched '}'.")
+ }
+ if ($open -lt 0) {
+ $null = $pattern.Append([regex]::Escape($Template.Substring($position)))
+ break
+ }
+ $null = $pattern.Append([regex]::Escape($Template.Substring($position, $open - $position)))
+ $close = $Template.IndexOf('}', $open)
+ if ($close -lt 0) { throw [System.ArgumentException]::new("URI template '$Template' has an unmatched '{'.") }
+ $expression = $Template.Substring($open + 1, $close - $open - 1)
+ $position = $close + 1
+ if ($expression.Length -eq 0) { throw [System.ArgumentException]::new("URI template '$Template' has an empty expression.") }
+ $operator = ''
+ if ('+#./;?&=,!@|'.Contains($expression[0])) {
+ $operator = [string] $expression[0]
+ $expression = $expression.Substring(1)
+ }
+ if ($operator -notin $script:McpUriTemplateOperators) {
+ throw [System.ArgumentException]::new("URI template '$Template' uses the reserved operator '$operator'.")
+ }
+ $names = @($expression.Split(','))
+ foreach ($name in $names) {
+ if ($name -match '[:*]') {
+ throw [System.ArgumentException]::new("URI template '$Template' uses the level 4 modifier in '$name'; prefix (:n) and explode (*) modifiers are not supported.")
+ }
+ if ($name -notmatch $script:McpUriTemplateVariablePattern) {
+ throw [System.ArgumentException]::new("URI template '$Template' has an invalid variable name '$name'.")
+ }
+ if ($variables.Contains($name)) {
+ throw [System.ArgumentException]::new("URI template '$Template' uses the variable '$name' more than once.")
+ }
+ $variables.Add($name)
+ }
+
+ if ($operator -in @('?', '&')) {
+ # Query expansions are matched as a whole and parsed into name=value pairs.
+ $group = 'q' + $groupIndex++
+ $groups[$group] = @{ Operator = $operator; Names = $names }
+ $lead = if ($operator -eq '?') { '\?' } else { '&' }
+ $null = $pattern.Append("(?:$lead(?<$group>[^#]*?))?")
+ continue
+ }
+ $value = if ($operator -in @('+', '#')) { $script:McpUriTemplateReserved } else { $script:McpUriTemplateUnreserved }
+ if ($operator -eq '.') { $value = '(?:[A-Za-z0-9\-_~]|%[0-9A-Fa-f]{2})' }
+ $first = $true
+ foreach ($name in $names) {
+ $group = 'v' + $groupIndex++
+ $groups[$group] = @{ Operator = $operator; Names = @($name) }
+ switch ($operator) {
+ { $_ -in @('', '+') } {
+ if ($first -and $names.Count -eq 1) { $null = $pattern.Append("(?<$group>$value+)") }
+ elseif ($first) { $null = $pattern.Append("(?<$group>$value*)") }
+ else { $null = $pattern.Append("(?:,(?<$group>$value*))?") }
+ }
+ '#' {
+ if ($first) { $null = $pattern.Append("(?:#(?<$group>$value*)") }
+ else { $null = $pattern.Append("(?:,(?<$group>$value*))?") }
+ }
+ '.' { $null = $pattern.Append("(?:\.(?<$group>$value*))?") }
+ '/' { $null = $pattern.Append("(?:/(?<$group>$value*))?") }
+ ';' { $null = $pattern.Append("(?:;$([regex]::Escape($name))(?:=(?<$group>$value*))?)?") }
+ }
+ $first = $false
+ }
+ if ($operator -eq '#') { $null = $pattern.Append(')?') }
+ }
+ $null = $pattern.Append('$')
+ @{
+ Template = $Template
+ Variables = $variables.ToArray()
+ Regex = [regex]::new($pattern.ToString(), [System.Text.RegularExpressions.RegexOptions]::CultureInvariant)
+ Groups = $groups
+ }
+}
+
+function Test-McpUriTemplateMatch {
+ <#
+ .SYNOPSIS
+ Matches a URI against a parsed template; returns the decoded variables, or $null when it does not match.
+ #>
+ [CmdletBinding()]
+ [OutputType([System.Collections.Specialized.OrderedDictionary])]
+ param(
+ [Parameter(Mandatory)]
+ [hashtable] $Template,
+
+ [Parameter(Mandatory)]
+ [string] $Uri
+ )
+
+ $match = $Template.Regex.Match($Uri)
+ if (-not $match.Success) { return $null }
+ $variables = [ordered]@{}
+ foreach ($entry in $Template.Groups.GetEnumerator()) {
+ $group = $match.Groups[$entry.Key]
+ if (-not $group.Success) { continue }
+ if ($entry.Value.Operator -in @('?', '&')) {
+ $query = $group.Value
+ if ($entry.Value.Operator -eq '&' -and $query.StartsWith('&')) { $query = $query.Substring(1) }
+ foreach ($pair in $query.Split('&')) {
+ if ($pair.Length -eq 0) { continue }
+ $parts = $pair.Split('=', 2)
+ $name = [System.Uri]::UnescapeDataString($parts[0])
+ if ($name -notin $entry.Value.Names -or $variables.Contains($name)) { continue }
+ $variables[$name] = if ($parts.Count -eq 2) { [System.Uri]::UnescapeDataString($parts[1]) } else { '' }
+ }
+ continue
+ }
+ $variables[$entry.Value.Names[0]] = [System.Uri]::UnescapeDataString($group.Value)
+ }
+ $variables
+}
diff --git a/src/Private/Worker.ps1 b/src/Private/Worker.ps1
index cf09857..b20edfc 100644
--- a/src/Private/Worker.ps1
+++ b/src/Private/Worker.ps1
@@ -1,5 +1,6 @@
-# Worker side of a tools/call request: runs in a runspace of the server's pool, builds the request context,
-# invokes the handler through Invoke-McpToolHandler and enqueues the response for the dispatcher.
+# 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.
$script:McpModuleManifestPath = Join-Path $PSScriptRoot 'ModelContextProtocol.psd1'
@@ -25,7 +26,8 @@ function New-McpRequestContext {
PSTypeName = 'Mcp.RequestContext'
RequestId = $Envelope.RequestId
Method = $Envelope.Method
- ToolName = $Envelope.ToolName
+ Name = $Envelope.Name
+ ToolName = if ($Envelope.Kind -eq 'Tool') { $Envelope.Name } else { $null }
Era = 'Modern'
ProtocolVersion = $meta.ProtocolVersion
ClientInfo = $meta.ClientInfo
@@ -72,7 +74,7 @@ function Send-McpSinkMessage {
function Invoke-McpWorkerRequest {
<#
.SYNOPSIS
- Handles one tools/call request in a worker runspace and enqueues the response.
+ Handles one request in a worker runspace and enqueues the response.
#>
[CmdletBinding()]
param(
@@ -84,7 +86,12 @@ function Invoke-McpWorkerRequest {
$response = $null
$errorCode = $null
try {
- $result = Invoke-McpToolHandler -Registration $Envelope.Registration -Arguments $Envelope.Arguments -Context $context -UseCommandName
+ $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 }
+ 'Prompt' { Invoke-McpPromptHandler -Registration $Envelope.Registration -Arguments $Envelope.Arguments -Context $context -UseCommandName }
+ 'Completion' { Invoke-McpCompletionHandler -Request $Envelope.Completion -Context $context -UseCommandName }
+ }
if ($Envelope.IncludeServerInfo -and $null -ne $Envelope.ServerInfo) {
$meta = if ($result.Contains('_meta') -and $result['_meta'] -is [System.Collections.IDictionary]) { $result['_meta'] } else { [ordered]@{} }
$meta[$script:McpMetaKey.ServerInfo] = $Envelope.ServerInfo
@@ -94,10 +101,7 @@ function Invoke-McpWorkerRequest {
} catch [System.Management.Automation.PipelineStoppedException] {
throw
} catch {
- $exception = $_.Exception
- if ($exception -is [System.Management.Automation.RuntimeException] -and $null -ne $exception.InnerException -and $exception.GetType() -eq [System.Management.Automation.RuntimeException]) {
- $exception = $exception.InnerException
- }
+ $exception = Get-McpHandlerException -Exception $_.Exception
$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 816daba..c2630c3 100644
--- a/src/Public/Connect-McpServer.ps1
+++ b/src/Public/Connect-McpServer.ps1
@@ -59,6 +59,7 @@ function Connect-McpServer {
.OUTPUTS
Mcp.Session
#>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseLiteralInitializerForHashtable', '', Justification = 'The result cache is keyed by case-sensitive method names and URIs.')]
[CmdletBinding(DefaultParameterSetName = 'Stdio', SupportsShouldProcess)]
[OutputType('Mcp.Session')]
param(
@@ -157,6 +158,7 @@ function Connect-McpServer {
ServerInfo = $null
Tools = $null
ToolHeaders = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
+ Cache = [hashtable]::new([System.StringComparer]::Ordinal)
NextId = 1
RequestTimeoutMs = $RequestTimeoutSeconds * 1000
LogLevel = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $null }
@@ -199,6 +201,7 @@ function Connect-McpServer {
}
$session.ServerInfo = ConvertTo-McpServerInfoObject -DiscoverResult $discover -ProtocolVersion $session.ProtocolVersion
$session.Name = $session.ServerInfo.Name
+ Set-McpClientCacheEntry -Session $session -Key 'server/discover' -Value $session.ServerInfo -CacheHint (Get-McpResultCacheHint -Result $discover)
} catch {
try { Disconnect-McpServer -Session $session -Confirm:$false } catch { Write-Debug 'Cleanup after a failed connection failed.' }
throw
diff --git a/src/Public/Get-McpCompletion.ps1 b/src/Public/Get-McpCompletion.ps1
new file mode 100644
index 0000000..9a945ff
--- /dev/null
+++ b/src/Public/Get-McpCompletion.ps1
@@ -0,0 +1,68 @@
+function Get-McpCompletion {
+ <#
+ .SYNOPSIS
+ Asks the server for completions of a prompt argument or a resource template variable (completion/complete).
+ .DESCRIPTION
+ The server returns at most 100 values; Total and HasMore tell whether it knows more. Servers without
+ the completions capability answer with a method-not-found error, which is thrown.
+ .PARAMETER PromptName
+ The prompt whose argument is completed.
+ .PARAMETER ResourceTemplate
+ The URI template of the resource template whose variable is completed.
+ .PARAMETER Argument
+ The argument or variable name.
+ .PARAMETER Value
+ The text typed so far.
+ .PARAMETER ContextArguments
+ Values of other arguments that are already known (context.arguments).
+ .PARAMETER Session
+ The session; defaults to the default session.
+ .EXAMPLE
+ (Get-McpCompletion -PromptName weather-report -Argument city -Value 'Ber').Values
+ .OUTPUTS
+ Mcp.Completion
+ #>
+ [CmdletBinding(DefaultParameterSetName = 'Prompt')]
+ [OutputType('Mcp.Completion')]
+ param(
+ [Parameter(ParameterSetName = 'Prompt', Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $PromptName,
+
+ [Parameter(ParameterSetName = 'ResourceTemplate', Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $ResourceTemplate,
+
+ [Parameter(Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Argument,
+
+ [AllowEmptyString()]
+ [string] $Value = '',
+
+ [System.Collections.IDictionary] $ContextArguments,
+
+ [object] $Session
+ )
+
+ $target = Resolve-McpSession -Session $Session
+ $reference = if ($PSCmdlet.ParameterSetName -eq 'Prompt') {
+ [ordered]@{ type = 'ref/prompt'; name = $PromptName }
+ } else {
+ [ordered]@{ type = 'ref/resource'; uri = $ResourceTemplate }
+ }
+ $params = [ordered]@{
+ ref = $reference
+ argument = [ordered]@{ name = $Argument; value = $Value }
+ }
+ if ($null -ne $ContextArguments -and $ContextArguments.Count -gt 0) {
+ $known = [ordered]@{}
+ foreach ($key in $ContextArguments.Keys) { $known[[string] $key] = [string] $ContextArguments[$key] }
+ $params['context'] = [ordered]@{ arguments = $known }
+ }
+ $result = Invoke-McpClientRequest -Session $target -Method 'completion/complete' -Params $params
+ if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains('completion')) {
+ throw [System.InvalidOperationException]::new('The completion/complete result has no completion member.')
+ }
+ ConvertTo-McpCompletionObject -Result $result
+}
diff --git a/src/Public/Get-McpPrompt.ps1 b/src/Public/Get-McpPrompt.ps1
new file mode 100644
index 0000000..0b760c8
--- /dev/null
+++ b/src/Public/Get-McpPrompt.ps1
@@ -0,0 +1,43 @@
+function Get-McpPrompt {
+ <#
+ .SYNOPSIS
+ Lists the server's prompts (prompts/list).
+ .DESCRIPTION
+ All pages are followed. The list is cached in the session for the ttlMs the server sent with it (the
+ shortest of all pages); afterwards, or with -Refresh, the server is queried again. Render a prompt with
+ Invoke-McpPrompt.
+ .PARAMETER Name
+ Only prompts whose name matches this wildcard pattern.
+ .PARAMETER Session
+ The session; defaults to the default session.
+ .PARAMETER Refresh
+ Query the server again instead of using a cached list.
+ .EXAMPLE
+ Get-McpPrompt | Select-Object Name, Description
+ .OUTPUTS
+ Mcp.Prompt
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.Prompt')]
+ param(
+ [Parameter(Position = 0)]
+ [SupportsWildcards()]
+ [string] $Name,
+
+ [object] $Session,
+
+ [switch] $Refresh
+ )
+
+ $target = Resolve-McpSession -Session $Session
+ $entry = if ($Refresh) { $null } else { Get-McpClientCacheEntry -Session $target -Key 'prompts/list' }
+ if ($null -ne $entry) {
+ $prompts = $entry.Value
+ } else {
+ $list = Invoke-McpClientListRequest -Session $target -Method 'prompts/list' -ItemKey 'prompts'
+ $prompts = @($list.Items | ForEach-Object { ConvertTo-McpPromptObject -Prompt $_ })
+ Set-McpClientCacheEntry -Session $target -Key 'prompts/list' -Value $prompts -CacheHint $list.CacheHint
+ }
+ if ($Name) { $prompts = @($prompts | Where-Object { $_.Name -like $Name }) }
+ $prompts
+}
diff --git a/src/Public/Get-McpResource.ps1 b/src/Public/Get-McpResource.ps1
new file mode 100644
index 0000000..e9759c3
--- /dev/null
+++ b/src/Public/Get-McpResource.ps1
@@ -0,0 +1,53 @@
+function Get-McpResource {
+ <#
+ .SYNOPSIS
+ Lists the server's resources (resources/list) or resource templates (resources/templates/list).
+ .DESCRIPTION
+ All pages are followed. The list is cached in the session for the ttlMs the server sent with it (the
+ shortest of all pages); afterwards, or with -Refresh, the server is queried again.
+ .PARAMETER Name
+ Only resources or templates whose name matches this wildcard pattern.
+ .PARAMETER Template
+ List the resource templates instead of the resources.
+ .PARAMETER Session
+ The session; defaults to the default session.
+ .PARAMETER Refresh
+ Query the server again instead of using a cached list.
+ .EXAMPLE
+ Get-McpResource | Read-McpResource
+ .EXAMPLE
+ Get-McpResource -Template | Select-Object Name, UriTemplate
+ .OUTPUTS
+ Mcp.Resource, Mcp.ResourceTemplate
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.Resource', 'Mcp.ResourceTemplate')]
+ param(
+ [Parameter(Position = 0)]
+ [SupportsWildcards()]
+ [string] $Name,
+
+ [switch] $Template,
+
+ [object] $Session,
+
+ [switch] $Refresh
+ )
+
+ $target = Resolve-McpSession -Session $Session
+ $method = if ($Template) { 'resources/templates/list' } else { 'resources/list' }
+ $entry = if ($Refresh) { $null } else { Get-McpClientCacheEntry -Session $target -Key $method }
+ if ($null -ne $entry) {
+ $items = $entry.Value
+ } else {
+ $list = Invoke-McpClientListRequest -Session $target -Method $method -ItemKey $(if ($Template) { 'resourceTemplates' } else { 'resources' })
+ $items = if ($Template) {
+ @($list.Items | ForEach-Object { ConvertTo-McpResourceTemplateObject -Template $_ })
+ } else {
+ @($list.Items | ForEach-Object { ConvertTo-McpResourceObject -Resource $_ })
+ }
+ Set-McpClientCacheEntry -Session $target -Key $method -Value $items -CacheHint $list.CacheHint
+ }
+ if ($Name) { $items = @($items | Where-Object { $_.Name -like $Name }) }
+ $items
+}
diff --git a/src/Public/Get-McpServerInfo.ps1 b/src/Public/Get-McpServerInfo.ps1
index 3f8dc0a..6385db9 100644
--- a/src/Public/Get-McpServerInfo.ps1
+++ b/src/Public/Get-McpServerInfo.ps1
@@ -2,10 +2,13 @@ function Get-McpServerInfo {
<#
.SYNOPSIS
The server's implementation info, capabilities, instructions and supported versions (from server/discover).
+ .DESCRIPTION
+ The result is cached in the session for the ttlMs the server sent with it; afterwards, or with
+ -Refresh, server/discover is queried again.
.PARAMETER Session
The session; defaults to the default session.
.PARAMETER Refresh
- Query server/discover again instead of returning the cached result.
+ Query server/discover again instead of returning a cached result.
.EXAMPLE
Get-McpServerInfo | Format-List
.OUTPUTS
@@ -20,10 +23,13 @@ function Get-McpServerInfo {
)
$target = Resolve-McpSession -Session $Session
- if ($Refresh -or $null -eq $target.ServerInfo) {
- $discover = Invoke-McpClientRequest -Session $target -Method 'server/discover'
- $target.ServerInfo = ConvertTo-McpServerInfoObject -DiscoverResult $discover -ProtocolVersion $target.ProtocolVersion
- $target.Name = $target.ServerInfo.Name
+ if (-not $Refresh) {
+ $entry = Get-McpClientCacheEntry -Session $target -Key 'server/discover'
+ if ($null -ne $entry) { return $entry.Value }
}
+ $discover = Invoke-McpClientRequest -Session $target -Method 'server/discover'
+ $target.ServerInfo = ConvertTo-McpServerInfoObject -DiscoverResult $discover -ProtocolVersion $target.ProtocolVersion
+ $target.Name = $target.ServerInfo.Name
+ Set-McpClientCacheEntry -Session $target -Key 'server/discover' -Value $target.ServerInfo -CacheHint (Get-McpResultCacheHint -Result $discover)
$target.ServerInfo
}
diff --git a/src/Public/Get-McpTool.ps1 b/src/Public/Get-McpTool.ps1
index 09920d0..fa6685f 100644
--- a/src/Public/Get-McpTool.ps1
+++ b/src/Public/Get-McpTool.ps1
@@ -3,7 +3,8 @@ function Get-McpTool {
.SYNOPSIS
Lists the server's tools (tools/list, following all pages) or gets one tool by name.
.DESCRIPTION
- The list is cached in the session; -Refresh queries the server again. Over Streamable HTTP a tool whose
+ The list is cached in the session for the ttlMs the server sent with it (the shortest of all pages);
+ afterwards, or with -Refresh, tools/list is queried again. Over Streamable HTTP a tool whose
x-mcp-header annotations are invalid is excluded from the list with a warning, as the specification
requires; the valid annotations tell Invoke-McpTool which arguments to mirror into Mcp-Param-* headers.
.PARAMETER Name
@@ -11,7 +12,7 @@ function Get-McpTool {
.PARAMETER Session
The session; defaults to the default session.
.PARAMETER Refresh
- Query tools/list again instead of using the cached list.
+ Query tools/list again instead of using a cached list.
.EXAMPLE
Get-McpTool | Select-Object Name, Description
.OUTPUTS
@@ -29,46 +30,38 @@ function Get-McpTool {
)
$target = Resolve-McpSession -Session $Session
- if ($Refresh -or $null -eq $target.Tools) {
- $tools = [System.Collections.Generic.List[object]]::new()
+ $entry = if ($Refresh) { $null } else { Get-McpClientCacheEntry -Session $target -Key 'tools/list' }
+ if ($null -ne $entry) {
+ $tools = $entry.Value
+ } else {
+ $list = Invoke-McpClientListRequest -Session $target -Method 'tools/list' -ItemKey 'tools'
+ $converted = [System.Collections.Generic.List[object]]::new()
$headers = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
- $cursor = $null
- $pages = 0
- do {
- $params = [ordered]@{}
- if ($null -ne $cursor) { $params['cursor'] = $cursor }
- $result = Invoke-McpClientRequest -Session $target -Method 'tools/list' -Params $params
- if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains('tools')) {
- throw [System.InvalidOperationException]::new('The tools/list result has no tools member.')
- }
- foreach ($tool in @($result['tools'])) {
- if ($tool -isnot [System.Collections.IDictionary]) { continue }
- if ($target.Kind -eq 'Http') {
- $toolName = if ($tool.Contains('name')) { [string] $tool['name'] } else { '(unnamed)' }
- $headerParameters = @()
- try {
- $headerParameters = @(Get-McpToolHeaderParameter -InputSchema $(if ($tool.Contains('inputSchema')) { $tool['inputSchema'] } else { $null }))
- } catch [System.ArgumentException] {
- Write-Warning "Excluding tool '$toolName' from the list: $($_.Exception.Message)"
- continue
- }
- $headers[$toolName] = $headerParameters
+ foreach ($tool in $list.Items) {
+ if ($target.Kind -eq 'Http') {
+ $toolName = if ($tool.Contains('name')) { [string] $tool['name'] } else { '(unnamed)' }
+ $headerParameters = @()
+ try {
+ $headerParameters = @(Get-McpToolHeaderParameter -InputSchema $(if ($tool.Contains('inputSchema')) { $tool['inputSchema'] } else { $null }))
+ } catch [System.ArgumentException] {
+ Write-Warning "Excluding tool '$toolName' from the list: $($_.Exception.Message)"
+ continue
}
- $tools.Add((ConvertTo-McpToolObject -Tool $tool))
+ $headers[$toolName] = $headerParameters
}
- $cursor = if ($result.Contains('nextCursor') -and $null -ne $result['nextCursor']) { [string] $result['nextCursor'] } else { $null }
- $pages++
- if ($pages -gt 10000) { throw [System.InvalidOperationException]::new('tools/list paged more than 10000 times.') }
- } while ($null -ne $cursor)
- $target.Tools = $tools.ToArray()
+ $converted.Add((ConvertTo-McpToolObject -Tool $tool))
+ }
+ $tools = $converted.ToArray()
+ $target.Tools = $tools
$target.ToolHeaders = $headers
+ Set-McpClientCacheEntry -Session $target -Key 'tools/list' -Value $tools -CacheHint $list.CacheHint
}
if ($Name) {
- $tool = $target.Tools | Where-Object { $_.Name -ceq $Name } | Select-Object -First 1
+ $tool = $tools | Where-Object { $_.Name -ceq $Name } | Select-Object -First 1
if (-not $tool) {
throw [System.ArgumentException]::new("The server has no tool named '$Name'.")
}
return $tool
}
- $target.Tools
+ $tools
}
diff --git a/src/Public/Invoke-McpPrompt.ps1 b/src/Public/Invoke-McpPrompt.ps1
new file mode 100644
index 0000000..dba61e2
--- /dev/null
+++ b/src/Public/Invoke-McpPrompt.ps1
@@ -0,0 +1,60 @@
+function Invoke-McpPrompt {
+ <#
+ .SYNOPSIS
+ Renders a prompt (prompts/get) with arguments and returns its messages.
+ .DESCRIPTION
+ Argument values are sent as strings (other values are converted with the invariant culture). The result
+ is an Mcp.PromptResult with the prompt's Description, its Messages (Role and an Mcp.Content block) and
+ the Text of all text blocks. Protocol errors (unknown prompt, missing required arguments) are thrown.
+ .PARAMETER Name
+ The prompt name.
+ .PARAMETER Arguments
+ The argument values.
+ .PARAMETER Session
+ The session; defaults to the default session.
+ .PARAMETER TimeoutSeconds
+ The timeout for this request; defaults to the session's request timeout.
+ .PARAMETER LogLevel
+ Ask for notifications/message at this level and above (see the session's Log).
+ .EXAMPLE
+ (Invoke-McpPrompt -Name summarize -Arguments @{ Text = $report }).Messages
+ .OUTPUTS
+ Mcp.PromptResult
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.PromptResult')]
+ param(
+ [Parameter(Mandatory, Position = 0)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Name,
+
+ [Parameter(Position = 1)]
+ [System.Collections.IDictionary] $Arguments,
+
+ [object] $Session,
+
+ [ValidateRange(0, 86400)]
+ [int] $TimeoutSeconds = 0,
+
+ [McpLoggingLevel] $LogLevel
+ )
+
+ $target = Resolve-McpSession -Session $Session
+ $params = [ordered]@{ name = $Name }
+ if ($null -ne $Arguments -and $Arguments.Count -gt 0) {
+ $values = [ordered]@{}
+ foreach ($key in $Arguments.Keys) {
+ $value = $Arguments[$key]
+ $values[[string] $key] = if ($null -eq $value) { '' }
+ elseif ($value -is [bool] -or $value -is [switch]) { ([bool] $value).ToString().ToLowerInvariant() }
+ else { [System.Management.Automation.LanguagePrimitives]::ConvertTo($value, [string], [cultureinfo]::InvariantCulture) }
+ }
+ $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)
+ if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains('messages')) {
+ throw [System.InvalidOperationException]::new('The prompts/get result has no messages member.')
+ }
+ ConvertTo-McpPromptResultObject -Result $result -Name $Name
+}
diff --git a/src/Public/Invoke-McpToolHandler.ps1 b/src/Public/Invoke-McpToolHandler.ps1
index 6bc81a7..f58b4aa 100644
--- a/src/Public/Invoke-McpToolHandler.ps1
+++ b/src/Public/Invoke-McpToolHandler.ps1
@@ -59,26 +59,16 @@ function Invoke-McpToolHandler {
throw [McpProtocolException]::new($script:McpErrorCode.InvalidParams, "Invalid arguments for tool '$($Registration.Name)': $($validation.Errors -join '; ')", $data)
}
$splat = ConvertTo-McpToolArgument -Registration $Registration -Arguments $Arguments -Context $Context
- $handler = $Registration.Handler
$threshold = if ($null -ne $Context -and $Context.PSObject.Properties['ServerLogLevel'] -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel }
$merged = $null
try {
- if ($UseCommandName) {
- $merged = @(& $handler.CommandName @splat *>&1)
- } elseif ($handler.Kind -eq 'ScriptBlock') {
- $merged = @(& $handler.ScriptBlock @splat *>&1)
- } else {
- $merged = @(& $handler.CommandInfo @splat *>&1)
- }
+ $merged = @(Invoke-McpHandlerCommand -Handler $Registration.Handler -Splat $splat -UseCommandName:$UseCommandName)
} catch [System.Management.Automation.PipelineStoppedException] {
throw
} catch {
- $exception = $_.Exception
- if ($exception -is [System.Management.Automation.RuntimeException] -and $null -ne $exception.InnerException -and $exception.GetType() -eq [System.Management.Automation.RuntimeException]) {
- $exception = $exception.InnerException
- }
- if ($exception -is [McpProtocolException]) { throw }
+ $exception = Get-McpHandlerException -Exception $_.Exception
+ if ($exception -is [McpProtocolException]) { throw $exception }
$failure = ConvertTo-McpTextBlock -Text ('Error: ' + $exception.Message)
$result = [ordered]@{
content = @($failure)
@@ -88,6 +78,6 @@ function Invoke-McpToolHandler {
return $result
}
$parts = Split-McpHandlerOutput -Merged $merged
- Write-McpHandlerDiagnostic -Diagnostics $parts.Diagnostics -ToolName $Registration.Name -Threshold $threshold
+ Write-McpHandlerDiagnostic -Diagnostics $parts.Diagnostics -Name $Registration.Name -Threshold $threshold -Context $Context
ConvertTo-McpCallToolResult -Output $parts.Output -Registration $Registration -ErrorRecords $parts.Errors
}
diff --git a/src/Public/New-McpContent.ps1 b/src/Public/New-McpContent.ps1
index e764113..66b644d 100644
--- a/src/Public/New-McpContent.ps1
+++ b/src/Public/New-McpContent.ps1
@@ -1,10 +1,11 @@
function New-McpContent {
<#
.SYNOPSIS
- Creates a content block (text, image, audio, resource link or embedded resource) for tool results.
+ Creates a content block (text, image, audio, resource link or embedded resource) for tool results and prompt messages.
.DESCRIPTION
- Content blocks are the items of CallToolResult.content. Return them from a tool handler, or pass them
- to New-McpToolResult. Binary data may be given as byte[] or as a base64 string.
+ Content blocks are the items of CallToolResult.content and the content of prompt messages. Return them
+ from a tool or prompt handler, or pass them to New-McpToolResult or New-McpPromptMessage. Binary data
+ may be given as byte[] or as a base64 string.
.PARAMETER Text
The text of a text block.
.PARAMETER Image
@@ -29,8 +30,13 @@ function New-McpContent {
The text contents of an embedded resource.
.PARAMETER ResourceBlob
The binary contents (byte[] or base64 string) of an embedded resource.
+ .PARAMETER Icons
+ Icon objects of a resource link (hashtables with src, and optionally mimeType, sizes, theme).
+ .PARAMETER ResourceMeta
+ Additional _meta members of the contents of an embedded resource.
.PARAMETER Annotations
- Annotations (audience, priority, lastModified) of the block.
+ Annotations of the block: Audience (user, assistant), Priority (0 to 1), LastModified (DateTime or
+ ISO 8601 text).
.PARAMETER Meta
Additional _meta members of the block.
.EXAMPLE
@@ -91,7 +97,13 @@ function New-McpContent {
[Parameter(ParameterSetName = 'EmbeddedResource')]
[object] $ResourceBlob,
- [hashtable] $Annotations,
+ [Parameter(ParameterSetName = 'ResourceLink')]
+ [object[]] $Icons,
+
+ [Parameter(ParameterSetName = 'EmbeddedResource')]
+ [object] $ResourceMeta,
+
+ [object] $Annotations,
[hashtable] $Meta
)
@@ -120,6 +132,8 @@ function New-McpContent {
if ($Description) { $block['description'] = $Description }
if ($MimeType) { $block['mimeType'] = $MimeType }
if ($Size -ge 0) { $block['size'] = $Size }
+ $iconList = ConvertTo-McpIconList -Icons $Icons
+ if ($null -ne $iconList) { $block['icons'] = $iconList }
}
'EmbeddedResource' {
if (-not $PSBoundParameters.ContainsKey('ResourceText') -and $null -eq $ResourceBlob) {
@@ -128,11 +142,14 @@ function New-McpContent {
$resource = [ordered]@{ uri = $EmbeddedResource }
if ($MimeType) { $resource['mimeType'] = $MimeType }
if ($PSBoundParameters.ContainsKey('ResourceText')) { $resource['text'] = $ResourceText } else { $resource['blob'] = ConvertTo-McpBase64 -Data $ResourceBlob }
+ $resourceMetaObject = ConvertTo-McpMetaObject -Meta $ResourceMeta
+ if ($null -ne $resourceMetaObject) { $resource['_meta'] = $resourceMetaObject }
$block['type'] = 'resource'
$block['resource'] = $resource
}
}
- if ($Annotations -and $Annotations.Count -gt 0) { $block['annotations'] = $Annotations }
+ $annotationObject = ConvertTo-McpContentAnnotation -Annotations $Annotations
+ if ($null -ne $annotationObject) { $block['annotations'] = $annotationObject }
if ($Meta -and $Meta.Count -gt 0) { $block['_meta'] = $Meta }
$object = [pscustomobject] $block
$object.PSObject.TypeNames.Insert(0, 'Mcp.Content')
diff --git a/src/Public/New-McpPromptMessage.ps1 b/src/Public/New-McpPromptMessage.ps1
new file mode 100644
index 0000000..543dcb9
--- /dev/null
+++ b/src/Public/New-McpPromptMessage.ps1
@@ -0,0 +1,46 @@
+function New-McpPromptMessage {
+ <#
+ .SYNOPSIS
+ Creates a prompt message (role and one content block) to return from a prompt handler.
+ .DESCRIPTION
+ Prompt handlers return messages; plain strings and content blocks already become user messages. Use
+ this command for assistant messages or to set the content block explicitly.
+ .PARAMETER Role
+ The speaker: user (default) or assistant.
+ .PARAMETER Text
+ The text of a text content block.
+ .PARAMETER Content
+ A content block from New-McpContent (text, image, audio, resource link or embedded resource).
+ .EXAMPLE
+ New-McpPromptMessage -Role assistant -Text 'Which city do you mean?'
+ .EXAMPLE
+ New-McpPromptMessage -Content (New-McpContent -Image $bytes -MimeType image/png)
+ .OUTPUTS
+ Mcp.PromptMessage
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object only.')]
+ [CmdletBinding(DefaultParameterSetName = 'Text')]
+ [OutputType('Mcp.PromptMessage')]
+ param(
+ [ValidateSet('user', 'assistant')]
+ [string] $Role = 'user',
+
+ [Parameter(ParameterSetName = 'Text', Mandatory, Position = 0)]
+ [AllowEmptyString()]
+ [string] $Text,
+
+ [Parameter(ParameterSetName = 'Content', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Content
+ )
+
+ if ($PSCmdlet.ParameterSetName -eq 'Content' -and -not (Test-McpContentObject -Value $Content)) {
+ throw [System.ArgumentException]::new('-Content must be a content block (New-McpContent).')
+ }
+ $message = [pscustomobject]@{
+ role = $Role.ToLowerInvariant()
+ content = if ($PSCmdlet.ParameterSetName -eq 'Text') { New-McpContent -Text $Text } else { $Content }
+ }
+ $message.PSObject.TypeNames.Insert(0, 'Mcp.PromptMessage')
+ $message
+}
diff --git a/src/Public/New-McpResourceContent.ps1 b/src/Public/New-McpResourceContent.ps1
new file mode 100644
index 0000000..5a9ab6c
--- /dev/null
+++ b/src/Public/New-McpResourceContent.ps1
@@ -0,0 +1,55 @@
+function New-McpResourceContent {
+ <#
+ .SYNOPSIS
+ Creates resource contents (text or binary) to return from a resource handler.
+ .DESCRIPTION
+ Resource handlers may return strings, byte arrays or objects; use this command to return several
+ contents, contents of another URI (for example the files of a directory), or to set the MIME type and
+ _meta of a content explicitly.
+ .PARAMETER Text
+ The text contents.
+ .PARAMETER Blob
+ The binary contents as byte[] or base64 string.
+ .PARAMETER Uri
+ The URI of the contents; defaults to the requested URI.
+ .PARAMETER MimeType
+ The MIME type of the contents.
+ .PARAMETER Meta
+ Additional _meta members of the contents.
+ .EXAMPLE
+ New-McpResourceContent -Text '{ "ok": true }' -MimeType application/json
+ .OUTPUTS
+ Mcp.ResourceContents
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory object only.')]
+ [CmdletBinding(DefaultParameterSetName = 'Text')]
+ [OutputType('Mcp.ResourceContents')]
+ param(
+ [Parameter(ParameterSetName = 'Text', Mandatory, Position = 0)]
+ [AllowEmptyString()]
+ [string] $Text,
+
+ [Parameter(ParameterSetName = 'Blob', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Blob,
+
+ [string] $Uri,
+
+ [string] $MimeType,
+
+ [object] $Meta
+ )
+
+ if ($Uri -and -not (Test-McpResourceUri -Uri $Uri)) {
+ throw [System.ArgumentException]::new("'$Uri' is not an absolute URI.")
+ }
+ $content = [ordered]@{}
+ if ($Uri) { $content['uri'] = $Uri }
+ if ($MimeType) { $content['mimeType'] = $MimeType }
+ if ($PSCmdlet.ParameterSetName -eq 'Text') { $content['text'] = $Text } else { $content['blob'] = ConvertTo-McpBase64 -Data $Blob }
+ $metaObject = ConvertTo-McpMetaObject -Meta $Meta
+ if ($null -ne $metaObject) { $content['_meta'] = $metaObject }
+ $object = [pscustomobject] $content
+ $object.PSObject.TypeNames.Insert(0, 'Mcp.ResourceContents')
+ $object
+}
diff --git a/src/Public/New-McpServer.ps1 b/src/Public/New-McpServer.ps1
index defa97d..2316198 100644
--- a/src/Public/New-McpServer.ps1
+++ b/src/Public/New-McpServer.ps1
@@ -5,8 +5,9 @@ function New-McpServer {
.DESCRIPTION
The server object carries the implementation info (name, version, title, description, website URL,
icons), the instructions for clients, the supported protocol versions and the runtime options. It is
- a plain object (PSTypeName Mcp.Server); tools are registered on it with Register-McpTool. With
- -SetDefault the object becomes the default for the other server commands of this session.
+ a plain object (PSTypeName Mcp.Server); tools, resources and prompts are registered on it with
+ Register-McpTool, Register-McpResource and Register-McpPrompt. With -SetDefault the object becomes the
+ default for the other server commands of this session.
.PARAMETER Name
The implementation name reported as serverInfo.name.
.PARAMETER Version
@@ -24,15 +25,16 @@ function New-McpServer {
.PARAMETER SupportedVersions
The protocol revisions the server speaks. This milestone supports 2026-07-28 only.
.PARAMETER MaxConcurrency
- The maximum number of tool handlers running at the same time (the size of the worker runspace pool).
+ The maximum number of handlers running at the same time (the size of the worker runspace pool).
.PARAMETER RequestTimeoutSeconds
- Seconds after which a running tool handler is stopped and the request answered with an error; 0 disables the timeout.
+ Seconds after which a running handler is stopped and the request answered with an error; 0 disables the timeout.
.PARAMETER DefaultTtlMs
- The ttlMs caching hint sent with server/discover and tools/list results.
+ The ttlMs caching hint sent with server/discover, the list results and resources/read (unless the
+ resource sets its own with Register-McpResource -TtlMs).
.PARAMETER DefaultCacheScope
- The cacheScope caching hint sent with server/discover and tools/list results (public or private).
+ The cacheScope caching hint (public or private) sent with the same results.
.PARAMETER PageSize
- The number of tools per tools/list page.
+ The number of items per page of tools/list, resources/list, resources/templates/list and prompts/list.
.PARAMETER LogLevel
The minimum level of diagnostics written to stderr (default: warning).
.PARAMETER NoServerInfo
@@ -104,10 +106,13 @@ function New-McpServer {
Title = $Title
Description = $Description
WebsiteUrl = $WebsiteUrl
- Icons = $Icons
+ Icons = ConvertTo-McpIconList -Icons $Icons
Instructions = $Instructions
SupportedVersions = [string[]] $SupportedVersions
Tools = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
+ Resources = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
+ ResourceTemplates = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
+ Prompts = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal)
Options = @{
MaxConcurrency = $MaxConcurrency
RequestTimeoutSeconds = $RequestTimeoutSeconds
@@ -116,7 +121,8 @@ function New-McpServer {
PageSize = $PageSize
LogLevel = $LogLevel
IncludeServerInfo = -not $NoServerInfo
- # tools.listChanged is advertised once subscriptions/listen can deliver the notification (milestone M4).
+ # listChanged (tools, prompts, resources) is advertised once subscriptions/listen can deliver the
+ # notifications (milestone M4).
ListChanged = $false
}
State = @{
diff --git a/src/Public/Read-McpResource.ps1 b/src/Public/Read-McpResource.ps1
new file mode 100644
index 0000000..0922e9d
--- /dev/null
+++ b/src/Public/Read-McpResource.ps1
@@ -0,0 +1,76 @@
+function Read-McpResource {
+ <#
+ .SYNOPSIS
+ Reads resources (resources/read) and returns their contents.
+ .DESCRIPTION
+ Every content of the result is returned as Mcp.ResourceContent (Uri, MimeType, Text or Blob; GetBytes()
+ returns the bytes of either). Results are cached per URI for the ttlMs the server sent with them. A URI
+ the server does not know is reported as a non-terminating ObjectNotFound error, both for the -32602
+ error of protocol version 2026-07-28 and the -32002 of earlier revisions; other errors are thrown.
+ .PARAMETER Uri
+ The resource URIs; accepts pipeline input, including Mcp.Resource objects from Get-McpResource.
+ .PARAMETER Session
+ The session; defaults to the default session.
+ .PARAMETER Refresh
+ Read from the server even when a cached result is fresh.
+ .PARAMETER TimeoutSeconds
+ The timeout for each read; defaults to the session's request timeout.
+ .PARAMETER LogLevel
+ Ask for notifications/message at this level and above (see the session's Log).
+ .EXAMPLE
+ Read-McpResource -Uri 'config://app' | Select-Object -ExpandProperty Text
+ .EXAMPLE
+ [System.IO.File]::WriteAllBytes('logo.png', (Read-McpResource 'images://logo').GetBytes())
+ .OUTPUTS
+ Mcp.ResourceContent
+ #>
+ [CmdletBinding()]
+ [OutputType('Mcp.ResourceContent')]
+ param(
+ [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
+ [ValidateNotNullOrEmpty()]
+ [string[]] $Uri,
+
+ [object] $Session,
+
+ [switch] $Refresh,
+
+ [ValidateRange(0, 86400)]
+ [int] $TimeoutSeconds = 0,
+
+ [McpLoggingLevel] $LogLevel
+ )
+
+ begin {
+ $target = Resolve-McpSession -Session $Session
+ $level = if ($PSBoundParameters.ContainsKey('LogLevel')) { $LogLevel } else { $target.LogLevel }
+ }
+ process {
+ foreach ($item in $Uri) {
+ $key = "resources/read $item"
+ $entry = if ($Refresh) { $null } else { Get-McpClientCacheEntry -Session $target -Key $key }
+ if ($null -ne $entry) {
+ foreach ($content in $entry.Value) { $content }
+ continue
+ }
+ try {
+ $result = Invoke-McpClientRequest -Session $target -Method 'resources/read' -Params ([ordered]@{ uri = $item }) -LogLevel $level -TimeoutMs ($TimeoutSeconds * 1000)
+ } catch [McpProtocolException] {
+ if (-not (Test-McpResourceNotFoundError -Exception $_.Exception)) { throw }
+ $record = [System.Management.Automation.ErrorRecord]::new(
+ [System.Management.Automation.ItemNotFoundException]::new("The server has no resource '$item': $($_.Exception.Message)", $_.Exception),
+ 'McpResourceNotFound',
+ [System.Management.Automation.ErrorCategory]::ObjectNotFound,
+ $item)
+ $PSCmdlet.WriteError($record)
+ continue
+ }
+ if ($result -isnot [System.Collections.IDictionary] -or -not $result.Contains('contents')) {
+ 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)
+ foreach ($content in $contents) { $content }
+ }
+ }
+}
diff --git a/src/Public/Register-McpPrompt.ps1 b/src/Public/Register-McpPrompt.ps1
new file mode 100644
index 0000000..219c993
--- /dev/null
+++ b/src/Public/Register-McpPrompt.ps1
@@ -0,0 +1,146 @@
+function Register-McpPrompt {
+ <#
+ .SYNOPSIS
+ Registers a prompt template (a script block or command that produces messages) on a server.
+ .DESCRIPTION
+ A prompt is listed by prompts/list and rendered by prompts/get. Its arguments are strings; unless
+ -Arguments is given they are derived from the handler's parameters: a mandatory parameter is a
+ required argument, the comment-based help describes it, and a ValidateSet offers its values as argument
+ completion. Argument values are converted to the parameter types; a parameter named Context receives the
+ request context. With -Arguments, a handler that declares a parameter named Arguments receives all
+ argument values as a dictionary instead.
+
+ The handler runs in the server's worker runspace pool. Its output becomes the messages: strings are
+ joined into one user text message, content blocks (New-McpContent) become user messages, and
+ New-McpPromptMessage sets the role (user or assistant) or the content explicitly.
+ .PARAMETER Name
+ The prompt name; defaults to the command name with -Command.
+ .PARAMETER ScriptBlock
+ The handler as a script block.
+ .PARAMETER Command
+ The handler as a command name or CommandInfo of a function, cmdlet or script file.
+ .PARAMETER Arguments
+ The arguments as hashtables with Name and optionally Title, Description and Required (or plain names);
+ replaces the arguments derived from the handler's parameters.
+ .PARAMETER Title
+ A human-readable title.
+ .PARAMETER Description
+ The prompt description; defaults to the synopsis of the handler's comment-based help. Clients show it
+ in their prompt lists, so every prompt should have one.
+ .PARAMETER Icons
+ Icon objects (hashtables with src, and optionally mimeType, sizes, theme).
+ .PARAMETER Meta
+ Additional _meta members of the prompt definition.
+ .PARAMETER Completion
+ Argument completion: a hashtable of argument name to a list of values (offered when they start with
+ the typed text) or a script block that receives the parameters it declares of Value, Argument,
+ Arguments and Context and returns the candidates. Replaces the values derived from ValidateSet.
+ .PARAMETER Server
+ The server to register on; defaults to the server set with New-McpServer -SetDefault.
+ .PARAMETER Force
+ Replace an existing registration with the same name.
+ .PARAMETER PassThru
+ Return the registration object.
+ .EXAMPLE
+ Register-McpPrompt -Name 'summarize' -Description 'Summarises a text.' -ScriptBlock {
+ param([Parameter(Mandatory)][string] $Text)
+ "Summarise the following text in three sentences:`n$Text"
+ }
+ .OUTPUTS
+ Mcp.PromptRegistration (with -PassThru)
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Changes an in-memory registry only.')]
+ [CmdletBinding(DefaultParameterSetName = 'ScriptBlock')]
+ [OutputType('Mcp.PromptRegistration')]
+ param(
+ [Parameter(ParameterSetName = 'ScriptBlock', Mandatory, Position = 0)]
+ [Parameter(ParameterSetName = 'Command')]
+ [ValidateNotNullOrEmpty()]
+ [string] $Name,
+
+ [Parameter(ParameterSetName = 'ScriptBlock', Mandatory, Position = 1)]
+ [scriptblock] $ScriptBlock,
+
+ [Parameter(ParameterSetName = 'Command', Mandatory)]
+ [ValidateNotNull()]
+ [object] $Command,
+
+ [object[]] $Arguments,
+
+ [string] $Title,
+
+ [string] $Description,
+
+ [object[]] $Icons,
+
+ [object] $Meta,
+
+ [System.Collections.IDictionary] $Completion,
+
+ [object] $Server,
+
+ [switch] $Force,
+
+ [switch] $PassThru
+ )
+
+ $target = Resolve-McpServer -Server $Server
+ if ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') {
+ $descriptor = New-McpHandlerDescriptor -Prefix 'McpPrompt' -Key $Name -ScriptBlock $ScriptBlock
+ } else {
+ $commandInfo = Resolve-McpHandlerCommand -Command $Command -Cmdlet $PSCmdlet
+ if (-not $Name) { $Name = $commandInfo.Name }
+ $descriptor = New-McpHandlerDescriptor -Prefix 'McpPrompt' -Key $Name -CommandInfo $commandInfo
+ }
+ if ($target.Prompts.Contains($Name) -and -not $Force) {
+ throw [System.InvalidOperationException]::new("A prompt named '$Name' is already registered; use -Force to replace it.")
+ }
+ $handler = $descriptor.Handler
+ $help = Get-McpCommandHelp -Ast $descriptor.Ast
+ if (-not $Description) {
+ $Description = if ($help.Synopsis) { $help.Synopsis } elseif ($help.Description) { $help.Description } else { $null }
+ }
+
+ $derivedCompletion = [ordered]@{}
+ if ($PSBoundParameters.ContainsKey('Arguments')) {
+ $argumentList = ConvertTo-McpPromptArgumentList -Arguments $Arguments
+ if ($handler.ParameterNames -contains 'Arguments' -and @($argumentList | Where-Object { $_['name'] -ieq 'Arguments' }).Count -eq 0) {
+ $handler.ArgumentStyle = 'Arguments'
+ }
+ } else {
+ $generated = New-McpToolInputSchema -Parameters $descriptor.Parameters -Help $help -Defaults (Get-McpParameterDefaultValue -Ast $descriptor.Ast) -AllowAdditionalProperties
+ $handler.ParameterTypes = $generated.ParameterTypes
+ $required = @($generated.Schema['required'])
+ $argumentList = @(foreach ($entry in @(if ($generated.Schema.Contains('properties')) { $generated.Schema['properties'].GetEnumerator() })) {
+ $argument = [ordered]@{ name = [string] $entry.Key }
+ if ($entry.Value.Contains('description')) { $argument['description'] = [string] $entry.Value['description'] }
+ if ($required -contains $entry.Key) { $argument['required'] = $true }
+ if ($entry.Value.Contains('enum')) { $derivedCompletion[[string] $entry.Key] = @($entry.Value['enum'] | ForEach-Object { [string] $_ }) }
+ $argument
+ })
+ }
+ $argumentNames = [string[]] @($argumentList | ForEach-Object { $_['name'] })
+ foreach ($key in @($derivedCompletion.Keys)) {
+ if ($null -ne $Completion -and $Completion.Contains($key)) { $derivedCompletion.Remove($key) }
+ }
+ if ($null -ne $Completion) {
+ foreach ($key in $Completion.Keys) { $derivedCompletion[$key] = $Completion[$key] }
+ }
+ if (-not $Description) {
+ Write-Warning "The prompt '$Name' has no description; clients show descriptions in their prompt lists."
+ }
+
+ $registration = [pscustomobject]@{
+ PSTypeName = 'Mcp.PromptRegistration'
+ Name = $Name
+ Title = $Title
+ Description = $Description
+ Arguments = $argumentList
+ Icons = ConvertTo-McpIconList -Icons $Icons
+ Meta = ConvertTo-McpMetaObject -Meta $Meta
+ Handler = $handler
+ Completion = ConvertTo-McpCompletionSource -Completion $derivedCompletion -ArgumentNames $argumentNames -Key $Name
+ }
+ $target.Prompts[$Name] = $registration
+ if ($PassThru) { $registration }
+}
diff --git a/src/Public/Register-McpResource.ps1 b/src/Public/Register-McpResource.ps1
new file mode 100644
index 0000000..b1a49cd
--- /dev/null
+++ b/src/Public/Register-McpResource.ps1
@@ -0,0 +1,248 @@
+function Register-McpResource {
+ <#
+ .SYNOPSIS
+ Registers a resource (fixed content, a file, a handler) or a resource template (a handler or a directory) on a server.
+ .DESCRIPTION
+ A resource has a URI and is listed by resources/list; a resource template has an RFC 6570 URI template
+ (levels 1 to 3, for example 'weather://{city}/current' or 'docs://{+path}') and is listed by
+ resources/templates/list. resources/read serves an exact resource URI first and otherwise the first
+ template, in registration order, that matches the URI.
+
+ The content comes from one source:
+ - -Content: fixed text (string) or binary data (byte[]), answered without running user code.
+ - -ScriptBlock or -Command: a handler that runs in the server's worker runspace pool. It receives the
+ parameters it declares of: Uri (the requested URI), Variables (the template variables as a
+ dictionary), every template variable by name, and Context (the request context). Strings become text
+ contents, byte arrays blob contents, FileInfo objects the contents of the file, other objects JSON
+ text; New-McpResourceContent returns several contents or sets their MIME type and _meta. A handler
+ that returns nothing or throws ItemNotFoundException reports the resource as not found.
+ - -Path to a file: the file, read at request time (text for text MIME types, otherwise a blob). The URI
+ defaults to the file:// URI of the file.
+ - -Path to a directory: a template for every file below the directory, 'file:////{+path}' or
+ '/{+path}'. Paths that leave the directory ('..', absolute paths, symbolic links to the outside)
+ are reported as not found.
+ .PARAMETER Uri
+ The resource URI (an absolute URI such as 'config://app' or 'https://example.com/data.json'); with -Path
+ to a directory, the base of the template URI.
+ .PARAMETER UriTemplate
+ The URI template of a resource template.
+ .PARAMETER Path
+ A file or directory to expose.
+ .PARAMETER Content
+ Fixed content: a string (text) or byte[] (blob).
+ .PARAMETER ScriptBlock
+ The handler as a script block.
+ .PARAMETER Command
+ The handler as a command name or CommandInfo of a function, cmdlet or script file.
+ .PARAMETER Name
+ The name of the resource or template; defaults to the URI, the URI template or the file name.
+ .PARAMETER Title
+ A human-readable title.
+ .PARAMETER Description
+ A description of the resource.
+ .PARAMETER MimeType
+ The MIME type of the content. Defaults to text/plain for text and application/octet-stream for binary
+ -Content, and to the type derived from the file extension for -Path.
+ .PARAMETER Size
+ The size of the raw content in bytes, listed with the resource (computed for -Content and files).
+ .PARAMETER Annotations
+ Annotations: Audience (user, assistant), Priority (0 to 1), LastModified (DateTime or ISO 8601 text).
+ .PARAMETER Icons
+ Icon objects (hashtables with src, and optionally mimeType, sizes, theme).
+ .PARAMETER Meta
+ Additional _meta members of the resource definition.
+ .PARAMETER TtlMs
+ The ttlMs caching hint of resources/read results of this resource; defaults to the server's.
+ .PARAMETER CacheScope
+ The cacheScope caching hint (public or private) of resources/read results; defaults to the server's.
+ .PARAMETER Completion
+ Argument completion for template variables: a hashtable of variable name to a list of values (offered
+ when they start with the typed text) or a script block that receives the parameters it declares of
+ Value, Argument, Arguments and Context and returns the candidates.
+ .PARAMETER Server
+ The server to register on; defaults to the server set with New-McpServer -SetDefault.
+ .PARAMETER Force
+ Replace an existing registration with the same URI or URI template.
+ .PARAMETER PassThru
+ Return the registration object.
+ .EXAMPLE
+ Register-McpResource -Uri 'config://app' -Name 'app-config' -MimeType 'application/json' -Content '{ "mode": "demo" }'
+ .EXAMPLE
+ Register-McpResource -UriTemplate 'weather://{city}/current' -Name 'current-weather' -ScriptBlock { param($city) Get-Weather -Location $city }
+ .EXAMPLE
+ Register-McpResource -Path ./docs -Uri 'docs://' -Description 'Project documentation'
+ .OUTPUTS
+ Mcp.ResourceRegistration (with -PassThru)
+ #>
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Changes an in-memory registry only.')]
+ [CmdletBinding(DefaultParameterSetName = 'Uri')]
+ [OutputType('Mcp.ResourceRegistration')]
+ param(
+ [Parameter(ParameterSetName = 'Uri', Mandatory, Position = 0)]
+ [Parameter(ParameterSetName = 'Path')]
+ [ValidateNotNullOrEmpty()]
+ [string] $Uri,
+
+ [Parameter(ParameterSetName = 'UriTemplate', Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $UriTemplate,
+
+ [Parameter(ParameterSetName = 'Path', Mandatory)]
+ [ValidateNotNullOrEmpty()]
+ [string] $Path,
+
+ [Parameter(ParameterSetName = 'Uri')]
+ [object] $Content,
+
+ [Parameter(ParameterSetName = 'Uri')]
+ [Parameter(ParameterSetName = 'UriTemplate')]
+ [scriptblock] $ScriptBlock,
+
+ [Parameter(ParameterSetName = 'Uri')]
+ [Parameter(ParameterSetName = 'UriTemplate')]
+ [object] $Command,
+
+ [string] $Name,
+
+ [string] $Title,
+
+ [string] $Description,
+
+ [string] $MimeType,
+
+ [ValidateRange(0, [long]::MaxValue)]
+ [long] $Size,
+
+ [object] $Annotations,
+
+ [object[]] $Icons,
+
+ [object] $Meta,
+
+ [ValidateRange(0, [int]::MaxValue)]
+ [int] $TtlMs,
+
+ [ValidateSet('public', 'private')]
+ [string] $CacheScope,
+
+ [Parameter(ParameterSetName = 'UriTemplate')]
+ [Parameter(ParameterSetName = 'Path')]
+ [System.Collections.IDictionary] $Completion,
+
+ [object] $Server,
+
+ [switch] $Force,
+
+ [switch] $PassThru
+ )
+
+ $target = Resolve-McpServer -Server $Server
+ $sources = @('Content', 'ScriptBlock', 'Command') | Where-Object { $PSBoundParameters.ContainsKey($_) }
+ $kind = 'Resource'
+ $source = $null
+ $template = $null
+ $handler = $null
+ $filePath = $null
+
+ switch ($PSCmdlet.ParameterSetName) {
+ 'Uri' {
+ if (@($sources).Count -ne 1) { throw [System.ArgumentException]::new('A resource needs exactly one of -Content, -ScriptBlock and -Command.') }
+ $source = if ($sources -eq 'Content') { 'Content' } else { 'Handler' }
+ }
+ 'UriTemplate' {
+ if (@($sources).Count -ne 1) { throw [System.ArgumentException]::new('A resource template needs exactly one of -ScriptBlock and -Command.') }
+ $kind = 'Template'
+ $source = 'Handler'
+ }
+ 'Path' {
+ $resolved = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
+ if ([System.IO.Directory]::Exists($resolved)) {
+ $kind = 'Template'
+ $source = 'Directory'
+ $filePath = [System.IO.Path]::TrimEndingDirectorySeparator([System.IO.Path]::GetFullPath($resolved))
+ $base = if ($Uri) { $Uri } else { [System.Uri]::new($filePath, [System.UriKind]::Absolute).AbsoluteUri }
+ $UriTemplate = if ($base.EndsWith('/')) { $base + '{+path}' } else { $base + '/{+path}' }
+ if (-not $Name) { $Name = [System.IO.Path]::GetFileName($filePath) }
+ } elseif ([System.IO.File]::Exists($resolved)) {
+ $source = 'File'
+ $filePath = [System.IO.Path]::GetFullPath($resolved)
+ if (-not $Uri) { $Uri = [System.Uri]::new($filePath, [System.UriKind]::Absolute).AbsoluteUri }
+ if (-not $Name) { $Name = [System.IO.Path]::GetFileName($filePath) }
+ if (-not $MimeType) { $MimeType = Get-McpMimeType -Path $filePath }
+ } else {
+ throw [System.Management.Automation.ItemNotFoundException]::new("The path '$Path' does not exist.")
+ }
+ }
+ }
+
+ if ($kind -eq 'Resource') {
+ if (-not (Test-McpResourceUri -Uri $Uri)) { throw [System.ArgumentException]::new("'$Uri' is not an absolute URI.") }
+ if ($target.Resources.Contains($Uri) -and -not $Force) {
+ throw [System.InvalidOperationException]::new("A resource with the URI '$Uri' is already registered; use -Force to replace it.")
+ }
+ if (-not $Name) { $Name = $Uri }
+ $key = $Uri
+ } else {
+ $template = ConvertFrom-McpUriTemplate -Template $UriTemplate
+ if ($target.ResourceTemplates.Contains($UriTemplate) -and -not $Force) {
+ throw [System.InvalidOperationException]::new("A resource template '$UriTemplate' is already registered; use -Force to replace it.")
+ }
+ if (-not $Name) { $Name = $UriTemplate }
+ $key = $UriTemplate
+ }
+
+ if ($source -eq 'Handler') {
+ $descriptor = if ($PSBoundParameters.ContainsKey('ScriptBlock')) {
+ New-McpHandlerDescriptor -Prefix 'McpResource' -Key $key -ScriptBlock $ScriptBlock
+ } else {
+ New-McpHandlerDescriptor -Prefix 'McpResource' -Key $key -CommandInfo (Resolve-McpHandlerCommand -Command $Command -Cmdlet $PSCmdlet)
+ }
+ $handler = $descriptor.Handler
+ if (-not $Description) {
+ $help = Get-McpCommandHelp -Ast $descriptor.Ast
+ $Description = if ($help.Synopsis) { $help.Synopsis } elseif ($help.Description) { $help.Description } else { $null }
+ }
+ }
+ if ($source -eq 'Content') {
+ if ($Content -is [string]) {
+ if (-not $MimeType) { $MimeType = 'text/plain' }
+ } elseif ($null -ne $Content -and ($Content -is [byte[]] -or $Content -is [System.Collections.IEnumerable])) {
+ $Content = [System.Convert]::FromBase64String((ConvertTo-McpBase64 -Data $Content))
+ if (-not $MimeType) { $MimeType = 'application/octet-stream' }
+ } else {
+ throw [System.ArgumentException]::new('-Content must be a string or a byte[].')
+ }
+ }
+
+ $completionSources = $null
+ if ($kind -eq 'Template') {
+ $completionSources = ConvertTo-McpCompletionSource -Completion $Completion -ArgumentNames $template.Variables -Key $key
+ }
+
+ $registration = [pscustomobject]@{
+ PSTypeName = 'Mcp.ResourceRegistration'
+ Kind = $kind
+ Uri = if ($kind -eq 'Resource') { $Uri } else { $null }
+ UriTemplate = if ($kind -eq 'Template') { $UriTemplate } else { $null }
+ Template = $template
+ Name = $Name
+ Title = $Title
+ Description = $Description
+ MimeType = $MimeType
+ Size = if ($PSBoundParameters.ContainsKey('Size')) { $Size } else { $null }
+ Annotations = ConvertTo-McpContentAnnotation -Annotations $Annotations
+ Icons = ConvertTo-McpIconList -Icons $Icons
+ Meta = ConvertTo-McpMetaObject -Meta $Meta
+ TtlMs = if ($PSBoundParameters.ContainsKey('TtlMs')) { $TtlMs } else { $null }
+ CacheScope = if ($CacheScope) { $CacheScope } else { $null }
+ Source = $source
+ Content = $null
+ Path = $filePath
+ Handler = $handler
+ Completion = $completionSources
+ }
+ # 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 ($PassThru) { $registration }
+}
diff --git a/src/Public/Register-McpTool.ps1 b/src/Public/Register-McpTool.ps1
index fedff7b..250bebf 100644
--- a/src/Public/Register-McpTool.ps1
+++ b/src/Public/Register-McpTool.ps1
@@ -97,89 +97,17 @@ function Register-McpTool {
)
$target = Resolve-McpServer -Server $Server
- $handler = @{
- Kind = $null
- CommandName = $null
- Definition = $null
- ModuleName = $null
- ModulePath = $null
- CommandInfo = $null
- ScriptBlock = $null
- ArgumentStyle = 'Splat'
- ContextParameter = $null
- ParameterTypes = @{}
- }
- $ast = $null
- $parameters = $null
-
if ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') {
if (-not $Name) { throw [System.ArgumentException]::new('A script block tool needs a -Name.') }
- $handler.Kind = 'ScriptBlock'
- $handler.ScriptBlock = $ScriptBlock
- $handler.Definition = $ScriptBlock.ToString()
- $handler.CommandName = 'McpTool_' + ($Name -replace '[^A-Za-z0-9_]', '_')
- $ast = $ScriptBlock.Ast
- $temporaryName = 'McpTemporaryTool_' + [guid]::NewGuid().ToString('n')
- Set-Item -Path "function:script:$temporaryName" -Value $ScriptBlock
- try {
- $parameters = (Get-Command -Name $temporaryName -CommandType Function).Parameters
- } finally {
- Remove-Item -Path "function:script:$temporaryName" -ErrorAction SilentlyContinue
- }
+ $descriptor = New-McpHandlerDescriptor -Prefix 'McpTool' -Key $Name -ScriptBlock $ScriptBlock
} else {
- $commandInfo = $Command
- if ($Command -is [string]) {
- # Resolve the name in the caller's scope first so that functions of the calling script are found;
- # functions defined in nested scopes must be passed as CommandInfo (Get-Command) or script block.
- $commandInfo = $PSCmdlet.SessionState.InvokeCommand.GetCommand($Command, [System.Management.Automation.CommandTypes]::All)
- if ($null -eq $commandInfo) {
- $commandInfo = Get-Command -Name $Command -ErrorAction SilentlyContinue | Select-Object -First 1
- }
- if ($null -eq $commandInfo) {
- throw [System.Management.Automation.CommandNotFoundException]::new("The command '$Command' was not found. Pass the result of Get-Command for functions defined in a nested scope.")
- }
- }
- if ($commandInfo -isnot [System.Management.Automation.CommandInfo]) {
- throw [System.ArgumentException]::new('-Command must be a command name or a CommandInfo object.')
- }
- if ($commandInfo -is [System.Management.Automation.AliasInfo]) {
- $commandInfo = $commandInfo.ResolvedCommand
- }
- $handler.CommandInfo = $commandInfo
+ $commandInfo = Resolve-McpHandlerCommand -Command $Command -Cmdlet $PSCmdlet
if (-not $Name) { $Name = $commandInfo.Name }
- switch ($commandInfo.GetType().Name) {
- 'FunctionInfo' {
- $handler.Kind = 'Function'
- $handler.CommandName = $commandInfo.Name
- $ast = $commandInfo.ScriptBlock.Ast
- if ($commandInfo.Module -and $commandInfo.Module.Path) {
- $handler.ModuleName = $commandInfo.Module.Name
- $handler.ModulePath = $commandInfo.Module.Path
- } else {
- $handler.Definition = $commandInfo.Definition
- }
- }
- 'CmdletInfo' {
- $handler.Kind = 'Cmdlet'
- $handler.CommandName = $commandInfo.Name
- if ($commandInfo.Module) {
- $handler.ModuleName = $commandInfo.Module.Name
- $handler.ModulePath = $commandInfo.Module.Path
- } elseif ($commandInfo.ModuleName) {
- $handler.ModuleName = $commandInfo.ModuleName
- }
- }
- 'ExternalScriptInfo' {
- $handler.Kind = 'Script'
- $handler.CommandName = $commandInfo.Path
- $ast = $commandInfo.ScriptBlock.Ast
- }
- default {
- throw [System.ArgumentException]::new("Commands of type $($commandInfo.CommandType) cannot be registered as tools.")
- }
- }
- $parameters = $commandInfo.Parameters
+ $descriptor = New-McpHandlerDescriptor -Prefix 'McpTool' -Key $Name -CommandInfo $commandInfo
}
+ $handler = $descriptor.Handler
+ $ast = $descriptor.Ast
+ $parameters = $descriptor.Parameters
if ($Name -notmatch $script:McpToolNamePattern) {
throw [System.ArgumentException]::new("'$Name' is not a valid tool name: 1-128 characters from A-Z, a-z, 0-9, '_', '-' and '.'.")
@@ -193,9 +121,6 @@ function Register-McpTool {
$Description = if ($help.Synopsis) { $help.Synopsis } elseif ($help.Description) { $help.Description } else { $null }
}
if ($null -ne $parameters) {
- foreach ($entry in $parameters.GetEnumerator()) {
- if ($entry.Key -ieq 'Context') { $handler.ContextParameter = $entry.Value.Name }
- }
$generated = New-McpToolInputSchema -Parameters $parameters -Help $help -Defaults (Get-McpParameterDefaultValue -Ast $ast) -AllowAdditionalProperties:$AllowAdditionalProperties
$handler.ParameterTypes = $generated.ParameterTypes
$schema = $generated.Schema
@@ -233,7 +158,7 @@ function Register-McpTool {
InputSchema = $schema
OutputSchema = $outputSchemaObject
Annotations = ConvertTo-McpAnnotationObject -Annotations $Annotations
- Icons = $Icons
+ Icons = ConvertTo-McpIconList -Icons $Icons
Meta = $Meta
HeaderParameters = $headerParameters
Handler = $handler
diff --git a/src/Public/Write-McpLog.ps1 b/src/Public/Write-McpLog.ps1
index eb795bb..4c23d84 100644
--- a/src/Public/Write-McpLog.ps1
+++ b/src/Public/Write-McpLog.ps1
@@ -13,7 +13,7 @@ function Write-McpLog {
.PARAMETER Context
The request context (the handler's Context parameter).
.PARAMETER Logger
- An optional logger name.
+ The logger name; defaults to the name of the tool or prompt or the URI of the resource being served.
.PARAMETER Data
Structured data sent instead of the message text in the notification (any JSON-serialisable value).
.EXAMPLE
@@ -35,7 +35,7 @@ function Write-McpLog {
)
$threshold = if ($null -ne $Context -and $Context.PSObject.Properties['ServerLogLevel'] -and $null -ne $Context.ServerLogLevel) { $Context.ServerLogLevel } else { $script:McpDefaultLogLevel }
- $loggerName = if ($Logger) { $Logger } elseif ($null -ne $Context -and $Context.PSObject.Properties['ToolName']) { $Context.ToolName } else { $null }
+ $loggerName = if ($Logger) { $Logger } elseif ($null -ne $Context -and $Context.PSObject.Properties['Name']) { $Context.Name } else { $null }
Write-McpStderr -Level $Level -Threshold $threshold -Logger $loggerName -Message $Message
if ($null -eq $Context -or -not $Context.PSObject.Properties['LogLevel'] -or $null -eq $Context.LogLevel -or $null -eq $Context.Sink) { return }
diff --git a/src/Public/Write-McpProgress.ps1 b/src/Public/Write-McpProgress.ps1
index e762423..d74f2e3 100644
--- a/src/Public/Write-McpProgress.ps1
+++ b/src/Public/Write-McpProgress.ps1
@@ -33,7 +33,7 @@ function Write-McpProgress {
if ($null -eq $Context.ProgressToken -or $null -eq $Context.Sink) { return }
$state = $Context.ProgressState
if ($null -ne $state -and $null -ne $state.Last -and $Progress -le [double] $state.Last) {
- Write-McpStderr -Level Warning -Threshold $Context.ServerLogLevel -Logger $Context.ToolName -Message "Progress $Progress does not increase over $($state.Last); the notification is not sent."
+ Write-McpStderr -Level Warning -Threshold $Context.ServerLogLevel -Logger $Context.Name -Message "Progress $Progress does not increase over $($state.Last); the notification is not sent."
return
}
if ($null -ne $state) { $state.Last = $Progress }
diff --git a/src/Types/ModelContextProtocol.Types.ps1xml b/src/Types/ModelContextProtocol.Types.ps1xml
index 890d400..f881393 100644
--- a/src/Types/ModelContextProtocol.Types.ps1xml
+++ b/src/Types/ModelContextProtocol.Types.ps1xml
@@ -1,7 +1,41 @@
+
+ Mcp.Content
+
+
+ GetBytes
+
+
+
+
+
+ Mcp.ResourceContent
+
+
+ GetBytes
+
+
+
+
diff --git a/src/en-US/about_ModelContextProtocol.help.txt b/src/en-US/about_ModelContextProtocol.help.txt
index f0f00fa..c14646f 100644
--- a/src/en-US/about_ModelContextProtocol.help.txt
+++ b/src/en-US/about_ModelContextProtocol.help.txt
@@ -17,22 +17,27 @@ LONG DESCRIPTION
Supported transports are stdio and Streamable HTTP.
CURRENT STATUS
- Milestone M2 (Streamable HTTP): servers expose PowerShell commands and
- script blocks as tools over stdio and over Streamable HTTP with the
- stateless 2026-07-28 lifecycle (server/discover, per-request _meta,
- request metadata headers, progress, cancellation), and clients connect to
- such servers over both transports. The official conformance suite runs in
- CI. Resources, prompts, input requests, subscriptions, the legacy
- revisions, authorization and the extensions follow in later milestones
- (ROADMAP.md).
+ 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
+ follow in later milestones (ROADMAP.md).
COMMANDS
- Server: New-McpServer, Register-McpTool, Start-McpServer, Stop-McpServer,
+ Server: New-McpServer, Register-McpTool, Register-McpResource,
+ Register-McpPrompt, Start-McpServer, Stop-McpServer,
Invoke-McpToolHandler
- Handlers: New-McpContent, New-McpToolResult, Write-McpProgress, Write-McpLog,
+ Handlers: New-McpContent, New-McpToolResult, New-McpPromptMessage,
+ New-McpResourceContent, Write-McpProgress, Write-McpLog,
Test-McpClientCapability
Client: Connect-McpServer, Disconnect-McpServer, Get-McpServerInfo,
- Get-McpTool, Invoke-McpTool
+ Get-McpTool, Invoke-McpTool, Get-McpResource, Read-McpResource,
+ Get-McpPrompt, Invoke-McpPrompt, Get-McpCompletion
Start-McpServer serves stdio by default; -Transport Http -Url serves a
Streamable HTTP endpoint (POST-only, JSON or SSE responses, request
@@ -42,11 +47,22 @@ COMMANDS
Mcp-Param-* headers (the x-mcp-header annotation), which the client
mirrors and the server validates.
- A tool handler receives the request context through a parameter named
- Context (request id, protocol version, client info and capabilities, log
- level, progress token, cancellation token). Handlers run in a worker
+ Register-McpResource serves fixed content, a file, the files below a
+ directory (with protection against paths that leave it) or the output of a
+ handler; -UriTemplate registers an RFC 6570 template (levels 1 to 3) whose
+ variables are bound to the handler's parameters. Register-McpPrompt derives
+ the prompt arguments from the handler's parameters; -Completion (and a
+ ValidateSet) provides argument completion. Resources, prompts and
+ completions are declared in server/discover only when something is
+ registered.
+
+ 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
runspace pool: pass everything they need as parameters; nothing they write
- to the host reaches the client.
+ 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
+ notifications/message.
REQUIREMENTS
PowerShell 7.4 or later (Core edition). Windows PowerShell 5.1 is not
diff --git a/tests/Conformance/everything-client.ps1 b/tests/Conformance/everything-client.ps1
index 408cf87..171fb60 100644
--- a/tests/Conformance/everything-client.ps1
+++ b/tests/Conformance/everything-client.ps1
@@ -117,6 +117,32 @@ try {
Write-ClientLog "tools/call $($call.name) failed: $($_.Exception.Message)"
}
}
+
+ # Resources and prompts, when the server declares them (http-standard-headers checks the Mcp-Method and
+ # Mcp-Name headers of resources/read and prompts/get).
+ $capabilities = $info.Capabilities
+ if ($capabilities -is [System.Collections.IDictionary] -and $capabilities.Contains('resources')) {
+ try {
+ foreach ($resource in @(Get-McpResource -Session $session)) {
+ $contents = @(Read-McpResource -Uri $resource.Uri -Session $session -ErrorAction Continue)
+ Write-ClientLog "resources/read $($resource.Uri): $($contents.Count) content(s)"
+ }
+ } catch {
+ Write-ClientLog "resources failed: $($_.Exception.Message)"
+ }
+ }
+ if ($capabilities -is [System.Collections.IDictionary] -and $capabilities.Contains('prompts')) {
+ try {
+ foreach ($prompt in @(Get-McpPrompt -Session $session)) {
+ $promptArguments = @{}
+ foreach ($argument in @($prompt.Arguments | Where-Object { $_.Required })) { $promptArguments[$argument.Name] = 'value' }
+ $rendered = Invoke-McpPrompt -Name $prompt.Name -Arguments $promptArguments -Session $session
+ Write-ClientLog "prompts/get $($prompt.Name): $(@($rendered.Messages).Count) message(s)"
+ }
+ } catch {
+ Write-ClientLog "prompts failed: $($_.Exception.Message)"
+ }
+ }
} finally {
Disconnect-McpServer -Session $session
}
diff --git a/tests/Conformance/everything-server.ps1 b/tests/Conformance/everything-server.ps1
index dd217a4..3bc16e3 100644
--- a/tests/Conformance/everything-server.ps1
+++ b/tests/Conformance/everything-server.ps1
@@ -1,15 +1,15 @@
#Requires -Version 7.4
<#
.SYNOPSIS
- The conformance fixture server: the tools that the server scenarios of @modelcontextprotocol/conformance
- exercise for revision 2026-07-28, served over Streamable HTTP.
+ The conformance fixture server: the tools, resources, prompts and completions that the server scenarios of
+ @modelcontextprotocol/conformance exercise for revision 2026-07-28, served over Streamable HTTP.
.DESCRIPTION
The Conformance build task and .github/workflows/conformance.yml start it with
pwsh -NoLogo -NoProfile -NonInteractive -File tests/Conformance/everything-server.ps1 -Port 3001
and run the suite against http://127.0.0.1:3001/mcp. The module is imported from $env:MCP_MODULE_MANIFEST
when set (the build sets it to the built module), otherwise from the installed ModelContextProtocol module.
- Scenarios of later milestones (resources, prompts, completion, subscriptions, input requests) are listed in
- conformance-baseline.yml until their milestone lands.
+ Scenarios of later milestones (subscriptions, input requests) are listed in conformance-baseline.yml until
+ their milestone lands.
.PARAMETER Port
The TCP port on the loopback interface.
.PARAMETER Hostname
@@ -138,4 +138,38 @@ Register-McpTool -Name 'json_schema_2020_12_tool' -Description 'Tool with JSON S
"Received $($Arguments.Count) argument(s)."
}
+# Resources: the caching scenario reads the first listed resource, so the static text resource comes first.
+$png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=='
+Register-McpResource -Uri 'test://static-text' -Name 'Static text resource' -Description 'A static text resource.' -Content 'This is the content of the static text resource.'
+Register-McpResource -Uri 'test://static-binary' -Name 'Static binary resource' -Description 'A 1x1 PNG image.' -MimeType 'image/png' -Content ([System.Convert]::FromBase64String($png))
+Register-McpResource -UriTemplate 'test://template/{id}/data' -Name 'Template resource' -Description 'Data for an ID.' -MimeType 'application/json' -ScriptBlock {
+ param([string] $id)
+ [ordered]@{ id = $id; templateTest = $true; data = "Data for ID: $id" }
+} -Completion @{ id = @('1', '12', '123') }
+
+Register-McpPrompt -Name 'test_simple_prompt' -Description 'A simple prompt without arguments.' -ScriptBlock {
+ 'This is a simple prompt for testing.'
+}
+
+Register-McpPrompt -Name 'test_prompt_with_arguments' -Description 'A prompt with two required arguments.' -Arguments @(
+ @{ Name = 'arg1'; Description = 'First test argument'; Required = $true }
+ @{ Name = 'arg2'; Description = 'Second test argument'; Required = $true }
+) -ScriptBlock {
+ param([string] $arg1, [string] $arg2)
+ "Prompt with arguments: arg1='$arg1', arg2='$arg2'"
+} -Completion @{ arg1 = @('paris', 'park', 'party', 'test', 'testing') }
+
+Register-McpPrompt -Name 'test_prompt_with_embedded_resource' -Description 'A prompt that embeds a resource.' -Arguments @(
+ @{ Name = 'resourceUri'; Description = 'The URI of the embedded resource'; Required = $true }
+) -ScriptBlock {
+ param([string] $resourceUri)
+ New-McpContent -EmbeddedResource $resourceUri -MimeType 'text/plain' -ResourceText 'Embedded resource content for testing.'
+ 'Please process the embedded resource above.'
+}
+
+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.'
+}
+
Start-McpServer -Server $server -Transport Http -Url "http://${Hostname}:$Port/mcp/"
diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1
index cfe692d..e2aa2fa 100644
--- a/tests/Integration/HttpServer.Tests.ps1
+++ b/tests/Integration/HttpServer.Tests.ps1
@@ -33,6 +33,8 @@ BeforeAll {
}
'sampled'
} -Server $script:server
+ Register-McpResource -Uri 'test://doc' -Name 'doc' -Content 'document' -Server $script:server
+ Register-McpPrompt -Name 'hello' -Description 'Says hello.' -ScriptBlock { param([string] $Name = 'world') "Hello, $Name!" } -Server $script:server
$script:handle = Start-McpTestHttpServer -Server $script:server -Parameters @{ KeepAliveSeconds = 1 }
$script:url = $script:handle.Url
$script:meta = '"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}'
@@ -227,6 +229,31 @@ Describe 'Raw Streamable HTTP behaviour' -Tag 'Integration' {
(Send-Raw -Body $script:echoCall -Headers @{ 'Mcp-Method' = 'tools/call'; 'Mcp-Name' = '=?base64?ZWNobw==?=' }).Status | Should -Be 200
}
+ It 'validates Mcp-Name for resources/read and prompts/get and answers unknown resources with 400 and the URI' {
+ $read = "{`"jsonrpc`":`"2.0`",`"id`":30,`"method`":`"resources/read`",`"params`":{$($script:meta),`"uri`":`"test://doc`"}}"
+ $ok = Send-Raw -Body $read -Headers @{ 'Mcp-Method' = 'resources/read'; 'Mcp-Name' = 'test://doc' }
+ $ok.Status | Should -Be 200
+ $ok.Json['result']['contents'][0]['text'] | Should -Be 'document'
+ (Test-McpSpecShape -Definition 'ReadResourceResult' -Instance $ok.Json['result']).IsValid | Should -BeTrue
+ $mismatch = Send-Raw -Body $read -Headers @{ 'Mcp-Method' = 'resources/read'; 'Mcp-Name' = 'test://other' }
+ $mismatch.Status | Should -Be 400
+ $mismatch.Json['error']['code'] | Should -Be -32020
+ (Send-Raw -Body $read -Headers @{ 'Mcp-Method' = 'resources/read' }).Status | Should -Be 400
+ $missing = "{`"jsonrpc`":`"2.0`",`"id`":31,`"method`":`"resources/read`",`"params`":{$($script:meta),`"uri`":`"test://missing`"}}"
+ $notFound = Send-Raw -Body $missing -Headers @{ 'Mcp-Method' = 'resources/read'; 'Mcp-Name' = 'test://missing' }
+ $notFound.Status | Should -Be 400
+ $notFound.Json['error']['code'] | Should -Be -32602
+ $notFound.Json['error']['data']['uri'] | Should -Be 'test://missing'
+ $prompt = "{`"jsonrpc`":`"2.0`",`"id`":32,`"method`":`"prompts/get`",`"params`":{$($script:meta),`"name`":`"hello`",`"arguments`":{`"Name`":`"HTTP`"}}}"
+ (Send-Raw -Body $prompt -Headers @{ 'Mcp-Method' = 'prompts/get'; 'Mcp-Name' = 'hello' }).Json['result']['messages'][0]['content']['text'] | Should -Be 'Hello, HTTP!'
+ (Send-Raw -Body $prompt -Headers @{ 'Mcp-Method' = 'prompts/get'; 'Mcp-Name' = 'bye' }).Json['error']['code'] | Should -Be -32020
+ }
+
+ It 'serves resources and prompts to the HTTP client' {
+ (Read-McpResource -Uri 'test://doc' -Session $script:session).Text | Should -Be 'document'
+ (Invoke-McpPrompt -Name 'hello' -Session $script:session).Text | Should -Be 'Hello, world!'
+ }
+
It 'validates Mcp-Param headers ()' -TestCases @(
@{ Name = 'plain value'; Headers = @{ 'Mcp-Param-Region' = 'Hello'; 'Mcp-Param-Priority' = '42' }; Status = 200 }
@{ Name = 'Base64 sentinel'; Headers = @{ 'Mcp-Param-Region' = '=?base64?SGVsbG8=?='; 'Mcp-Param-Priority' = '42.0' }; Status = 200 }
diff --git a/tests/Integration/ServerPrimitives.Tests.ps1 b/tests/Integration/ServerPrimitives.Tests.ps1
new file mode 100644
index 0000000..29d2dfc
--- /dev/null
+++ b/tests/Integration/ServerPrimitives.Tests.ps1
@@ -0,0 +1,208 @@
+[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:root = Join-Path $TestDrive 'files'
+ $null = New-Item -ItemType Directory -Path $script:root -Force
+ Set-Content -Path (Join-Path $script:root 'notes.txt') -Value 'file notes' -NoNewline
+
+ $script:server = New-McpServer -Name 'primitives' -Version '1.0.0' -PageSize 2 -RequestTimeoutSeconds 10 -DefaultTtlMs 0
+ Register-McpResource -Server $script:server -Uri 'test://text' -Name 'text' -Description 'Text.' -Content 'static text'
+ Register-McpResource -Server $script:server -Uri 'test://binary' -Name 'binary' -MimeType 'image/png' -Content ([byte[]] (1, 2, 3))
+ Register-McpResource -Server $script:server -Uri 'test://cached' -Name 'cached' -TtlMs 60000 -CacheScope private -ScriptBlock { [guid]::NewGuid().ToString() }
+ Register-McpResource -Server $script:server -Uri 'test://logging' -Name 'logging' -ScriptBlock {
+ Write-Warning 'resource warning'
+ Write-Information 'resource info'
+ 'logged'
+ }
+ Register-McpResource -Server $script:server -UriTemplate 'items://{id}' -Name 'item' -MimeType 'application/json' -ScriptBlock {
+ param([int] $id)
+ if ($id -gt 100) { return }
+ [ordered]@{ id = $id; square = $id * $id }
+ } -Completion @{ id = @('1', '2', '10', '20') }
+ Register-McpResource -Server $script:server -Path $script:root -Uri 'files://'
+ Register-McpPrompt -Server $script:server -Name 'greet' -Description 'Greets someone.' -ScriptBlock {
+ param(
+ [Parameter(Mandatory)][string] $Name,
+ [ValidateSet('formal', 'casual')][string] $Style = 'casual'
+ )
+ if ($Style -eq 'formal') { "Good day, $Name." } else { "Hi $Name!" }
+ New-McpPromptMessage -Role assistant -Text 'How can I help?'
+ }
+ Register-McpPrompt -Server $script:server -Name 'picture' -Description 'Shows a picture.' -ScriptBlock {
+ New-McpContent -Image ([byte[]] (9, 8, 7)) -MimeType 'image/png'
+ }
+ Register-McpPrompt -Server $script:server -Name 'third' -Description 'Third page.' -ScriptBlock { 'third' }
+ $script:session = Connect-McpServer -Server $script:server
+}
+
+AfterAll {
+ if ($script:session) { Disconnect-McpServer -Session $script:session }
+}
+
+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
+ }
+
+ It 'lists resources and templates across pages' {
+ $resources = @(Get-McpResource -Session $script:session)
+ @($resources | ForEach-Object Name) | Should -Be @('text', 'binary', 'cached', 'logging')
+ $resources[0].PSObject.TypeNames | Should -Contain 'Mcp.Resource'
+ $resources[1].Size | Should -Be 3
+ @(Get-McpResource -Name 'b*' -Session $script:session).Count | Should -Be 1
+ $templates = @(Get-McpResource -Template -Session $script:session)
+ @($templates | ForEach-Object UriTemplate) | Should -Be @('items://{id}', 'files://{+path}')
+ $templates[0].PSObject.TypeNames | Should -Contain 'Mcp.ResourceTemplate'
+ }
+
+ It 'reads text, binary, template and file resources' {
+ $text = Read-McpResource -Uri 'test://text' -Session $script:session
+ $text.PSObject.TypeNames | Should -Contain 'Mcp.ResourceContent'
+ $text.Text | Should -Be 'static text'
+ $text.MimeType | Should -Be 'text/plain'
+ $binary = Read-McpResource -Uri 'test://binary' -Session $script:session
+ $binary.Blob | Should -Be 'AQID'
+ $binary.GetBytes() | Should -Be @(1, 2, 3)
+ (ConvertFrom-Json (Read-McpResource -Uri 'items://7' -Session $script:session).Text).square | Should -Be 49
+ (Read-McpResource -Uri 'files://notes.txt' -Session $script:session).Text | Should -Be 'file notes'
+ }
+
+ It 'reads the resources piped from Get-McpResource' {
+ $contents = @(Get-McpResource -Session $script:session | Where-Object Name -In 'text', 'binary' | Read-McpResource -Session $script:session)
+ @($contents | ForEach-Object Uri) | Should -Be @('test://text', 'test://binary')
+ }
+
+ It 'reports unknown resources as non-terminating ObjectNotFound errors' {
+ $contents = @(Read-McpResource -Uri 'test://nope', 'items://500', 'test://text' -Session $script:session -ErrorVariable errors -ErrorAction SilentlyContinue)
+ $contents.Count | Should -Be 1
+ # -ErrorVariable also collects the protocol exceptions caught inside the command (not all as ErrorRecords).
+ $failures = @($errors | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] -and $_.FullyQualifiedErrorId -like 'McpResourceNotFound,*' })
+ $failures.Count | Should -Be 2
+ $failures[0].CategoryInfo.Category | Should -Be 'ObjectNotFound'
+ $failures[0].TargetObject | Should -Be 'test://nope'
+ $failures[0].Exception.InnerException.Code | Should -Be -32602
+ $failures[1].TargetObject | Should -Be 'items://500'
+ }
+
+ It 'rejects reads that escape a directory resource' {
+ { Read-McpResource -Uri 'files://../secret' -Session $script:session -ErrorAction Stop } | Should -Throw -ExpectedMessage '*no resource*'
+ }
+
+ It 'caches reads for the ttlMs of the result and not for ttlMs 0' {
+ $first = (Read-McpResource -Uri 'test://cached' -Session $script:session).Text
+ (Read-McpResource -Uri 'test://cached' -Session $script:session).Text | Should -Be $first
+ $script:session.Cache['resources/read test://cached'].CacheScope | Should -Be 'private'
+ (Read-McpResource -Uri 'test://cached' -Session $script:session -Refresh).Text | Should -Not -Be $first
+ $null = Read-McpResource -Uri 'test://text' -Session $script:session
+ $script:session.Cache.ContainsKey('resources/read test://text') | Should -BeFalse
+ $script:session.Cache.ContainsKey('resources/list') | Should -BeFalse
+ }
+
+ It 'sends handler warnings and information as log notifications when asked' {
+ $script:session.Log.Clear()
+ $content = Read-McpResource -Uri 'test://logging' -Session $script:session -LogLevel info
+ $content.Text | Should -Be 'logged'
+ @($script:session.Log | ForEach-Object Level) | Should -Be @('warning', 'info')
+ $script:session.Log[0].Data | Should -Be 'resource warning'
+ $script:session.Log[0].Logger | Should -Be 'test://logging'
+ $script:session.Log.Clear()
+ $null = Read-McpResource -Uri 'test://logging' -Session $script:session
+ $script:session.Log.Count | Should -Be 0
+ }
+}
+
+Describe 'Prompts and completion through the client' -Tag 'Integration' {
+ It 'lists prompts across pages with their arguments' {
+ $prompts = @(Get-McpPrompt -Session $script:session)
+ @($prompts | ForEach-Object Name) | Should -Be @('greet', 'picture', 'third')
+ $prompts[0].PSObject.TypeNames | Should -Contain 'Mcp.Prompt'
+ $prompts[0].Arguments[0].Name | Should -Be 'Name'
+ $prompts[0].Arguments[0].Required | Should -BeTrue
+ $prompts[0].Arguments[1].Required | Should -BeFalse
+ @(Get-McpPrompt -Name 'pic*' -Session $script:session).Name | Should -Be 'picture'
+ }
+
+ It 'renders prompts with arguments' {
+ $result = Invoke-McpPrompt -Name 'greet' -Arguments @{ Name = 'Ada'; Style = 'formal' } -Session $script:session
+ $result.PSObject.TypeNames | Should -Contain 'Mcp.PromptResult'
+ $result.Description | Should -Be 'Greets someone.'
+ $result.Messages.Count | Should -Be 2
+ $result.Messages[0].Role | Should -Be 'user'
+ $result.Messages[0].Content.text | Should -Be 'Good day, Ada.'
+ $result.Messages[1].Role | Should -Be 'assistant'
+ $result.Text | Should -Be "Good day, Ada.`nHow can I help?"
+ $image = Invoke-McpPrompt -Name 'picture' -Session $script:session
+ $image.Messages[0].Content.PSObject.TypeNames | Should -Contain 'Mcp.Content'
+ $image.Messages[0].Content.GetBytes() | Should -Be @(9, 8, 7)
+ }
+
+ It 'throws protocol errors for unknown prompts and missing arguments' {
+ { Invoke-McpPrompt -Name 'nope' -Session $script:session } | Should -Throw -ExpectedMessage "*Unknown prompt 'nope'*"
+ { Invoke-McpPrompt -Name 'greet' -Session $script:session } | Should -Throw -ExpectedMessage '*Missing required argument*Name*'
+ }
+
+ It 'completes prompt arguments and template variables' {
+ $style = Get-McpCompletion -PromptName 'greet' -Argument 'Style' -Value 'f' -Session $script:session
+ $style.PSObject.TypeNames | Should -Contain 'Mcp.Completion'
+ $style.Values | Should -Be @('formal')
+ $style.Total | Should -Be 1
+ $style.HasMore | Should -BeFalse
+ (Get-McpCompletion -ResourceTemplate 'items://{id}' -Argument 'id' -Value '1' -Session $script:session).Values | Should -Be @('1', '10')
+ { Get-McpCompletion -PromptName 'greet' -Argument 'Missing' -Value '' -Session $script:session } | Should -Throw -ExpectedMessage '*no argument*'
+ }
+}
+
+Describe 'Capability gating and the client cache' -Tag 'Integration' {
+ It 'answers the methods of undeclared capabilities with -32601' {
+ $bare = New-McpServer -Name 'bare' -Version '1'
+ $session = Connect-McpServer -Server $bare
+ try {
+ @((Get-McpServerInfo -Session $session).Capabilities.Keys) | Should -Be @('tools')
+ foreach ($call in @(
+ { Get-McpResource -Session $session }
+ { Get-McpResource -Template -Session $session }
+ { Read-McpResource -Uri 'test://x' -Session $session }
+ { Get-McpPrompt -Session $session }
+ { Invoke-McpPrompt -Name 'x' -Session $session }
+ { Get-McpCompletion -PromptName 'x' -Argument 'y' -Session $session }
+ )) {
+ $caught = $null
+ try { & $call } catch { $caught = $_.Exception }
+ $caught | Should -BeOfType [McpProtocolException]
+ $caught.Code | Should -Be -32601
+ }
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+
+ It 'caches lists and the server info for their ttlMs' {
+ $server = New-McpServer -Name 'cached' -Version '1' -DefaultTtlMs 60000
+ Register-McpTool -Server $server -Name 'one' -ScriptBlock { 1 }
+ Register-McpPrompt -Server $server -Name 'p' -Description 'P.' -ScriptBlock { 'p' }
+ $session = Connect-McpServer -Server $server
+ try {
+ @(Get-McpTool -Session $session).Count | Should -Be 1
+ @(Get-McpPrompt -Session $session).Count | Should -Be 1
+ $session.Cache.ContainsKey('server/discover') | Should -BeTrue
+ $session.Cache['tools/list'].CacheScope | Should -Be 'public'
+ # The cached list hides a later registration until it expires or -Refresh asks again.
+ Register-McpTool -Server $server -Name 'two' -ScriptBlock { 2 }
+ @(Get-McpTool -Session $session).Count | Should -Be 1
+ @(Get-McpTool -Session $session -Refresh).Count | Should -Be 2
+ Register-McpTool -Server $server -Name 'three' -ScriptBlock { 3 }
+ $session.Cache['tools/list'].ExpiresAt = [datetime]::UtcNow.AddSeconds(-1)
+ @(Get-McpTool -Session $session).Count | Should -Be 3
+ $session.Cache['tools/list'].ExpiresAt | Should -BeGreaterThan ([datetime]::UtcNow)
+ } finally {
+ Disconnect-McpServer -Session $session
+ }
+ }
+}
diff --git a/tests/Integration/StdioServer.Tests.ps1 b/tests/Integration/StdioServer.Tests.ps1
index 6cc0106..f4b5306 100644
--- a/tests/Integration/StdioServer.Tests.ps1
+++ b/tests/Integration/StdioServer.Tests.ps1
@@ -126,3 +126,33 @@ Describe 'Raw stdio behaviour of the example server' -Tag 'Integration' {
$result.StdErr | Should -Match 'a warning for the server log'
}
}
+
+Describe 'The weather example over stdio' -Tag 'Integration' {
+ BeforeAll {
+ $weatherArguments = @('-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path (Get-McpRepositoryRoot) 'examples' 'weather-server.ps1'))
+ $script:weather = Connect-McpServer -Command $script:pwsh -Arguments $weatherArguments -ConnectTimeoutSeconds 60
+ }
+
+ AfterAll {
+ if ($script:weather) { Disconnect-McpServer -Session $script:weather }
+ }
+
+ It 'serves resources, templates, prompts and completions' {
+ @((Get-McpServerInfo -Session $script:weather).Capabilities.Keys) | Should -Be @('completions', 'prompts', 'resources', 'tools')
+ (Get-McpResource -Session $script:weather).Uri | Should -Be 'weather://stations'
+ (ConvertFrom-Json (Read-McpResource -Uri 'weather://stations' -Session $script:weather).Text) | Should -Contain 'Vienna'
+ (Get-McpResource -Template -Session $script:weather).UriTemplate | Should -Be 'weather://{city}/current'
+ (ConvertFrom-Json (Read-McpResource -Uri 'weather://Vienna/current' -Session $script:weather).Text).city | Should -Be 'Vienna'
+ Read-McpResource -Uri 'weather://Atlantis/current' -Session $script:weather -ErrorAction SilentlyContinue | Should -BeNullOrEmpty
+ (Get-McpCompletion -ResourceTemplate 'weather://{city}/current' -Argument 'city' -Value 'Mu' -Session $script:weather).Values | Should -Be @('Munich')
+ (Get-McpCompletion -PromptName 'weather-report' -Argument 'Tone' -Value 'd' -Session $script:weather).Values | Should -Be @('dramatic')
+ @(Get-McpPrompt -Session $script:weather | ForEach-Object Name) | Should -Be @('weather-report', 'packing-list')
+ $report = Invoke-McpPrompt -Name 'weather-report' -Arguments @{ City = 'Zurich' } -Session $script:weather
+ $report.Messages[0].Content.type | Should -Be 'resource'
+ $report.Text | Should -BeLike '*neutral three-sentence weather report for Zurich*'
+ $packing = Invoke-McpPrompt -Name 'packing-list' -Arguments @{ destination = 'Hamburg'; days = 4 } -Session $script:weather
+ $packing.Messages[1].Role | Should -Be 'assistant'
+ $packing.Messages[0].Content.text | Should -Be 'I am travelling to Hamburg for 4 days. What should I pack?'
+ (Invoke-McpTool -Name 'forecast' -Arguments @{ City = 'Berlin'; Days = 2 } -Session $script:weather).StructuredContent['days'].Count | Should -Be 2
+ }
+}
diff --git a/tests/Unit/Metadata.Tests.ps1 b/tests/Unit/Metadata.Tests.ps1
new file mode 100644
index 0000000..7561326
--- /dev/null
+++ b/tests/Unit/Metadata.Tests.ps1
@@ -0,0 +1,115 @@
+[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 ConvertTo-Wire {
+ param($InputObject)
+ Invoke-McpInModule { param($o) ConvertFrom-McpJson (ConvertTo-McpJson -InputObject $o) } -Parameters @{ o = $InputObject }
+ }
+}
+
+Describe 'Icons' {
+ It 'normalises icons given as hashtables, objects and strings' {
+ $icons = Invoke-McpInModule {
+ ConvertTo-McpIconList -Icons @(
+ @{ Src = 'https://example.com/a.png'; MimeType = 'image/png'; Sizes = '48x48'; Theme = 'Dark' }
+ [pscustomobject]@{ src = 'data:image/svg+xml;base64,PHN2Zy8+'; sizes = @('any') }
+ 'http://example.com/b.jpg'
+ )
+ }
+ $icons.Count | Should -Be 3
+ $icons[0]['src'] | Should -Be 'https://example.com/a.png'
+ $icons[0]['sizes'] | Should -Be @('48x48')
+ $icons[0]['theme'] | Should -Be 'dark'
+ foreach ($icon in $icons) { (Test-McpSpecShape -Definition 'Icon' -Instance $icon).IsValid | Should -BeTrue }
+ }
+
+ It 'rejects ' -TestCases @(
+ @{ Case = 'a relative src'; Icon = @{ src = 'icon.png' }; Message = '*absolute http, https or data URI*' }
+ @{ Case = 'an invalid size'; Icon = @{ src = 'https://x/i.png'; sizes = '48' }; Message = '*WIDTHxHEIGHT*' }
+ @{ Case = 'an unknown theme'; Icon = @{ src = 'https://x/i.png'; theme = 'blue' }; Message = '*light or dark*' }
+ @{ Case = 'an unknown member'; Icon = @{ src = 'https://x/i.png'; color = 'red' }; Message = "*Unknown icon member 'color'*" }
+ ) {
+ { Invoke-McpInModule { param($i) ConvertTo-McpIconList -Icons @($i) } -Parameters @{ i = $Icon } } | Should -Throw -ExpectedMessage $Message
+ }
+
+ It 'validates the icons of servers, tools and prompts' {
+ { New-McpServer -Name 's' -Version '1' -Icons @(@{ src = 'nope' }) } | Should -Throw -ExpectedMessage '*absolute*'
+ $server = New-McpServer -Name 's' -Version '1' -Icons @('https://example.com/s.png')
+ $server.Icons[0]['src'] | Should -Be 'https://example.com/s.png'
+ { Register-McpTool -Server $server -Name 't' -ScriptBlock { 'x' } -Icons @(@{ src = 'nope' }) } | Should -Throw -ExpectedMessage '*absolute*'
+ { Register-McpPrompt -Server $server -Name 'p' -Description 'P.' -ScriptBlock { 'x' } -Icons @(@{ src = 'nope' }) } | Should -Throw -ExpectedMessage '*absolute*'
+ }
+}
+
+Describe 'New-McpContent' {
+ It 'builds spec-valid blocks of every type' {
+ $blocks = @(
+ New-McpContent -Text 'hi' -Annotations @{ audience = @('user', 'assistant'); priority = 1 }
+ New-McpContent -Image ([byte[]] (1, 2)) -MimeType 'image/png'
+ New-McpContent -Audio 'UklGRg==' -MimeType 'audio/wav'
+ New-McpContent -ResourceLink 'test://doc' -Name 'doc' -Title 'Doc' -Description 'A doc.' -MimeType 'text/plain' -Size 10 -Icons @('https://example.com/d.png')
+ New-McpContent -EmbeddedResource 'test://doc' -MimeType 'text/plain' -ResourceText 'body' -ResourceMeta @{ source = 'test' } -Annotations @{ lastModified = '2026-07-28T00:00:00Z' }
+ New-McpContent -EmbeddedResource 'test://bin' -ResourceBlob ([byte[]] (3)) -Meta @{ note = 'x' }
+ )
+ foreach ($block in $blocks) {
+ $block.PSObject.TypeNames | Should -Contain 'Mcp.Content'
+ (Test-McpSpecShape -Definition 'ContentBlock' -Instance (ConvertTo-Wire $block)).IsValid | Should -BeTrue
+ }
+ $blocks[0].annotations['priority'] | Should -Be 1.0
+ $blocks[3].icons[0]['src'] | Should -Be 'https://example.com/d.png'
+ $blocks[4].resource['_meta']['source'] | Should -Be 'test'
+ }
+
+ It 'decodes binary data with GetBytes()' {
+ (New-McpContent -Image ([byte[]] (1, 2)) -MimeType 'image/png').GetBytes() | Should -Be @(1, 2)
+ (New-McpContent -EmbeddedResource 'test://bin' -ResourceBlob ([byte[]] (3, 4))).GetBytes() | Should -Be @(3, 4)
+ [System.Text.Encoding]::UTF8.GetString((New-McpContent -Text 'ä').GetBytes()) | Should -Be 'ä'
+ }
+
+ It 'rejects invalid annotations' {
+ { New-McpContent -Text 'x' -Annotations @{ priority = -0.1 } } | Should -Throw -ExpectedMessage '*from 0 to 1*'
+ { New-McpContent -Text 'x' -Annotations @{ lastModified = 'yesterday' } } | Should -Throw -ExpectedMessage '*ISO 8601*'
+ { New-McpContent -Text 'x' -Annotations @{ importance = 1 } } | Should -Throw -ExpectedMessage "*Unknown annotation 'importance'*"
+ }
+}
+
+Describe 'New-McpPromptMessage and New-McpResourceContent' {
+ It 'builds prompt messages' {
+ $message = New-McpPromptMessage -Role assistant -Text 'ok'
+ $message.PSObject.TypeNames | Should -Contain 'Mcp.PromptMessage'
+ (Test-McpSpecShape -Definition 'PromptMessage' -Instance (ConvertTo-Wire $message)).IsValid | Should -BeTrue
+ (New-McpPromptMessage -Content (New-McpContent -Image 'AQI=' -MimeType 'image/png')).content.type | Should -Be 'image'
+ { New-McpPromptMessage -Content 'plain' } | Should -Throw -ExpectedMessage '*content block*'
+ }
+
+ It 'builds resource contents' {
+ $text = New-McpResourceContent -Text 'x' -Uri 'test://a' -MimeType 'text/plain'
+ (Test-McpSpecShape -Definition 'TextResourceContents' -Instance (ConvertTo-Wire $text)).IsValid | Should -BeTrue
+ $blob = New-McpResourceContent -Blob ([byte[]] (1)) -Uri 'test://b'
+ (Test-McpSpecShape -Definition 'BlobResourceContents' -Instance (ConvertTo-Wire $blob)).IsValid | Should -BeTrue
+ $blob.PSObject.TypeNames | Should -Contain 'Mcp.ResourceContents'
+ { New-McpResourceContent -Text 'x' -Uri 'relative' } | Should -Throw -ExpectedMessage '*absolute URI*'
+ }
+}
+
+Describe 'Cursor pagination' {
+ It 'binds cursors to their list' {
+ $server = New-McpServer -Name 's' -Version '1' -PageSize 1
+ Register-McpTool -Server $server -Name 'a' -ScriptBlock { 'a' }
+ Register-McpTool -Server $server -Name 'b' -ScriptBlock { 'b' }
+ Register-McpPrompt -Server $server -Name 'p' -Description 'P.' -ScriptBlock { 'p' }
+ Register-McpPrompt -Server $server -Name 'q' -Description 'Q.' -ScriptBlock { 'q' }
+ $first = Invoke-McpInModule { param($s) Get-McpToolListResult -Server $s -Cursor $null } $server
+ $first['nextCursor'] | Should -Not -BeNullOrEmpty
+ $second = Invoke-McpInModule { param($s, $c) Get-McpToolListResult -Server $s -Cursor $c } $server $first['nextCursor']
+ $second['tools'][0]['name'] | Should -Be 'b'
+ $second.Contains('nextCursor') | Should -BeFalse
+ { Invoke-McpInModule { param($s, $c) Get-McpPromptListResult -Server $s -Cursor $c } $server $first['nextCursor'] } | Should -Throw -ExpectedMessage 'Invalid cursor.'
+ $prompts = Invoke-McpInModule { param($s) Get-McpPromptListResult -Server $s -Cursor $null } $server
+ (Invoke-McpInModule { param($s, $c) Get-McpPromptListResult -Server $s -Cursor $c } $server $prompts['nextCursor'])['prompts'][0]['name'] | Should -Be 'q'
+ }
+}
diff --git a/tests/Unit/Prompts.Tests.ps1 b/tests/Unit/Prompts.Tests.ps1
new file mode 100644
index 0000000..c314e77
--- /dev/null
+++ b/tests/Unit/Prompts.Tests.ps1
@@ -0,0 +1,172 @@
+[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
+
+ # Renders a prompt in the current runspace, as the worker would, and returns the wire result after a JSON round trip.
+ function Get-TestPrompt {
+ param([pscustomobject] $Server, [string] $Name, [hashtable] $Arguments)
+ Invoke-McpInModule {
+ param($s, $n, $a)
+ $registration = Get-McpPromptRegistration -Server $s -Name $n
+ $values = Test-McpPromptArgument -Registration $registration -Arguments $a
+ $result = Invoke-McpPromptHandler -Registration $registration -Arguments $values
+ ConvertFrom-McpJson (ConvertTo-McpJson -InputObject $result)
+ } -Parameters @{ s = $Server; n = $Name; a = $Arguments }
+ }
+
+ function Get-TestCompletion {
+ param([pscustomobject] $Server, [hashtable] $Params)
+ Invoke-McpInModule {
+ param($s, $p)
+ $request = Resolve-McpCompletionRequest -Server $s -Params $p
+ Invoke-McpCompletionHandler -Request $request
+ } -Parameters @{ s = $Server; p = $Params }
+ }
+}
+
+Describe 'Register-McpPrompt' {
+ It 'derives arguments, descriptions and completions from the param block' {
+ $server = New-McpServer -Name 'p' -Version '1'
+ $registration = Register-McpPrompt -Server $server -Name 'weather' -PassThru -ScriptBlock {
+ <#
+ .SYNOPSIS
+ Asks for a weather report.
+ .PARAMETER City
+ The city.
+ .PARAMETER Units
+ The unit system.
+ #>
+ param(
+ [Parameter(Mandatory)] [string] $City,
+ [ValidateSet('metric', 'imperial')] [string] $Units = 'metric',
+ [int] $Days = 1,
+ $Context
+ )
+ "Weather for $City in $Units units for $Days day(s)$(if ($null -eq $Context) { ' (no context)' })."
+ }
+ $registration.Description | Should -Be 'Asks for a weather report.'
+ @($registration.Arguments | ForEach-Object { $_['name'] }) | Should -Be @('City', 'Units', 'Days')
+ $registration.Arguments[0]['required'] | Should -BeTrue
+ $registration.Arguments[0]['description'] | Should -Be 'The city.'
+ $registration.Arguments[1].Contains('required') | Should -BeFalse
+ $registration.Completion['Units'].Values | Should -Be @('metric', 'imperial')
+ $list = Invoke-McpInModule { param($s) Get-McpPromptListResult -Server $s -Cursor $null } $server
+ (Test-McpSpecShape -Definition 'ListPromptsResult' -Instance $list).IsValid | Should -BeTrue
+ $result = Get-TestPrompt -Server $server -Name 'weather' -Arguments @{ City = 'Berlin'; Days = '3' }
+ (Test-McpSpecShape -Definition 'GetPromptResult' -Instance $result).IsValid | Should -BeTrue
+ $result['description'] | Should -Be 'Asks for a weather report.'
+ $result['messages'][0]['role'] | Should -Be 'user'
+ $result['messages'][0]['content']['text'] | Should -Be 'Weather for Berlin in metric units for 3 day(s) (no context).'
+ }
+
+ It 'passes all values to an Arguments parameter with explicit -Arguments' {
+ $server = New-McpServer -Name 'p' -Version '1'
+ $registration = Register-McpPrompt -Server $server -Name 'raw' -Description 'Raw.' -PassThru -Arguments @('a', @{ Name = 'b'; Title = 'B'; Description = 'Second'; Required = $true }) -ScriptBlock {
+ param($Arguments)
+ ($Arguments.Keys | Sort-Object | ForEach-Object { "$_=$($Arguments[$_])" }) -join ';'
+ }
+ $registration.Handler.ArgumentStyle | Should -Be 'Arguments'
+ $registration.Arguments[1]['title'] | Should -Be 'B'
+ (Get-TestPrompt -Server $server -Name 'raw' -Arguments @{ a = '1'; b = '2'; extra = '3' })['messages'][0]['content']['text'] | Should -Be 'a=1;b=2;extra=3'
+ }
+
+ It 'shapes content blocks, assistant messages and objects' {
+ $server = New-McpServer -Name 'p' -Version '1'
+ Register-McpPrompt -Server $server -Name 'mixed' -Description 'Mixed.' -ScriptBlock {
+ 'first'
+ 'second'
+ New-McpContent -Image ([byte[]] (1, 2)) -MimeType 'image/png'
+ New-McpPromptMessage -Role assistant -Text 'Understood.'
+ New-McpContent -EmbeddedResource 'test://doc' -MimeType 'text/plain' -ResourceText 'doc'
+ [pscustomobject]@{ a = 1 }
+ }
+ $result = Get-TestPrompt -Server $server -Name 'mixed'
+ (Test-McpSpecShape -Definition 'GetPromptResult' -Instance $result).IsValid | Should -BeTrue
+ $messages = $result['messages']
+ $messages.Count | Should -Be 5
+ $messages[0]['content']['text'] | Should -Be "first`nsecond"
+ $messages[1]['content']['type'] | Should -Be 'image'
+ $messages[2]['role'] | Should -Be 'assistant'
+ $messages[3]['content']['resource']['uri'] | Should -Be 'test://doc'
+ $messages[4]['content']['text'] | Should -Be '{"a":1}'
+ }
+
+ It 'validates arguments of prompts/get' {
+ $server = New-McpServer -Name 'p' -Version '1'
+ Register-McpPrompt -Server $server -Name 'needs' -Description 'Needs x.' -ScriptBlock { param([Parameter(Mandatory)][string] $x) $x }
+ { Get-TestPrompt -Server $server -Name 'needs' -Arguments @{} } | Should -Throw -ExpectedMessage '*Missing required argument*x*'
+ { Get-TestPrompt -Server $server -Name 'needs' -Arguments @{ x = 5 } } | Should -Throw -ExpectedMessage '*must be a string*'
+ { Get-TestPrompt -Server $server -Name 'unknown' -Arguments @{} } | Should -Throw -ExpectedMessage "*Unknown prompt 'unknown'*"
+ (Get-TestPrompt -Server $server -Name 'needs' -Arguments @{ x = 'ok'; ignored = 'y' })['messages'][0]['content']['text'] | Should -Be 'ok'
+ }
+
+ It 'turns handler failures into internal errors' {
+ $server = New-McpServer -Name 'p' -Version '1'
+ Register-McpPrompt -Server $server -Name 'broken' -Description 'Broken.' -ScriptBlock { throw 'kaputt' }
+ $caught = $null
+ try { Get-TestPrompt -Server $server -Name 'broken' } catch { $caught = $_.Exception }
+ while ($caught -and $caught -isnot [McpProtocolException] -and $caught.InnerException) { $caught = $caught.InnerException }
+ $caught.Code | Should -Be -32603
+ $caught.Message | Should -Match 'kaputt'
+ }
+
+ It 'warns about a prompt without description and refuses duplicates' {
+ $server = New-McpServer -Name 'p' -Version '1'
+ Register-McpPrompt -Server $server -Name 'bare' -ScriptBlock { 'x' } -WarningVariable warnings -WarningAction SilentlyContinue
+ @($warnings).Count | Should -Be 1
+ { Register-McpPrompt -Server $server -Name 'bare' -Description 'Again.' -ScriptBlock { 'x' } } | Should -Throw -ExpectedMessage '*already registered*'
+ Register-McpPrompt -Server $server -Name 'bare' -Description 'Again.' -ScriptBlock { 'y' } -Force
+ $server.Prompts['bare'].Description | Should -Be 'Again.'
+ }
+}
+
+Describe 'completion/complete' {
+ BeforeAll {
+ $script:server = New-McpServer -Name 'c' -Version '1'
+ Register-McpPrompt -Server $script:server -Name 'city' -Description 'City.' -ScriptBlock { param([ValidateSet('Berlin', 'Bern', 'Bonn', 'Paris')][string] $Name, [string] $Country) "$Name, $Country" } -Completion @{
+ Country = { param($Value, $Arguments) @('Germany', 'Switzerland', 'France') | Where-Object { $_ -like "$Value*" } | ForEach-Object { "$_ ($($Arguments['Name']))" } }
+ }
+ Register-McpResource -Server $script:server -UriTemplate 'numbers://{n}' -ScriptBlock { param($n) $n } -Completion @{ n = @(1..250 | ForEach-Object { [string] $_ }) }
+ }
+
+ It 'filters value lists by prefix, case-insensitively' {
+ $result = Get-TestCompletion -Server $script:server -Params @{ ref = @{ type = 'ref/prompt'; name = 'city' }; argument = @{ name = 'Name'; value = 'be' } }
+ (Test-McpSpecShape -Definition 'CompleteResult' -Instance $result).IsValid | Should -BeTrue
+ $result['completion']['values'] | Should -Be @('Berlin', 'Bern')
+ $result['completion']['total'] | Should -Be 2
+ $result['completion']['hasMore'] | Should -BeFalse
+ }
+
+ It 'runs completion handlers with the context arguments' {
+ $result = Get-TestCompletion -Server $script:server -Params @{ ref = @{ type = 'ref/prompt'; name = 'city' }; argument = @{ name = 'Country'; value = 'Ger' }; context = @{ arguments = @{ Name = 'Berlin' } } }
+ $result['completion']['values'] | Should -Be @('Germany (Berlin)')
+ }
+
+ It 'caps the values at 100 and reports the total' {
+ $result = Get-TestCompletion -Server $script:server -Params @{ ref = @{ type = 'ref/resource'; uri = 'numbers://{n}' }; argument = @{ name = 'n'; value = '' } }
+ (Test-McpSpecShape -Definition 'CompleteResult' -Instance $result).IsValid | Should -BeTrue
+ $result['completion']['values'].Count | Should -Be 100
+ $result['completion']['total'] | Should -Be 250
+ $result['completion']['hasMore'] | Should -BeTrue
+ }
+
+ It 'returns no values for an argument without a completion source' {
+ Register-McpPrompt -Server $script:server -Name 'plain' -Description 'Plain.' -ScriptBlock { param([string] $Free) $Free }
+ (Get-TestCompletion -Server $script:server -Params @{ ref = @{ type = 'ref/prompt'; name = 'plain' }; argument = @{ name = 'Free'; value = 'x' } })['completion']['values'].Count | Should -Be 0
+ }
+
+ It 'rejects invalid references: ' -TestCases @(
+ @{ Case = 'unknown prompt'; Params = @{ ref = @{ type = 'ref/prompt'; name = 'nope' }; argument = @{ name = 'Name'; value = '' } }; Message = '*Unknown prompt*' }
+ @{ Case = 'unknown argument'; Params = @{ ref = @{ type = 'ref/prompt'; name = 'city' }; argument = @{ name = 'Nope'; value = '' } }; Message = '*no argument*' }
+ @{ Case = 'unknown template'; Params = @{ ref = @{ type = 'ref/resource'; uri = 'numbers://x' }; argument = @{ name = 'n'; value = '' } }; Message = '*Unknown resource template*' }
+ @{ Case = 'unknown variable'; Params = @{ ref = @{ type = 'ref/resource'; uri = 'numbers://{n}' }; argument = @{ name = 'm'; value = '' } }; Message = '*no variable*' }
+ @{ Case = 'unknown ref type'; Params = @{ ref = @{ type = 'ref/tool'; name = 'x' }; argument = @{ name = 'n'; value = '' } }; Message = '*Unknown completion reference type*' }
+ @{ Case = 'missing argument'; Params = @{ ref = @{ type = 'ref/prompt'; name = 'city' } }; Message = "*requires 'argument'*" }
+ @{ Case = 'non-string context'; Params = @{ ref = @{ type = 'ref/prompt'; name = 'city' }; argument = @{ name = 'Name'; value = '' }; context = @{ arguments = @{ x = 1 } } }; Message = '*must be a string*' }
+ ) {
+ { Get-TestCompletion -Server $script:server -Params $Params } | Should -Throw -ExpectedMessage $Message
+ }
+}
diff --git a/tests/Unit/Resources.Tests.ps1 b/tests/Unit/Resources.Tests.ps1
new file mode 100644
index 0000000..4e5ff12
--- /dev/null
+++ b/tests/Unit/Resources.Tests.ps1
@@ -0,0 +1,206 @@
+[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
+
+ # Reads a resource in the current runspace, as the worker would, and returns the wire result after a JSON round trip.
+ function Read-TestResource {
+ param([pscustomobject] $Server, [string] $Uri)
+ Invoke-McpInModule {
+ param($s, $u)
+ $resolved = Resolve-McpResourceRequest -Server $s -Uri $u
+ $hint = Get-McpResourceCacheHint -Server $s -Registration $resolved.Registration
+ $result = Invoke-McpResourceHandler -Registration $resolved.Registration -Uri $u -Variables $resolved.Variables -CacheHint $hint
+ ConvertFrom-McpJson (ConvertTo-McpJson -InputObject $result)
+ } $Server $Uri
+ }
+
+ $script:root = Join-Path $TestDrive 'root'
+ $null = New-Item -ItemType Directory -Path (Join-Path $script:root 'sub') -Force
+ Set-Content -Path (Join-Path $script:root 'readme.md') -Value '# Readme' -NoNewline
+ Set-Content -Path (Join-Path $script:root 'sub' 'data.json') -Value '{"a":1}' -NoNewline
+ [System.IO.File]::WriteAllBytes((Join-Path $script:root 'image.png'), [byte[]] (137, 80, 78, 71))
+ Set-Content -Path (Join-Path $TestDrive 'secret.txt') -Value 'secret' -NoNewline
+}
+
+Describe 'Register-McpResource' {
+ It 'registers fixed text and binary content with MIME types and sizes' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ Register-McpResource -Server $server -Uri 'test://text' -Content 'héllo'
+ Register-McpResource -Server $server -Uri 'test://bin' -Content ([byte[]] (1, 2, 3)) -Name 'bin' -Title 'Binary' -Description 'Three bytes.'
+ $list = Invoke-McpInModule { param($s) Get-McpResourceListResult -Server $s -Cursor $null } $server
+ (Test-McpSpecShape -Definition 'ListResourcesResult' -Instance $list).IsValid | Should -BeTrue
+ $list['resources'][0]['mimeType'] | Should -Be 'text/plain'
+ $list['resources'][0]['size'] | Should -Be 6
+ $list['resources'][0]['name'] | Should -Be 'test://text'
+ $list['resources'][1]['mimeType'] | Should -Be 'application/octet-stream'
+ $list['resources'][1]['size'] | Should -Be 3
+ $list['resources'][1]['title'] | Should -Be 'Binary'
+ $binary = Read-TestResource -Server $server -Uri 'test://bin'
+ (Test-McpSpecShape -Definition 'ReadResourceResult' -Instance $binary).IsValid | Should -BeTrue
+ $binary['contents'][0]['blob'] | Should -Be 'AQID'
+ (Read-TestResource -Server $server -Uri 'test://text')['contents'][0]['text'] | Should -Be 'héllo'
+ }
+
+ It 'validates URIs, sources and duplicates' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ { Register-McpResource -Server $server -Uri 'not a uri' -Content 'x' } | Should -Throw -ExpectedMessage '*absolute URI*'
+ { Register-McpResource -Server $server -Uri 'test://x' } | Should -Throw -ExpectedMessage '*exactly one*'
+ { Register-McpResource -Server $server -Uri 'test://x' -Content 'a' -ScriptBlock { 'b' } } | Should -Throw -ExpectedMessage '*exactly one*'
+ { Register-McpResource -Server $server -Uri 'test://x' -Content 42 } | Should -Throw -ExpectedMessage '*string or a byte*'
+ Register-McpResource -Server $server -Uri 'test://x' -Content 'a'
+ { Register-McpResource -Server $server -Uri 'test://x' -Content 'b' } | Should -Throw -ExpectedMessage '*already registered*'
+ Register-McpResource -Server $server -Uri 'test://x' -Content 'b' -Force
+ (Read-TestResource -Server $server -Uri 'test://x')['contents'][0]['text'] | Should -Be 'b'
+ { Register-McpResource -Server $server -UriTemplate 'test://{a*}' -ScriptBlock { 'x' } } | Should -Throw -ExpectedMessage '*level 4*'
+ { Register-McpResource -Server $server -UriTemplate 'test://{a}' -ScriptBlock { 'x' } -Completion @{ b = @('1') } } | Should -Throw -ExpectedMessage '*not one of the arguments*'
+ }
+
+ It 'validates annotations and icons' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ $registration = Register-McpResource -Server $server -Uri 'test://a' -Content 'x' -PassThru -Annotations @{ Audience = 'user'; Priority = 0.5; LastModified = [datetime]::new(2026, 1, 2, 3, 4, 5, [System.DateTimeKind]::Utc) } -Icons @('https://example.com/i.png')
+ $registration.Annotations['audience'] | Should -Be @('user')
+ $registration.Annotations['priority'] | Should -Be 0.5
+ $registration.Annotations['lastModified'] | Should -Be '2026-01-02T03:04:05Z'
+ $registration.Icons[0]['src'] | Should -Be 'https://example.com/i.png'
+ $definition = Invoke-McpInModule { param($r) ConvertTo-McpResourceDefinition -Registration $r } $registration
+ (Test-McpSpecShape -Definition 'Resource' -Instance $definition).IsValid | Should -BeTrue
+ { Register-McpResource -Server $server -Uri 'test://b' -Content 'x' -Annotations @{ Priority = 2 } } | Should -Throw -ExpectedMessage '*from 0 to 1*'
+ { Register-McpResource -Server $server -Uri 'test://b' -Content 'x' -Annotations @{ Audience = 'robot' } } | Should -Throw -ExpectedMessage '*user or assistant*'
+ { Register-McpResource -Server $server -Uri 'test://b' -Content 'x' -Icons @(@{ src = 'ftp://x/i.png' }) } | Should -Throw -ExpectedMessage '*http, https or data*'
+ }
+}
+
+Describe 'Resource handlers and templates' {
+ It 'binds template variables by name and shapes objects as JSON' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ Register-McpResource -Server $server -UriTemplate 'items://{kind}/{id}' -MimeType 'application/json' -ScriptBlock {
+ param([string] $kind, [int] $id, $Uri, $Variables)
+ [ordered]@{ kind = $kind; id = $id; uri = $Uri; count = $Variables.Count }
+ }
+ $result = Read-TestResource -Server $server -Uri 'items://book/7'
+ (Test-McpSpecShape -Definition 'ReadResourceResult' -Instance $result).IsValid | Should -BeTrue
+ $result['contents'][0]['mimeType'] | Should -Be 'application/json'
+ $payload = ConvertFrom-Json $result['contents'][0]['text']
+ $payload.kind | Should -Be 'book'
+ $payload.id | Should -Be 7
+ $payload.uri | Should -Be 'items://book/7'
+ $payload.count | Should -Be 2
+ $templates = Invoke-McpInModule { param($s) Get-McpResourceTemplateListResult -Server $s -Cursor $null } $server
+ (Test-McpSpecShape -Definition 'ListResourceTemplatesResult' -Instance $templates).IsValid | Should -BeTrue
+ $templates['resourceTemplates'][0]['uriTemplate'] | Should -Be 'items://{kind}/{id}'
+ }
+
+ It 'joins strings, keeps byte arrays whole and passes New-McpResourceContent through' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ Register-McpResource -Server $server -Uri 'test://lines' -ScriptBlock { 'one'; 'two' }
+ Register-McpResource -Server $server -Uri 'test://bytes' -MimeType 'image/png' -ScriptBlock { [byte[]] (1, 2, 3) }
+ Register-McpResource -Server $server -Uri 'test://many' -ScriptBlock {
+ New-McpResourceContent -Text 'a' -MimeType 'text/markdown'
+ New-McpResourceContent -Blob ([byte[]] (255)) -Uri 'test://many/blob' -Meta @{ note = 'x' }
+ }
+ (Read-TestResource -Server $server -Uri 'test://lines')['contents'][0]['text'] | Should -Be "one`ntwo"
+ $bytes = (Read-TestResource -Server $server -Uri 'test://bytes')['contents']
+ $bytes.Count | Should -Be 1
+ $bytes[0]['blob'] | Should -Be 'AQID'
+ $bytes[0]['mimeType'] | Should -Be 'image/png'
+ $many = Read-TestResource -Server $server -Uri 'test://many'
+ (Test-McpSpecShape -Definition 'ReadResourceResult' -Instance $many).IsValid | Should -BeTrue
+ $many['contents'][0]['uri'] | Should -Be 'test://many'
+ $many['contents'][0]['mimeType'] | Should -Be 'text/markdown'
+ $many['contents'][1]['uri'] | Should -Be 'test://many/blob'
+ $many['contents'][1]['blob'] | Should -Be '/w=='
+ $many['contents'][1]['_meta']['note'] | Should -Be 'x'
+ }
+
+ It 'reports unknown URIs, empty output and ItemNotFoundException as not found (-32602 with the URI)' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ Register-McpResource -Server $server -Uri 'test://empty' -ScriptBlock { }
+ Register-McpResource -Server $server -Uri 'test://missing' -ScriptBlock { throw [System.Management.Automation.ItemNotFoundException]::new('gone') }
+ Register-McpResource -Server $server -Uri 'test://broken' -ScriptBlock { throw 'boom' }
+ foreach ($uri in 'test://unknown', 'test://empty', 'test://missing') {
+ $caught = $null
+ try { Read-TestResource -Server $server -Uri $uri } catch { $caught = $_.Exception }
+ while ($caught -and $caught -isnot [McpProtocolException] -and $caught.InnerException) { $caught = $caught.InnerException }
+ $caught | Should -BeOfType [McpProtocolException]
+ $caught.Code | Should -Be -32602
+ $caught.Message | Should -Be 'Resource not found'
+ $caught.Data['uri'] | Should -Be $uri
+ }
+ $caught = $null
+ try { Read-TestResource -Server $server -Uri 'test://broken' } catch { $caught = $_.Exception }
+ while ($caught -and $caught -isnot [McpProtocolException] -and $caught.InnerException) { $caught = $caught.InnerException }
+ $caught.Code | Should -Be -32603
+ $caught.Message | Should -Match 'boom'
+ }
+
+ It 'uses the resource caching hints and falls back to the server defaults' {
+ $server = New-McpServer -Name 'r' -Version '1' -DefaultTtlMs 1000 -DefaultCacheScope private
+ Register-McpResource -Server $server -Uri 'test://own' -Content 'x' -TtlMs 60000 -CacheScope public
+ Register-McpResource -Server $server -Uri 'test://default' -Content 'x'
+ $own = Read-TestResource -Server $server -Uri 'test://own'
+ $own['ttlMs'] | Should -Be 60000
+ $own['cacheScope'] | Should -Be 'public'
+ $default = Read-TestResource -Server $server -Uri 'test://default'
+ $default['ttlMs'] | Should -Be 1000
+ $default['cacheScope'] | Should -Be 'private'
+ }
+}
+
+Describe 'File and directory resources' {
+ It 'serves a file with the MIME type of its extension' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ $registration = Register-McpResource -Server $server -Path (Join-Path $script:root 'readme.md') -PassThru
+ $registration.Uri | Should -BeLike 'file:///*readme.md'
+ $registration.Name | Should -Be 'readme.md'
+ $registration.MimeType | Should -Be 'text/markdown'
+ $definition = Invoke-McpInModule { param($r) ConvertTo-McpResourceDefinition -Registration $r } $registration
+ $definition['size'] | Should -Be 8
+ (Read-TestResource -Server $server -Uri $registration.Uri)['contents'][0]['text'] | Should -Be '# Readme'
+ }
+
+ It 'serves the files below a directory as a template' {
+ $server = New-McpServer -Name 'r' -Version '1'
+ $registration = Register-McpResource -Server $server -Path $script:root -Uri 'docs://' -PassThru
+ $registration.UriTemplate | Should -Be 'docs://{+path}'
+ (Read-TestResource -Server $server -Uri 'docs://sub/data.json')['contents'][0]['mimeType'] | Should -Be 'application/json'
+ $image = (Read-TestResource -Server $server -Uri 'docs://image.png')['contents'][0]
+ $image['mimeType'] | Should -Be 'image/png'
+ $image['blob'] | Should -Be ([System.Convert]::ToBase64String([byte[]] (137, 80, 78, 71)))
+ $fileTemplate = Register-McpResource -Server $server -Path (Join-Path $script:root 'sub') -PassThru
+ $fileTemplate.UriTemplate | Should -BeLike 'file:///*/sub/{+path}'
+ }
+
+ It 'rejects paths that leave the directory: ' -TestCases @(
+ @{ Path = '../secret.txt' }
+ @{ Path = '%2e%2e/secret.txt' }
+ @{ Path = 'sub/../../secret.txt' }
+ @{ Path = 'sub' }
+ @{ Path = 'missing.txt' }
+ ) {
+ $server = New-McpServer -Name 'r' -Version '1'
+ Register-McpResource -Server $server -Path $script:root -Uri 'docs://'
+ { Read-TestResource -Server $server -Uri "docs://$Path" } | Should -Throw -ExpectedMessage '*Resource not found*'
+ }
+
+ It 'rejects absolute paths' {
+ $absolute = Invoke-McpInModule { param($r, $p) Resolve-McpDirectoryResourcePath -Root $r -RelativePath $p } $script:root (Join-Path $TestDrive 'secret.txt')
+ $absolute | Should -BeNullOrEmpty
+ }
+
+ It 'rejects symbolic links that lead outside the directory' -Skip:$IsWindows {
+ $linkRoot = Join-Path $TestDrive 'linked'
+ $null = New-Item -ItemType Directory -Path $linkRoot -Force
+ $null = New-Item -ItemType SymbolicLink -Path (Join-Path $linkRoot 'escape.txt') -Target (Join-Path $TestDrive 'secret.txt')
+ $null = New-Item -ItemType SymbolicLink -Path (Join-Path $linkRoot 'outside') -Target $TestDrive
+ $null = New-Item -ItemType SymbolicLink -Path (Join-Path $linkRoot 'sibling.md') -Target (Join-Path $linkRoot '..' 'root' 'readme.md')
+ Set-Content -Path (Join-Path $linkRoot 'plain.txt') -Value 'plain' -NoNewline
+ $resolve = { param($p) Invoke-McpInModule { param($r, $p) Resolve-McpDirectoryResourcePath -Root $r -RelativePath $p } $linkRoot $p }
+ & $resolve 'escape.txt' | Should -BeNullOrEmpty
+ & $resolve 'outside/secret.txt' | Should -BeNullOrEmpty
+ & $resolve 'sibling.md' | Should -BeNullOrEmpty
+ & $resolve 'plain.txt' | Should -Not -BeNullOrEmpty
+ }
+}
diff --git a/tests/Unit/Tools.Tests.ps1 b/tests/Unit/Tools.Tests.ps1
index c7e802c..9e61d86 100644
--- a/tests/Unit/Tools.Tests.ps1
+++ b/tests/Unit/Tools.Tests.ps1
@@ -57,6 +57,10 @@ Describe 'Register-McpTool' {
$registration = Register-McpTool -Name 'add' -ScriptBlock { param([Parameter(Mandatory)][int] $A, [int] $B = 1) $A + $B } -Server $script:server -PassThru
$registration.Handler.Kind | Should -Be 'ScriptBlock'
$registration.Handler.CommandName | Should -Be 'McpTool_add'
+ $separate = New-McpServer -Name 'names' -Version '1'
+ $dashed = Register-McpTool -Name 'a-b' -ScriptBlock { 'dash' } -Server $separate -PassThru
+ $underscored = Register-McpTool -Name 'a_b' -ScriptBlock { 'underscore' } -Server $separate -PassThru
+ $dashed.Handler.CommandName | Should -Not -Be $underscored.Handler.CommandName
$registration.InputSchema['properties']['A']['type'] | Should -Be 'integer'
$registration.InputSchema['properties']['B']['default'] | Should -Be 1
$registration.InputSchema['required'] | Should -Be @('A')
diff --git a/tests/Unit/UriTemplate.Tests.ps1 b/tests/Unit/UriTemplate.Tests.ps1
new file mode 100644
index 0000000..f826e5b
--- /dev/null
+++ b/tests/Unit/UriTemplate.Tests.ps1
@@ -0,0 +1,64 @@
+[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 Test-TemplateMatch {
+ param([string] $Template, [string] $Uri)
+ Invoke-McpInModule {
+ param($t, $u)
+ $parsed = ConvertFrom-McpUriTemplate -Template $t
+ Test-McpUriTemplateMatch -Template $parsed -Uri $u
+ } $Template $Uri
+ }
+}
+
+Describe 'RFC 6570 URI template matching' {
+ It 'matches against ' -TestCases @(
+ @{ Template = 'test://template/{id}/data'; Uri = 'test://template/123/data'; Expected = @{ id = '123' } }
+ @{ Template = 'weather://{city}/current'; Uri = 'weather://Berlin%20Mitte/current'; Expected = @{ city = 'Berlin Mitte' } }
+ @{ Template = 'docs://{+path}'; Uri = 'docs://guide/intro.md'; Expected = @{ path = 'guide/intro.md' } }
+ @{ Template = 'file:///srv{/dir,name}'; Uri = 'file:///srv/a/b.txt'; Expected = @{ dir = 'a'; name = 'b.txt' } }
+ @{ Template = 'app://x{.format}'; Uri = 'app://x.json'; Expected = @{ format = 'json' } }
+ @{ Template = 'app://x{;version}'; Uri = 'app://x;version=2'; Expected = @{ version = '2' } }
+ @{ Template = 'search://items{?q,limit}'; Uri = 'search://items?limit=5&q=a%26b'; Expected = @{ q = 'a&b'; limit = '5' } }
+ @{ Template = 'search://items?fixed=1{&page}'; Uri = 'search://items?fixed=1&page=3'; Expected = @{ page = '3' } }
+ @{ Template = 'page://doc{#section}'; Uri = 'page://doc#intro'; Expected = @{ section = 'intro' } }
+ @{ Template = 'pair://{a,b}'; Uri = 'pair://x,y'; Expected = @{ a = 'x'; b = 'y' } }
+ ) {
+ $variables = Test-TemplateMatch -Template $Template -Uri $Uri
+ $variables | Should -Not -BeNullOrEmpty
+ foreach ($key in $Expected.Keys) {
+ $variables[$key] | Should -BeExactly $Expected[$key]
+ }
+ }
+
+ It 'does not match against ' -TestCases @(
+ @{ Template = 'test://template/{id}/data'; Uri = 'test://template//data' }
+ @{ Template = 'test://template/{id}/data'; Uri = 'test://template/1/2/data' }
+ @{ Template = 'test://template/{id}/data'; Uri = 'test://template/1/data/more' }
+ @{ Template = 'weather://{city}/current'; Uri = 'WEATHER://berlin/current' }
+ ) {
+ Test-TemplateMatch -Template $Template -Uri $Uri | Should -BeNullOrEmpty
+ }
+
+ It 'lists the variables of a template in order' {
+ $parsed = Invoke-McpInModule { ConvertFrom-McpUriTemplate -Template 'a://{x}/{+y}{?z,w}' }
+ $parsed.Variables | Should -Be @('x', 'y', 'z', 'w')
+ }
+
+ It 'rejects ' -TestCases @(
+ @{ Template = 'a://{path*}'; Message = '*level 4*' }
+ @{ Template = 'a://{name:3}'; Message = '*level 4*' }
+ @{ Template = 'a://{x'; Message = "*unmatched '{'*" }
+ @{ Template = 'a://x}'; Message = "*unmatched '}'*" }
+ @{ Template = 'a://{}'; Message = '*empty expression*' }
+ @{ Template = 'a://{=x}'; Message = '*reserved operator*' }
+ @{ Template = 'a://{x}/{x}'; Message = '*more than once*' }
+ @{ Template = 'a://{bad-name}'; Message = '*invalid variable name*' }
+ ) {
+ { Invoke-McpInModule { param($t) ConvertFrom-McpUriTemplate -Template $t } $Template } | Should -Throw -ExpectedMessage $Message
+ }
+}