mirror of
https://github.com/badlogic/pi-mono.git
synced 2026-12-05 13:56:25 +00:00
feat(mcp,coding-agent): support the stateless MCP protocol 2026-07-28
Every connection still starts with initialize, so servers of earlier revisions see exactly what they saw before. Only servers that reject initialize (a JSON-RPC error, or HTTP 400) are asked with server/discover and spoken to with 2026-07-28; a stdio server that exits after rejecting initialize with a 2026-07-28 error (rmcp) is started once more with it. "protocol": "2026-07-28" pins the stateless revision. On the stateless revision: per-request _meta, multi round-trip requests answered with the client's handlers (roots/list), Mcp-Method, Mcp-Name and Mcp-Param-* headers with x-mcp-header validation and one re-list on header mismatch, sessionless HTTP with cancel by closing the stream, and logLevel. Reworked from #12479 by @dmmulroy without probing servers first, which broke Python servers before mcp 1.9.4 and rmcp 0.8. Refs #10416
This commit is contained in:
parent
2126569de4
commit
356d346e48
23 changed files with 1940 additions and 70 deletions
|
|
@ -2,6 +2,10 @@
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Added MCP `2026-07-28`, the stateless revision. Pi still starts every connection with `initialize`, so existing servers work as before. Servers that reject `initialize` are spoken to with `2026-07-28`; a stdio server that exits after rejecting it is started once more. `"protocol": "2026-07-28"` in `mcp.json` uses it with servers that speak both revisions. See [Protocol versions](docs/mcp.md#protocol-versions). Based on [#12479](https://github.com/earendil-works/pi/pull/12479) by [@dmmulroy](https://github.com/dmmulroy) ([#10416](https://github.com/earendil-works/pi/issues/10416))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed WSL detection in terminals that start the shell without the WSL environment variables (for example from a systemd user service): the Windows keybinding defaults (`alt+v` image paste, `ctrl+q` follow-up) and the footer's branch polling for repos under `/mnt/<drive>` now apply there too, because all WSL checks share one detection that falls back to `/proc/version`.
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ HTTP servers use `url`, `headers`, and `oauth` (see [Authenticate with OAuth](#a
|
|||
Both server types support:
|
||||
|
||||
- `timeout`: per-request timeout in seconds (default 60). Progress notifications reset it.
|
||||
- `protocol`: `"2026-07-28"` to speak only the stateless MCP revision (see [Protocol versions](#protocol-versions)). Default: `"auto"`.
|
||||
- `enabled: false`: keep the entry without connecting to it.
|
||||
- `exposure` and `toolExposure`: control how tools reach the model (see [Control tool exposure](#control-tool-exposure)).
|
||||
- `description`: what the server offers, in a sentence. It lists the server in the system prompt (see [Control tool exposure](#control-tool-exposure)), tool search ranks the server's tools by it, and codemode's `describeNamespace()` returns it. Without it, the first line of the server instructions is used once the server connects.
|
||||
|
|
@ -101,6 +102,16 @@ Pi connects every enabled server in the background when a session starts. A serv
|
|||
|
||||
Stopping a stdio server closes its stdin, sends SIGTERM, then sends SIGKILL to its process group. This also stops servers launched through wrappers such as `npx` or `uvx`.
|
||||
|
||||
### Protocol versions
|
||||
|
||||
MCP `2026-07-28` is a stateless revision without the `initialize` handshake of earlier revisions. Pi starts every connection with `initialize`, as servers of earlier revisions expect, so they work as before. Servers that speak both revisions answer it and use the earlier one: older servers break on any request they do not know (Python servers before mcp 1.9.4 stop answering), so pi does not ask them whether they speak `2026-07-28` too.
|
||||
|
||||
A server that rejects `initialize` is asked with `server/discover` and spoken to with `2026-07-28`. A stdio server that exits after rejecting `initialize` is started once more with `2026-07-28`.
|
||||
|
||||
Set `"protocol": "2026-07-28"` to use the stateless revision with a server that speaks both.
|
||||
|
||||
With `2026-07-28` servers, pi answers their requests for the workspace roots, and fails tool calls that ask for other input (elicitation or sampling), which pi does not support. Their tool list changes are not followed: reconnect the server to pick up new tools.
|
||||
|
||||
## Migrate configuration from another client
|
||||
|
||||
Move the converted entry under `mcpServers` in `mcp.json`, then run `pi mcp list` to validate it.
|
||||
|
|
|
|||
|
|
@ -66,8 +66,8 @@ const MCP_EXPOSURES: readonly string[] = ["codemode", "deferred", "direct", "hid
|
|||
const MCP_EXPOSURE_ALIASES: Readonly<Record<string, McpExposure>> = { "codemode-deferred": "codemode" };
|
||||
|
||||
/**
|
||||
* pi's fields of every server entry, beside the shared `mcpServers` fields of pi-mcp. `description`
|
||||
* and `timeout` are shared fields, declared again for pi's documentation.
|
||||
* pi's fields of every server entry, beside the shared `mcpServers` fields of pi-mcp. `description`,
|
||||
* `timeout` and `protocol` are shared fields, declared again for pi's documentation.
|
||||
*/
|
||||
interface McpServerConfigBase {
|
||||
/** Default: `codemode`. */
|
||||
|
|
@ -86,6 +86,11 @@ interface McpServerConfigBase {
|
|||
toolExposure?: Record<string, McpExposure>;
|
||||
/** Per-request timeout in seconds. Progress notifications from the server reset it. Default: 60. */
|
||||
timeout?: number;
|
||||
/**
|
||||
* `auto` (default): `initialize`, and MCP 2026-07-28 (stateless) only for servers that reject it.
|
||||
* `2026-07-28`: only the stateless revision, also for servers that speak both.
|
||||
*/
|
||||
protocol?: "auto" | "2026-07-28";
|
||||
}
|
||||
|
||||
export interface McpStdioServerConfig extends McpStdioServerFields, McpServerConfigBase {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { pathToFileURL } from "node:url";
|
|||
import {
|
||||
type AuthProvider,
|
||||
type CallToolResult,
|
||||
isStatelessRevisionError,
|
||||
JSON_RPC_ERROR_CODES,
|
||||
type ListResourcesResult,
|
||||
type ListResourceTemplatesResult,
|
||||
|
|
@ -18,6 +19,7 @@ import {
|
|||
McpClient,
|
||||
McpError,
|
||||
McpHttpError,
|
||||
type McpProtocolMode,
|
||||
type McpRequestOptions,
|
||||
McpSessionExpiredError,
|
||||
type Tool as McpTool,
|
||||
|
|
@ -25,6 +27,7 @@ import {
|
|||
type ReadResourceResult,
|
||||
type Resource,
|
||||
type ResourceTemplate,
|
||||
STATELESS_PROTOCOL_VERSION,
|
||||
StdioTransport,
|
||||
StreamableHttpTransport,
|
||||
} from "@earendil-works/pi-mcp";
|
||||
|
|
@ -343,12 +346,27 @@ export class McpServerConnection implements McpToolCaller, McpResourceServer {
|
|||
this.state = "connecting";
|
||||
this.changed();
|
||||
const retries = "url" in this.entry.config ? CONNECT_RETRY_DELAYS_MS : [];
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const configured = this.entry.config.protocol;
|
||||
let protocol: McpProtocolMode = configured ?? "auto";
|
||||
let restarted = false;
|
||||
for (let attempt = 0; ; ) {
|
||||
this.stderrTail = undefined;
|
||||
try {
|
||||
return await this.connectOnce();
|
||||
return await this.connectOnce(protocol);
|
||||
} catch (error) {
|
||||
const delay = retries[attempt];
|
||||
// A stdio server that only speaks the stateless revision may exit after rejecting
|
||||
// `initialize` (rmcp servers do); start it once more with that revision.
|
||||
const restart =
|
||||
configured === undefined &&
|
||||
!restarted &&
|
||||
!("url" in this.entry.config) &&
|
||||
isStatelessRevisionError(error);
|
||||
if (restart && !this.closed) {
|
||||
restarted = true;
|
||||
protocol = STATELESS_PROTOCOL_VERSION;
|
||||
continue;
|
||||
}
|
||||
const delay = retries[attempt++];
|
||||
if (this.closed || delay === undefined || !isTransientError(error)) {
|
||||
throw this.connectFailed(error);
|
||||
}
|
||||
|
|
@ -358,14 +376,17 @@ export class McpServerConnection implements McpToolCaller, McpResourceServer {
|
|||
}
|
||||
}
|
||||
|
||||
private async connectOnce(): Promise<McpClient> {
|
||||
private async connectOnce(protocol: McpProtocolMode): Promise<McpClient> {
|
||||
const log = this.log;
|
||||
const client = new McpClient({
|
||||
name: "pi",
|
||||
version: VERSION,
|
||||
protocol,
|
||||
requestTimeoutMs: this.timeoutMs,
|
||||
roots: [{ uri: pathToFileURL(this.cwd).href, name: basename(this.cwd) }],
|
||||
// Servers on the stateless revision send log messages only for requests that ask for them.
|
||||
...(log ? { logLevel: "info" as const } : {}),
|
||||
});
|
||||
const log = this.log;
|
||||
if (log) client.onNotification("notifications/message", (params) => log.write(this.entry.name, params));
|
||||
// Closing the client fails its pending initialize or discovery requests and closes the transport.
|
||||
// Memoized: a second `client.close()` returns before the first finished closing the transport.
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ CI runs it in the `mcp-conformance` job of `.github/workflows/ci.yml`. Requires
|
|||
|
||||
## How it works
|
||||
|
||||
For every protocol version pi negotiates (`2025-03-26`, `2025-06-18`, `2025-11-25`), `run.ts` lists the suite's client scenarios and runs them one at a time. The suite starts a scenario server and runs `client.ts` against it.
|
||||
For every protocol version pi speaks (`2025-03-26`, `2025-06-18`, `2025-11-25` through `initialize`, and the stateless `2026-07-28`), `run.ts` lists the suite's client scenarios and runs them one at a time. The suite starts a scenario server and runs `client.ts` against it.
|
||||
|
||||
`client.ts` uses the code pi runs for an HTTP server in `mcp.json`: `McpServerConnection` connects and calls tools, and `signInMcpServer` runs the OAuth sign-in that `/mcp` starts. A simulated browser fetches the authorization URL and delivers the redirect to pi's loopback callback server. When the server asks for sign-in again (for example for more scope), the simulated user signs in again, up to three times.
|
||||
|
||||
|
|
@ -41,5 +41,7 @@ node packages/coding-agent/test/mcp-conformance/run.ts --update-baseline
|
|||
- `elicitation-sep1034-client-defaults`: pi does not support elicitation.
|
||||
- `auth/basic-cimd`: pi uses its Client ID Metadata Document on pi.dev, not the suite's `https://conformance-test.local/client-metadata.json`.
|
||||
- `auth/scope-retry-limit`: `pi-client` fails by design; the server never accepts the granted scope.
|
||||
|
||||
2026-07-28 is not covered: it is a stateless protocol pi does not implement.
|
||||
- `request-metadata` and `http-standard-headers` (2026-07-28): pi sends `initialize` first and stays on the earlier revision with servers that answer it, so these servers, which speak both, get no stateless requests (`request-metadata`), and the `initialize` request has no `Mcp-Method` header (`http-standard-headers`).
|
||||
- `sep-2322-client-request-state` (2026-07-28): the scenario asks for input with `elicitation/create`, which pi does not support, so the checks of retried requests fail. pi-mcp's tests cover the retries with `roots/list`.
|
||||
- `auth/resource-mismatch`, `auth/iss-supported-missing`, `auth/iss-wrong-issuer`, `auth/iss-unexpected`, `auth/iss-normalized`, `auth/metadata-issuer-mismatch` (2026-07-28): `pi-client` fails by design; pi refuses the sign-in, which these scenarios check.
|
||||
- `auth/authorization-server-migration` (2026-07-28): pi does not register again when the protected resource names a new authorization server (SEP-2352).
|
||||
|
|
|
|||
|
|
@ -407,6 +407,522 @@
|
|||
],
|
||||
"failing": []
|
||||
}
|
||||
},
|
||||
"2026-07-28": {
|
||||
"tools_call": {
|
||||
"passing": [
|
||||
"pi-client",
|
||||
"tool-add-numbers",
|
||||
"wire-schema-valid"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"request-metadata": {
|
||||
"passing": [
|
||||
"pi-client",
|
||||
"sep-2575-client-declares-roots-capability",
|
||||
"sep-2575-client-retry-supported-version",
|
||||
"sep-2575-http-version-header-matches-meta"
|
||||
],
|
||||
"failing": [
|
||||
"sep-2575-client-populates-meta",
|
||||
"sep-2575-client-sends-client-info",
|
||||
"sep-2575-http-client-sends-version-header"
|
||||
]
|
||||
},
|
||||
"auth/metadata-default": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/metadata-var1": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/metadata-var2": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/metadata-var3": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/basic-cimd": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": [
|
||||
"cimd-client-id-used"
|
||||
]
|
||||
},
|
||||
"auth/scope-from-www-authenticate": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"scope-from-www-authenticate",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/scope-from-scopes-supported": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"scope-from-scopes-supported",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/scope-omitted-when-undefined": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"scope-omitted-when-undefined",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/scope-step-up": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"scope-step-up-escalation",
|
||||
"scope-step-up-initial",
|
||||
"sep-2350-scope-union-on-reauth",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/scope-retry-limit": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"scope-retry-limit",
|
||||
"sep-837-application-type-present",
|
||||
"token-request"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"auth/token-endpoint-auth-basic": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"resource-parameter-consistency",
|
||||
"resource-parameter-in-authorization",
|
||||
"resource-parameter-in-token",
|
||||
"resource-parameter-valid-uri",
|
||||
"sep-837-application-type-present",
|
||||
"token-endpoint-auth-method",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/token-endpoint-auth-post": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"resource-parameter-consistency",
|
||||
"resource-parameter-in-authorization",
|
||||
"resource-parameter-in-token",
|
||||
"resource-parameter-valid-uri",
|
||||
"sep-837-application-type-present",
|
||||
"token-endpoint-auth-method",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/token-endpoint-auth-none": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"resource-parameter-consistency",
|
||||
"resource-parameter-in-authorization",
|
||||
"resource-parameter-in-token",
|
||||
"resource-parameter-valid-uri",
|
||||
"sep-837-application-type-present",
|
||||
"token-endpoint-auth-method",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/pre-registration": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"pre-registration-auth",
|
||||
"prm-pathbased-requested",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/resource-mismatch": {
|
||||
"passing": [
|
||||
"authorization-server-metadata",
|
||||
"prm-pathbased-requested",
|
||||
"resource-mismatch-rejected"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"auth/offline-access-scope": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/offline-access-not-supported": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2207-offline-access-not-requested",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/authorization-server-migration": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2352-no-cross-as-credential-reuse",
|
||||
"sep-2352-no-reuse-on-as-change",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client",
|
||||
"sep-2352-reregister-on-as-change"
|
||||
]
|
||||
},
|
||||
"auth/iss-supported": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-compare-iss-supported",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/iss-not-advertised": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pi-client",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-code-verifier-sent",
|
||||
"pkce-s256-method-used",
|
||||
"pkce-verifier-matches-challenge",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-proceed-no-iss",
|
||||
"sep-837-application-type-present",
|
||||
"token-request",
|
||||
"valid-bearer-token"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"auth/iss-supported-missing": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-s256-method-used",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-reject-missing-iss",
|
||||
"sep-837-application-type-present"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"auth/iss-wrong-issuer": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-s256-method-used",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-compare-iss-supported",
|
||||
"sep-837-application-type-present"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"auth/iss-unexpected": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-s256-method-used",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-compare-iss-unadvertised",
|
||||
"sep-837-application-type-present"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"auth/iss-normalized": {
|
||||
"passing": [
|
||||
"authorization-request",
|
||||
"authorization-server-metadata",
|
||||
"client-registration",
|
||||
"pkce-code-challenge-sent",
|
||||
"pkce-s256-method-used",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-no-normalization",
|
||||
"sep-837-application-type-present"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"auth/metadata-issuer-mismatch": {
|
||||
"passing": [
|
||||
"authorization-server-metadata",
|
||||
"prm-pathbased-requested",
|
||||
"sep-2468-client-validate-metadata-issuer"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client"
|
||||
]
|
||||
},
|
||||
"sep-2322-client-request-state": {
|
||||
"passing": [
|
||||
"sep-2322-client-parallel-isolation",
|
||||
"sep-2322-default-result-type-complete"
|
||||
],
|
||||
"failing": [
|
||||
"pi-client",
|
||||
"sep-2322-client-jsonrpc-id-different",
|
||||
"sep-2322-client-no-state-omitted",
|
||||
"sep-2322-client-request-state-echoed"
|
||||
]
|
||||
},
|
||||
"http-standard-headers": {
|
||||
"passing": [
|
||||
"pi-client"
|
||||
],
|
||||
"failing": [
|
||||
"sep-2243-client-includes-standard-headers"
|
||||
]
|
||||
},
|
||||
"http-custom-headers": {
|
||||
"passing": [
|
||||
"pi-client",
|
||||
"sep-2243-client-base64-unsafe",
|
||||
"sep-2243-client-encode-values",
|
||||
"sep-2243-client-mirrors-designated-params",
|
||||
"sep-2243-client-omit-null",
|
||||
"sep-2243-client-supports-custom-headers"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"http-invalid-tool-headers": {
|
||||
"passing": [
|
||||
"pi-client",
|
||||
"sep-2243-client-reject-invalid-tool",
|
||||
"sep-2243-x-mcp-header-charset",
|
||||
"sep-2243-x-mcp-header-not-empty",
|
||||
"sep-2243-x-mcp-header-primitive-only",
|
||||
"sep-2243-x-mcp-header-unique"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"json-schema-ref-no-deref": {
|
||||
"passing": [
|
||||
"pi-client",
|
||||
"sep-2106-no-network-ref-deref"
|
||||
],
|
||||
"failing": []
|
||||
},
|
||||
"json-schema-2020-12-preservation": {
|
||||
"passing": [
|
||||
"json-schema-2020-12-client-$defs-preserved",
|
||||
"json-schema-2020-12-client-$schema-preserved",
|
||||
"json-schema-2020-12-client-additionalProperties-preserved",
|
||||
"json-schema-2020-12-client-echo-completed",
|
||||
"json-schema-2020-12-client-tool-found",
|
||||
"pi-client",
|
||||
"sep-2106-client-anchor-keyword-preserved",
|
||||
"sep-2106-client-composition-keywords-preserved",
|
||||
"sep-2106-client-conditional-keywords-preserved",
|
||||
"wire-schema-valid"
|
||||
],
|
||||
"failing": []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,12 +36,31 @@ interface ToolCall {
|
|||
arguments: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Tool calls of a scenario after connecting. `undefined` for scenarios this client does not know. */
|
||||
function toolCalls(scenario: string, connection: McpServerConnection): ToolCall[] | undefined {
|
||||
/**
|
||||
* Tool calls of a scenario after connecting. `undefined` for scenarios this client does not know. A
|
||||
* scenario's context may list its calls itself.
|
||||
*/
|
||||
function toolCalls(
|
||||
scenario: string,
|
||||
connection: McpServerConnection,
|
||||
context: Record<string, unknown>,
|
||||
): ToolCall[] | undefined {
|
||||
if (Array.isArray(context.toolCalls)) return context.toolCalls as ToolCall[];
|
||||
if (scenario.startsWith("auth/")) return [{ name: "test-tool", arguments: {} }];
|
||||
switch (scenario) {
|
||||
case "initialize":
|
||||
case "request-metadata":
|
||||
case "json-schema-ref-no-deref":
|
||||
return [];
|
||||
// pi must have left out the tools with invalid `x-mcp-header` annotations.
|
||||
case "http-invalid-tool-headers":
|
||||
case "http-standard-headers":
|
||||
return connection.tools.map((tool) => ({ name: tool.name, arguments: {} }));
|
||||
// Calls that need no input first: the others ask for elicitation, which pi does not provide.
|
||||
case "sep-2322-client-request-state":
|
||||
return ["test_mrtr_unrelated", "test_mrtr_no_result_type", "test_mrtr_no_state", "test_mrtr_echo_state"].map(
|
||||
(name) => ({ name, arguments: {} }),
|
||||
);
|
||||
case "tools_call":
|
||||
return [{ name: "add_numbers", arguments: { a: 2, b: 3 } }];
|
||||
case "sse-retry":
|
||||
|
|
@ -162,15 +181,28 @@ async function run(serverUrl: string, scenario: string): Promise<void> {
|
|||
};
|
||||
|
||||
try {
|
||||
await withSignIn(() => connection.getClient());
|
||||
log(`connected, tools: ${connection.tools.map((tool) => tool.name).join(", ") || "(none)"}`);
|
||||
const calls = toolCalls(scenario, connection);
|
||||
const client = await withSignIn(() => connection.getClient());
|
||||
log(
|
||||
`connected (${client.protocolVersion}), tools: ${connection.tools.map((tool) => tool.name).join(", ") || "(none)"}`,
|
||||
);
|
||||
const calls = toolCalls(scenario, connection, context);
|
||||
if (!calls) throw new Error(`Unknown scenario ${scenario}`);
|
||||
const failures: string[] = [];
|
||||
for (const call of calls) {
|
||||
const result = await withSignIn(() => connection.callTool(call.name, call.arguments, {}));
|
||||
log(`${call.name}: ${JSON.stringify(result.content)}`);
|
||||
if (result.isError) throw new Error(`Tool ${call.name} failed: ${JSON.stringify(result.content)}`);
|
||||
try {
|
||||
const result = await withSignIn(() => connection.callTool(call.name, call.arguments, {}));
|
||||
log(`${call.name}: ${JSON.stringify(result.content)}`);
|
||||
if (result.isError) failures.push(`Tool ${call.name} failed: ${JSON.stringify(result.content)}`);
|
||||
} catch (error) {
|
||||
// Later calls may exercise other checks.
|
||||
failures.push(`Tool ${call.name} failed: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
if (scenario === "http-standard-headers" && connection.hasResources) {
|
||||
const [resource] = await connection.allResources({});
|
||||
if (resource) await connection.readResource(resource.uri, {});
|
||||
}
|
||||
if (failures.length > 0) throw new Error(failures.join("; "));
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,8 +23,8 @@ import { parseArgs } from "node:util";
|
|||
|
||||
/** The pinned upstream suite. Bumping it requires reviewing and regenerating the baseline. */
|
||||
const CONFORMANCE_PACKAGE = "@modelcontextprotocol/conformance@0.2.0-alpha.11";
|
||||
/** Protocol versions pi negotiates. 2026-07-28 is a different (stateless) protocol pi does not speak. */
|
||||
const MODES = ["2025-03-26", "2025-06-18", "2025-11-25"] as const;
|
||||
/** Protocol versions pi speaks: the ones `initialize` negotiates, and the stateless 2026-07-28. */
|
||||
const MODES = ["2025-03-26", "2025-06-18", "2025-11-25", "2026-07-28"] as const;
|
||||
const SCENARIO_TIMEOUT_MS = 30_000;
|
||||
/** Checks that are part of the suite's HTTP trace, not assertions. */
|
||||
const IGNORED_STATUSES = new Set(["INFO", "SKIPPED"]);
|
||||
|
|
|
|||
|
|
@ -585,6 +585,105 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|||
await connection.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* In-memory server that only speaks MCP 2026-07-28 and records requests: it rejects `initialize`.
|
||||
* `exit`: it is gone after that, as rmcp servers are.
|
||||
*/
|
||||
function createStatelessTransport(requests: { method: string; params: unknown }[], kind: "stay" | "exit" = "stay") {
|
||||
const pair = createInMemoryTransportPair();
|
||||
servers.push(pair.server);
|
||||
let rejected = false;
|
||||
pair.server.onMessage((message) => {
|
||||
if (!("id" in message) || !("method" in message)) return;
|
||||
requests.push({ method: message.method, params: message.params });
|
||||
const reply = (payload: Record<string, unknown>) =>
|
||||
queueMicrotask(
|
||||
() => void pair.server.send({ jsonrpc: "2.0", id: message.id, ...payload } as JsonRpcMessage),
|
||||
);
|
||||
if (rejected && kind === "exit") {
|
||||
void pair.server.close();
|
||||
} else if (message.method === "initialize") {
|
||||
reply({
|
||||
error: { code: -32022, message: "Unsupported protocol version", data: { supported: ["2026-07-28"] } },
|
||||
});
|
||||
rejected = true;
|
||||
} else if (message.method === "server/discover") {
|
||||
reply({ result: { supportedVersions: ["2026-07-28"], capabilities: { tools: {} } } });
|
||||
} else if (message.method === "tools/list") {
|
||||
reply({ result: { tools: [{ name: "echo", inputSchema: { type: "object" } }] } });
|
||||
} else {
|
||||
reply({ result: { resultType: "complete", content: [{ type: "text", text: "ok" }] } });
|
||||
}
|
||||
});
|
||||
void pair.server.start();
|
||||
return pair.client;
|
||||
}
|
||||
|
||||
it("connects to servers that only speak MCP 2026-07-28, asking for log messages", async () => {
|
||||
const requests: { method: string; params: unknown }[] = [];
|
||||
const log = new McpServerLog(join(tmpdir(), "unused-mcp.log"));
|
||||
const { connection } = connect(
|
||||
{ name: "fake", config: { command: "unused" }, source: "test" },
|
||||
[() => createStatelessTransport(requests)],
|
||||
log,
|
||||
);
|
||||
expect((await connection.getClient()).protocolVersion).toBe("2026-07-28");
|
||||
expect(connection.tools.map((tool) => tool.name)).toEqual(["echo"]);
|
||||
expect(await connection.callTool("echo", {}, {})).toEqual({
|
||||
resultType: "complete",
|
||||
content: [{ type: "text", text: "ok" }],
|
||||
});
|
||||
expect(requests.map((request) => request.method)).toEqual([
|
||||
"initialize",
|
||||
"server/discover",
|
||||
"tools/list",
|
||||
"tools/call",
|
||||
]);
|
||||
expect(requests[1]?.params).toMatchObject({
|
||||
_meta: {
|
||||
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
||||
"io.modelcontextprotocol/clientInfo": { name: "pi" },
|
||||
"io.modelcontextprotocol/clientCapabilities": { roots: {} },
|
||||
"io.modelcontextprotocol/logLevel": "info",
|
||||
},
|
||||
});
|
||||
await connection.close();
|
||||
|
||||
// Pinned, the server is not asked to initialize.
|
||||
requests.length = 0;
|
||||
const pinned = connect({ name: "fake", config: { command: "unused", protocol: "2026-07-28" }, source: "test" }, [
|
||||
() => createStatelessTransport(requests),
|
||||
]);
|
||||
await pinned.connection.getClient();
|
||||
expect(requests.map((request) => request.method)).toEqual(["server/discover", "tools/list"]);
|
||||
await pinned.connection.close();
|
||||
});
|
||||
|
||||
it("starts a stdio server again with MCP 2026-07-28 when it is gone after rejecting initialize", async () => {
|
||||
const requests: { method: string; params: unknown }[] = [];
|
||||
const { connection, opened } = connect({ name: "fake", config: { command: "unused" }, source: "test" }, [
|
||||
() => createStatelessTransport(requests, "exit"),
|
||||
() => createStatelessTransport(requests, "exit"),
|
||||
]);
|
||||
expect((await connection.getClient()).protocolVersion).toBe("2026-07-28");
|
||||
expect(opened()).toBe(2);
|
||||
expect(requests.map((request) => request.method)).toEqual([
|
||||
"initialize",
|
||||
"server/discover",
|
||||
"server/discover",
|
||||
"tools/list",
|
||||
]);
|
||||
await connection.close();
|
||||
|
||||
// Only once, and not for servers that answer `initialize`.
|
||||
const legacy = connect({ name: "fake", config: { command: "unused" }, source: "test" }, [
|
||||
() => createTransport(),
|
||||
]);
|
||||
await legacy.connection.getClient();
|
||||
expect(legacy.opened()).toBe(1);
|
||||
await legacy.connection.close();
|
||||
});
|
||||
|
||||
it("marks a dropped connection and reconnects on the next call", async () => {
|
||||
const { connection, opened } = connect({ name: "fake", config: { command: "unused" }, source: "test" }, [
|
||||
() => createTransport(),
|
||||
|
|
|
|||
|
|
@ -2,6 +2,12 @@
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Added MCP `2026-07-28`, the stateless protocol revision. `McpClient` still sends `initialize` first, so servers of earlier revisions see no change. It switches to `server/discover` and the stateless revision only for servers that reject `initialize`. `protocol: "2026-07-28"` speaks only that revision. Supports multi round-trip requests (answered with the client's request handlers, such as `roots/list`), the `Mcp-Method`, `Mcp-Name`, and `Mcp-Param-*` HTTP headers, and `logLevel` for servers' log messages. Based on [#12479](https://github.com/earendil-works/pi/pull/12479) by [@dmmulroy](https://github.com/dmmulroy) ([#10416](https://github.com/earendil-works/pi/issues/10416))
|
||||
- Added `isStatelessRevisionError(error)`, which tells errors only servers of `2026-07-28` send
|
||||
- Added `protocol` to the shared `mcpServers` config fields (`"auto"` or `"2026-07-28"`)
|
||||
|
||||
## [1.7.0] - 2026-11-27
|
||||
|
||||
## [1.6.1] - 2026-11-25
|
||||
|
|
|
|||
|
|
@ -29,6 +29,20 @@ For a remote server, use `new StreamableHttpTransport({ url, headers })`. Fetch
|
|||
|
||||
An MCP transport owns framing and I/O. It delivers individual JSON-RPC messages to `McpClient`; the client owns request correlation, initialization, timeouts, cancellation, server requests, and protocol-level helpers.
|
||||
|
||||
### Protocol versions
|
||||
|
||||
MCP `2026-07-28` is a stateless revision: there is no `initialize` handshake and no session, and every request carries the protocol version and the client's info and capabilities in `_meta`. Earlier revisions start with `initialize`.
|
||||
|
||||
`McpClient` sends `initialize` first, so servers of every earlier revision see what they always saw. `isStatelessRevisionError(error)` tells errors only servers of that revision send, for applications that start a stdio server again with `protocol: "2026-07-28"` after it exited on rejecting `initialize`. Servers that speak both revisions answer it and stay on the earlier one. Only when a server rejects `initialize` (with a JSON-RPC error, or over HTTP with status 400) does the client send `server/discover` and, when the server lists `2026-07-28`, speak that. When `server/discover` fails as well, `connect()` fails with the server's answer to `initialize`. `protocol: "2026-07-28"` skips `initialize` and speaks only the stateless revision, also to servers that speak both.
|
||||
|
||||
On the stateless revision, the client:
|
||||
|
||||
- answers results that ask for input (`resultType: "input_required"`) with the handler of the input request's method (`roots/list` from `roots`, or one registered with `setRequestHandler`), and sends the request again with the answers. Input it has no handler for fails the request.
|
||||
- sends `Mcp-Method`, `Mcp-Name`, and the `Mcp-Param-*` headers that tools' `x-mcp-header` annotations ask for over HTTP, leaves out tools whose annotations are invalid (reported through `onError`), and lists the tools again once when the server reports mismatching headers.
|
||||
- asks for log messages at `logLevel` with every request, when that option is set.
|
||||
|
||||
It does not open `subscriptions/listen` streams, so tool list changes of such servers are not delivered.
|
||||
|
||||
### Stdio servers started elsewhere
|
||||
|
||||
`PipeTransport` speaks MCP's stdio framing over a program that something else starts, for example on another machine. `open` starts the program, connects its stdout and stderr to the given handlers, and returns an `McpPipe` (`write`, `closeStdin`, `close` to kill, and an `exited` promise). `@earendil-works/pi-env`'s `openProcess()` returns one, without an adapter:
|
||||
|
|
@ -151,7 +165,7 @@ The OAuth implementation is adapted from the MIT-licensed Model Context Protocol
|
|||
|
||||
### Configuration
|
||||
|
||||
`validateMcpServerConfig(name, entry, options)` validates one entry of the `mcpServers` shape that MCP clients share: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`, `oauth`), and `enabled`, `description`, and `timeout`. It returns `{ kind: "stdio" | "http", config }` or `{ kind: "invalid", error }`. Fields it does not know stay in `config`, typed `unknown`, for the application to check afterwards, depending on `kind` where it matters. Resolving `${VAR}` references and relative paths is left to the application. `oauth.clientRegistration: "cimd"` is accepted only with `options.checkMetadataDocumentCallback`, which checks that the application's Client ID Metadata Documents list the callback.
|
||||
`validateMcpServerConfig(name, entry, options)` validates one entry of the `mcpServers` shape that MCP clients share: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`, `oauth`), and `enabled`, `description`, `timeout`, and `protocol`. It returns `{ kind: "stdio" | "http", config }` or `{ kind: "invalid", error }`. Fields it does not know stay in `config`, typed `unknown`, for the application to check afterwards, depending on `kind` where it matters. Resolving `${VAR}` references and relative paths is left to the application. `oauth.clientRegistration: "cimd"` is accepted only with `options.checkMetadataDocumentCallback`, which checks that the application's Client ID Metadata Documents list the callback.
|
||||
|
||||
```typescript
|
||||
import { validateMcpServerConfig } from "@earendil-works/pi-mcp";
|
||||
|
|
@ -170,6 +184,7 @@ for (const [name, entry] of Object.entries(file.mcpServers)) {
|
|||
## Supported protocol surface
|
||||
|
||||
- MCP protocol version `2025-11-25`, accepting servers that negotiate `2025-06-18`, `2025-03-26`, or `2024-11-05`
|
||||
- the stateless revision `2026-07-28` for servers that reject `initialize` (see [Protocol versions](#protocol-versions)), with `server/discover`, multi round-trip requests, and the `Mcp-*` HTTP headers
|
||||
- initialization and `notifications/initialized`
|
||||
- ping
|
||||
- paginated `tools/list`
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { CallToolResult } from "./protocol/content.ts";
|
||||
import { type ToolHeaderBinding, toolHeaderBindings, toolParamHeaders } from "./protocol/http-headers.ts";
|
||||
import {
|
||||
isJsonRpcId,
|
||||
isJsonRpcNotification,
|
||||
|
|
@ -17,27 +18,52 @@ import {
|
|||
normalizeOwnRequestId,
|
||||
toError,
|
||||
} from "./protocol/jsonrpc.ts";
|
||||
import {
|
||||
HEADER_MISMATCH_ERROR_CODE,
|
||||
readStatelessResult,
|
||||
STATELESS_ERROR_CODES,
|
||||
type StatelessRequestMeta,
|
||||
validateDiscoverResult,
|
||||
withStatelessMeta,
|
||||
} from "./protocol/stateless.ts";
|
||||
import {
|
||||
type ClientCapabilities,
|
||||
type Implementation,
|
||||
type InitializeResult,
|
||||
type InputRequest,
|
||||
LATEST_PROTOCOL_VERSION,
|
||||
type ListResourcesResult,
|
||||
type ListResourceTemplatesResult,
|
||||
type LoggingLevel,
|
||||
type McpProtocolMode,
|
||||
type ProgressNotification,
|
||||
type ReadResourceResult,
|
||||
type Resource,
|
||||
type ResourceTemplate,
|
||||
type Root,
|
||||
type ServerCapabilities,
|
||||
STATELESS_PROTOCOL_VERSION,
|
||||
SUPPORTED_PROTOCOL_VERSIONS,
|
||||
type SupportedProtocolVersion,
|
||||
type Tool,
|
||||
} from "./protocol/types.ts";
|
||||
import { jsonRpcErrorIn, McpHttpError } from "./transports/streamable-http.ts";
|
||||
import type { McpTransport } from "./transports/transport.ts";
|
||||
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
||||
const MAX_LIST_PAGES = 1_000;
|
||||
/**
|
||||
* Bounds `server/discover` after a rejected `initialize`. The server already answered once, so a
|
||||
* stateless server answers quickly; a legacy server that ignores the request must not hold up the error.
|
||||
*/
|
||||
const DISCOVER_AFTER_INITIALIZE_TIMEOUT_MS = 10_000;
|
||||
/**
|
||||
* Rounds of input a server may ask for before one request completes. Servers may ask again until they
|
||||
* have what they need; this bounds a server that never does.
|
||||
*/
|
||||
const MAX_INPUT_ROUNDS = 16;
|
||||
/** Methods whose results may ask for input in MCP 2026-07-28 (multi round-trip requests). */
|
||||
const INPUT_METHODS = new Set(["tools/call", "resources/read", "prompts/get"]);
|
||||
|
||||
type ClientState = "idle" | "connecting" | "connected" | "closed";
|
||||
type NotificationListener = (params: unknown) => void;
|
||||
|
|
@ -47,7 +73,15 @@ type RequestHandler = (params: unknown, context: { signal: AbortSignal }) => unk
|
|||
|
||||
export interface McpClientOptions extends Implementation {
|
||||
capabilities?: ClientCapabilities;
|
||||
/** Version the `initialize` handshake asks for. Default: {@link LATEST_PROTOCOL_VERSION}. */
|
||||
protocolVersion?: SupportedProtocolVersion;
|
||||
/** How the protocol is picked (see {@link McpProtocolMode}). Default: `auto`. */
|
||||
protocol?: McpProtocolMode;
|
||||
/**
|
||||
* Servers on the stateless revision send log messages (`notifications/message`) only for requests
|
||||
* that name a level, so every such request names this one. Without it, they send none.
|
||||
*/
|
||||
logLevel?: LoggingLevel;
|
||||
requestTimeoutMs?: number;
|
||||
roots?: readonly Root[] | (() => readonly Root[] | Promise<readonly Root[]>);
|
||||
}
|
||||
|
|
@ -153,6 +187,34 @@ function validateCallToolResult(value: unknown): CallToolResult {
|
|||
return (value.content === undefined ? { ...value, content: [] } : value) as unknown as CallToolResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a failed `initialize` tells about the server. Servers that only speak the stateless revision
|
||||
* reject it with a JSON-RPC error, over HTTP with a 400: `stateless` when the error has a code only that
|
||||
* revision uses, `unknown` for other such rejections, and undefined for failures that are no answer
|
||||
* (timeouts, closed connections, authorization).
|
||||
*/
|
||||
function initializeRejection(error: unknown): "stateless" | "unknown" | undefined {
|
||||
const code =
|
||||
error instanceof McpError
|
||||
? error.code
|
||||
: error instanceof McpHttpError && error.status === 400
|
||||
? jsonRpcErrorIn(error.body)?.code
|
||||
: null;
|
||||
if (code === null) return undefined;
|
||||
return code !== undefined && STATELESS_ERROR_CODES.includes(code) ? "stateless" : "unknown";
|
||||
}
|
||||
|
||||
/** The connection closed under a request: the transport closed, or the stdio server was gone when written to. */
|
||||
function isConnectionLost(error: unknown): boolean {
|
||||
// Node's write errors are the trust boundary here: `code` is all they carry.
|
||||
return (
|
||||
error instanceof McpConnectionClosedError || (error instanceof Error && "code" in error && error.code === "EPIPE")
|
||||
);
|
||||
}
|
||||
|
||||
/** Thrown for an `initialize` answered with the stateless revision, which has no handshake. */
|
||||
class StatelessInitializeError extends Error {}
|
||||
|
||||
export class McpClient {
|
||||
readonly options: Readonly<McpClientOptions>;
|
||||
private state: ClientState = "idle";
|
||||
|
|
@ -162,6 +224,11 @@ export class McpClient {
|
|||
private serverCapabilitiesValue: ServerCapabilities | undefined;
|
||||
private instructionsValue: string | undefined;
|
||||
private protocolVersionValue: string | undefined;
|
||||
/** Whether the connection speaks the stateless revision: every request carries {@link meta}. */
|
||||
private stateless = false;
|
||||
private readonly meta: StatelessRequestMeta;
|
||||
/** `Mcp-Param-*` bindings of the tools last listed, for servers on the stateless revision. */
|
||||
private toolHeaders = new Map<string, ToolHeaderBinding[]>();
|
||||
private pending = new Map<JsonRpcId, PendingRequest>();
|
||||
private progressRequests = new Map<JsonRpcId, JsonRpcId>();
|
||||
private incoming = new Map<JsonRpcId, AbortController>();
|
||||
|
|
@ -173,6 +240,18 @@ export class McpClient {
|
|||
|
||||
constructor(options: McpClientOptions) {
|
||||
this.options = Object.freeze({ ...options });
|
||||
const capabilities: ClientCapabilities = { ...options.capabilities };
|
||||
if (options.roots && capabilities.roots === undefined) capabilities.roots = {};
|
||||
this.meta = {
|
||||
protocolVersion: STATELESS_PROTOCOL_VERSION,
|
||||
clientInfo: {
|
||||
name: options.name,
|
||||
version: options.version,
|
||||
...(options.title === undefined ? {} : { title: options.title }),
|
||||
},
|
||||
clientCapabilities: capabilities,
|
||||
logLevel: options.logLevel,
|
||||
};
|
||||
this.requestHandlers.set("ping", () => ({}));
|
||||
const roots = options.roots;
|
||||
if (roots) {
|
||||
|
|
@ -202,6 +281,10 @@ export class McpClient {
|
|||
return this.protocolVersionValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect over `transport`. Resolves to what the server reported about itself; for servers on the
|
||||
* stateless revision, a result in the shape of `initialize` built from `server/discover`.
|
||||
*/
|
||||
async connect(transport: McpTransport): Promise<InitializeResult> {
|
||||
if (this.state !== "idle") throw new Error(`Cannot connect MCP client in ${this.state} state`);
|
||||
this.state = "connecting";
|
||||
|
|
@ -215,33 +298,10 @@ export class McpClient {
|
|||
|
||||
try {
|
||||
await transport.start();
|
||||
const capabilities: ClientCapabilities = { ...this.options.capabilities };
|
||||
if (this.options.roots && capabilities.roots === undefined) capabilities.roots = {};
|
||||
const result = validateInitializeResult(
|
||||
await this.requestInternal(
|
||||
"initialize",
|
||||
{
|
||||
protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
|
||||
capabilities,
|
||||
clientInfo: {
|
||||
name: this.options.name,
|
||||
version: this.options.version,
|
||||
...(this.options.title === undefined ? {} : { title: this.options.title }),
|
||||
},
|
||||
},
|
||||
{},
|
||||
true,
|
||||
),
|
||||
);
|
||||
if (!(SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(result.protocolVersion)) {
|
||||
throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
|
||||
}
|
||||
this.protocolVersionValue = result.protocolVersion;
|
||||
this.serverInfoValue = result.serverInfo;
|
||||
this.serverCapabilitiesValue = result.capabilities;
|
||||
this.instructionsValue = result.instructions;
|
||||
transport.setProtocolVersion?.(result.protocolVersion);
|
||||
await this.notifyInternal("notifications/initialized", undefined, true);
|
||||
const result =
|
||||
this.options.protocol === STATELESS_PROTOCOL_VERSION
|
||||
? await this.discover(transport, this.requestTimeoutMs())
|
||||
: await this.initializeOrDiscover(transport);
|
||||
this.state = "connected";
|
||||
return result;
|
||||
} catch (error) {
|
||||
|
|
@ -250,18 +310,97 @@ export class McpClient {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `initialize` first, so servers of every earlier revision see what they always saw. Only a server
|
||||
* that rejects it is asked with `server/discover`. When that fails too, the error is the rejection,
|
||||
* unless the rejection proved a stateless server and the connection is still open: then
|
||||
* `server/discover` failed for its own reason (sign-in required, say). Some stdio servers exit
|
||||
* after rejecting `initialize`; they need a new connection with `protocol: "2026-07-28"`.
|
||||
*/
|
||||
private async initializeOrDiscover(transport: McpTransport): Promise<InitializeResult> {
|
||||
try {
|
||||
return await this.initialize(transport);
|
||||
} catch (error) {
|
||||
const rejection = error instanceof StatelessInitializeError ? "stateless" : initializeRejection(error);
|
||||
if (rejection === undefined) throw error;
|
||||
if (rejection === "stateless") {
|
||||
return await this.discover(transport, this.requestTimeoutMs()).catch((discoverError: unknown) => {
|
||||
throw isConnectionLost(discoverError) ? error : discoverError;
|
||||
});
|
||||
}
|
||||
const timeoutMs = Math.min(this.requestTimeoutMs(), DISCOVER_AFTER_INITIALIZE_TIMEOUT_MS);
|
||||
return await this.discover(transport, timeoutMs).catch(() => {
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async initialize(transport: McpTransport): Promise<InitializeResult> {
|
||||
const result = validateInitializeResult(
|
||||
await this.requestInternal(
|
||||
"initialize",
|
||||
{
|
||||
protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
|
||||
capabilities: this.meta.clientCapabilities,
|
||||
clientInfo: this.meta.clientInfo,
|
||||
},
|
||||
{},
|
||||
true,
|
||||
),
|
||||
);
|
||||
if (result.protocolVersion === STATELESS_PROTOCOL_VERSION) {
|
||||
throw new StatelessInitializeError("MCP server answered initialize with the stateless protocol revision");
|
||||
}
|
||||
if (!(SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(result.protocolVersion)) {
|
||||
throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
|
||||
}
|
||||
this.protocolVersionValue = result.protocolVersion;
|
||||
this.serverInfoValue = result.serverInfo;
|
||||
this.serverCapabilitiesValue = result.capabilities;
|
||||
this.instructionsValue = result.instructions;
|
||||
transport.setProtocolVersion?.(result.protocolVersion);
|
||||
await this.notifyInternal("notifications/initialized", undefined, true);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Speak the stateless revision: no handshake, `server/discover` tells what the server offers. */
|
||||
private async discover(transport: McpTransport, timeoutMs: number): Promise<InitializeResult> {
|
||||
this.stateless = true;
|
||||
transport.setProtocolVersion?.(STATELESS_PROTOCOL_VERSION);
|
||||
const { result, serverInfo } = validateDiscoverResult(
|
||||
await this.requestInternal("server/discover", undefined, { timeoutMs }, true),
|
||||
);
|
||||
if (!result.supportedVersions.includes(STATELESS_PROTOCOL_VERSION)) {
|
||||
throw new Error(`MCP server supports none of this client's protocol versions: ${result.supportedVersions}`);
|
||||
}
|
||||
this.protocolVersionValue = STATELESS_PROTOCOL_VERSION;
|
||||
this.serverInfoValue = serverInfo;
|
||||
this.serverCapabilitiesValue = result.capabilities;
|
||||
this.instructionsValue = result.instructions;
|
||||
return {
|
||||
protocolVersion: STATELESS_PROTOCOL_VERSION,
|
||||
capabilities: result.capabilities,
|
||||
serverInfo: serverInfo ?? { name: "", version: "" },
|
||||
...(result.instructions === undefined ? {} : { instructions: result.instructions }),
|
||||
};
|
||||
}
|
||||
|
||||
request<Result = unknown>(
|
||||
method: string,
|
||||
params?: Record<string, unknown>,
|
||||
options: McpRequestOptions = {},
|
||||
): Promise<Result> {
|
||||
return this.requestInternal(method, params, options, false) as Promise<Result>;
|
||||
return this.requestConnected(method, params, options) as Promise<Result>;
|
||||
}
|
||||
|
||||
notify(method: string, params?: Record<string, unknown>): Promise<void> {
|
||||
return this.notifyInternal(method, params, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer requests of `method` from the server: requests a legacy server sends, and the input requests
|
||||
* of the same method that results of the stateless revision ask for (`roots/list`, say).
|
||||
*/
|
||||
setRequestHandler(method: string, handler: RequestHandler): () => void {
|
||||
this.requestHandlers.set(method, handler);
|
||||
return () => {
|
||||
|
|
@ -294,8 +433,26 @@ export class McpClient {
|
|||
await this.request("ping", undefined, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every tool, following `nextCursor` through all pages. On the stateless revision, tools whose
|
||||
* `x-mcp-header` annotations are invalid are left out and reported through `onError`.
|
||||
*/
|
||||
async listTools(options: McpRequestOptions = {}): Promise<Tool[]> {
|
||||
return (await this.listAll("tools/list", "tools", isTool, options)) as unknown as Tool[];
|
||||
const tools = (await this.listAll("tools/list", "tools", isTool, options)) as unknown as Tool[];
|
||||
if (!this.stateless) return tools;
|
||||
const kept: Tool[] = [];
|
||||
const headers = new Map<string, ToolHeaderBinding[]>();
|
||||
for (const tool of tools) {
|
||||
const bindings = toolHeaderBindings(tool.inputSchema);
|
||||
if (bindings.kind === "invalid") {
|
||||
this.emitError(new Error(`Excluded MCP tool "${tool.name}": ${bindings.reason}`));
|
||||
continue;
|
||||
}
|
||||
if (bindings.bindings.length > 0) headers.set(tool.name, bindings.bindings);
|
||||
kept.push(tool);
|
||||
}
|
||||
this.toolHeaders = headers;
|
||||
return kept;
|
||||
}
|
||||
|
||||
/** Every resource, following `nextCursor` through all pages. */
|
||||
|
|
@ -376,14 +533,29 @@ export class McpClient {
|
|||
throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call a tool. On the stateless revision, arguments the tool marks with `x-mcp-header` go into
|
||||
* `Mcp-Param-*` headers too; when the server reports that they do not match, the tools are listed
|
||||
* again for their current annotations and the call is sent once more.
|
||||
*/
|
||||
async callTool(
|
||||
name: string,
|
||||
args?: Record<string, unknown>,
|
||||
options: McpRequestOptions = {},
|
||||
): Promise<CallToolResult> {
|
||||
return validateCallToolResult(
|
||||
await this.request("tools/call", { name, ...(args === undefined ? {} : { arguments: args }) }, options),
|
||||
);
|
||||
const params = { name, ...(args === undefined ? {} : { arguments: args }) };
|
||||
const call = async () => {
|
||||
const bindings = this.toolHeaders.get(name);
|
||||
const headers = bindings ? toolParamHeaders(bindings, args) : undefined;
|
||||
return validateCallToolResult(await this.requestConnected("tools/call", params, options, headers));
|
||||
};
|
||||
try {
|
||||
return await call();
|
||||
} catch (error) {
|
||||
if (!(this.stateless && error instanceof McpError && error.code === HEADER_MISMATCH_ERROR_CODE)) throw error;
|
||||
await this.listTools(options.signal ? { signal: options.signal } : {});
|
||||
return await call();
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
|
|
@ -394,20 +566,69 @@ export class McpClient {
|
|||
await transport?.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* A request on the connection. On the stateless revision, a result that asks for input is answered
|
||||
* with the handlers of the input requests' methods, and the request is sent again with the answers
|
||||
* until it completes. Every attempt is a new JSON-RPC request.
|
||||
*/
|
||||
private async requestConnected(
|
||||
method: string,
|
||||
params: Record<string, unknown> | undefined,
|
||||
options: McpRequestOptions,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<unknown> {
|
||||
if (!this.stateless) return this.requestInternal(method, params, options, false, headers);
|
||||
let input: Record<string, unknown> = {};
|
||||
for (let round = 0; ; round++) {
|
||||
const result = readStatelessResult(
|
||||
method,
|
||||
await this.requestInternal(method, { ...params, ...input }, options, false, headers),
|
||||
);
|
||||
if (result.kind === "complete") return result.result;
|
||||
if (!INPUT_METHODS.has(method)) throw new Error(`MCP ${method} result asks for input, which it may not`);
|
||||
if (round + 1 >= MAX_INPUT_ROUNDS) {
|
||||
throw new Error(`MCP ${method} still asks for input after ${MAX_INPUT_ROUNDS} rounds`);
|
||||
}
|
||||
input = {
|
||||
inputResponses: await this.answerInputRequests(result.inputRequests, options.signal),
|
||||
...(result.requestState === undefined ? {} : { requestState: result.requestState }),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async answerInputRequests(
|
||||
requests: Record<string, InputRequest>,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const responses: Record<string, unknown> = {};
|
||||
for (const [key, request] of Object.entries(requests)) {
|
||||
const handler = this.requestHandlers.get(request.method);
|
||||
if (!handler) throw new Error(`MCP server asked for input this client does not provide: ${request.method}`);
|
||||
responses[key] = (await handler(request.params, { signal: signal ?? new AbortController().signal })) ?? {};
|
||||
}
|
||||
return responses;
|
||||
}
|
||||
|
||||
private requestTimeoutMs(): number {
|
||||
return this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
private async requestInternal(
|
||||
method: string,
|
||||
params: Record<string, unknown> | undefined,
|
||||
options: McpRequestOptions,
|
||||
allowConnecting: boolean,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<unknown> {
|
||||
const transport = this.requireTransport(allowConnecting);
|
||||
if (options.signal?.aborted) throw new McpAbortError();
|
||||
const id = this.nextRequestId++;
|
||||
const progressToken = options.onProgress ? id : undefined;
|
||||
const metaParams = this.stateless ? withStatelessMeta(params, this.meta) : params;
|
||||
const requestParams =
|
||||
progressToken === undefined
|
||||
? params
|
||||
: { ...params, _meta: { ...(isObject(params?._meta) ? params._meta : {}), progressToken } };
|
||||
? metaParams
|
||||
: { ...metaParams, _meta: { ...(isObject(metaParams?._meta) ? metaParams._meta : {}), progressToken } };
|
||||
const message: JsonRpcRequest = {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
|
|
@ -418,7 +639,7 @@ export class McpClient {
|
|||
const entry: PendingRequest = {
|
||||
resolve,
|
||||
reject,
|
||||
timeoutMs: options.timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
timeoutMs: options.timeoutMs ?? this.requestTimeoutMs(),
|
||||
timer: undefined,
|
||||
signal: options.signal,
|
||||
// The spec forbids cancelling `initialize`.
|
||||
|
|
@ -439,7 +660,7 @@ export class McpClient {
|
|||
options.signal?.addEventListener("abort", entry.onAbort, { once: true });
|
||||
this.armTimeout(id, entry);
|
||||
transport
|
||||
.send(message, { signal: entry.sendController.signal })
|
||||
.send(message, { signal: entry.sendController.signal, ...(headers === undefined ? {} : { headers }) })
|
||||
.catch((error) => this.cancelPending(id, error, false));
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* The `mcpServers` configuration shape that MCP clients share, so configurations can be copied between
|
||||
* them: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`,
|
||||
* `oauth`), and `enabled`, `description` and `timeout` for both.
|
||||
* `oauth`), and `enabled`, `description`, `timeout` and `protocol` for both.
|
||||
*
|
||||
* ```json
|
||||
* {
|
||||
|
|
@ -16,6 +16,8 @@
|
|||
* for the caller to check afterwards.
|
||||
*/
|
||||
|
||||
import { type McpProtocolMode, STATELESS_PROTOCOL_VERSION } from "./protocol/types.ts";
|
||||
|
||||
/** Fields every server entry may have. */
|
||||
interface McpServerConfigBase {
|
||||
/** What the server offers, in a sentence. */
|
||||
|
|
@ -24,6 +26,11 @@ interface McpServerConfigBase {
|
|||
enabled?: boolean;
|
||||
/** Per-request timeout in seconds. */
|
||||
timeout?: number;
|
||||
/**
|
||||
* `auto` (default): `initialize`, and the stateless revision only for servers that reject it.
|
||||
* `2026-07-28`: only the stateless revision, also for servers that speak both.
|
||||
*/
|
||||
protocol?: McpProtocolMode;
|
||||
}
|
||||
|
||||
/** A server started as a local program that speaks MCP over stdin and stdout. */
|
||||
|
|
@ -143,8 +150,11 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|||
}
|
||||
|
||||
function validateBaseFields(entry: Record<string, unknown>): string | undefined {
|
||||
const { enabled, timeout, description } = entry;
|
||||
const { enabled, timeout, description, protocol } = entry;
|
||||
if (enabled !== undefined && typeof enabled !== "boolean") return "enabled must be a boolean";
|
||||
if (protocol !== undefined && protocol !== "auto" && protocol !== STATELESS_PROTOCOL_VERSION) {
|
||||
return `protocol must be "auto" or "${STATELESS_PROTOCOL_VERSION}"`;
|
||||
}
|
||||
if (description !== undefined && typeof description !== "string") return "description must be a string";
|
||||
if (timeout !== undefined && (typeof timeout !== "number" || !(timeout > 0))) {
|
||||
return "timeout must be a positive number of seconds";
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ export {
|
|||
McpTimeoutError,
|
||||
parseJsonRpcMessage,
|
||||
} from "./protocol/jsonrpc.ts";
|
||||
export { isStatelessRevisionError } from "./protocol/stateless.ts";
|
||||
export {
|
||||
type CancelledNotification,
|
||||
type ClientCapabilities,
|
||||
|
|
@ -62,12 +63,15 @@ export {
|
|||
type ListResourcesResult,
|
||||
type ListResourceTemplatesResult,
|
||||
type ListToolsResult,
|
||||
type LoggingLevel,
|
||||
type McpProtocolMode,
|
||||
type ProgressNotification,
|
||||
type ReadResourceResult,
|
||||
type Resource,
|
||||
type ResourceTemplate,
|
||||
type Root,
|
||||
type ServerCapabilities,
|
||||
STATELESS_PROTOCOL_VERSION,
|
||||
SUPPORTED_PROTOCOL_VERSIONS,
|
||||
type SupportedProtocolVersion,
|
||||
type Tool,
|
||||
|
|
|
|||
134
packages/mcp/src/protocol/http-headers.ts
Normal file
134
packages/mcp/src/protocol/http-headers.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// HTTP headers that MCP 2026-07-28 mirrors from the request body: `Mcp-Method`, `Mcp-Name`, and
|
||||
// `Mcp-Param-*` for tool arguments a tool's input schema marks with `x-mcp-header`.
|
||||
import { isObject } from "./jsonrpc.ts";
|
||||
|
||||
/** One tool argument mirrored into a header: the `properties` path to it and the header name part. */
|
||||
export interface ToolHeaderBinding {
|
||||
path: string[];
|
||||
header: string;
|
||||
}
|
||||
|
||||
/** A tool's header bindings, or why its `x-mcp-header` annotations are invalid. */
|
||||
export type ToolHeaderBindings = { kind: "valid"; bindings: ToolHeaderBinding[] } | { kind: "invalid"; reason: string };
|
||||
|
||||
const HEADER_ANNOTATION = "x-mcp-header";
|
||||
const BASE64_SENTINEL = /^=\?base64\?.*\?=$/s;
|
||||
// RFC 9110 token characters.
|
||||
const HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||||
const PRIMITIVE_TYPES = new Set(["string", "integer", "boolean"]);
|
||||
// Input schemas come from the server; deeper nesting is not worth walking.
|
||||
const MAX_SCHEMA_DEPTH = 64;
|
||||
// Keywords whose values are instance data, not schemas, so an `x-mcp-header` key in them is no annotation.
|
||||
const DATA_KEYWORDS = new Set(["const", "default", "enum", "examples"]);
|
||||
|
||||
/**
|
||||
* A header value for `value`: as is when it is plain ASCII without leading or trailing whitespace,
|
||||
* otherwise Base64 of its UTF-8 in the `=?base64?…?=` form. Values that look like that form are
|
||||
* encoded too, so they are not mistaken for it.
|
||||
*/
|
||||
export function encodeHeaderValue(value: string): string {
|
||||
let plain = value === value.trim() && !BASE64_SENTINEL.test(value);
|
||||
for (let i = 0; plain && i < value.length; i++) {
|
||||
const code = value.charCodeAt(i);
|
||||
plain = code >= 0x20 && code <= 0x7e;
|
||||
}
|
||||
return plain ? value : `=?base64?${Buffer.from(value, "utf8").toString("base64")}?=`;
|
||||
}
|
||||
|
||||
/** `Mcp-Method`, and `Mcp-Name` for the methods that name a tool, prompt, or resource. */
|
||||
export function standardRequestHeaders(method: string, params: unknown): Record<string, string> {
|
||||
const headers: Record<string, string> = { "Mcp-Method": method };
|
||||
const name =
|
||||
method === "resources/read"
|
||||
? isObject(params) && params.uri
|
||||
: (method === "tools/call" || method === "prompts/get") && isObject(params) && params.name;
|
||||
if (typeof name === "string") headers["Mcp-Name"] = encodeHeaderValue(name);
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* The arguments a tool mirrors into headers (wire input). Annotations are valid only on `string`,
|
||||
* `integer`, and `boolean` properties reached from the schema root through `properties` alone, with
|
||||
* non-empty token names that are unique ignoring case. Clients on HTTP exclude tools with an invalid
|
||||
* annotation.
|
||||
*/
|
||||
export function toolHeaderBindings(inputSchema: Record<string, unknown>): ToolHeaderBindings {
|
||||
const bindings: ToolHeaderBinding[] = [];
|
||||
const seen = new Set<string>();
|
||||
let problem: string | undefined;
|
||||
const visit = (schema: unknown, path: string[] | undefined, depth: number): void => {
|
||||
if (problem || depth > MAX_SCHEMA_DEPTH) return;
|
||||
if (Array.isArray(schema)) {
|
||||
for (const item of schema) visit(item, undefined, depth + 1);
|
||||
return;
|
||||
}
|
||||
if (!isObject(schema)) return;
|
||||
if (HEADER_ANNOTATION in schema) {
|
||||
if (!path) {
|
||||
problem = `${HEADER_ANNOTATION} outside of nested properties`;
|
||||
return;
|
||||
}
|
||||
const annotation = readAnnotation(schema, seen);
|
||||
if (annotation.kind === "invalid") {
|
||||
problem = annotation.reason;
|
||||
return;
|
||||
}
|
||||
seen.add(annotation.header.toLowerCase());
|
||||
bindings.push({ path, header: annotation.header });
|
||||
}
|
||||
for (const [key, value] of Object.entries(schema)) {
|
||||
if (key === "properties" && path && isObject(value)) {
|
||||
for (const [name, property] of Object.entries(value)) visit(property, [...path, name], depth + 1);
|
||||
} else if (key !== HEADER_ANNOTATION && !DATA_KEYWORDS.has(key)) {
|
||||
visit(value, undefined, depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (isObject(inputSchema.properties)) {
|
||||
for (const [name, property] of Object.entries(inputSchema.properties)) visit(property, [name], 1);
|
||||
}
|
||||
for (const [key, value] of Object.entries(inputSchema)) {
|
||||
if (key === HEADER_ANNOTATION) problem ??= `${HEADER_ANNOTATION} on the schema root`;
|
||||
else if (key !== "properties" && !DATA_KEYWORDS.has(key)) visit(value, undefined, 1);
|
||||
}
|
||||
return problem ? { kind: "invalid", reason: problem } : { kind: "valid", bindings };
|
||||
}
|
||||
|
||||
/** The header name of a property's annotation, or why the annotation is invalid. */
|
||||
function readAnnotation(
|
||||
schema: Record<string, unknown>,
|
||||
seen: Set<string>,
|
||||
): { kind: "valid"; header: string } | { kind: "invalid"; reason: string } {
|
||||
const header = schema[HEADER_ANNOTATION];
|
||||
const invalid = (reason: string) => ({ kind: "invalid" as const, reason: `${HEADER_ANNOTATION} ${reason}` });
|
||||
if (typeof header !== "string" || header === "") return invalid("must be a non-empty string");
|
||||
if (!HEADER_TOKEN.test(header)) return invalid(`"${header}" is not a valid header name`);
|
||||
if (seen.has(header.toLowerCase())) return invalid(`"${header}" is not unique`);
|
||||
const types = Array.isArray(schema.type) ? schema.type.filter((type) => type !== "null") : [schema.type];
|
||||
if (types.length !== 1 || typeof types[0] !== "string" || !PRIMITIVE_TYPES.has(types[0])) {
|
||||
return invalid(`"${header}" must be on a string, integer, or boolean property`);
|
||||
}
|
||||
return { kind: "valid", header };
|
||||
}
|
||||
|
||||
/** `Mcp-Param-*` headers for a tool call. Arguments that are absent, null, or not primitive get no header. */
|
||||
export function toolParamHeaders(
|
||||
bindings: readonly ToolHeaderBinding[],
|
||||
args: Record<string, unknown> | undefined,
|
||||
): Record<string, string> {
|
||||
const headers: Record<string, string> = {};
|
||||
for (const { path, header } of bindings) {
|
||||
let value: unknown = args;
|
||||
for (const key of path) value = isObject(value) ? value[key] : undefined;
|
||||
const encoded = paramHeaderValue(value);
|
||||
if (encoded !== undefined) headers[`Mcp-Param-${header}`] = encoded;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function paramHeaderValue(value: unknown): string | undefined {
|
||||
if (typeof value === "string") return encodeHeaderValue(value);
|
||||
if (typeof value === "boolean") return String(value);
|
||||
if (typeof value === "number" && Number.isInteger(value)) return String(value);
|
||||
return undefined;
|
||||
}
|
||||
113
packages/mcp/src/protocol/stateless.ts
Normal file
113
packages/mcp/src/protocol/stateless.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
// Wire rules of the stateless MCP revision (2026-07-28): request metadata, result types, and the
|
||||
// `server/discover` result.
|
||||
import { isObject, JSON_RPC_ERROR_CODES, McpError } from "./jsonrpc.ts";
|
||||
import type {
|
||||
ClientCapabilities,
|
||||
DiscoverResult,
|
||||
Implementation,
|
||||
InputRequest,
|
||||
LoggingLevel,
|
||||
STATELESS_PROTOCOL_VERSION,
|
||||
} from "./types.ts";
|
||||
|
||||
/** Error code of a request whose `Mcp-*` headers do not match its body (MCP 2026-07-28). */
|
||||
export const HEADER_MISMATCH_ERROR_CODE = -32020;
|
||||
|
||||
/**
|
||||
* Error codes MCP 2026-07-28 reserves: header mismatch, missing required client capability, and
|
||||
* unsupported protocol version. Only servers of that revision send them.
|
||||
*/
|
||||
export const STATELESS_ERROR_CODES: readonly number[] = [HEADER_MISMATCH_ERROR_CODE, -32021, -32022];
|
||||
|
||||
/** Whether `error` is an error response only servers of the stateless revision send. */
|
||||
export function isStatelessRevisionError(error: unknown): boolean {
|
||||
return error instanceof McpError && STATELESS_ERROR_CODES.includes(error.code);
|
||||
}
|
||||
|
||||
/** What every stateless request declares about the client in its `_meta`. */
|
||||
export interface StatelessRequestMeta {
|
||||
protocolVersion: typeof STATELESS_PROTOCOL_VERSION;
|
||||
clientInfo: Implementation;
|
||||
clientCapabilities: ClientCapabilities;
|
||||
logLevel: LoggingLevel | undefined;
|
||||
}
|
||||
|
||||
/** `params` with the stateless request metadata added to its `_meta`, keeping the `_meta` keys it has. */
|
||||
export function withStatelessMeta(
|
||||
params: Record<string, unknown> | undefined,
|
||||
meta: StatelessRequestMeta,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...params,
|
||||
_meta: {
|
||||
...(isObject(params?._meta) ? params._meta : {}),
|
||||
"io.modelcontextprotocol/protocolVersion": meta.protocolVersion,
|
||||
"io.modelcontextprotocol/clientInfo": meta.clientInfo,
|
||||
"io.modelcontextprotocol/clientCapabilities": meta.clientCapabilities,
|
||||
...(meta.logLevel === undefined ? {} : { "io.modelcontextprotocol/logLevel": meta.logLevel }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A result of a stateless request, by `resultType`. */
|
||||
export type StatelessResult =
|
||||
| { kind: "complete"; result: unknown }
|
||||
| { kind: "input_required"; inputRequests: Record<string, InputRequest>; requestState: string | undefined };
|
||||
|
||||
/**
|
||||
* Read the `resultType` of a stateless result (wire input). A result without one is complete; unknown
|
||||
* result types are invalid.
|
||||
*/
|
||||
export function readStatelessResult(method: string, value: unknown): StatelessResult {
|
||||
if (!isObject(value)) throw invalid(`Invalid MCP ${method} result`);
|
||||
const { resultType, inputRequests, requestState } = value;
|
||||
if (resultType === undefined || resultType === "complete") return { kind: "complete", result: value };
|
||||
if (resultType !== "input_required") throw invalid(`Unsupported MCP ${method} result type: ${String(resultType)}`);
|
||||
if (inputRequests !== undefined && !isInputRequests(inputRequests)) {
|
||||
throw invalid(`Invalid input requests in MCP ${method} result`);
|
||||
}
|
||||
if (requestState !== undefined && typeof requestState !== "string") {
|
||||
throw invalid(`Invalid request state in MCP ${method} result`);
|
||||
}
|
||||
if (inputRequests === undefined && requestState === undefined) {
|
||||
throw invalid(`MCP ${method} result requires input but names neither input requests nor request state`);
|
||||
}
|
||||
return { kind: "input_required", inputRequests: inputRequests ?? {}, requestState };
|
||||
}
|
||||
|
||||
function isInputRequests(value: unknown): value is Record<string, InputRequest> {
|
||||
if (!isObject(value)) return false;
|
||||
return Object.values(value).every(
|
||||
(request) =>
|
||||
isObject(request) &&
|
||||
typeof request.method === "string" &&
|
||||
(request.params === undefined || isObject(request.params)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Validate a `server/discover` result (wire input), with the server's name and version from its `_meta`. */
|
||||
export function validateDiscoverResult(value: unknown): { result: DiscoverResult; serverInfo?: Implementation } {
|
||||
if (
|
||||
!isObject(value) ||
|
||||
!Array.isArray(value.supportedVersions) ||
|
||||
!value.supportedVersions.every((version) => typeof version === "string") ||
|
||||
!isObject(value.capabilities) ||
|
||||
(value.instructions !== undefined && typeof value.instructions !== "string")
|
||||
) {
|
||||
throw invalid("Invalid MCP server/discover result");
|
||||
}
|
||||
const result = value as unknown as DiscoverResult;
|
||||
// Servers SHOULD name themselves, but need not.
|
||||
const info = isObject(value._meta) ? value._meta["io.modelcontextprotocol/serverInfo"] : undefined;
|
||||
if (!isObject(info) || typeof info.name !== "string" || typeof info.version !== "string") return { result };
|
||||
const serverInfo = {
|
||||
name: info.name,
|
||||
version: info.version,
|
||||
...(typeof info.title === "string" ? { title: info.title } : {}),
|
||||
};
|
||||
return { result, serverInfo };
|
||||
}
|
||||
|
||||
function invalid(message: string): McpError {
|
||||
return new McpError(JSON_RPC_ERROR_CODES.invalidRequest, message);
|
||||
}
|
||||
|
|
@ -9,6 +9,21 @@ export const LATEST_PROTOCOL_VERSION = "2025-11-25";
|
|||
export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"] as const;
|
||||
export type SupportedProtocolVersion = (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];
|
||||
|
||||
/**
|
||||
* The stateless protocol revision: no `initialize` handshake and no session; every request carries the
|
||||
* protocol version and the client's info and capabilities in `_meta`.
|
||||
*/
|
||||
export const STATELESS_PROTOCOL_VERSION = "2026-07-28";
|
||||
|
||||
/**
|
||||
* How a client picks the protocol. `auto`: `initialize` first, as servers of every earlier revision
|
||||
* expect; only when the server rejects it, `server/discover` for the stateless revision. A version
|
||||
* (`2026-07-28`) speaks only that revision.
|
||||
*/
|
||||
export type McpProtocolMode = "auto" | typeof STATELESS_PROTOCOL_VERSION;
|
||||
|
||||
export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency";
|
||||
|
||||
export interface Implementation {
|
||||
name: string;
|
||||
version: string;
|
||||
|
|
@ -49,6 +64,20 @@ export interface InitializeResult {
|
|||
instructions?: string;
|
||||
}
|
||||
|
||||
/** The answer to `server/discover` (MCP 2026-07-28). */
|
||||
export interface DiscoverResult {
|
||||
supportedVersions: string[];
|
||||
capabilities: ServerCapabilities;
|
||||
instructions?: string;
|
||||
_meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** A request the server needs answered before it can complete a request (MCP 2026-07-28). */
|
||||
export interface InputRequest {
|
||||
method: string;
|
||||
params?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ProgressNotification {
|
||||
progressToken: string | number;
|
||||
progress: number;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
import type { AuthProvider, McpFetch } from "../auth-provider.ts";
|
||||
import { standardRequestHeaders } from "../protocol/http-headers.ts";
|
||||
import {
|
||||
isJsonRpcNotification,
|
||||
isJsonRpcRequest,
|
||||
isJsonRpcResponse,
|
||||
isObject,
|
||||
JSON_RPC_ERROR_CODES,
|
||||
type JsonRpcErrorObject,
|
||||
type JsonRpcId,
|
||||
type JsonRpcMessage,
|
||||
McpAbortError,
|
||||
|
|
@ -11,6 +15,7 @@ import {
|
|||
parseJsonRpcMessage,
|
||||
toError,
|
||||
} from "../protocol/jsonrpc.ts";
|
||||
import { STATELESS_PROTOCOL_VERSION } from "../protocol/types.ts";
|
||||
import {
|
||||
DEFAULT_MAX_MESSAGE_BYTES,
|
||||
type McpTransport,
|
||||
|
|
@ -243,6 +248,20 @@ function describeHttpFailure(status: number, body: string): string {
|
|||
return `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : ""}`;
|
||||
}
|
||||
|
||||
/** The JSON-RPC error in an HTTP error body, which servers on the stateless revision send with 4xx statuses. */
|
||||
export function jsonRpcErrorIn(body: string): JsonRpcErrorObject | undefined {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(body);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!isObject(parsed) || parsed.jsonrpc !== "2.0" || !isObject(parsed.error)) return undefined;
|
||||
const { code, message, data } = parsed.error;
|
||||
if (typeof code !== "number" || typeof message !== "string") return undefined;
|
||||
return { code, message, ...(data === undefined ? {} : { data }) };
|
||||
}
|
||||
|
||||
interface StreamCursor {
|
||||
lastEventId: string | undefined;
|
||||
retryMs: number | undefined;
|
||||
|
|
@ -259,6 +278,11 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
private closed = false;
|
||||
private sessionIdValue: string | undefined;
|
||||
private protocolVersion: string | undefined;
|
||||
/**
|
||||
* MCP 2026-07-28: no session, `Mcp-Method` and `Mcp-Name` headers, response streams that cannot be
|
||||
* resumed, and closing a request's response stream cancels it.
|
||||
*/
|
||||
private stateless = false;
|
||||
private getStreamStarted = false;
|
||||
/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */
|
||||
private lastToken: string | undefined;
|
||||
|
|
@ -285,18 +309,37 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
|
||||
setProtocolVersion(version: string): void {
|
||||
this.protocolVersion = version;
|
||||
this.stateless = version === STATELESS_PROTOCOL_VERSION;
|
||||
// A server that answered `initialize` with the stateless revision may have started a session.
|
||||
if (this.stateless) this.sessionIdValue = undefined;
|
||||
}
|
||||
|
||||
async send(message: JsonRpcMessage, { signal }: McpTransportSendOptions = {}): Promise<void> {
|
||||
async send(message: JsonRpcMessage, { signal, headers }: McpTransportSendOptions = {}): Promise<void> {
|
||||
if (!this.started || this.closed) throw new McpConnectionClosedError();
|
||||
const statelessRequest = this.stateless && isJsonRpcRequest(message);
|
||||
// Aborting the request's response stream already cancelled it.
|
||||
if (this.stateless && isJsonRpcNotification(message) && message.method === "notifications/cancelled") return;
|
||||
const response = await this.authorizedFetch(
|
||||
"POST",
|
||||
{
|
||||
headers: { accept: "application/json, text/event-stream", "content-type": "application/json" },
|
||||
headers: {
|
||||
accept: "application/json, text/event-stream",
|
||||
"content-type": "application/json",
|
||||
...(statelessRequest ? { ...headers, ...standardRequestHeaders(message.method, message.params) } : {}),
|
||||
},
|
||||
body: JSON.stringify(message),
|
||||
// Closing the connection cancels a stateless request, also before its response arrives.
|
||||
...(statelessRequest && signal ? { signal } : {}),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (statelessRequest && response.status >= 400 && response.status < 500 && response.status !== 401) {
|
||||
const body = (await readBodyText(response, MAX_ERROR_BODY_BYTES).catch(() => ({ text: "" }))).text;
|
||||
const error = jsonRpcErrorIn(body);
|
||||
if (!error) throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);
|
||||
this.emitMessage({ jsonrpc: "2.0", id: message.id, error });
|
||||
return;
|
||||
}
|
||||
await this.checkResponse(response);
|
||||
this.captureSession(response);
|
||||
|
||||
|
|
@ -320,7 +363,7 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
return;
|
||||
}
|
||||
if (type === "text/event-stream" && response.body) {
|
||||
void this.consumeResponseStream(response.body, message.id);
|
||||
void this.consumeResponseStream(response.body, message.id, signal);
|
||||
return;
|
||||
}
|
||||
await discard(response);
|
||||
|
|
@ -348,7 +391,8 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
|
||||
/**
|
||||
* Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider
|
||||
* once, and the request is retried with whatever credentials it left behind.
|
||||
* once, and the request is retried with whatever credentials it left behind. `init.signal` aborts
|
||||
* the fetch itself.
|
||||
*
|
||||
* `signal` only stops dispatch: getting a token or the authorization recovery can take a while, and a
|
||||
* request its sender gave up on in the meantime must not reach the server. It does not abort the shared
|
||||
|
|
@ -356,10 +400,11 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
*/
|
||||
private async authorizedFetch(
|
||||
method: "GET" | "POST",
|
||||
init: { headers: Record<string, string>; body?: string },
|
||||
init: { headers: Record<string, string>; body?: string; signal?: AbortSignal },
|
||||
signal?: AbortSignal,
|
||||
): Promise<Response> {
|
||||
const onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);
|
||||
const fetchSignal = init.signal ? AbortSignal.any([this.controller.signal, init.signal]) : this.controller.signal;
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const { headers, token } = await this.headers(init.headers);
|
||||
if (signal?.aborted) throw new McpAbortError();
|
||||
|
|
@ -367,7 +412,7 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
method,
|
||||
headers,
|
||||
body: init.body,
|
||||
signal: this.controller.signal,
|
||||
signal: fetchSignal,
|
||||
});
|
||||
if (attempt > 0 || !onUnauthorized || !needsAuthorization(response)) return response;
|
||||
try {
|
||||
|
|
@ -395,7 +440,7 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
|
||||
private captureSession(response: Response): void {
|
||||
const sessionId = response.headers.get("mcp-session-id");
|
||||
if (sessionId) this.sessionIdValue = sessionId;
|
||||
if (sessionId && !this.stateless) this.sessionIdValue = sessionId;
|
||||
}
|
||||
|
||||
private async checkResponse(response: Response): Promise<void> {
|
||||
|
|
@ -440,9 +485,14 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
/**
|
||||
* Read the SSE stream answering one request. When the stream ends or breaks before the response
|
||||
* arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the
|
||||
* server may close response streams at will. Otherwise only this request fails.
|
||||
* server may close response streams at will. Otherwise, and always on the stateless revision,
|
||||
* only this request fails.
|
||||
*/
|
||||
private async consumeResponseStream(body: ReadableStream<Uint8Array>, requestId: JsonRpcId): Promise<void> {
|
||||
private async consumeResponseStream(
|
||||
body: ReadableStream<Uint8Array>,
|
||||
requestId: JsonRpcId,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<void> {
|
||||
const cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };
|
||||
let answered = false;
|
||||
const onMessage = (message: JsonRpcMessage) => {
|
||||
|
|
@ -459,9 +509,10 @@ export class StreamableHttpTransport extends TransportEvents implements McpTrans
|
|||
failure = error;
|
||||
}
|
||||
}
|
||||
if (answered || this.closed) return;
|
||||
// An aborted `signal`: the request settled without this stream (timed out, cancelled).
|
||||
if (answered || this.closed || signal?.aborted) return;
|
||||
if (failure !== undefined && !this.isRetryable(failure)) break;
|
||||
if (cursor.lastEventId === undefined || attempt >= this.maxRetries()) break;
|
||||
if (this.stateless || cursor.lastEventId === undefined || attempt >= this.maxRetries()) break;
|
||||
if (cursor.received) attempt = 0;
|
||||
cursor.received = false;
|
||||
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ export interface McpTransportSendOptions {
|
|||
* retrying it after an authorization refresh. It does not undo a message already dispatched.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
/** HTTP headers for this message (`Mcp-Param-*` of MCP 2026-07-28). Transports without headers ignore them. */
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface McpTransport {
|
||||
|
|
@ -22,6 +24,11 @@ export interface McpTransport {
|
|||
onMessage(listener: McpTransportMessageListener): () => void;
|
||||
onError(listener: McpTransportErrorListener): () => void;
|
||||
onClose(listener: McpTransportCloseListener): () => void;
|
||||
/**
|
||||
* The negotiated protocol version, for transports that send it with every message. Also called with
|
||||
* `2026-07-28` before the first request of the stateless revision, which some transports carry
|
||||
* differently (no session over HTTP).
|
||||
*/
|
||||
setProtocolVersion?(version: string): void;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
McpClient,
|
||||
McpError,
|
||||
McpTimeoutError,
|
||||
type McpTransport,
|
||||
} from "../src/index.ts";
|
||||
import { createInMemoryTransportPair, type InMemoryTransport } from "../src/testing/index.ts";
|
||||
|
||||
|
|
@ -337,3 +338,264 @@ describe("McpClient", () => {
|
|||
await client.close();
|
||||
});
|
||||
});
|
||||
|
||||
const STATELESS_META = {
|
||||
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
||||
"io.modelcontextprotocol/clientInfo": { name: "test-client", version: "1.0.0" },
|
||||
"io.modelcontextprotocol/clientCapabilities": { roots: {} },
|
||||
};
|
||||
|
||||
/** A server that only speaks MCP 2026-07-28: it rejects `initialize` as SDK servers without legacy support do. */
|
||||
async function createStatelessServer(): Promise<{ clientTransport: InMemoryTransport; server: TestServer }> {
|
||||
const created = await createServer();
|
||||
created.server.setHandler("initialize", () => {
|
||||
throw new McpError(-32022, "Unsupported protocol version: 2025-11-25", {
|
||||
supported: ["2026-07-28"],
|
||||
requested: "2025-11-25",
|
||||
});
|
||||
});
|
||||
created.server.setHandler("server/discover", () => ({
|
||||
supportedVersions: ["2026-07-28"],
|
||||
capabilities: { tools: {} },
|
||||
instructions: "Stateless tools.",
|
||||
resultType: "complete",
|
||||
_meta: { "io.modelcontextprotocol/serverInfo": { name: "stateless-server", version: "3.0.0" } },
|
||||
}));
|
||||
return created;
|
||||
}
|
||||
|
||||
function requestsOf(server: TestServer): JsonRpcRequest[] {
|
||||
return server.messages.filter((message): message is JsonRpcRequest => "method" in message && "id" in message);
|
||||
}
|
||||
|
||||
async function connectStateless(options: { protocol?: "2026-07-28"; logLevel?: "info" } = {}) {
|
||||
const { clientTransport, server } = await createStatelessServer();
|
||||
const sent: { method: string; headers: Record<string, string> | undefined }[] = [];
|
||||
const send = clientTransport.send.bind(clientTransport);
|
||||
// The in-memory transport carries no headers; record what the client asks for.
|
||||
const transport: McpTransport = clientTransport;
|
||||
transport.send = (message, sendOptions) => {
|
||||
if ("method" in message) sent.push({ method: message.method, headers: sendOptions?.headers });
|
||||
return send(message);
|
||||
};
|
||||
const client = new McpClient({
|
||||
name: "test-client",
|
||||
version: "1.0.0",
|
||||
roots: [{ uri: "file:///workspace", name: "workspace" }],
|
||||
...options,
|
||||
});
|
||||
await client.connect(clientTransport);
|
||||
return { client, server, sent };
|
||||
}
|
||||
|
||||
describe("McpClient on the stateless revision (2026-07-28)", () => {
|
||||
it("asks with server/discover only when the server rejects initialize", async () => {
|
||||
const { client, server } = await connectStateless({ logLevel: "info" });
|
||||
expect(client.protocolVersion).toBe("2026-07-28");
|
||||
expect(client.serverInfo).toEqual({ name: "stateless-server", version: "3.0.0" });
|
||||
expect(client.serverCapabilities).toEqual({ tools: {} });
|
||||
expect(client.instructions).toBe("Stateless tools.");
|
||||
server.setHandler("tools/list", () => ({ tools: [] }));
|
||||
await client.listTools();
|
||||
const requests = requestsOf(server);
|
||||
expect(requests.map((request) => request.method)).toEqual(["initialize", "server/discover", "tools/list"]);
|
||||
// No handshake notification; every request names the version, the client, and the log level.
|
||||
expect(server.messages).toHaveLength(requests.length);
|
||||
const meta = { ...STATELESS_META, "io.modelcontextprotocol/logLevel": "info" };
|
||||
expect(requests[1]?.params).toEqual({ _meta: meta });
|
||||
expect(requests[2]?.params).toEqual({ _meta: meta });
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("speaks only the stateless revision when pinned", async () => {
|
||||
const { client, server } = await connectStateless({ protocol: "2026-07-28" });
|
||||
expect(client.protocolVersion).toBe("2026-07-28");
|
||||
expect(requestsOf(server).map((request) => request.method)).toEqual(["server/discover"]);
|
||||
await client.close();
|
||||
|
||||
const legacy = await createServer();
|
||||
const pinned = new McpClient({ name: "test-client", version: "1.0.0", protocol: "2026-07-28" });
|
||||
await expect(pinned.connect(legacy.clientTransport)).rejects.toThrow("Method not found: server/discover");
|
||||
expect(requestsOf(legacy.server).map((request) => request.method)).toEqual(["server/discover"]);
|
||||
});
|
||||
|
||||
it("reports the initialize error when server/discover fails too", async () => {
|
||||
const { clientTransport, server } = await createServer();
|
||||
server.setHandler("initialize", () => {
|
||||
throw new McpError(-32600, "bad initialize");
|
||||
});
|
||||
const client = new McpClient({ name: "test-client", version: "1.0.0" });
|
||||
await expect(client.connect(clientTransport)).rejects.toThrow("bad initialize");
|
||||
expect(requestsOf(server).map((request) => request.method)).toEqual(["initialize", "server/discover"]);
|
||||
|
||||
// A server that ignores the request does not hold up the error for longer than the request timeout.
|
||||
const silent = await createServer();
|
||||
silent.server.setHandler("initialize", () => {
|
||||
throw new McpError(-32600, "bad initialize");
|
||||
});
|
||||
silent.server.setHandler("server/discover", () => new Promise(() => {}));
|
||||
const waiting = new McpClient({ name: "test-client", version: "1.0.0", requestTimeoutMs: 20 });
|
||||
await expect(waiting.connect(silent.clientTransport)).rejects.toThrow("bad initialize");
|
||||
});
|
||||
|
||||
it("asks with server/discover when initialize is answered with the stateless revision", async () => {
|
||||
const { clientTransport, server } = await createStatelessServer();
|
||||
server.setHandler("initialize", () => ({
|
||||
protocolVersion: "2026-07-28",
|
||||
capabilities: {},
|
||||
serverInfo: { name: "stateless-server", version: "3.0.0" },
|
||||
}));
|
||||
const client = new McpClient({ name: "test-client", version: "1.0.0" });
|
||||
await client.connect(clientTransport);
|
||||
expect(client.protocolVersion).toBe("2026-07-28");
|
||||
expect(server.messages.map((message) => ("method" in message ? message.method : ""))).toEqual([
|
||||
"initialize",
|
||||
"server/discover",
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("reports the server/discover error when the rejection proved a stateless server", async () => {
|
||||
const { clientTransport, server } = await createStatelessServer();
|
||||
server.setHandler("server/discover", () => {
|
||||
throw new McpError(-32021, "Missing required client capability: elicitation");
|
||||
});
|
||||
const client = new McpClient({ name: "test-client", version: "1.0.0" });
|
||||
await expect(client.connect(clientTransport)).rejects.toThrow("Missing required client capability: elicitation");
|
||||
});
|
||||
|
||||
it("reports the initialize rejection when the server is gone after it", async () => {
|
||||
const { clientTransport, server } = await createStatelessServer();
|
||||
server.setHandler("server/discover", async () => {
|
||||
await server.transport.close();
|
||||
return new Promise(() => {});
|
||||
});
|
||||
const client = new McpClient({ name: "test-client", version: "1.0.0" });
|
||||
await expect(client.connect(clientTransport)).rejects.toMatchObject({ code: -32022 });
|
||||
});
|
||||
|
||||
it("does not ask with server/discover when initialize fails without an answer", async () => {
|
||||
const { clientTransport, server } = await createServer();
|
||||
server.setHandler("initialize", () => new Promise(() => {}));
|
||||
const client = new McpClient({ name: "test-client", version: "1.0.0", requestTimeoutMs: 5 });
|
||||
await expect(client.connect(clientTransport)).rejects.toBeInstanceOf(McpTimeoutError);
|
||||
expect(requestsOf(server).map((request) => request.method)).toEqual(["initialize"]);
|
||||
});
|
||||
|
||||
it("rejects a discover result without this client's version", async () => {
|
||||
const { clientTransport, server } = await createStatelessServer();
|
||||
server.setHandler("server/discover", () => ({ supportedVersions: ["2027-01-01"], capabilities: {} }));
|
||||
const client = new McpClient({ name: "test-client", version: "1.0.0", protocol: "2026-07-28" });
|
||||
await expect(client.connect(clientTransport)).rejects.toThrow(
|
||||
"MCP server supports none of this client's protocol versions: 2027-01-01",
|
||||
);
|
||||
});
|
||||
|
||||
it("answers input requests and sends the request again until it completes", async () => {
|
||||
const { client, server } = await connectStateless();
|
||||
server.setHandler("tools/call", (request) => {
|
||||
const params = request.params as Record<string, unknown>;
|
||||
if (params.requestState === undefined) {
|
||||
return {
|
||||
resultType: "input_required",
|
||||
inputRequests: { roots: { method: "roots/list" } },
|
||||
requestState: "state-1",
|
||||
};
|
||||
}
|
||||
return { resultType: "complete", content: [{ type: "text", text: JSON.stringify(params.inputResponses) }] };
|
||||
});
|
||||
const result = await client.callTool("needs-roots", { a: 1 });
|
||||
expect(result.content).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({ roots: { roots: [{ uri: "file:///workspace", name: "workspace" }] } }),
|
||||
},
|
||||
]);
|
||||
const calls = requestsOf(server).filter((request) => request.method === "tools/call");
|
||||
expect(calls.map((request) => request.params)).toEqual([
|
||||
{ name: "needs-roots", arguments: { a: 1 }, _meta: STATELESS_META },
|
||||
{
|
||||
name: "needs-roots",
|
||||
arguments: { a: 1 },
|
||||
inputResponses: { roots: { roots: [{ uri: "file:///workspace", name: "workspace" }] } },
|
||||
requestState: "state-1",
|
||||
_meta: STATELESS_META,
|
||||
},
|
||||
]);
|
||||
// Every attempt is a new request.
|
||||
expect(new Set(calls.map((request) => request.id)).size).toBe(2);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("fails requests that ask for input the client does not provide, or that never complete", async () => {
|
||||
const { client, server } = await connectStateless();
|
||||
server.setHandler("tools/call", (request) =>
|
||||
(request.params as { name: string }).name === "form"
|
||||
? { resultType: "input_required", inputRequests: { form: { method: "elicitation/create", params: {} } } }
|
||||
: { resultType: "input_required", requestState: "again" },
|
||||
);
|
||||
await expect(client.callTool("form")).rejects.toThrow(
|
||||
"MCP server asked for input this client does not provide: elicitation/create",
|
||||
);
|
||||
await expect(client.callTool("loop")).rejects.toThrow("MCP tools/call still asks for input after 16 rounds");
|
||||
server.setHandler("tools/list", () => ({ resultType: "input_required", requestState: "x" }));
|
||||
await expect(client.listTools()).rejects.toThrow("MCP tools/list result asks for input, which it may not");
|
||||
server.setHandler("tools/list", () => ({ resultType: "task", tools: [] }));
|
||||
await expect(client.listTools()).rejects.toThrow("Unsupported MCP tools/list result type: task");
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("mirrors x-mcp-header arguments into headers and leaves out tools with invalid annotations", async () => {
|
||||
const { client, server, sent } = await connectStateless();
|
||||
const errors: string[] = [];
|
||||
client.onError((error) => errors.push(error.message));
|
||||
const regionTool = {
|
||||
name: "deploy",
|
||||
inputSchema: { type: "object", properties: { region: { type: "string", "x-mcp-header": "Region" } } },
|
||||
};
|
||||
const invalidTool = {
|
||||
name: "broken",
|
||||
inputSchema: { type: "object", properties: { data: { type: "object", "x-mcp-header": "Data" } } },
|
||||
};
|
||||
server.setHandler("tools/list", () => ({ tools: [regionTool, invalidTool] }));
|
||||
expect((await client.listTools()).map((tool) => tool.name)).toEqual(["deploy"]);
|
||||
expect(errors).toEqual([
|
||||
'Excluded MCP tool "broken": x-mcp-header "Data" must be on a string, integer, or boolean property',
|
||||
]);
|
||||
|
||||
server.setHandler("tools/call", () => ({ content: [] }));
|
||||
await client.callTool("deploy", { region: "us-west1" });
|
||||
expect(sent.at(-1)).toEqual({ method: "tools/call", headers: { "Mcp-Param-Region": "us-west1" } });
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("lists the tools again and retries once when the server reports mismatching headers", async () => {
|
||||
const { client, server, sent } = await connectStateless();
|
||||
server.setHandler("tools/list", () => ({
|
||||
tools: [
|
||||
{
|
||||
name: "deploy",
|
||||
inputSchema: { type: "object", properties: { region: { type: "string", "x-mcp-header": "Region" } } },
|
||||
},
|
||||
],
|
||||
}));
|
||||
let calls = 0;
|
||||
server.setHandler("tools/call", () => {
|
||||
if (++calls === 1) throw new McpError(-32020, "Header mismatch: Mcp-Param-Region");
|
||||
return { content: [{ type: "text", text: "ok" }] };
|
||||
});
|
||||
// Called before the tools were listed: no bindings yet.
|
||||
expect(await client.callTool("deploy", { region: "eu" })).toEqual({ content: [{ type: "text", text: "ok" }] });
|
||||
expect(sent.slice(-3)).toEqual([
|
||||
{ method: "tools/call", headers: undefined },
|
||||
{ method: "tools/list", headers: undefined },
|
||||
{ method: "tools/call", headers: { "Mcp-Param-Region": "eu" } },
|
||||
]);
|
||||
|
||||
server.setHandler("tools/call", () => {
|
||||
throw new McpError(-32020, "Header mismatch");
|
||||
});
|
||||
await expect(client.callTool("deploy", { region: "eu" })).rejects.toThrow("Header mismatch");
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ describe("validateMcpServerConfig", () => {
|
|||
oauth: { clientId: "id", callbackPort: 8080, scope: "read" },
|
||||
timeout: 30,
|
||||
description: "Docs",
|
||||
protocol: "2026-07-28",
|
||||
};
|
||||
const result = validateMcpServerConfig("docs", http);
|
||||
expect(result).toEqual({ kind: "http", config: http });
|
||||
|
|
@ -54,6 +55,7 @@ describe("validateMcpServerConfig", () => {
|
|||
["s", { command: "x", enabled: "yes" }, 'server "s": enabled must be a boolean'],
|
||||
["s", { command: "x", description: 1 }, 'server "s": description must be a string'],
|
||||
["s", { command: "x", timeout: 0 }, 'server "s": timeout must be a positive number of seconds'],
|
||||
["s", { command: "x", protocol: "legacy" }, 'server "s": protocol must be "auto" or "2026-07-28"'],
|
||||
["s", { command: "x", args: "a b" }, 'server "s": args must be an array of strings'],
|
||||
["s", { command: "x", env: { A: 1 } }, 'server "s": env must map names to strings'],
|
||||
["s", { command: "x", cwd: 1 }, 'server "s": cwd must be a string'],
|
||||
|
|
|
|||
138
packages/mcp/test/http-headers.test.ts
Normal file
138
packages/mcp/test/http-headers.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
encodeHeaderValue,
|
||||
standardRequestHeaders,
|
||||
toolHeaderBindings,
|
||||
toolParamHeaders,
|
||||
} from "../src/protocol/http-headers.ts";
|
||||
|
||||
describe("encodeHeaderValue", () => {
|
||||
// The examples of the 2026-07-28 Streamable HTTP spec.
|
||||
it.each([
|
||||
["us-west1", "us-west1"],
|
||||
["us west 1", "us west 1"],
|
||||
["", ""],
|
||||
["Hello, 世界", "=?base64?SGVsbG8sIOS4lueVjA==?="],
|
||||
[" padded ", "=?base64?IHBhZGRlZCA=?="],
|
||||
["line1\nline2", "=?base64?bGluZTEKbGluZTI=?="],
|
||||
["\tindented", "=?base64?CWluZGVudGVk?="],
|
||||
["=?base64?literal?=", "=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?="],
|
||||
])("encodes %j as %j", (value, encoded) => {
|
||||
expect(encodeHeaderValue(value)).toBe(encoded);
|
||||
});
|
||||
});
|
||||
|
||||
describe("standardRequestHeaders", () => {
|
||||
it("names the method, and the tool, prompt, or resource where the method has one", () => {
|
||||
expect(standardRequestHeaders("tools/list", {})).toEqual({ "Mcp-Method": "tools/list" });
|
||||
expect(standardRequestHeaders("tools/call", { name: "my-tool" })).toEqual({
|
||||
"Mcp-Method": "tools/call",
|
||||
"Mcp-Name": "my-tool",
|
||||
});
|
||||
expect(standardRequestHeaders("prompts/get", { name: "greet" })).toEqual({
|
||||
"Mcp-Method": "prompts/get",
|
||||
"Mcp-Name": "greet",
|
||||
});
|
||||
expect(standardRequestHeaders("resources/read", { uri: "file:///a%20b.txt" })).toEqual({
|
||||
"Mcp-Method": "resources/read",
|
||||
"Mcp-Name": "file:///a%20b.txt",
|
||||
});
|
||||
expect(standardRequestHeaders("tools/call", { name: "café" })["Mcp-Name"]).toBe("=?base64?Y2Fmw6k=?=");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toolHeaderBindings", () => {
|
||||
it("collects annotations reached through properties, including nested objects", () => {
|
||||
expect(
|
||||
toolHeaderBindings({
|
||||
type: "object",
|
||||
properties: {
|
||||
region: { type: "string", "x-mcp-header": "Region" },
|
||||
options: {
|
||||
type: "object",
|
||||
properties: { verbose: { type: ["boolean", "null"], "x-mcp-header": "Verbose" } },
|
||||
},
|
||||
count: { type: "integer", "x-mcp-header": "Count" },
|
||||
query: { type: "string" },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "valid",
|
||||
bindings: [
|
||||
{ path: ["region"], header: "Region" },
|
||||
{ path: ["options", "verbose"], header: "Verbose" },
|
||||
{ path: ["count"], header: "Count" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores the key in instance data", () => {
|
||||
expect(
|
||||
toolHeaderBindings({
|
||||
type: "object",
|
||||
properties: { config: { type: "object", default: { "x-mcp-header": "nope" } } },
|
||||
}),
|
||||
).toEqual({ kind: "valid", bindings: [] });
|
||||
});
|
||||
|
||||
// The invalid tools of the conformance scenario `http-invalid-tool-headers`.
|
||||
it.each([
|
||||
["empty", { value: { type: "string", "x-mcp-header": "" } }],
|
||||
["object", { data: { type: "object", "x-mcp-header": "Data" } }],
|
||||
["array", { items: { type: "array", items: { type: "string" }, "x-mcp-header": "Items" } }],
|
||||
["null", { nil: { type: "null", "x-mcp-header": "Nil" } }],
|
||||
["number", { ratio: { type: "number", "x-mcp-header": "Ratio" } }],
|
||||
["untyped", { value: { "x-mcp-header": "Value" } }],
|
||||
[
|
||||
"duplicate",
|
||||
{ field1: { type: "string", "x-mcp-header": "Region" }, field2: { type: "string", "x-mcp-header": "Region" } },
|
||||
],
|
||||
[
|
||||
"duplicate ignoring case",
|
||||
{
|
||||
field1: { type: "string", "x-mcp-header": "MyField" },
|
||||
field2: { type: "string", "x-mcp-header": "myfield" },
|
||||
},
|
||||
],
|
||||
["space", { value: { type: "string", "x-mcp-header": "My Region" } }],
|
||||
["colon", { value: { type: "string", "x-mcp-header": "Region:Primary" } }],
|
||||
["non-ASCII", { value: { type: "string", "x-mcp-header": "Région" } }],
|
||||
["control character", { value: { type: "string", "x-mcp-header": "Region\t1" } }],
|
||||
["array items", { list: { type: "array", items: { type: "string", "x-mcp-header": "Item" } } }],
|
||||
["composition", { value: { anyOf: [{ type: "string", "x-mcp-header": "Value" }] } }],
|
||||
])("rejects an annotation that is %s", (_case, properties) => {
|
||||
expect(toolHeaderBindings({ type: "object", properties }).kind).toBe("invalid");
|
||||
});
|
||||
|
||||
it("rejects annotations in definitions and on the root", () => {
|
||||
expect(toolHeaderBindings({ type: "object", $defs: { id: { type: "string", "x-mcp-header": "Id" } } }).kind).toBe(
|
||||
"invalid",
|
||||
);
|
||||
expect(toolHeaderBindings({ type: "object", "x-mcp-header": "Root" }).kind).toBe("invalid");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toolParamHeaders", () => {
|
||||
const bindings = [
|
||||
{ path: ["region"], header: "Region" },
|
||||
{ path: ["priority"], header: "Priority" },
|
||||
{ path: ["verbose"], header: "Verbose" },
|
||||
{ path: ["options", "mode"], header: "Mode" },
|
||||
];
|
||||
|
||||
it("mirrors strings, integers, and booleans, encoding unsafe strings", () => {
|
||||
expect(
|
||||
toolParamHeaders(bindings, { region: " us-west1", priority: 42, verbose: false, options: { mode: "fast" } }),
|
||||
).toEqual({
|
||||
"Mcp-Param-Region": "=?base64?IHVzLXdlc3Qx?=",
|
||||
"Mcp-Param-Priority": "42",
|
||||
"Mcp-Param-Verbose": "false",
|
||||
"Mcp-Param-Mode": "fast",
|
||||
});
|
||||
});
|
||||
|
||||
it("omits absent, null, and non-primitive values", () => {
|
||||
expect(toolParamHeaders(bindings, { region: null, priority: 1.5, options: "flat" })).toEqual({});
|
||||
expect(toolParamHeaders(bindings, undefined)).toEqual({});
|
||||
});
|
||||
});
|
||||
|
|
@ -683,3 +683,191 @@ describe("StreamableHttpTransport", () => {
|
|||
await client.close();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A server that only speaks MCP 2026-07-28, answering like SDK servers without legacy support:
|
||||
* `initialize` gets a 400 with an `UnsupportedProtocolVersionError`.
|
||||
*/
|
||||
async function statelessHandler(
|
||||
request: IncomingMessage,
|
||||
response: ServerResponse,
|
||||
requests: RecordedRequest[],
|
||||
body?: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
if (request.method !== "POST") {
|
||||
requests.push({ method: request.method ?? "", headers: request.headers });
|
||||
response.statusCode = 405;
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
const message = body ?? (JSON.parse(await readBody(request)) as Record<string, unknown>);
|
||||
requests.push({ method: "POST", headers: request.headers, message });
|
||||
const reply = (status: number, payload: Record<string, unknown>) => {
|
||||
// A session header the client must not send back.
|
||||
response.writeHead(status, { "content-type": "application/json", "mcp-session-id": "ignored" });
|
||||
response.end(JSON.stringify({ jsonrpc: "2.0", id: message.id ?? null, ...payload }));
|
||||
};
|
||||
switch (message.method) {
|
||||
case "initialize":
|
||||
reply(400, {
|
||||
error: { code: -32022, message: "Unsupported protocol version", data: { supported: ["2026-07-28"] } },
|
||||
});
|
||||
return;
|
||||
case "server/discover":
|
||||
reply(200, { result: { supportedVersions: ["2026-07-28"], capabilities: { tools: {} } } });
|
||||
return;
|
||||
case "tools/list":
|
||||
reply(200, {
|
||||
result: {
|
||||
tools: [
|
||||
{
|
||||
name: "deploy",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { region: { type: "string", "x-mcp-header": "Region" } },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "resources/read":
|
||||
reply(404, { error: { code: -32602, message: "Unknown resource" } });
|
||||
return;
|
||||
default:
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
response.end(
|
||||
`id: 1\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: "done" }] } })}\n\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
describe("StreamableHttpTransport on the stateless revision (2026-07-28)", () => {
|
||||
it("falls back from a rejected initialize and sends requests without a session", async () => {
|
||||
const { url, requests } = await startServer(statelessHandler);
|
||||
const transport = new StreamableHttpTransport({ url });
|
||||
const client = new McpClient({ name: "http-test", version: "1.0.0" });
|
||||
await client.connect(transport);
|
||||
expect(client.protocolVersion).toBe("2026-07-28");
|
||||
await client.listTools();
|
||||
expect(await client.callTool("deploy", { region: "Zürich" })).toEqual({
|
||||
content: [{ type: "text", text: "done" }],
|
||||
});
|
||||
await expect(client.readResource("file:///missing")).rejects.toMatchObject({
|
||||
name: "McpError",
|
||||
code: -32602,
|
||||
message: "Unknown resource",
|
||||
});
|
||||
await client.close();
|
||||
expect(transport.sessionId).toBeUndefined();
|
||||
|
||||
// No GET stream, no session to delete, no handshake notification.
|
||||
expect(requests.map((entry) => entry.message?.method ?? entry.method)).toEqual([
|
||||
"initialize",
|
||||
"server/discover",
|
||||
"tools/list",
|
||||
"tools/call",
|
||||
"resources/read",
|
||||
]);
|
||||
const [initialize, ...stateless] = requests;
|
||||
expect(initialize?.headers["mcp-method"]).toBeUndefined();
|
||||
for (const entry of stateless) {
|
||||
expect(entry.headers["mcp-protocol-version"]).toBe("2026-07-28");
|
||||
expect(entry.headers["mcp-method"]).toBe(entry.message?.method);
|
||||
expect(entry.headers["mcp-session-id"]).toBeUndefined();
|
||||
}
|
||||
const call = requests.find((entry) => entry.message?.method === "tools/call");
|
||||
expect(call?.headers["mcp-name"]).toBe("deploy");
|
||||
expect(call?.headers["mcp-param-region"]).toBe("=?base64?WsO8cmljaA==?=");
|
||||
expect(requests.find((entry) => entry.message?.method === "resources/read")?.headers["mcp-name"]).toBe(
|
||||
"file:///missing",
|
||||
);
|
||||
});
|
||||
|
||||
it("drops the session of an initialize answered with the stateless revision", async () => {
|
||||
const { url, requests } = await startServer(async (request, response, requests) => {
|
||||
if (request.method !== "POST") return statelessHandler(request, response, requests);
|
||||
const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
|
||||
if (message.method !== "initialize") return statelessHandler(request, response, requests, message);
|
||||
requests.push({ method: "POST", headers: request.headers, message });
|
||||
response.writeHead(200, { "content-type": "application/json", "mcp-session-id": "session-1" });
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { protocolVersion: "2026-07-28", capabilities: {}, serverInfo: { name: "s", version: "1" } },
|
||||
}),
|
||||
);
|
||||
});
|
||||
const transport = new StreamableHttpTransport({ url });
|
||||
const client = new McpClient({ name: "http-test", version: "1.0.0" });
|
||||
await client.connect(transport);
|
||||
await client.listTools();
|
||||
await client.close();
|
||||
expect(requests.map((entry) => entry.message?.method ?? entry.method)).toEqual([
|
||||
"initialize",
|
||||
"server/discover",
|
||||
"tools/list",
|
||||
]);
|
||||
expect(requests.slice(1).every((entry) => entry.headers["mcp-session-id"] === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("reports a sign-in a stateless server requires after rejecting initialize", async () => {
|
||||
const { url } = await startServer(async (request, response) => {
|
||||
const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
|
||||
if (message.method === "initialize") {
|
||||
response.writeHead(400, { "content-type": "application/json" });
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
error: { code: -32020, message: "Missing MCP-Protocol-Version header" },
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
response.writeHead(401, { "www-authenticate": 'Bearer resource_metadata="https://example.com/meta"' });
|
||||
response.end();
|
||||
});
|
||||
const client = new McpClient({ name: "http-test", version: "1.0.0" });
|
||||
await expect(client.connect(new StreamableHttpTransport({ url }))).rejects.toMatchObject({
|
||||
name: "McpAuthRequiredError",
|
||||
status: 401,
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels a request by closing its response stream, and does not resume streams", async () => {
|
||||
const closed: string[] = [];
|
||||
const { url, requests } = await startServer(async (request, response, requests) => {
|
||||
if (request.method !== "POST") return statelessHandler(request, response, requests);
|
||||
const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
|
||||
const name = (message.params as { name?: string } | undefined)?.name;
|
||||
if (message.method !== "tools/call") return statelessHandler(request, response, requests, message);
|
||||
requests.push({ method: "POST", headers: request.headers, message });
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
if (name === "dropped") {
|
||||
// An event id would let a legacy client resume; this stream ends without an answer.
|
||||
response.end("id: 1\nretry: 5\ndata:\n\n");
|
||||
return;
|
||||
}
|
||||
response.write(": waiting\n\n");
|
||||
response.on("close", () => closed.push(String(name)));
|
||||
});
|
||||
const client = new McpClient({ name: "http-test", version: "1.0.0" });
|
||||
await client.connect(new StreamableHttpTransport({ url }));
|
||||
|
||||
const controller = new AbortController();
|
||||
const waiting = client.callTool("wait", {}, { signal: controller.signal });
|
||||
await vi.waitFor(() => expect(requests.some((entry) => entry.message?.method === "tools/call")).toBe(true));
|
||||
controller.abort("stop");
|
||||
await expect(waiting).rejects.toThrow("MCP request aborted");
|
||||
await vi.waitFor(() => expect(closed).toEqual(["wait"]));
|
||||
|
||||
await expect(client.callTool("dropped")).rejects.toThrow(
|
||||
"MCP response stream failed: stream ended without a response",
|
||||
);
|
||||
await client.close();
|
||||
expect(requests.some((entry) => entry.method === "GET")).toBe(false);
|
||||
expect(requests.some((entry) => entry.message?.method === "notifications/cancelled")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue