Skip to content

M1 + M2: protocol core, stdio, tools, Streamable HTTP and the conformance suite - #3

Merged
t11z merged 5 commits into
mainfrom
claude/admiring-tesla-r738sg
Sep 19, 2026
Merged

t11z merged 5 commits into
mainfrom
claude/admiring-tesla-r738sg

Conversation

@t11z

@t11z t11z commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Milestones M1 (protocol core, stdio, tools) and M2 (Streamable HTTP) of docs/implementation-plan.md / ROADMAP.md: the module speaks the stateless 2026-07-28 lifecycle over stdio and over Streamable HTTP on both sides, and the official conformance suite runs in CI against a baseline.

M1: protocol core, stdio, tools

Protocol core

  • System.Text.Json codec that keeps wire shapes: ordered, case-sensitive objects, arrays never unrolled, Int64/Double numbers, no DateTime coercion, request id types preserved, compact single-line output (ConvertFrom-/ConvertTo-McpJson).
  • JSON-RPC model with the specification's error codes and McpProtocolException (type accelerator); per-request _meta validation: -32602 for missing protocolVersion/clientCapabilities, -32022 with supported/requested for unknown versions; capability paths.
  • JSON Schema 2020-12: input schema generation from parameters (types, ValidateSet/Range/Length/Pattern/Count, comment-based help, constant defaults, common parameters and Context excluded); validation through the bundled JsonSchema.Net (2020-12 default, external $ref refused, depth and size limits) with a PowerShell fallback validator that also takes over when JsonSchema.Net 7.0 reports a circular reference for valid recursive schemas.

Server

  • New-McpServer, Register-McpTool (functions, cmdlets, script files, script blocks; explicit -InputSchema/-OutputSchema, annotations, icons, _meta), Start-McpServer, Stop-McpServer, Invoke-McpToolHandler (direct calls for tool unit tests).
  • Dispatcher: server/discover, tools/list (cursor pagination, ttlMs/cacheScope), tools/call in a hostless runspace pool with per-request cancellation tokens, notifications/progress, notifications/message when the request carries logLevel, notifications/cancelled, optional server-side timeout, EOF shutdown with a grace period; -32700/-32600/-32601 (also for the legacy initialize, naming the supported versions)/-32602/-32603 where the specification requires them.
  • Handler commands New-McpContent, New-McpToolResult, Write-McpProgress, Write-McpLog, Test-McpClientCapability; result shaping (strings → text, objects → JSON text plus structuredContent, outputSchema checks, handler errors → isError).

Client

  • Connect-McpServer (stdio process with captured stderr, or a server object in a background runspace over an in-memory transport), Disconnect-McpServer, Get-McpServerInfo, Get-McpTool, Invoke-McpTool with progress callbacks, log notifications, timeouts and cancellation; format views for the result objects.

M2: Streamable HTTP and the conformance suite

Server (Start-McpServer -Transport Http -Url ...)

  • System.Net.HttpListener host: one JSON-RPC request or notification per POST; the response is a single JSON object, or a request-scoped SSE stream when the handler sends progress or log notifications (keep-alive comments; a request that outlives the keep-alive interval switches to SSE so that a closed stream is detected and cancels the handler).
  • Validation of the request metadata headers against the body: MCP-Protocol-Version (must equal _meta.protocolVersion), Mcp-Method, Mcp-Name (tools/call, prompts/get, resources/read), Mcp-Param-* for parameters annotated with x-mcp-header, including the =?base64?...?= sentinel and numeric comparison for integers; violations answer 400 with -32020.
  • HTTP statuses per error code: 400 for -32700/-32600/-32602/-32020/-32021/-32022, 404 with -32601 for unknown and removed methods (initialize, ping, logging/setLevel, resources/subscribe, …), 202 without body for notifications, 405 with Allow: POST for GET and DELETE, 415, 413 (-MaxBodyBytes), 408 (body timeout).
  • DNS rebinding protection: the Host header must name the endpoint's host and port (404 otherwise; checked by the server itself because http.sys on Windows delivers any Host to an IP-bound prefix while the managed listener on Linux/macOS rejects other hosts on its own), and Origin validation (403): loopback origins and the server's own origin by default, -AllowedOrigins for others or *. -KeepAliveSeconds controls the SSE keep-alive.

Client (Connect-McpServer -Url ..., -Headers, -NoProxy)

  • HttpClient/SocketsHttpHandler transport without redirects or cookies, infinite client timeout with per-request cancellation, ResponseHeadersRead, an SSE reader that dispatches notifications/progress and notifications/message while waiting for the response, and timeouts that close the response stream (which cancels the request server-side; no notifications/cancelled on HTTP).
  • The request metadata headers on every request; Get-McpTool validates the x-mcp-header annotations of every tool and excludes invalid tools with a warning; Invoke-McpTool mirrors annotated arguments into Mcp-Param-* headers and retries once after a -32020 with a refreshed tool list. Sessions carry Endpoint.

Shared

  • Register-McpTool -Header @{ Parameter = 'HeaderName' } annotates the input schema; annotations are validated on registration (field-name tokens, primitive types, case-insensitive uniqueness, reachability through properties only).
  • Error responses without a determinable request id omit the id member (the specification schema types id as string or integer); sink messages carry the error code for the status mapping; tools.listChanged is advertised as false until subscriptions/listen lands in M4.

Conformance

  • tests/Conformance/everything-server.ps1 (every tool the server scenarios call, including test_custom_headers and the 2020-12 schema tool) and everything-client.ps1 (reads MCP_CONFORMANCE_*, calls the tools the scenario context names); the Conformance build task runs both legs of the pinned @modelcontextprotocol/conformance alpha (--requirements 2026-07-28) against conformance-baseline.yml (-ConformanceLeg, -ConformanceScenario, -ConformanceRequirements); .github/workflows/conformance.yml runs it on push and pull request and uploads output/conformance/.
  • Passing on the server leg: server-stateless (25 checks), tools-list, all seven tools-call-*, dns-rebinding-protection, server-sse-multiple-streams, plus the not-scored json-schema-2020-12, http-header-validation (14) and http-custom-header-server-validation (10). Client leg: tools_call, request-metadata, http-standard-headers, http-custom-headers (18), http-invalid-tool-headers (11), json-schema-ref-no-deref, auth/resource-mismatch, json-schema-2020-12-preservation (9).
  • The initial baseline lists the scenarios of later milestones: resources, prompts, completion and caching (M3), the input-required-result-* scenarios and sep-2322-client-request-state (M4), and the auth/* client scenarios (M6/M7).

Verification

  • 321 tests (87 new): header value encoding and decoding, x-mcp-header collection with every invalid placement, header matching, status mapping, Host and Origin checks, SSE parsing; an HTTP server in a background runspace with client round trips, SSE progress and logs, header mirroring, disconnect → cancellation (a timed-out client closes the stream and the handler stops within the keep-alive interval), and raw requests for every status and error code the specification assigns.
  • Performance over loopback HTTP: about 400 ms to connect (first request, worker warm-up), 35–40 ms per sequential tools/call; stdio numbers unchanged (in docs/development.md).

Build tooling

  • Format task (Invoke-Formatter); examples/ is analysed too; build.ps1 gained the conformance parameters.
  • The Analyze task runs every analysis in a fresh pwsh process with a timeout (tools/Invoke-ScriptAnalyzerWorker.ps1) and recovers from PSScriptAnalyzer 1.25's sporadic rule failures: its rules run in parallel tasks that are not entirely thread-safe, so a rule occasionally fails on a file with a NullReferenceException or, after a lost command lookup in its runspace pool, with "The term 'Get-Command' is not recognized", the process keeps the lost lookup in its command cache, and once in a while an analysis hangs (the Lint job of this PR hit all three in one run). The worker records findings and rule failures; the build re-runs a path whose process failed, timed out or lost a lookup, and re-analyses the remaining affected files one by one in further fresh processes, so a failure never hides a finding. Retries appear as build warnings.

Notes:

  • Functions defined in a nested scope of the caller must be registered as (Get-Command X) or as script blocks: a module function cannot see the caller's local scope.
  • Handlers blocked in a .NET call that ignores pipeline stops are only stopped when the call returns; long loops should watch $Context.CancellationToken.
  • The HTTP listener cannot terminate TLS on Linux/macOS; put a reverse proxy in front of it (or an http.sys certificate binding on Windows). Legacy (initialize) servers over HTTP are refused until M5.

Checklist

  • ./build.ps1 -Task CI passes locally (Analyze, Test, Package, PublishLocal) on PowerShell 7.4.20 / Linux: 321 passed, 5 skipped; ./build.ps1 -Task Conformance passes both legs against the baseline
  • New behaviour is covered by tests (unit, integration or spec)
  • CHANGELOG.md has an entry under [Unreleased] for user-visible changes
  • conformance-baseline.yml is unchanged or shrank — this PR introduces the conformance runs, so the baseline goes from empty to its initial list (scenarios of M3 to M7); from here on it may only shrink
  • Documentation updated where behaviour or public API changed (README, about topic, CONTRIBUTING, transports, conformance and development docs, tools README, roadmap, examples/http-server.ps1)

🤖 Generated with Claude Code

https://claude.ai/code/session_01BQgAZXnNBuZ3VREXtrWa82


Generated by Claude Code

…registry

Protocol core of milestone M1 without transports yet:

- System.Text.Json codec (ConvertFrom-/ConvertTo-McpJson) that keeps wire
  shapes: ordered, case-sensitive dictionaries, arrays never unrolled, Int64
  or Double numbers, no DateTime coercion, compact single-line output.
- JSON-RPC constructors and classification, the specification's error codes
  and McpProtocolException (exported as a type accelerator).
- Per-request _meta validation (-32602 for missing fields, -32022 with the
  supported versions for unknown protocol versions) and capability paths.
- JSON Schema support: input schema generation from parameter metadata,
  validation attributes, comment-based help and constant defaults; validation
  through the bundled JsonSchema.Net (2020-12 default, external $ref refused,
  size and depth limits) with a PowerShell fallback validator that also takes
  over when JsonSchema.Net 7.0 reports a circular reference for valid
  recursive schemas.
- New-McpServer, Register-McpTool (functions, cmdlets, scripts, script
  blocks), New-McpContent, New-McpToolResult and Invoke-McpToolHandler
  (validation, typed binding, result shaping, output schema checks);
  server/discover and tools/list results with cursor pagination and caching
  hints, checked against the vendored specification schema in the tests.
- Build: Format task (Invoke-Formatter), analyzer retries in fresh processes
  because a failed PSScriptAnalyzer command cache stays broken in-process.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQgAZXnNBuZ3VREXtrWa82
…ommands

Completes milestone M1 (protocol core, stdio, tools):

- Transports as data (stdio over raw UTF-8 streams, server processes with
  captured stderr, in-memory channel pairs) behind a few private functions.
- Dispatcher loop that decodes messages, answers server/discover and
  tools/list, hands tools/call to a hostless runspace pool, forwards the
  workers' responses and notifications, honours notifications/cancelled,
  enforces the request timeout and shuts down on end of stream or
  Stop-McpServer; answers to malformed input, unknown methods and the
  legacy initialize handshake follow the specification's error codes.
- Start-McpServer, Stop-McpServer, Write-McpProgress, Write-McpLog,
  Test-McpClientCapability; handlers get an Mcp.RequestContext with the
  request's metadata, cancellation token and message sink.
- Client: Connect-McpServer (stdio process or in-memory server object),
  Disconnect-McpServer, Get-McpServerInfo, Get-McpTool, Invoke-McpTool with
  progress callbacks, log notifications, timeouts and cancellation; format
  views for sessions, server info, tools and results.
- examples/echo-server.ps1, integration tests for the in-memory client and
  the stdio server (encoding, 1 MB payloads, progress, cancellation, stderr,
  BOM-free stdout, EOF shutdown, parallel handlers, raw protocol errors),
  Inspector CLI verification and measured performance in the docs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQgAZXnNBuZ3VREXtrWa82
…suite

Server: Start-McpServer -Transport Http serves the MCP endpoint on
System.Net.HttpListener with one JSON-RPC message per POST, JSON or
request-scoped SSE responses (progress, logs, keep-alives, disconnect
cancels the handler), validation of the request metadata headers
(MCP-Protocol-Version, Mcp-Method, Mcp-Name, Mcp-Param-* with the base64
sentinel), Origin checks, body limits and the HTTP statuses the
specification assigns to the JSON-RPC error codes.

Client: Connect-McpServer -Url on HttpClient with the request metadata
headers, an SSE reader, timeouts that close the stream, x-mcp-header
validation in Get-McpTool and header mirroring with one retry in
Invoke-McpTool. Register-McpTool -Header annotates input schemas.

Error responses without a determinable id omit the id member; sink
messages carry the error code for the status mapping; tools.listChanged
is advertised as false until subscriptions land.

Conformance: everything-server.ps1 and everything-client.ps1 fixtures,
the Conformance build task (both legs of the pinned alpha against
conformance-baseline.yml), the conformance workflow and an HTTP example.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQgAZXnNBuZ3VREXtrWa82
@t11z t11z changed the title M1: protocol core, stdio transport, tools and the client commands M1 + M2: protocol core, stdio, tools, Streamable HTTP and the conformance suite Sep 19, 2026
The managed HttpListener on Linux and macOS answers requests whose Host
header does not match the prefix host with 404 on its own, but http.sys
on Windows delivers requests with any Host header to a prefix bound to
an IP address, so the DNS rebinding test received 200 on the Windows
jobs. The server now checks the Host header (host and port, the port
optional when it is the scheme default) before anything else and answers
404, so the behaviour no longer depends on the listener implementation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQgAZXnNBuZ3VREXtrWa82
PSScriptAnalyzer 1.25 runs its rules in parallel tasks that are not
entirely thread-safe: now and then a rule fails on a file with a
NullReferenceException or, after a lost command lookup in its runspace
pool, with "The term 'Get-Command' is not recognized"; the process keeps
the failed lookup in its command cache, so every later analysis in the
process fails too, and once in a while an analysis hangs. The Lint job
of the pull request hit all three in one run.

The Analyze task now runs every analysis in a fresh pwsh process with a
timeout (tools/Invoke-ScriptAnalyzerWorker.ps1). The worker records the
findings together with the rule failures, which the analyzer reports as
non-terminating errors targeting the affected file. The build re-runs a
path whose process failed, timed out or lost a lookup that affected many
files, and re-analyses the remaining affected files one by one in
further fresh processes, so a failure never hides a finding. Retries
appear as build warnings.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQgAZXnNBuZ3VREXtrWa82
@t11z
t11z merged commit 1557b5f into main Sep 19, 2026
13 checks passed
@t11z
t11z deleted the claude/admiring-tesla-r738sg branch September 19, 2026 18:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants