Skip to content

chore: update spec.types.ts from upstream#2027

Open
github-actions[bot] wants to merge 1 commit into
mainfrom
update-spec-types
Open

chore: update spec.types.ts from upstream#2027
github-actions[bot] wants to merge 1 commit into
mainfrom
update-spec-types

Conversation

@github-actions

@github-actions github-actions Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

This PR updates packages/core/src/types/spec.types.2026-07-28.ts from the Model Context Protocol specification.

Source file: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/77cb26481e439d3437bc2bd6ccd19fcae86bb1ec/schema/draft/schema.ts

This is an automated update triggered by the nightly cron job.

@github-actions github-actions Bot requested a review from a team as a code owner May 7, 2026 05:08
@changeset-bot

changeset-bot Bot commented May 7, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 0435878

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot force-pushed the update-spec-types branch from fe613a8 to 5f450ff Compare May 8, 2026 05:01
Comment thread packages/core/src/types/spec.types.ts Outdated
Comment thread packages/core/src/types/spec.types.ts
Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch 2 times, most recently from a64a23e to af35bb5 Compare May 10, 2026 05:12
Comment thread packages/core/src/types/spec.types.ts Outdated
Comment on lines +406 to +418
/* Request parameter type that includes input responses and request state.
* These parameters may be included in any client-initiated request.
*/
export interface InputResponseRequestParams extends RequestParams {
/* New field to carry the responses for the server's requests from the
* InputRequiredResult message. For each key in the response's inputRequests
* field, the same key must appear here with the associated response.
*/
inputResponses?: InputResponses;
/* Request state passed back to the server from the client.
*/
requestState?: string;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Nit (upstream): the field/interface comments here use plain /* ... */ instead of /** ... */ JSDoc, so the TS language service / TypeDoc will not surface them — and InputResponseRequestParams ends up with no doc comment and no @category Multi Round-Trip tag at all, unlike every sibling type in this section. Since spec.types.ts is not re-exported from this package the SDK's own docs are unaffected, but it's worth folding into the same upstream schema.ts fix as the resultType issue so the spec repo's generated docs and the forthcoming hand-written schemas.ts mirror get proper descriptions.

Extended reasoning...

What the issue is

In the new Multi Round-Trip block, several comments use plain block-comment syntax /* ... */ instead of JSDoc syntax /** ... */:

  • InputRequiredResult.inputRequests (lines 394-396)
  • InputRequiredResult.requestState (lines 398-402)
  • the interface-level comment on InputResponseRequestParams (lines 406-408)
  • InputResponseRequestParams.inputResponses (lines 410-413)
  • InputResponseRequestParams.requestState (lines 415-416)

Because the opening delimiter is /* (single asterisk) rather than /**, TypeScript's language service and TypeDoc treat these as ordinary comments, not documentation. Additionally, since InputResponseRequestParams has no /** */ block at all, it also has no @category Multi Round-Trip tag — every other exported type in this section (InputRequests, InputResponses, InputRequiredResult, TaskInputResponseRequest, etc.) carries that tag.

Why this is an upstream slip, not intentional

This is not the file's convention. Every surrounding declaration in the same diff hunk uses proper /** ... */ JSDoc: ResultType (148-156), InputRequests (354-362), InputResponses (366-375), InputRequiredResult itself (380-392), TaskInputResponseRequest (2031-2039), TaskInputResponseRequestParams (2046-2056). The pre-existing /* Empty result */ and /* Cancellation */ lines are one-line section dividers, not API documentation, so they are not precedent for multi-line field descriptions. The five blocks above are the only multi-line API descriptions in the file using /* — a clear authoring inconsistency in the upstream commit.

Addressing the "not SDK-public" objection

It is true that spec.types.ts is not part of this SDK's public surface — packages/core/src/types/index.ts re-exports constants/enums/errors/guards/schemas/specTypeSchema/types but not spec.types, and the only importer in the package is test/spec.types.test.ts. So this has zero effect on the typescript-sdk's generated docs or consumer .d.ts, and CLAUDE.md's "JSDoc for public APIs" rule does not directly apply to this file in this repo.

The reason it is still worth a (nit-level) mention is that this file is a verbatim mirror of the spec repo's schema/draft/schema.ts, which is the source for the protocol's own TypeDoc site. In the upstream output, InputResponseRequestParams will render with no description and will be uncategorised (it will not appear under the "Multi Round-Trip" group), and the normative "client must treat this as an opaque blob" guidance on requestState will be invisible in IDE hover for anyone consuming the spec types. The fix lives in the same upstream file that already needs editing for the resultType? optionality issue flagged elsewhere on this PR, so the marginal cost of including it in that upstream report is near zero.

Step-by-step proof

  1. Hover InputResponseRequestParams at line 409 in VS Code → tooltip shows only interface InputResponseRequestParams extends RequestParams with no description, because lines 406-408 start with /* not /**.
  2. Hover InputRequiredResult at line 393 → tooltip shows the full "An InputRequiredResult sent by the server…" text, because lines 380-392 start with /**.
  3. Hover requestState at line 403 → no description; the "client must treat this as an opaque blob" note (398-402) is dropped.
  4. Run TypeDoc over upstream schema.tsInputRequests, InputResponses, InputRequiredResult are grouped under Multi Round-Trip; InputResponseRequestParams is not (no @category tag, because there is no JSDoc block to carry one).

How to fix

In upstream schema.ts, change /*/** on the five blocks listed above and add @category Multi Round-Trip to the InputResponseRequestParams doc comment, then re-run pnpm run fetch:spec-types. No change is appropriate in this repo directly (the file header says DO NOT EDIT). This is purely documentation rendering — it does not affect type-checking, the drift guard, or runtime behaviour — hence nit, raised only because an upstream schema.ts fix is already on the table for this sync.

Comment on lines +393 to +404
export interface InputRequiredResult extends Result {
/* Requests issued by the server that must be complete before the
* client can retry the original request.
*/
inputRequests?: InputRequests;
/* Request state to be passed back to the server when the client
* retries the original request.
* Note: The client must treat this as an opaque blob; it must not
* interpret it in any way.
*/
requestState?: string;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream design gap worth flagging alongside the other schema.ts feedback: InputRequiredResult extends Result without redeclaring resultType: 'input_required', and none of the "complete" subtypes (CallToolResult/ReadResourceResult/GetPromptResult/GetTaskPayloadResult) narrow to resultType: 'complete' either — so the new result: CallToolResult | InputRequiredResult unions (lines 1122/1455/1650/2028) are not TypeScript discriminated unions and if (r.resultType === 'input_required') will not narrow. This is orthogonal to the "resultType is required" comment above (fixing one doesn't fix the other) and constrains the SDK from modeling these with z.discriminatedUnion('resultType', ...) while keeping the bidirectional spec↔SDK assignability check green.

Extended reasoning...

What the bug is

The spec introduces ResultType = 'complete' | 'input_required' and adds resultType: ResultType to the base Result interface (line 165), with the JSDoc explicitly stating its purpose is to "allow the client to determine how to parse the result object." It then defines InputRequiredResult extends Result (line 393) and unions it into four response envelopes — CallToolResultResponse.result: CallToolResult | InputRequiredResult (1650), and likewise for ReadResourceResultResponse (1122), GetPromptResultResponse (1455), and GetTaskPayloadResultResponse (2028).

However, InputRequiredResult does not redeclare resultType: 'input_required', and none of CallToolResult / ReadResourceResult / GetPromptResult / GetTaskPayloadResult redeclare resultType: 'complete'. A grep confirms resultType appears exactly once in spec.types.ts — only on the base Result. So every arm of every X | InputRequiredResult union has resultType typed as the full 'complete' | 'input_required', and TypeScript's discriminated-union narrowing does not engage.

Step-by-step proof

  1. Result.resultType: 'complete' | 'input_required' (line 165).
  2. InputRequiredResult extends Result { inputRequests?: ...; requestState?: ... } (line 393) — inherits resultType: 'complete' | 'input_required' unchanged.
  3. CallToolResult extends Result { content: ...; ... } — also inherits resultType: 'complete' | 'input_required' unchanged.
  4. Given declare const r: CallToolResult | InputRequiredResult:
    if (r.resultType === 'input_required') {
      r.inputRequests; // ❌ TS error: Property 'inputRequests' does not exist on type 'CallToolResult | InputRequiredResult'
    }
    TypeScript cannot eliminate CallToolResult from the union because CallToolResult['resultType'] also includes 'input_required'. Narrowing requires the discriminant property to have disjoint literal types across union members.
  5. Additionally, since Result carries [key: string]: unknown and InputRequiredResult's only additions (inputRequests?, requestState?) are optional, InputRequiredResult is structurally a subtype of CallToolResult — the union is effectively degenerate at the type level.

Why this is distinct from the existing "resultType is required" comment

The comment on line 165 is about resultType being declared required despite @default "complete", which breaks SDK→spec assignability for every result. This finding is about resultType not being narrowed on subtypes, which breaks discriminated-union narrowing within the spec types themselves. They are orthogonal: making resultType optional on Result does not give InputRequiredResult a narrowed discriminant, and adding resultType: 'input_required' to InputRequiredResult does not make the base field optional. Both should be raised upstream together.

Impact on the SDK

The companion schemas.ts work (already requested in another comment on this PR) will need to define InputRequiredResultSchema and the four result: X | InputRequiredResult unions. The natural Zod encoding is z.discriminatedUnion('resultType', [...]), which requires each arm to declare a z.literal(...) discriminant. But if the SDK narrows InputRequiredResultSchema to resultType: z.literal('input_required'), the spec→SDK direction of the bidirectional assignability check in spec.types.test.ts fails: the spec's InputRequiredResult['resultType'] is 'complete' | 'input_required', which is not assignable to the SDK's 'input_required'. So the SDK is forced to either (a) use a non-discriminated z.union and lose narrowing, or (b) narrow anyway and add a carve-out in the bidirectional test — neither is great, and both go away if upstream narrows the discriminant.

At runtime the wire-level discriminator still works (a client can string-compare resultType and cast), so this is a type-ergonomics / SDK-modeling defect rather than a protocol-correctness one.

How to fix

Upstream in schema.ts: add resultType: 'input_required'; to InputRequiredResult, and add resultType?: 'complete'; (or required 'complete', depending on how the optionality question is resolved) to each concrete "complete" result that participates in an | InputRequiredResult union — at minimum CallToolResult, ReadResourceResult, GetPromptResult, GetTaskPayloadResult. Then re-run pnpm run fetch:spec-types. Batch this with the resultType? optionality fix and the other upstream feedback already noted on this PR.

@github-actions github-actions Bot force-pushed the update-spec-types branch from af35bb5 to 879139a Compare May 11, 2026 05:19
Comment on lines +339 to +349
/* Empty result */
/**
* A result that indicates success but carries no data.
*
* @category Common Types
*/
export type EmptyResult = Result;

/** @internal */
export type InputRequest = CreateMessageRequest | ListRootsRequest | ElicitRequest;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 🔴 The spec deletes URL_ELICITATION_REQUIRED = -32042 / URLElicitationRequiredError (replaced by the InputRequiredResult flow), but the SDK still ships this mechanism as public API: ProtocolErrorCode.UrlElicitationRequired (enums.ts:15), the UrlElicitationRequiredError class + ProtocolError.fromError() special-case (errors.ts:23-48), the public re-export (exports/public/index.ts:103), the tool-handler rethrow at packages/server/src/server/mcp.ts:211, and the examples/{client,server}/src/elicitationUrlExample.ts apps (plus docs/README links and test/integration/test/server/mcp.test.ts:1892-1937). None of these import spec.types.ts, so unlike the other findings on this PR they are silent — no typecheck or drift-guard failure surfaces them. The companion work needs to deprecate/remove the public error class + enum member (breaking change → migration.md), strip the mcp.ts special-case, and rewrite/remove the elicitationUrlExample apps.

Extended reasoning...

What changed in the spec

This sync deletes the entire -32042 error-response mechanism from the protocol. Before, the spec defined an implementation-specific JSON-RPC error code URL_ELICITATION_REQUIRED = -32042 and a URLElicitationRequiredError interface (a JSONRPCErrorResponse whose error.data.elicitations carried ElicitRequestURLParams[]). A server could respond to tools/call with this error to demand that the client open a browser URL before retrying. The diff removes both the constant and the interface; the replacement is the new InputRequiredResult result (with resultType: 'input_required' and inputRequests), which is delivered as a successful response, not an error. The error path is gone from the protocol entirely.

What the SDK still ships

The SDK implemented the -32042 flow end-to-end and exported it publicly. All of the following survive untouched after this PR:

  • packages/core/src/types/enums.ts:15ProtocolErrorCode.UrlElicitationRequired = -32_042, an error code the spec no longer defines.
  • packages/core/src/types/errors.ts:21-48ProtocolError.fromError() special-cases code -32042 and constructs a UrlElicitationRequiredError; the UrlElicitationRequiredError class itself wraps elicitations: ElicitRequestURLParams[] into error.data.
  • packages/core/src/exports/public/index.ts:103export { ProtocolError, UrlElicitationRequiredError } puts the class on the package's public surface.
  • packages/server/src/server/mcp.ts:211-213 — the tools/call handler catches thrown errors and, if error.code === ProtocolErrorCode.UrlElicitationRequired, rethrows so the framework serialises it onto the wire as a JSON-RPC error response instead of wrapping it into a CallToolResult with isError: true. This is runtime behaviour that emits a non-spec error code.
  • examples/server/src/elicitationUrlExample.ts:58,102 — tool handlers throw new UrlElicitationRequiredError([...]).
  • examples/client/src/elicitationUrlExample.ts:26,741 — client catches UrlElicitationRequiredError and drives the browser flow.
  • test/integration/test/server/mcp.test.ts:1892-1937 — integration test asserting the round-trip.
  • docs/client.md:471,626, docs/server.md:477, examples/{client,server}/README.md — documentation linking to the example apps.

Why this is silent (and distinct from the other comments)

Every other finding on this PR is surfaced by spec.types.test.ts or tsc because the affected code references spec.types.ts. This one is not: enums.ts, errors.ts, mcp.ts, and the example apps do not import spec.types.ts. The enum member is a hand-written numeric literal (-32_042); the error class is a hand-written subclass of ProtocolError; the mcp.ts rethrow checks the enum, not the spec interface. Nothing in CI fails when URL_ELICITATION_REQUIRED and URLElicitationRequiredError are removed from spec.types.ts. A reviewer addressing only the existing comments would fix the schemas, the unions, and the test allowlists — and ship a release that still publicly exports an error class for a protocol mechanism that no longer exists.

This is also not a duplicate of the existing comments. Comment #3206453743 (line 3291) covers the server→client request restructuring (createMessage/elicitInput/listRoots becoming InputRequiredResult payloads) and its remediation list is scoped to ServerRequestSchema/ClientResultSchema and the server.createMessage()/elicitInput()/listRoots() APIs — it never mentions the -32042 error-response path, which is a completely separate code path (a tool handler throws, mcp.ts rethrows onto the wire as a JSON-RPC error). Comment #3206453749 (line 418) mentions URLElicitationRequiredError only as a stale entry in the MISSING_SDK_TYPES allowlist affecting the spec.types.test.ts type count; it does not mention enums.ts, errors.ts, the public re-export, mcp.ts:211, or the example apps.

Step-by-step proof

  1. Before (spec.types.ts pre-diff): export const URL_ELICITATION_REQUIRED = -32042; and export interface URLElicitationRequiredError extends Omit<JSONRPCErrorResponse, 'error'> { error: Error & { code: typeof URL_ELICITATION_REQUIRED; data: { elicitations: ElicitRequestURLParams[]; ... } } }.
  2. After (this diff): both are deleted; the only remaining server-side mechanism for "need browser-based input before continuing" is to return { resultType: 'input_required', inputRequests: { ... } } as a successful result.
  3. SDK runtime (mcp.ts:200-215): a tool handler runs, throws new UrlElicitationRequiredError([...]). The catch block at line 211 sees error.code === ProtocolErrorCode.UrlElicitationRequired (i.e., -32_042) and rethrows. Protocol then serialises this into a JSON-RPC error response with error.code = -32042 and error.data.elicitations = [...].
  4. Wire: the SDK is now emitting an error code and error-data shape that the protocol no longer defines. A spec-compliant client built against the post-sync schema has no URLElicitationRequiredError type to deserialise this into and no -32042 constant to switch on.
  5. Public surface: import { UrlElicitationRequiredError } from '@modelcontextprotocol/sdk' still works (exports/public/index.ts:103), and examples/server/src/elicitationUrlExample.ts actively demonstrates throwing it from a tool handler — teaching consumers a pattern the protocol just removed.
  6. No CI signal: grep -r 'spec.types' packages/core/src/types/{enums,errors}.ts packages/server/src/server/mcp.ts returns nothing — these files have no compile-time link to the spec snapshot, so neither tsc nor spec.types.test.ts flags them.

Impact

After this sync the SDK publicly exports, documents, demonstrates in two example apps, and special-cases at runtime a protocol mechanism that the spec has removed. New consumers following docs/server.md and elicitationUrlExample.ts will build servers that emit non-spec error responses; spec-compliant clients will see an unrecognised -32042 error instead of an InputRequiredResult they know how to fulfil.

How to fix

This is non-mechanical, public-API companion work that must accompany the sync (or its companion PR):

  • Decide deprecate-vs-remove for UrlElicitationRequiredError and ProtocolErrorCode.UrlElicitationRequired. Either remove them outright (breaking → add a migration.md entry and a major changeset) or mark them @deprecated with JSDoc pointing at the InputRequiredResult replacement and schedule removal.
  • Strip the mcp.ts:211-213 rethrow special-case (and the ProtocolError.fromError() branch at errors.ts:23-28).
  • Rewrite or remove examples/{client,server}/src/elicitationUrlExample.ts to use the InputRequiredResult / inputResponses flow (this dovetails with the redesign already requested in comment #3206453743), and update the four README/docs links that point at them.
  • Delete test/integration/test/server/mcp.test.ts:1892-1937 (or rewrite it for the new flow).

Comment thread packages/core/src/types/spec.types.ts
Comment on lines +348 to +351
export type InputRequest = CreateMessageRequest | ListRootsRequest | ElicitRequest;

/** @internal */
export const URL_ELICITATION_REQUIRED = -32042;
export type InputResponse = CreateMessageResult | ListRootsResult | ElicitResult;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream design gap to batch with the other schema.ts feedback: InputResponse = CreateMessageResult | ListRootsResult | ElicitResult admits only success payloads, and the InputResponseRequestParams.inputResponses comment says every inputRequests key "must appear here". In the pre-sync model these were full JSON-RPC requests so a client could return a JSONRPCErrorResponse for user-denied sampling / LLM provider error / no roots configured; that error channel is gone with no replacement (ElicitResult has action: 'decline'|'cancel', but CreateMessageResult and ListRootsResult have no refusal field). The SDK redesign called for in the earlier comment will have no spec-defined way to propagate per-request failures and would have to invent an out-of-spec workaround that breaks once upstream adds a real error variant — suggest upstream add an InputResponseError arm (mirroring the JSON-RPC {code, message, data} shape) or relax the must-appear rule.

Extended reasoning...

What the bug is

InputResponse (spec.types.ts:351) is defined as CreateMessageResult | ListRootsResult | ElicitResult — a union of three success payloads only. InputResponses (line 376-378) is { [key: string]: InputResponse }, and the normative-sounding comment on InputResponseRequestParams.inputResponses (lines 410-413) says: "For each key in the response's inputRequests field, the same key must appear here with the associated response." So per the spec text, the client must supply a value for every requested key, and that value must be one of the three success result shapes.

In the pre-sync model these three exchanges were ordinary server→client JSON-RPC requests (CreateMessageRequest extends JSONRPCRequest, etc.), so a client that could not or would not fulfil one returned a JSONRPCErrorResponse carrying { code: number; message: string; data?: unknown }. By stripping extends JSONRPCRequest / extends Result and embedding the exchange inside the InputRequests/InputResponses maps, the spec discarded that error channel without adding a replacement.

Why the existing types don't cover it

  • ElicitResult happens to carry action: 'accept' | 'decline' | 'cancel', so elicitation can encode refusal in-band.
  • CreateMessageResult (line ~2335) is SamplingMessage & { model: string; stopReason?: ... } — required model/role/content, no refusal/error field, no index signature now that extends Result is dropped.
  • ListRootsResult (line ~2826) is bare { roots: Root[] } — same story.

The asymmetry (only ElicitResult has a decline arm) suggests this is an oversight rather than an intentional "refusal-via-abandonment" design — if abandoning the retry were the intended refusal signal, ElicitResult would not need action: 'decline' either.

Step-by-step proof

  1. Server returns CallToolResultResponse with result: InputRequiredResult { inputRequests: { 's1': <CreateMessageRequest>, 'e1': <ElicitRequest> } }.
  2. Client presents the elicitation; user accepts → { action: 'accept', content: {...} }.
  3. Client attempts the sampling call; the LLM provider returns HTTP 429 / content-policy refusal / the user denies the sampling-consent prompt.
  4. Client must now construct inputResponses for the retry. Per lines 410-413, both 's1' and 'e1' must appear. 'e1' is fine. For 's1' the only spec-permitted shapes are CreateMessageResult | ListRootsResult | ElicitResult — none of which can express "this request failed with code X / message Y".
  5. The client's only options are: (a) omit 's1' — textually non-compliant with the must-appear rule; (b) abandon the whole retry / call tasks/cancel — loses the successful elicitation and gives the server no error code/message to act on; (c) stuff a fake CreateMessageResult or an off-spec { error: {...} } object into 's1' — out of spec.

Why this matters for the SDK companion work

Today a client-side setRequestHandler(CreateMessageRequestSchema, …) can throw / reject and the SDK serialises a JSONRPCErrorResponse; the server's await ctx.sample() rejects with a ProtocolError carrying the code and message, and the tool handler can catch it and fall back. The redesign called for in comment #1 must preserve some equivalent of those semantics, but there is no spec-defined wire shape to carry them. Whatever workaround the SDK picks (drop the key, cancel the whole flow, invent an envelope) becomes public API that breaks once upstream adds a real error variant.

This is distinct from comment #1 (about the SDK still issuing these as wire requests), comment #4 (about tasks/input_response lacking taskId), and comment #6 (about the resultType discriminant) — none of those address the missing error arm in the InputResponse payload union itself.

Addressing "all-or-nothing is the intended design"

It is plausible the spec intends atomic fulfilment (client either satisfies every input or abandons). But (a) that loses the error code/message — the server cannot distinguish rate-limit vs. content-policy vs. user-denied, which is a real expressiveness regression vs. the JSON-RPC model; (b) it is contradicted by ElicitResult.action: 'decline'|'cancel' existing at all; and (c) even under that reading, the SDK still has to pick a public error-propagation contract for ctx.sample() rejection in the new flow, and it is better to do so against a spec-defined error variant than to guess.

How to fix

Raise upstream alongside the resultType? / taskId / discriminant fixes: either add an error arm, e.g.

export interface InputResponseError {
    code: number;
    message: string;
    data?: unknown;
}
export type InputResponse = CreateMessageResult | ListRootsResult | ElicitResult | InputResponseError;

(mirroring the removed JSON-RPC Error shape), or relax the "must appear" wording on inputResponses and define omission as refusal. Then re-run pnpm run fetch:spec-types. Don't encode InputResponsesSchema in schemas.ts until this is settled. Filed as a nit because it doesn't independently break CI and abandon-the-flow is a viable (if lossy) fallback — same tier as comments #5/#6.

@github-actions github-actions Bot force-pushed the update-spec-types branch from 879139a to 81ef4d8 Compare May 12, 2026 05:13
Comment thread packages/core/src/types/spec.types.ts
Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch from 81ef4d8 to 29aa626 Compare May 13, 2026 05:17
Comment on lines +1223 to 1226
export interface SubscriptionsListenRequest extends JSONRPCRequest {
method: 'subscriptions/listen';
params: SubscriptionsListenRequestParams;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 🟡 Upstream spec gap to batch with the other schema.ts feedback: SubscriptionsListenRequest extends JSONRPCRequest (so it carries an id and per JSON-RPC 2.0 must eventually receive exactly one response object), but unlike every other *Request extends JSONRPCRequest in this file it has no SubscriptionsListenResult / SubscriptionsListenResultResponse, and ServerResult includes none. The spec instead has the server send SubscriptionsAcknowledgedNotification "as the first message on the stream" — a notification (no id), not a response — so the wire contract for completing/closing the subscriptions/listen request is undefined, and when the SDK adds SubscriptionsListenRequestSchema it will have no spec-defined result schema to pair with Protocol.request() (the pending-request map would leak the id if the server never responds). Suggest upstream either add SubscriptionsListenResultResponse { result: EmptyResult } (sent on stream close) or document that this request is intentionally never JSON-RPC-responded so the SDK can special-case its id bookkeeping.

Extended reasoning...

What the bug is

SubscriptionsListenRequest (spec.types.ts:1223) is declared as:

export interface SubscriptionsListenRequest extends JSONRPCRequest {
    method: 'subscriptions/listen';
    params: SubscriptionsListenRequestParams;
}

Because it extends JSONRPCRequest, it carries jsonrpc: '2.0' and id: RequestId. Per JSON-RPC 2.0 §4.2, a request object that includes an id MUST eventually receive exactly one response object (either a result or an error) carrying that same id. But the spec defines no SubscriptionsListenResult or SubscriptionsListenResultResponse, and ServerResult (line 3296+) has no member for it. The only server reaction the spec defines is SubscriptionsAcknowledgedNotification — "sent by the server as the first message on a subscriptions/listen stream" — which extends JSONRPCNotification and therefore has no id and cannot satisfy the JSON-RPC response requirement.

Why this is uniquely inconsistent

Grepping the file shows 11 concrete interfaces that extends JSONRPCRequest (DiscoverRequest, PaginatedRequest and its derivatives, ReadResourceRequest, SubscriptionsListenRequest, GetPromptRequest, CallToolRequest, GetTaskRequest, GetTaskPayloadRequest, TaskInputResponseRequest, CancelTaskRequest, CompleteRequest) and 15 *ResultResponse extends JSONRPCResultResponse wrappers. Every JSONRPCRequest subtype has a paired *ResultResponse — except SubscriptionsListenRequest. The deleted predecessors it replaces (SubscribeRequest / UnsubscribeRequest) both had explicit { result: EmptyResult } wrappers (SubscribeResultResponse / UnsubscribeResultResponse), so this is a regression in spec completeness, not an established convention for "streaming" requests. ServerResult does include EmptyResult, so a server could respond with that on stream close, but the spec does not say so and there is no SubscriptionsListenResultResponse documenting it.

Step-by-step proof

  1. Client sends { jsonrpc: '2.0', id: 7, method: 'subscriptions/listen', params: { notifications: {...} } } (this is a JSON-RPC request because SubscriptionsListenRequest extends JSONRPCRequest, line 1223).
  2. Server replies with { jsonrpc: '2.0', method: 'notifications/subscriptions/acknowledged', params: { notifications: {...} } } (line 1255 — extends JSONRPCNotification, no id).
  3. Per JSON-RPC 2.0, message (2) is a notification, not a response to id: 7. The client's pending-request entry for id: 7 is still outstanding.
  4. The spec defines no message that ever carries id: 7 back. There is no SubscriptionsListenResultResponse; ServerResult has no dedicated arm; the JSDoc on SubscriptionsListenRequest does not say "the server never responds" or "the server responds with EmptyResult on stream close".
  5. Three behaviours are therefore equally spec-compliant and mutually incompatible: (a) server sends { id: 7, result: {} } immediately and then streams notifications; (b) server sends { id: 7, result: {} } only when the stream closes; (c) server never responds and the client must special-case the id. The wire contract is undefined.

Concrete SDK impact

The SDK's Protocol.request() API takes a request and a result schema, stores the id in a pending-request map, and resolves the returned promise when a matching response arrives. When the companion work (already requested in comment #3223937253) adds SubscriptionsListenRequestSchema, there is no spec-defined result schema to pass as the second argument. If the SDK uses EmptyResultSchema and a server follows interpretation (c), the promise never resolves and the pending-request map leaks id: 7 for the lifetime of the connection. If the SDK special-cases this method to not await a response and a server follows interpretation (a), the SDK will receive an unsolicited { id: 7, result: {} } it has no handler for. Either way, encoding SubscriptionsListenRequestSchema before this is settled bakes a guess into the public surface that breaks once upstream picks one.

Why this is distinct from existing PR comments

Comment #3223937253 lists SubscriptionsListenRequest/SubscriptionsListenRequestParams among the "new types needing SDK schemas" but does not note that there is no response type to pair them with — it assumes mechanical schema work, which is precisely what this gap blocks. Comment #3223937258 covers the SDK lifecycle redesign (subscribeResource()/unsubscribeResource()subscriptions/listen) but does not address the spec's own JSON-RPC response-contract gap. This is the same class of upstream-schema.ts design feedback as #3214351591 (taskId missing), #3214351594 (discriminant not narrowed), and #3216586357 (InputResponse error arm) — concrete enough to block correct SDK implementation, but doesn't independently break CI (the drift guard checks for types that exist, not types that should exist), hence nit.

How to fix

Raise upstream alongside the other schema.ts feedback. Two options:

  • Add a response wrapper: export interface SubscriptionsListenResultResponse extends JSONRPCResultResponse { result: EmptyResult; } and document that the server sends it when the stream closes (or immediately after the ack notification, depending on intended semantics). This matches the deleted SubscribeResultResponse/UnsubscribeResultResponse precedent.
  • Document the no-response contract: state explicitly in the SubscriptionsListenRequest JSDoc that the server MUST NOT send a JSON-RPC response for this request and that clients MUST NOT track its id in their pending-request map (or, more cleanly, change it to extend JSONRPCNotification so it carries no id at all — though that loses the ability to error-respond).

Then re-run pnpm run fetch:spec-types. Don't add SubscriptionsListenRequestSchema to schemas.ts until this is settled.

Comment on lines 144 to 146
export interface RequestParams {
_meta?: RequestMetaObject;
_meta: RequestMetaObject;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream spec self-inconsistency to batch with the other schema.ts feedback: RequestParams._meta is now required with three required client-identity keys (io.modelcontextprotocol/{protocolVersion,clientInfo,clientCapabilities}), but RequestParams is still referenced from contexts where that doesn't fit — DiscoverRequest.params? and PaginatedRequest.params? are still optional (so a client can type-validly omit the "Required" handshake metadata entirely, and discovery is circular: you must commit to a protocolVersion to ask which versions are supported); the server→client ListTasksRequest inherits PaginatedRequestParams → RequestParams, forcing a server sending tasks/list with a cursor to populate the client's clientInfo/clientCapabilities; and the server-authored ListRootsRequest (now only an InputRequest payload) kept params?: RequestParams while its siblings CreateMessageRequest/ElicitRequest had their RequestParams inheritance stripped. Suggest upstream make the three keys optional (or split RequestMetaObject by direction), make params non-optional on client wire requests, exempt server/discover, and drop the RequestParams reference from ListRootsRequest.

Extended reasoning...

What the issue is

This sync changes RequestParams (line 145) from _meta?: RequestMetaObject to _meta: RequestMetaObject and adds three required keys to RequestMetaObject (lines 82/89/97): 'io.modelcontextprotocol/protocolVersion', 'io.modelcontextprotocol/clientInfo', and 'io.modelcontextprotocol/clientCapabilities', each with JSDoc explicitly saying "Required." The intent — moving the handshake from a one-time initialize to per-request _meta — is clear, but RequestParams is still used in three places where mandatory client-identity metadata is either omittable, semantically wrong, or circular. This is the spec being internally inconsistent, distinct from comment #3223937258 which only notes that the SDK's RequestParamsSchema doesn't match the new required _meta.

Surface 1 — params? still optional on client wire requests

DiscoverRequest.params?: RequestParams (line 568) and PaginatedRequest.params?: PaginatedRequestParams (line 1014, inherited by ListResourcesRequest / ListResourceTemplatesRequest / ListPromptsRequest / ListToolsRequest / ListTasksRequest) declare params as optional. So { jsonrpc: '2.0', id: 1, method: 'tools/list' } is type-valid yet carries no _meta and therefore none of the "Required" handshake metadata — the spec contradicts itself. Pre-sync this was consistent because _meta was optional; the upstream commit tightened _meta without tightening params.

The DiscoverRequest case is additionally circular. Per its JSDoc, server/discover exists so the client can learn supportedVersions for use in subsequent requests, and per the JSDoc on protocolVersion (line 80) the server MUST return UnsupportedProtocolVersionError if the value is not supported. But if the client supplies params, it must include _meta['io.modelcontextprotocol/protocolVersion'] — i.e., commit to a version before learning which versions are supported. Either DiscoverRequest should not use RequestParams, or protocolVersion should be optional/exempt for discovery; the params? escape hatch is at best implicit and contradicts the unconditional "Required." prose.

Surface 2 — server→client wire request inherits client-direction keys

ServerRequest (line 3280) = GetTaskRequest | GetTaskPayloadRequest | ListTasksRequest | CancelTaskRequest. Three of these use inline params: { taskId: string } and escape, but ListTasksRequest (line 2155) extends PaginatedRequestparams?: PaginatedRequestParams (line 1004) extends RequestParams_meta: RequestMetaObject with required clientInfo/clientCapabilities. The JSDoc on those keys is unambiguously client→server ("Identifies the client software making the request", "The client's capabilities for this specific request", "Servers MUST NOT infer capabilities from prior requests"). So per the type, a server sending tasks/list with a pagination cursor must fabricate the client's identity and capabilities — semantically nonsensical. Concrete SDK consequence: when the companion work adds per-request _meta injection to Protocol.request(), the server-side outbound path has no sensible value to put here.

Surface 3 — server-authored embedded ListRootsRequest payload

ListRootsRequest (line 2820) dropped extends JSONRPCRequest (it is now only an InputRequest payload embedded in server-emitted InputRequiredResult.inputRequests, per InputRequest = CreateMessageRequest | ListRootsRequest | ElicitRequest at line 438), but unlike its two siblings it kept params?: RequestParams (line 2822). The siblings were cleaned: CreateMessageRequestParams (line 2257) and ElicitRequestFormParams/ElicitRequestURLParams (lines 2880/2913) all dropped extends TaskAugmentedRequestParams, so they no longer reference RequestParams/_meta at all. ListRootsRequest was missed — likely because it had no dedicated *Params wrapper to edit. params? is optional so a server can omit it, but a server wanting to attach e.g. _meta.progressToken would be type-forced to also fabricate clientInfo/clientCapabilities/protocolVersion for a server-authored embedded payload.

Step-by-step proof

  1. RequestMetaObject (lines 74-97) declares 'io.modelcontextprotocol/protocolVersion': string, '…/clientInfo': Implementation, '…/clientCapabilities': ClientCapabilities — none with ?.
  2. RequestParams (line 145) declares _meta: RequestMetaObject — no ?.
  3. PaginatedRequest (line 1014) declares params?: PaginatedRequestParamswith ?. PaginatedRequestParams extends RequestParams (line 1004).
  4. ListToolsRequest extends PaginatedRequest → a client may send { jsonrpc:'2.0', id:1, method:'tools/list' } with no params → no _meta → no protocolVersion/clientInfo/clientCapabilities. Type-valid, but the JSDoc on each key says "Required."
  5. ListTasksRequest extends PaginatedRequest and is a member of ServerRequest (line 3280). A server paginating tasks/list constructs params: { cursor: '…', _meta: { 'io.modelcontextprotocol/clientInfo': ???, 'io.modelcontextprotocol/clientCapabilities': ???, … } } — there is no value a server can sensibly put for the client's identity.
  6. ListRootsRequest (line 2822) keeps params?: RequestParams, while CreateMessageRequest.params: CreateMessageRequestParams and ElicitRequest.params: ElicitRequestParams no longer extend RequestParamsListRootsRequest is the odd one out among the three InputRequest members.

Impact

None of these independently break CI beyond what comment #3223937258 already documents (the SDK↔spec RequestParams assignability failure). They are upstream design gaps in the same tier as comments #3214351591 (taskId missing), #3214351594 (discriminant not narrowed), #3216586352 (tasks.requests orphaned), and #3216586357 (InputResponse no error arm) — they don't add new red CI, but they identify shapes the SDK should not encode as-is. In particular, the server-side Protocol.request() _meta-injection redesign called for in #3223937258 cannot follow the same logic as the client side while RequestMetaObject is client-direction-only.

How to fix

Raise upstream alongside the other schema.ts feedback. Plausible fixes (any one resolves all three surfaces, or they can be combined):

  • Make the three io.modelcontextprotocol/* keys optional on RequestMetaObject (or split into ClientRequestMetaObject / ServerRequestMetaObject), and have client→server wire request types make params non-optional so the handshake metadata is actually carried.
  • Have DiscoverRequest use a params type that does not extend RequestParams (or document an explicit exemption from the protocolVersion rejection rule for server/discover).
  • Have server→client request params (concretely ListTasksRequest via PaginatedRequest) not extend RequestParams, or use a server-direction _meta shape.
  • Change ListRootsRequest.params? to a bare { _meta?: MetaObject } or drop params entirely, matching CreateMessageRequest/ElicitRequest.

Then re-run pnpm run fetch:spec-types.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partially superseded by the latest re-pull (c47bd846), which deletes the entire tasks subsystem.

Surface 2 is now moot: ListTasksRequest and ServerRequest no longer exist (the spec defines no server→client requests at all), so there is no longer a server→client wire request inheriting the client-direction _meta keys via PaginatedRequestParams → RequestParams.

Surfaces 1 and 3 remain fully applicable:

  • RequestParams._meta is still required (line 128) with the three required io.modelcontextprotocol/* keys, while DiscoverRequest.params? (line 549) and PaginatedRequest.params? (line 932) are still optional — a client can still type-validly omit the "Required" handshake metadata, and the server/discover circularity (must commit to a protocolVersion to ask which versions are supported) is unchanged.
  • ListRootsRequest (line 2452) still keeps params?: RequestParams while its InputRequest siblings CreateMessageRequest/ElicitRequest have had their RequestParams inheritance stripped — still the odd one out among server-authored embedded payloads.

The remaining upstream feedback to batch: make the three keys optional (or split RequestMetaObject by direction), make params non-optional on client wire requests / exempt server/discover, and drop the RequestParams reference from ListRootsRequest.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated against the latest re-pull (bbcfc6) — the prior follow-up is now partially stale.

params? optionality (Surface 1, sub-issue) — now resolved upstream: DiscoverRequest.params (line 558) and PaginatedRequest.params (line 941) are now declared required (no ?), so a client can no longer type-validly omit the handshake _meta on those wire requests. This was one of the suggested fixes ("make params non-optional on client wire requests").

Discover circularity (Surface 1, sub-issue) — still applicable, arguably tightened: with DiscoverRequest.params: RequestParams now required, the client must populate _meta['io.modelcontextprotocol/protocolVersion'] to call server/discover at all — i.e. it must commit to a version before learning which versions are supported. The escape hatch is that the server responds with UnsupportedProtocolVersionError.data.supported (now a structured array), so a client can recover by trying a guess and reading the 400 body. Whether that should require an explicit exemption for server/discover remains an upstream design question.

ListRootsRequest (Surface 3) — still applicable: ListRootsRequest (line 2459) still keeps params?: RequestParams while its InputRequest siblings CreateMessageRequest/ElicitRequest had their RequestParams inheritance stripped — still the odd one out among server-authored embedded payloads.

Surface 2 — moot (unchanged from prior follow-up; ListTasksRequest/ServerRequest are gone).

Remaining upstream feedback to batch: exempt server/discover from the protocolVersion requirement (or document the try-and-recover-via-data.supported pattern as the intended bootstrap), and drop the RequestParams reference from ListRootsRequest.

@github-actions github-actions Bot force-pushed the update-spec-types branch from 29aa626 to 07e2103 Compare May 14, 2026 05:17
Comment on lines 1213 to 1226
/**
* A successful response from the server for a {@link SubscribeRequest | resources/subscribe} request.
* Sent from the client to open a long-lived channel for receiving notifications
* outside the context of a specific request. Replaces the previous HTTP GET
* endpoint and ensures consistent behavior between HTTP and STDIO.
*
* @example Subscribe result response
* {@includeCode ./examples/SubscribeResultResponse/subscribe-result-response.json}
* @example Listen for tools and resource list changes
* {@includeCode ./examples/SubscriptionsListenRequest/listen-for-list-changes.json}
*
* @category `resources/subscribe`
* @category `subscriptions/listen`
*/
export interface SubscribeResultResponse extends JSONRPCResultResponse {
result: EmptyResult;
export interface SubscriptionsListenRequest extends JSONRPCRequest {
method: 'subscriptions/listen';
params: SubscriptionsListenRequestParams;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 🟡 The companion redesign also has transport-layer work in packages/{server,client}/src/**/streamableHttp.ts that none of the existing comments mention and that nothing in CI surfaces (those files don't import spec.types.ts — same silent class as the -32042 finding). (1) This JSDoc says subscriptions/listen "Replaces the previous HTTP GET endpoint" — the server transport still implements that endpoint (handleGetRequest / _standaloneSseStreamId='_GET_stream', streamableHttp.ts:234/358/404/433/937/964) and the client transport still opens a bare GET stream for unsolicited notifications (_startOrAuthSse, streamableHttp.ts:233/251/647) instead of issuing subscriptions/listen. (2) The new RequestMetaObject JSDoc (lines 77-80) and the UnsupportedProtocolVersionError/MissingRequiredClientCapabilityError JSDoc add three HTTP MUSTs — _meta protocolVersion MUST match the MCP-Protocol-Version header else 400, and both error envelopes MUST be HTTP 400 — but validateProtocolVersion() (streamableHttp.ts:889) checks only the header (never cross-checks body _meta), and Protocol-layer JSON-RPC errors flow through send() into a hardcoded HTTP 200 (lines 817/1022/1024) with no error-code→HTTP-status hook. The redesign needs to: route subscriptions/listen to the long-lived SSE stream (and decide GET back-compat vs 405); have the client transport send subscriptions/listen instead of opening GET; add header↔_meta cross-validation; and add a Protocol→transport hook so these two error envelopes surface as HTTP 400.

Extended reasoning...

What this finding covers

Two transport-layer normative changes in this sync land in JSDoc prose only and affect packages/server/src/server/streamableHttp.ts and packages/client/src/client/streamableHttp.ts. Neither file imports spec.types.ts, so — like the -32042 / UrlElicitationRequiredError finding (#3216586348) — there is zero CI signal: tsc, spec.types.test.ts, and the specTypeSchema allowlist guard all stay green for these files. None of the 13 existing PR comments mention streamableHttp.ts, the GET handler, or HTTP-status-code mapping; comments #3223937253/#3223937258 cover the schema/lifecycle/subscribeResource() side of subscriptions/listen, and #3231781722 covers its missing JSON-RPC result type, but the transport plumbing is a separate code path.

(1) GET standalone-SSE endpoint replaced by subscriptions/listen

The SubscriptionsListenRequest JSDoc (this line) explicitly says it "Replaces the previous HTTP GET endpoint and ensures consistent behavior between HTTP and STDIO." The Streamable HTTP transport implements that GET endpoint as core functionality:

  • Server (packages/server/src/server/streamableHttp.ts): case 'GET'handleGetRequest() at lines 358-359/404; the standalone notification stream is keyed by _standaloneSseStreamId = '_GET_stream' (line 234) with 409-conflict handling (line 433), close/cleanup (449/469), and the unsolicited-message send path / event-store replay routed through it (lines 937/964/967).
  • Client (packages/client/src/client/streamableHttp.ts): _startOrAuthSse() issues method: 'GET' (lines 233/251) to open the unsolicited-notification stream, kicked off after notifications/initialized (line 647) and on resume (lines 535/756), with reconnect at 347.

After this sync the spec no longer defines a GET endpoint for the standalone notification stream; a spec-compliant server is not obligated to accept GET. The client transport already tolerates a 405 on GET (lines 285-288), so it would not crash against such a server — but it would silently degrade to never receiving any unsolicited server notifications, because nothing in the client transport sends subscriptions/listen. Conversely, the server transport has no path that routes an incoming subscriptions/listen JSON-RPC request to the long-lived SSE stream — the only way to open that stream is GET.

(2) New HTTP-400 MUSTs with no transport hook

This sync adds three HTTP-transport-specific MUST clauses in JSDoc:

  • RequestMetaObject['io.modelcontextprotocol/protocolVersion'] (lines 77-80): "For the HTTP transport, this value MUST match the MCP-Protocol-Version header; otherwise the server MUST return a 400 Bad Request."
  • UnsupportedProtocolVersionError (line ~383): "For HTTP, the response status code MUST be 400 Bad Request."
  • MissingRequiredClientCapabilityError (line ~413): "For HTTP, the response status code MUST be 400 Bad Request."

The server transport's validateProtocolVersion() (streamableHttp.ts:889-898) reads the MCP-Protocol-Version header on every request and 400s if it's not in _supportedProtocolVersions, but it never cross-checks the header against the body params._meta['io.modelcontextprotocol/protocolVersion'] (which the SDK doesn't populate yet — that's the per-request _meta injection work in #3223937258). And Protocol-layer JSON-RPC errors generated by handlers flow back through the transport's send() into an already-opened HTTP 200 SSE/JSON body (lines 817/1022/1024) — there is no hook by which Protocol can tell the transport "this particular JSONRPCErrorResponse should be delivered as HTTP 400 instead of inside a 200." So once the redesign starts emitting UnsupportedProtocolVersionError (INVALID_PARAMS + data.supported/requested) or MissingRequiredClientCapabilityError (-32003), they will go out as HTTP 200, violating the new MUSTs.

Step-by-step proof

GET → subscriptions/listen:

  1. Spec post-sync: SubscriptionsListenRequest JSDoc says it "Replaces the previous HTTP GET endpoint"; the GET endpoint is no longer part of the transport spec.
  2. SDK client connects, completes handshake, and at streamableHttp.ts:647 calls _startOrAuthSse({}), which issues fetch(url, { method: 'GET', headers: { Accept: 'text/event-stream', … } }) (line 251).
  3. A spec-compliant server with no GET handler returns 405. Client hits line 287 and silently returns — no error, no notification stream, no subscriptions/listen sent. The user's ToolListChangedNotification/ResourceUpdatedNotification handlers never fire.
  4. Conversely, an SDK server receiving a POST { method: 'subscriptions/listen', … } would dispatch it through handlePostRequestProtocol._onrequest like any RPC; nothing wires it to _standaloneSseStreamId, so unsolicited send() calls (line 937/967) still look up '_GET_stream' and find nothing.

HTTP-400 MUSTs:

  1. After the redesign, client sends POST with header MCP-Protocol-Version: 2026-03-01 and body params._meta['io.modelcontextprotocol/protocolVersion'] = '2025-11-07'.
  2. validateProtocolVersion() (line 889) reads only req.headers.get('mcp-protocol-version'), sees '2026-03-01'_supportedProtocolVersions, returns undefined. The header↔body mismatch is never checked → no 400, contrary to lines 77-80.
  3. Separately, a tool handler determines the request needs elicitation but _meta.clientCapabilities.elicitation is absent, and (per the redesign) emits a MissingRequiredClientCapabilityError (code: -32003). Protocol serialises it and calls transport.send(errorResponse, { relatedRequestId }).
  4. send() finds the pending stream for that request and either writes an SSE event into the already-200 stream or calls stream.resolveJson(Response.json(responses[0], { status: 200, … })) (lines 1022/1024). The -32003 error reaches the client inside an HTTP 200 body — violating the "MUST be 400" clause.

Why existing code doesn't prevent it

streamableHttp.ts (both packages) does not import spec.types.ts, so the drift guard / spec.types.test.ts cannot see this. The new requirements are JSDoc prose, not types, so even the bidirectional-assignability checks would not catch them. And the existing comments' remediation lists are scoped to schemas.ts/types.ts/client.ts/server.ts — a reviewer following only those could replace subscribeResource() with a subscriptions/listen API and add the two error-envelope schemas without ever touching the transport's GET handler or its hardcoded-200 send path.

Impact

This is forward-looking scoping for the companion redesign rather than an independent blocker (the SDK doesn't yet emit -32003 or populate _meta.protocolVersion, and keeping GET as a back-compat shim is a viable transitional state). But it identifies two non-obvious design decisions the redesign must make at the transport layer — (a) how subscriptions/listen is wired to the long-lived SSE stream and what happens to handleGetRequest, and (b) a new Protocol→transport hook to map specific JSON-RPC error envelopes to non-200 HTTP status — that someone doing pure schemas.ts/server.ts work would plausibly miss.

How to fix

In the companion redesign:

  • Server transport: route method: 'subscriptions/listen' to the long-lived SSE stream (taking over the role of _standaloneSseStreamId/event-store replay); decide whether handleGetRequest stays as a back-compat shim or returns 405. Extend validateProtocolVersion() (or add a sibling) to compare the MCP-Protocol-Version header against body params._meta['io.modelcontextprotocol/protocolVersion'] and 400 on mismatch. Add an error-code→HTTP-status hook so send() (or the pre-stream path) can emit HTTP 400 when the outgoing JSONRPCErrorResponse is an UnsupportedProtocolVersionError (INVALID_PARAMS + data.supported/requested) or MissingRequiredClientCapabilityError (-32003).
  • Client transport: replace _startOrAuthSse's bare GET with a POST subscriptions/listen carrying a SubscriptionFilter, and treat the resulting SSE stream (and SubscriptionsAcknowledgedNotification) as the unsolicited-notification channel; keep a GET fallback only if back-compat with pre-spec servers is desired.

Comment on lines +1179 to +1197
export interface SubscriptionFilter {
/**
* If true, receive {@link ToolListChangedNotification | notifications/tools/list_changed}.
*/
toolsListChanged?: boolean;
/**
* If true, receive {@link PromptListChangedNotification | notifications/prompts/list_changed}.
*/
promptsListChanged?: boolean;
/**
* If true, receive {@link ResourceListChangedNotification | notifications/resources/list_changed}.
*/
resourcesListChanged?: boolean;
/**
* Subscribe to {@link ResourceUpdatedNotification | notifications/resources/updated} for these resource URIs.
* Replaces the former `resources/subscribe` RPC.
*/
resourceSubscriptions?: string[];
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream spec gap to batch with the other schema.ts feedback: ElicitationCompleteNotification (line 3243, "informing it of a completion of a out-of-band elicitation request") survives in ServerNotification (line 3291), but after this sync there is no spec-defined channel to deliver it. ElicitRequest is now only an InputRequest payload inside InputRequiredResult (so the originating request's stream is closed when the result arrives), and the standalone GET stream is replaced by subscriptions/listen — whose SubscriptionFilter is an explicit opt-in allowlist with only four fields (toolsListChanged/promptsListChanged/resourcesListChanged/resourceSubscriptions) and JSDoc saying the server "MUST NOT send notification types the client has not explicitly requested here." So per the spec's own MUST NOT, a server cannot push elicitation-complete on the only out-of-band channel; a client doing a URL-mode elicitation can only poll by blindly retrying. (TaskStatusNotification, also in ServerNotification and absent from SubscriptionFilter, arguably has the same gap.) Same tier as comments #9/#12/#13 — suggest upstream either add elicitationComplete?: boolean (and taskStatus?: boolean) to SubscriptionFilter, or remove ElicitationCompleteNotification from ServerNotification if poll-via-retry is the intended model.

Extended reasoning...

What the bug is

ElicitationCompleteNotification (spec.types.ts:3243, method notifications/elicitation/complete, JSDoc: "informing it of a completion of a out-of-band elicitation request") survives this diff and remains a member of ServerNotification (line 3291). But after the stateless overhaul there is no spec-defined channel on which a server can actually deliver it.

The pre-sync flow was: a server emitted URLElicitationRequiredError (-32042) or sent an ElicitRequest JSON-RPC; the client opened the URL in a browser; the server detected completion out-of-band and pushed ElicitationCompleteNotification on the standalone HTTP GET/SSE stream so the client knew when to retry.

Post-sync, both halves of that delivery path are gone:

  • (a) ElicitRequest no longer extends JSONRPCRequest — it is only an InputRequest payload embedded inside InputRequiredResult (line 438). The InputRequiredResult is the terminal result of the originating tools/call/prompts/get/resources/read/tasks/result request, so that request's response stream is closed once the result is delivered. There is no still-open per-request stream to carry a later notification.
  • (b) The standalone HTTP GET stream is replaced by subscriptions/listen (line 1223; its JSDoc at 1214-1216 says it "Replaces the previous HTTP GET endpoint"). That stream's SubscriptionFilter (lines 1179-1197) is a closed, explicit opt-in allowlist with exactly four fields — toolsListChanged, promptsListChanged, resourcesListChanged, resourceSubscriptions — and the JSDoc at lines 1174-1175 (and again at 1206-1208) is normative: "Each notification type is opt-in; the server MUST NOT send notification types the client has not explicitly requested here." There is no field for elicitation-complete.

So per the spec's own MUST NOT, ElicitationCompleteNotification is undeliverable on the only out-of-request channel, and there is no in-request channel left. The notification type is in ServerNotification but unreachable.

Step-by-step proof

  1. Client sends tools/call. Server returns CallToolResultResponse { result: InputRequiredResult { inputRequests: { 'e1': { method: 'elicitation/create', params: { mode: 'url', url: 'https://…', elicitationId: 'abc' } } } } }. The tools/call request is complete; its response stream closes.
  2. Client opens https://… in a browser. The user completes the OAuth/consent flow there. The server learns this out-of-band (callback, webhook, etc.).
  3. The server now wants to send { method: 'notifications/elicitation/complete', params: { elicitationId: 'abc' } } so the client knows to retry the tools/call with inputResponses.
  4. Per-request stream: gone — the originating tools/call already returned in step 1.
  5. subscriptions/listen stream: the client could only have requested { toolsListChanged?, promptsListChanged?, resourcesListChanged?, resourceSubscriptions? } — there is no elicitationComplete field in SubscriptionFilter. Per lines 1174-1175 the server "MUST NOT send notification types the client has not explicitly requested", so sending notifications/elicitation/complete on this stream violates the spec's own normative text.
  6. There is no third channel. The client's only option is to poll: blindly retry tools/call (with requestState) on a timer until the server stops returning input_required.

Cross-checking the other ServerNotification members

This isn't a general "SubscriptionFilter is incomplete for everything" complaint — most ServerNotification members do have a defined channel:

Member Delivery channel
CancelledNotification / ProgressNotification / LoggingMessageNotification per-request stream (request-scoped)
SubscriptionsAcknowledgedNotification first message on the subscriptions/listen stream itself
ResourceListChangedNotification / ResourceUpdatedNotification / ToolListChangedNotification / PromptListChangedNotification subscriptions/listen, gated by the four SubscriptionFilter fields
ElicitationCompleteNotification none — by definition out-of-band, no SubscriptionFilter field
TaskStatusNotification arguably none — also absent from SubscriptionFilter; tasks at least have tasks/get polling as a documented fallback, whereas URL elicitation has none

ElicitationCompleteNotification is the clear odd-one-out (and TaskStatusNotification strengthens the case that the closed allowlist is incomplete rather than that elicitation-complete was intentionally dropped).

Why this is distinct from existing PR comments

None of comments #1-#13 mention ElicitationCompleteNotification. Comment #7 (#3216586348) covers the -32042/UrlElicitationRequiredError SDK-side removal (the error path), not this notification's reachability. Comments #11/#12 cover subscriptions/listen (the missing result wrapper and the new types needing schemas) but not the gap in SubscriptionFilter's allowlist. This is the same tier as #9 (InputResponse no error arm), #12 (SubscriptionsListenRequest no result), and #13 (RequestParams._meta direction mismatch): an upstream schema.ts self-inconsistency that doesn't independently break CI but identifies a shape the SDK should not encode as-is.

Impact

Doesn't independently break CI — ElicitationCompleteNotification itself is unchanged by the diff, so no assignability/coverage check trips on it specifically. But when the companion work adds SubscriptionFilterSchema to schemas.ts (per comment #10), encoding only the four fields bakes in a filter that can never permit elicitation-complete, and when it rewrites the URL-elicitation flow (per comments #1/#7) it will have no spec-defined replacement for the "server pushes when browser flow completes" signal. The SDK would have to either (a) ship a poll-on-timer client API, or (b) invent an off-spec extra SubscriptionFilter field — both break once upstream picks the real answer.

How to fix

Raise upstream alongside the other schema.ts feedback. Two options:

  • Extend SubscriptionFilter: add elicitationComplete?: boolean (or elicitationIds?: string[] for per-elicitation granularity), and probably taskStatus?: boolean for symmetry. This keeps ElicitationCompleteNotification deliverable on the subscriptions/listen stream and matches the four existing list-changed fields.
  • Remove ElicitationCompleteNotification from ServerNotification if poll-via-retry is the intended model — i.e., the client just re-issues the original request with requestState until resultType !== 'input_required'. In that case the notification type is dead and should be deleted alongside the other elicitation cleanup.

Then re-run pnpm run fetch:spec-types. Don't add SubscriptionFilterSchema to schemas.ts until this is settled. Filed as a nit because it doesn't add new red CI and poll-via-retry is a viable (if ugly) fallback — same tier as comments #5/#6/#8/#9/#12/#13.

* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
*
* @category `initialize`
* @category `server/discover`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 🟡 Upstream spec self-inconsistency to batch with the other schema.ts feedback (server-side analogue of comment #3216586352): the same diff that deletes SubscribeRequest/UnsubscribeRequest and makes all list-changed notifications opt-in via SubscriptionFilter leaves ServerCapabilities.resources.subscribe (line 776) and {prompts,resources,tools}.listChanged (755/780/795) untouched, and adds no capability flag for subscriptions/listen itself. The flags are not dead — each maps 1:1 to a SubscriptionFilter field — but their documented semantics have silently shifted from "server will push unsolicited *_list_changed" / "server accepts the resources/subscribe RPC" to "server will honor the corresponding SubscriptionFilter opt-in on a subscriptions/listen stream", and the JSDoc/@example references still describe the old model. Suggest upstream either re-document these four flags for the opt-in model or fold them into a structured subscriptions: { listen?, resourceSubscriptions?, …ListChanged? } capability so the SDK's subscriptions/listen client API (replacing the client.ts:599 gate) has an unambiguous flag to check.

Extended reasoning...

What the issue is

This sync replaces the per-resource resources/subscribe / resources/unsubscribe RPCs and unsolicited *_list_changed pushes with a single opt-in subscriptions/listen stream: the client sends a SubscriptionFilter naming which notification types it wants, and the server echoes back what it will honor in SubscriptionsAcknowledgedNotification.params.notifications (the JSDoc on SubscriptionFilter says the server "MUST NOT send notification types the client has not explicitly requested"). But ServerCapabilities — structurally untouched by this diff beyond the @category initialize → server/discover rename at line 721 — still declares:

  • resources.subscribe?: boolean (line 776) — "Whether this server supports subscribing to resource updates"
  • prompts.listChanged?: boolean / resources.listChanged?: boolean / tools.listChanged?: boolean (lines 755/780/795) — "Whether this server supports notifications for changes to the … list"

and adds no field advertising whether the server implements subscriptions/listen at all.

Addressing the "these flags map cleanly to SubscriptionFilter" objection

A reasonable counter-read is that these four flags are not orphaned: each corresponds 1:1 to a SubscriptionFilter field (resources.subscriberesourceSubscriptions, {prompts,resources,tools}.listChanged{prompts,resources,tools}ListChanged), the underlying notifications (ResourceUpdatedNotification, the three *ListChangedNotification types) all still exist in ServerNotification, and the JSDoc text on resources.subscribe ("subscribing to resource updates") is mechanism-agnostic. Under this reading, the static DiscoverResult.capabilities flags tell a client what to put in its SubscriptionFilter before opening a stream, and SubscriptionsAcknowledgedNotification confirms per-stream what was honored — two different purposes, not duplication. That counter-read is largely correct, and is why this is not the same as comment #3216586352's ClientCapabilities.tasks.requests case (where the advertised concept — task-augmented sampling/elicitation wire requests — was deleted entirely).

What that reading does not address is that the semantics of these flags changed without the spec saying so. Pre-sync, tools.listChanged: true meant "this server will send unsolicited notifications/tools/list_changed"; post-sync, per the SubscriptionFilter JSDoc, the server MUST NOT send that notification unless the client opts in on a subscriptions/listen stream — so the flag now means "this server will honor toolsListChanged: true in your filter." Pre-sync, resources.subscribe: true meant "this server accepts resources/subscribe requests" (and client.ts:599 gates on exactly that); post-sync, that RPC does not exist, so the flag must mean "this server will honor resourceSubscriptions: [...] in your filter." Neither shift is reflected in the JSDoc, and the @example {@includeCode ./examples/ServerCapabilities/resources-subscription-*.json} references (lines 763-770) still point at example files written for the old model. An implementer reading ServerCapabilities in isolation would reasonably conclude the server pushes list-changed notifications unprompted and accepts a resources/subscribe RPC — both now wrong.

Separately, there is no explicit capability for subscriptions/listen itself. Under the reinterpretation above, support is implied by any of the four sub-flags being present — but that is undocumented inference, and a server that implements subscriptions/listen for (say) LoggingMessageNotification only, with none of the four sub-flags, has no way to advertise the endpoint exists.

Step-by-step proof

  1. Diff deletes SubscribeRequest / UnsubscribeRequest / SubscribeResultResponse / UnsubscribeResultResponse; ClientRequest (line 3256) no longer contains either.
  2. Diff adds SubscriptionFilter (line 1176) with toolsListChanged? / promptsListChanged? / resourcesListChanged? / resourceSubscriptions?: string[] and JSDoc "the server MUST NOT send notification types the client has not explicitly requested here." SubscriptionFilter.resourceSubscriptions JSDoc (line 1194) explicitly says "Replaces the former resources/subscribe RPC."
  3. ServerCapabilities body (lines 723-833) is byte-identical to pre-sync apart from the @category tag. resources.subscribe (776), prompts.listChanged (755), resources.listChanged (780), tools.listChanged (795) all survive with pre-sync JSDoc. Grep for subscriptions under ServerCapabilities → no match.
  4. Pre-sync semantics of prompts.listChanged: true: server will send notifications/prompts/list_changed whenever its prompt set changes (no client opt-in required). Post-sync semantics per step 2: server MUST NOT send it unless the client included promptsListChanged: true in a subscriptions/listen filter. The JSDoc at line 753 still reads "Whether this server supports notifications for changes to the prompt list" — silent on the new opt-in requirement.
  5. SDK surface: packages/client/src/client/client.ts:599 does if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) throw …. After the redesign already requested in comment #3223937258 that branch is removed, and the new subscriptions/listen client API will need a capability gate — under the current spec it must either reuse resources.subscribe/*.listChanged under their reinterpreted meaning, or ship ungated.

Why this is distinct from existing PR comments

Comment #3216586352 covers the client-side mirror (ClientCapabilities.tasks.requests orphaned by InputRequiredResult). Comment #3223937258 covers the SDK lifecycle redesign, including replacing subscribeResource()/unsubscribeResource() — but that comment is about what the SDK must change, not about the upstream schema.ts leaving ServerCapabilities documenting the old subscription model. Comment #3231781722 covers SubscriptionsListenRequest lacking a JSON-RPC response wrapper. None of #1-#13 mention ServerCapabilities.resources.subscribe / *.listChanged or a missing subscriptions capability.

Impact

No independent CI breakage — all four fields are optional, the ServerCapabilities body is untouched, so spec.types.test.ts's bidirectional check for ServerCapabilities still passes. This is upstream documentation/modeling feedback in the same tier as #3214351593 (JSDoc), #3216586352 (tasks.requests), #3231781731 (RequestParams direction). Filed as nit.

How to fix

Raise upstream alongside the other schema.ts feedback. Two coherent options:

  • Re-document in place: keep the four flags, update their JSDoc to reference SubscriptionFilter (e.g., resources.subscribe → "Whether this server will honor resourceSubscriptions on a subscriptions/listen stream"; *.listChanged → "Whether this server will honor *ListChanged on a subscriptions/listen stream"), and refresh the @example JSON files. Optionally add a top-level subscriptions?: JSONObject to advertise the endpoint independently of which filter fields are honored.
  • Restructure: replace the four scattered flags with subscriptions?: { listen?: JSONObject; resourceSubscriptions?: boolean; toolsListChanged?: boolean; promptsListChanged?: boolean; resourcesListChanged?: boolean } so the capability shape mirrors SubscriptionFilter.

Then re-run pnpm run fetch:spec-types. Once re-pulled, ServerCapabilitiesSchema in schemas.ts and the client.ts capability gate for the new subscriptions/listen API can follow whichever shape upstream picks.

@github-actions github-actions Bot force-pushed the update-spec-types branch from 07e2103 to 0bcec2b Compare May 15, 2026 05:18
Comment on lines +566 to 569
export interface DiscoverRequest extends JSONRPCRequest {
method: 'server/discover';
params?: RequestParams;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Another silent transport-layer divergence (same class as #3216586348/#3239359153, distinct surface): the Streamable HTTP server transport's entire Mcp-Session-Id lifecycle is hard-keyed on isInitializeRequest() (packages/server/src/server/streamableHttp.ts:666) — sessionId minting (678), _initialized = true (679), and the public onsessioninitialized hook (683-684) only fire for method: 'initialize'; any other first request hits validateSession() and 400s "Server not initialized" in stateful mode (847-856). After this sync InitializeRequest is gone — a spec-compliant client sends server/discover or just tools/list-with-_meta and never initialize, so a stateful SDK HTTP server 400s every request and never establishes a session. Lines 720-722 also read the deleted initRequest.params.protocolVersion (version now lives in _meta['io.modelcontextprotocol/protocolVersion']). And grepping post-sync spec.types.ts for "session" returns zero matches — the stateless overhaul appears to have dropped Mcp-Session-Id semantics entirely, so the redesign must explicitly decide remove-sessions vs. mint-on-first-request vs. re-key-on-server/discover, and update the public isInitializeRequest guard (guards.ts:93, exports/public/index.ts:111) and sessionIdGenerator/onsessioninitialized/onsessionclosed transport options (streamableHttp.ts:80/89/101) accordingly.

Extended reasoning...

What this finding covers

The Streamable HTTP server transport's session-ID bootstrap is hard-wired to the deleted initialize method, and the post-sync spec appears to have dropped Mcp-Session-Id session semantics entirely. This is a third silent transport-layer divergence in packages/server/src/server/streamableHttp.ts that neither comment #3223937258 (Protocol-layer server.ts/client.ts initialize handling) nor comment #3239359153 (streamableHttp.ts GET→subscriptions/listen + HTTP-400 MUSTs) covers.

The code path

handlePostRequest in packages/server/src/server/streamableHttp.ts:

  • Line 666: const isInitializationRequest = messages.some(element => isInitializeRequest(element))isInitializeRequest (guards.ts:93) checks for method: 'initialize'.
  • Lines 667-685 (the if (isInitializationRequest) block): this.sessionId = this.sessionIdGenerator?.() (678), this._initialized = true (679), and await this._onsessioninitialized(this.sessionId) (683-684). This is the only place sessionId is minted and _initialized is flipped.
  • Lines 687-694 (the else path): every non-initialize POST goes through validateSession(req).
  • validateSession() (847-856): in stateful mode (sessionIdGenerator set), if (!this._initialized)return this.createJsonErrorResponse(400, -32_000, 'Bad Request: Server not initialized').
  • Lines 720-722: const initRequest = messages.find(m => isInitializeRequest(m)); const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : … — reads params.protocolVersion, a field of the deleted InitializeRequestParams. In the new model the protocol version lives in params._meta['io.modelcontextprotocol/protocolVersion'].

Why nothing in CI surfaces it

streamableHttp.ts imports isInitializeRequest from @modelcontextprotocol/core (guards.ts), not from spec.types.ts. InitializeRequestSchema still exists in schemas.ts, so guards.ts still typechecks; the transport never references spec.types.ts at all. Neither tsc --noEmit, spec.types.test.ts, nor the specTypeSchema allowlist guard sees this — same silent class as #3216586348 (-32042) and #3239359153 (GET endpoint).

Step-by-step proof

  1. User constructs the documented stateful server: new StreamableHTTPServerTransport({ sessionIdGenerator: () => crypto.randomUUID(), onsessioninitialized: id => sessions.set(id, …) }) (per the JSDoc example at streamableHttp.ts:195).
  2. A spec-compliant client built against the post-sync schema connects. Per this diff there is no initialize method; the client either sends { method: 'server/discover' } first or goes straight to { method: 'tools/list', params: { _meta: { 'io.modelcontextprotocol/protocolVersion': …, 'io.modelcontextprotocol/clientInfo': …, 'io.modelcontextprotocol/clientCapabilities': … } } }.
  3. handlePostRequest parses the body. isInitializeRequest({ method: 'server/discover', … })false (it checks for 'initialize'). isInitializationRequest = false.
  4. Control falls to line 687-691 → validateSession(req). sessionIdGenerator is set, this._initialized is still false (never flipped) → returns 400 "Bad Request: Server not initialized".
  5. The client retries; same result. No request ever succeeds, sessionId is never minted, onsessioninitialized never fires, the user's session map stays empty.
  6. Separately, even if a legacy client sent initialize, line 722 reads initRequest.params.protocolVersion — fine for legacy clients, but once the redesign re-keys the bootstrap on server/discover (whose params?: RequestParams has no protocolVersion field), this read returns undefined and the priming-event protocol-version logic silently picks the wrong branch.

The bigger design question

grep -i session packages/core/src/types/spec.types.ts post-sync → zero matches. The stateless overhaul has apparently dropped Mcp-Session-Id from the protocol entirely (consistent with "every request carries its own _meta handshake"). That means the SDK's public stateful-mode surface — sessionIdGenerator (line 80), onsessioninitialized (89), onsessionclosed (101), the Mcp-Session-Id header read at 859, the DELETE-ends-session path at 838, plus the four middleware READMEs and streamableHttp.examples.ts that demonstrate per-session transport maps keyed on isInitializeRequest — is now unanchored from the spec. The redesign must explicitly choose one of:

  • (a) Remove sessions from the transport (stateful mode goes away; sessionIdGenerator/onsessioninitialized/onsessionclosed deprecated → breaking change, migration.md entry).
  • (b) Mint on first request regardless of method (re-key the bootstrap on "first POST without Mcp-Session-Id header" instead of "is initialize").
  • (c) Re-key on server/discover (closest 1:1 swap, but server/discover is optional per its JSDoc, so clients that skip it would still 400).

Whichever is chosen, the public isInitializeRequest guard (re-exported at exports/public/index.ts:111, used verbatim in the four middleware READMEs and streamableHttp.examples.ts for per-session routing) needs deprecation or replacement, and lines 720-722 need to read _meta['io.modelcontextprotocol/protocolVersion'] instead of params.protocolVersion.

Why this is distinct from existing comments

  • #3223937258 (stateless overhaul) is scoped to the Protocol layer: client.connect() sending initialize, server.ts registering an initialize handler / assertInitialized() gating, and the schemas/guards cleanup. Its remediation list never mentions the transport's isInitializeRequest-gated session bootstrap, sessionIdGenerator, _initialized, onsessioninitialized, validateSession(), or the Mcp-Session-Id lifecycle.
  • #3239359153 is the only existing comment touching streamableHttp.ts, and it covers exactly two things: (1) GET→subscriptions/listen (handleGetRequest/_standaloneSseStreamId) and (2) the new HTTP-400 MUSTs (validateProtocolVersion() header↔body cross-check, error-code→status hook). It does not mention the session-ID bootstrap path, isInitializationRequest, or the params.protocolVersion read at 720-722.

A reviewer following only those two comments would rip out assertInitialized() in server.ts and rewire the GET handler — and still ship a stateful HTTP transport that 400s every request from a spec-compliant client.

How to fix

Add to the companion-redesign scope:

  • Decide (a)/(b)/(c) above for the Mcp-Session-Id lifecycle and update streamableHttp.ts:664-700 + validateSession() accordingly.
  • Replace the initRequest.params.protocolVersion read (720-722) with params._meta['io.modelcontextprotocol/protocolVersion'] (or the header, since the bootstrap branch will no longer be exempt from header validation).
  • Deprecate or repurpose isInitializeRequest (guards.ts:93, public re-export at exports/public/index.ts:111) and update packages/middleware/{node,hono,fastify,express}/README.md + streamableHttp.examples.ts which use it for per-session transport routing.
  • If sessions are removed, deprecate sessionIdGenerator/onsessioninitialized/onsessionclosed (breaking → changeset + migration.md).

Comment on lines +1174 to +1175
* Each notification type is **opt-in**; the server **MUST NOT** send
* notification types the client has not explicitly requested here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Nit (upstream): the JSDoc on ResourceListChangedNotification (line 1158), PromptListChangedNotification (1602), and ToolListChangedNotification (1741) still say "This may be issued by servers without any previous subscription from the client", which now directly contradicts the new SubscriptionFilter JSDoc here ("the server MUST NOT send notification types the client has not explicitly requested"). The same diff did update ResourceUpdatedNotification's JSDoc (line 1277) to the opt-in wording, so this looks like a partial migration that missed the three *ListChanged siblings — worth replacing the offending sentence on all three with wording mirroring the updated ResourceUpdatedNotification text and re-pulling. (Distinct from comment #3239359160, which covers the stale ServerCapabilities.{*.listChanged,resources.subscribe} JSDoc, and from #3239359156, which covers SubscriptionFilter's allowlist gaps.)

Extended reasoning...

What the issue is

Three notification-type JSDoc blocks — all untouched by this diff — still describe the pre-opt-in delivery model:

  • ResourceListChangedNotification (spec.types.ts:1158): "This may be issued by servers without any previous subscription from the client."
  • PromptListChangedNotification (spec.types.ts:1602): identical sentence.
  • ToolListChangedNotification (spec.types.ts:1741): identical sentence.

The new SubscriptionFilter JSDoc introduced by this same sync (lines 1174-1175, repeated at 1206-1208 on SubscriptionsListenRequestParams.notifications) is normative the opposite way: "Each notification type is opt-in; the server MUST NOT send notification types the client has not explicitly requested here." And SubscriptionFilter explicitly enumerates toolsListChanged / promptsListChanged / resourcesListChanged as the gates for exactly these three notifications. So the spec file now contains a direct internal contradiction: the type-level JSDoc says "may be issued without any previous subscription"; the channel-level JSDoc says "MUST NOT be sent unless explicitly subscribed."

Why this is a partial-migration slip, not intentional

This is not a case of the upstream author leaving older prose alone wholesale. The same diff hunk did update the fourth sibling, ResourceUpdatedNotification (spec.types.ts:1277), from:

"This should only be sent if the client previously sent a resources/subscribe request."

to:

"This is only sent for resources the client opted in to via the resourceSubscriptions field of a subscriptions/listen request."

So the upstream author migrated one of four notification descriptions to the new opt-in model and missed the other three. A grep for "may be issued by servers without any previous subscription" finds exactly three surviving instances — the classic partial-migration signature.

Step-by-step proof

  1. After this sync, the only out-of-request channel for unsolicited server notifications is subscriptions/listen (line 1223; its JSDoc at 1214-1216 says it "Replaces the previous HTTP GET endpoint").
  2. SubscriptionsListenRequestParams.notifications: SubscriptionFilter (line 1209) is the opt-in selector; the JSDoc at 1174-1175 says the server "MUST NOT send notification types the client has not explicitly requested here."
  3. SubscriptionFilter.toolsListChanged (line 1182) gates notifications/tools/list_changed; .promptsListChanged (1186) gates notifications/prompts/list_changed; .resourcesListChanged (1190) gates notifications/resources/list_changed.
  4. Therefore, per the spec's own MUST NOT, none of these three notifications can be "issued by servers without any previous subscription from the client." The sentence at lines 1158/1602/1741 is now affirmatively wrong, not merely stale.
  5. An implementer hovering ToolListChangedNotification in their IDE sees only the type's own JSDoc — "may be issued without any previous subscription" — and would reasonably build a server that pushes it unprompted, violating the new MUST NOT.

Why this is distinct from the existing PR comments

  • Comment #3239359160 covers stale ServerCapabilities.{prompts,resources,tools}.listChanged / resources.subscribe JSDoc (lines 755/776/780/795) — different location, different fix (capability-flag semantics vs. notification-type delivery semantics).
  • Comment #3239359156 covers SubscriptionFilter's allowlist being incomplete for ElicitationCompleteNotification / TaskStatusNotification — about missing filter fields, not about contradictory prose on the three notifications that do have filter fields.
  • None of the 16 prior comments mention lines 1158/1602/1741 or the "may be issued … without any previous subscription" sentence.

Impact

Same tier as comments #3214351593 (JSDoc /* vs /**) and #3239359160 — pure upstream prose, no CI/type impact, spec.types.ts is not re-exported from this package. Filed as a nit to fold into the same upstream schema.ts batch already on the table.

How to fix

In upstream schema.ts, replace "This may be issued by servers without any previous subscription from the client." on all three with wording mirroring the already-updated ResourceUpdatedNotification JSDoc, e.g.:

  • ResourceListChangedNotification: "This is only sent if the client opted in via the resourcesListChanged field of a {@link SubscriptionsListenRequest | subscriptions/listen} request."
  • PromptListChangedNotification: "…via the promptsListChanged field…"
  • ToolListChangedNotification: "…via the toolsListChanged field…"

Then re-run pnpm run fetch:spec-types. No change is appropriate in this repo directly (the file header says DO NOT EDIT).

Comment thread packages/core/src/types/spec.types.ts Outdated
Comment thread packages/core/src/types/spec.types.ts Outdated
@github-actions github-actions Bot force-pushed the update-spec-types branch from 0bcec2b to 57ccae0 Compare May 16, 2026 05:05
Comment thread packages/core/src/types/spec.types.ts
Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch 2 times, most recently from e9de0a8 to 786d94c Compare May 18, 2026 05:23
Comment on lines +99 to +105
* The desired log level for this request. Optional.
*
* If absent, the server MUST NOT send any {@link LoggingMessageNotification | notifications/message}
* notifications for this request. The client opts in to log messages by
* explicitly setting a level. Replaces the former `logging/setLevel` RPC.
*/
'io.modelcontextprotocol/logLevel'?: LoggingLevel;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Two new normative MUST-NOT clauses in this sync invert the unsolicited-notification default from opt-out to opt-in — _meta['io.modelcontextprotocol/logLevel'] for notifications/message, and SubscriptionFilter for the four list-changed/resource-updated notifications — and the SDK's server-side default-emit paths now actively violate both, silently (neither server.ts nor mcp.ts imports spec.types.ts, so no CI signal). isMessageIgnored() defaults to send when no level is set, and McpServer auto-fires send*ListChanged() on every registerTool/registerPrompt/registerResource/update gated only on isConnected(), never on a client-supplied filter. The companion redesign needs to invert both defaults (absent level/filter → suppress, not send) and add per-session SubscriptionFilter tracking — neither of which is captured by the existing porting checklists.

Extended reasoning...

What changed in the spec

Two separate JSDoc clauses in this sync flip the protocol's unsolicited-notification model from opt-out to opt-in with normative MUST NOT text:

  1. Logging (RequestMetaObject['io.modelcontextprotocol/logLevel'], lines ~99-105): "If absent, the server MUST NOT send any notifications/message notifications for this request. The client opts in to log messages by explicitly setting a level." This replaces the pre-sync LoggingMessageNotification JSDoc — "If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically." MAY-decide → MUST-NOT-without-opt-in.
  2. List-changed / ResourceUpdated (SubscriptionFilter JSDoc, lines ~1129-1135 and ~1163-1166): "Each notification type is opt-in; the server MUST NOT send notification types the client has not explicitly requested here." The four SubscriptionFilter fields gate exactly notifications/{tools,prompts,resources}/list_changed and notifications/resources/updated. Pre-sync the protocol's model was opt-out (the old *ListChangedNotification JSDoc says "may be issued by servers without any previous subscription from the client").

What the SDK does — both defaults are still opt-out

Logging (packages/server/src/server/server.ts):

  • server.ts:194private _loggingLevels = new Map<string | undefined, LoggingLevel>(), populated only by the logging/setLevel handler at server.ts:142-153. After this sync that RPC is deleted, so a spec-compliant client never populates the map.
  • server.ts:200-203isMessageIgnored() returns currentLevel ? <severity check> : false. With the map empty, currentLevel is undefined, so it returns false ("not ignored" = send) for every level on every session.
  • server.ts:646-650sendLoggingMessage() gates only on this._capabilities.logging && !isMessageIgnored(...). With isMessageIgnored() always false and the server advertising the logging capability, every call emits a notifications/message.
  • server.ts:162RequestHandlerExtra.log() (the per-request logging helper every tool/prompt/resource handler receives) wires straight through to sendLoggingMessage() with no _meta.logLevel check at all. mcp.ts:1024 (McpServer.sendLoggingMessage()) is the same path.

List-changed / ResourceUpdated (packages/server/src/server/mcp.ts + server.ts):

  • mcp.ts:605/621/652/685/747/830/836/996McpServer calls sendResourceListChanged()/sendToolListChanged()/sendPromptListChanged() unconditionally on every tool/prompt/resource register, update, enable, disable, and remove.
  • mcp.ts:1030-1052 — those wrappers gate only on isConnected(), nothing else.
  • server.ts:302-340assertNotificationCapability() checks only the server's own this._capabilities.{tools,resources,prompts} advertisement, never the client's per-stream SubscriptionFilter opt-in.
  • grep -rn 'SubscriptionFilter\|subscriptions/listen\|resourceSubscriptions' packages/server/src returns zero matches — there is no per-session filter tracking anywhere in the package.

Step-by-step proof

Logging:

  1. A spec-compliant client built against c47bd846 sends tools/call with _meta = { protocolVersion, clientInfo, clientCapabilities } (the three required keys) and no logLevel.
  2. The tool handler calls extra.log('info', 'starting work').
  3. server.ts:162sendLoggingMessage()isMessageIgnored('info', sessionId)_loggingLevels.get(sessionId) is undefined → returns false.
  4. The notification is emitted. The client receives an unsolicited notifications/message for a request where it never opted in — violating the new MUST NOT.

List-changed:

  1. A spec-compliant client connects, never sends subscriptions/listen, never sets toolsListChanged: true.
  2. Server code does mcpServer.registerTool('foo', { ... }, handler) — a routine post-connect registration.
  3. mcp.ts:836 unconditionally calls this.sendToolListChanged(); mcp.ts:1039-1041 sees isConnected() === true and forwards to server.sendToolListChanged().
  4. assertNotificationCapability('notifications/tools/list_changed') at server.ts:302+ passes because the server advertises capabilities.tools — it never consults a client filter.
  5. The transport emits notifications/tools/list_changed to a client that never requested it — violating the new MUST NOT. Same for prompts/resources/list_changed and resources/updated.

Why no CI signal & why the existing comments don't catch this

Neither server.ts nor mcp.ts imports spec.types.ts, so the drift guard never trips. This is the same silent-divergence class as #3216586348 (-32042 removal), #3246176899 (session bootstrap), and #3239359153 (GET endpoint) — distinct surface, same blind spot.

The existing comments cover adjacent surfaces but not these defaults: #3223937258 lists logging only as "Replace setLoggingLevel() with a per-request _meta logLevel setter" — a literal port (delete the setLevel handler, read _meta instead) could leave the : false default in isMessageIgnored() untouched and still spam every client. #3239359160 covers stale ServerCapabilities flag JSDoc, #3239359153 covers streamableHttp.ts GET routing, #3246176905 covers the upstream JSDoc contradiction in the *ListChangedNotification types — none mention McpServer's auto-fire-on-registration behavior or that assertNotificationCapability() gates on the wrong side of the connection.

How to fix (companion-redesign scope)

  • Logging: Invert isMessageIgnored()'s default — absent level → suppress. The level source must be the originating request's _meta['io.modelcontextprotocol/logLevel'] (threaded through RequestHandlerExtra.log()), not a per-session map. Delete _loggingLevels and the logging/setLevel handler. Decide whether the un-scoped server.sendLoggingMessage()/mcpServer.sendLoggingMessage() APIs survive at all — there is no spec-defined channel for unsolicited log notifications post-sync.
  • List-changed: Add per-session SubscriptionFilter tracking to Server (or the transport). Have mcp.ts:1030-1052 and server.ts:652-671 no-op when the active filter lacks the corresponding field, instead of gating only on isConnected(). Or, transitionally, drop the auto-fire-on-registration behavior and make sendXxxListChanged() an explicit user-called API gated on the discovered filter.

This is forward-looking scoping for the already-required companion redesign on an automated cron PR, not a defect this PR introduces — but it identifies two non-obvious default-direction flips that the existing 22-comment porting checklist would not catch.

@github-actions github-actions Bot force-pushed the update-spec-types branch from 786d94c to edb9e09 Compare May 19, 2026 05:20
Comment on lines 1794 to 1815

/**
* A JSON Schema object defining the expected parameters for the tool.
*
* Tool arguments are always JSON objects, so `type: "object"` is required at the root.
* Beyond that, any JSON Schema 2020-12 keyword may appear alongside `type` — including
* composition keywords (`oneOf`, `anyOf`, `allOf`, `not`), conditional keywords
* (`if`/`then`/`else`), reference keywords (`$ref`, `$defs`, `$anchor`), and any other
* standard validation or annotation keywords.
*
* Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided.
*/
inputSchema: {
$schema?: string;
type: 'object';
properties?: { [key: string]: JSONValue };
required?: string[];
};

/**
* Execution-related properties for this tool.
*/
execution?: ToolExecution;
inputSchema: { $schema?: string; type: 'object'; [key: string]: unknown };

/**
* An optional JSON Schema object defining the structure of the tool's output returned in
* the structuredContent field of a {@link CallToolResult}.
* the structuredContent field of a {@link CallToolResult}. This can be any valid JSON Schema 2020-12.
*
* Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided.
* Currently restricted to `type: "object"` at the root level.
*/
outputSchema?: {
$schema?: string;
type: 'object';
properties?: { [key: string]: JSONValue };
required?: string[];
};
outputSchema?: { $schema?: string; [key: string]: unknown };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Companion-work item: this sync changes Tool.outputSchema from { $schema?, type: 'object', properties?, required? } to { $schema?: string; [key: string]: unknown } — the type: 'object' root requirement is removed and the new JSDoc says "This can be any valid JSON Schema 2020-12." The SDK's ToolSchema in packages/core/src/types/schemas.ts:1326-1333 still hard-codes type: z.literal('object') on outputSchema (with the now-stale JSDoc "Must have type: 'object' at the root level per MCP spec"), so a spec-valid tool advertising e.g. outputSchema: { type: 'string' } or outputSchema: { oneOf: [...] } will be rejected by the SDK's Zod validator. The fix is to relax ToolSchema.outputSchema to accept arbitrary JSON Schema (e.g. z.object({ $schema: z.string().optional() }).catchall(z.unknown()).optional()); inputSchema should keep z.literal('object') since the spec still requires it there.

Extended reasoning...

What changed in the spec

This sync rewrites the Tool.inputSchema and Tool.outputSchema declarations at packages/core/src/types/spec.types.ts:1794-1815:

  • inputSchema goes from { $schema?, type: 'object', properties?, required? } to { $schema?: string; type: 'object'; [key: string]: unknown } — still requires type: 'object' at the root (the new JSDoc explicitly says "Tool arguments are always JSON objects, so type: \"object\" is required at the root"), but opens the rest to arbitrary JSON Schema 2020-12 keywords (composition, conditional, $ref/$defs, etc.).
  • outputSchema goes from { $schema?, type: 'object', properties?, required? } to { $schema?: string; [key: string]: unknown } — the type: 'object' requirement is removed entirely. The pre-sync JSDoc said "Currently restricted to type: \"object\" at the root level"; the post-sync JSDoc replaces it with "This can be any valid JSON Schema 2020-12." The companion change to CallToolResult.structuredContent (now unknown instead of { [key: string]: unknown }) confirms the intent: structured tool output is no longer required to be an object.

What the SDK still enforces

ToolSchema at packages/core/src/types/schemas.ts:1326-1333 still hard-codes the old restriction on outputSchema:

outputSchema: z
    .object({
        type: z.literal('object'),
        properties: z.record(z.string(), JSONValueSchema).optional(),
        required: z.array(z.string()).optional()
    })
    .catchall(z.unknown())
    .optional(),

with the JSDoc "Must have type: 'object' at the root level per MCP spec" — that comment is now factually wrong post-sync.

Why existing code does not prevent it

The .catchall(z.unknown()) only permits additional keys beyond the named shape — it does not relax type: z.literal('object'), which is a required key with a literal constraint. Any outputSchema whose root is not an object schema (e.g. { type: 'string' }, { type: 'array', items: ... }, { oneOf: [...] } with no type at all) fails ToolSchema.safeParse() even though it is now spec-valid.

The inputSchema half is not a defect: the spec still requires type: 'object' there, so z.literal('object') is correct, and .catchall(z.unknown()) already permits the new arbitrary-JSON-Schema keywords. The defect is specifically the outputSchema literal.

Step-by-step proof

  1. After this sync, Tool.outputSchema?: { $schema?: string; [key: string]: unknown } (spec.types.ts:1814). A tool definition like { name: 'count', inputSchema: { type: 'object' }, outputSchema: { type: 'integer' } } is a valid spec Tool.
  2. A spec-compliant server returns this tool in its tools/list result.
  3. An SDK client calls client.listTools(). Protocol.request() validates the response with ListToolsResultSchema, which contains tools: z.array(ToolSchema).
  4. ToolSchema.outputSchema requires type: z.literal('object'). The tool's outputSchema has type: 'integer'. Zod rejects: Invalid literal value, expected "object" at tools[0].outputSchema.type.
  5. The whole tools/list response is rejected and the SDK throws — the spec-valid tool is unusable.
  6. The same happens for tools with outputSchema: { oneOf: [...] } (no type key at all) or any non-object root.

Impact

This is the over-strict-Zod-rejecting-spec-valid-payloads class flagged in the repo's Recurring Catches (#1768/#1849/#1169). It is silent — schemas.ts doesn't import spec.types.ts, so neither tsc nor the drift guard's hardcoded type counts surface it directly (the bidirectional assignability check on Tool does fail, but that is buried under the dozens of other failures from this PR).

How to fix (companion work)

Relax ToolSchema.outputSchema to accept arbitrary JSON Schema, e.g.:

outputSchema: z
    .object({ $schema: z.string().optional() })
    .catchall(z.unknown())
    .optional(),

and update the JSDoc to drop the "Must have type: 'object'" line. Keep inputSchema.type: z.literal('object') as-is (still spec-required). Also update the CallToolResultSchema.structuredContent field (and ToolResultContent.structuredContent) from z.record(...)/z.object(...) to z.unknown() to match the spec change to structuredContent?: unknown. The output-schema-validation helper in mcp.ts that compiles outputSchema into an Ajv validator and asserts structuredContent is a record will also need to handle non-object schemas.

Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch from edb9e09 to 1896892 Compare May 20, 2026 05:21
Comment on lines 1627 to 1637
content: ContentBlock[];

/**
* An optional JSON object that represents the structured result of the tool call.
* An optional JSON value that represents the structured result of the tool call.
*
* This can be any JSON value (object, array, string, number, boolean, or null)
* that conforms to the tool's outputSchema if one is defined.
*/
structuredContent?: { [key: string]: unknown };
structuredContent?: unknown;

/**

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Companion-work item: this sync widens CallToolResult.structuredContent to unknown and Tool.outputSchema to any JSON Schema 2020-12 root, making false/0/''/null spec-valid structured results — but the SDK gates output validation on JS truthiness rather than presence: packages/server/src/server/mcp.ts:282 (if (!result.structuredContent) → throws InvalidParams), packages/client/src/client/client.ts:877 (if (!result.structuredContent && !result.isError) → throws InvalidRequest), and client.ts:885 (if (result.structuredContent) → silently skips schema validation). All three need to become === undefined / !== undefined presence checks; a literal port that only loosens the Zod schemas (per #3263885960/#3263885954) leaves these intact and re-introduces the rejection at the application layer.

Extended reasoning...

What the bug is

This sync widens CallToolResult.structuredContent (spec.types.ts:1635) from { [key: string]: unknown } to unknown and relaxes Tool.outputSchema (spec.types.ts:1814) to accept any JSON Schema 2020-12 root, with new JSDoc explicitly stating structuredContent "can be any JSON value (object, array, string, number, boolean, or null) that conforms to the tool's outputSchema if one is defined." That means a tool advertising outputSchema: { type: 'boolean' } legitimately returns structuredContent: false, and likewise 0, '', or null for number/string/null schemas.

Where the SDK conflates absent with falsy

Both the server and client output-validation paths gate on JS truthiness of structuredContent, not on !== undefined:

  1. Serverpackages/server/src/server/mcp.ts:282 in validateToolOutput():

    if (!result.structuredContent) {
        throw new ProtocolError(ProtocolErrorCode.InvalidParams,
            'Output validation error: Tool ... has an output schema but no structured content was provided');
    }

    A handler returning { content: [...], structuredContent: false } triggers this throw and the tool call fails — even though false is a valid result for { type: 'boolean' }.

  2. Clientpackages/client/src/client/client.ts:877 in callTool():

    if (!result.structuredContent && !result.isError) {
        throw new ProtocolError(ProtocolErrorCode.InvalidRequest,
            'Tool ... has an output schema but did not return structured content');
    }

    Same pattern — a spec-compliant server returning structuredContent: 0 causes the SDK client to throw.

  3. Clientpackages/client/src/client/client.ts:885:

    if (result.structuredContent) { /* validate against outputSchema */ }

    The converse — with a falsy structuredContent and isError: true, the validation block is silently skipped instead of running, so an error result with structuredContent: false bypasses output-schema validation entirely.

Why these checks were correct pre-sync but become wrong post-sync

Pre-sync, structuredContent was typed { [key: string]: unknown } and outputSchema required type: 'object' at the root — the only possible payloads were objects (always truthy) or absent. Truthiness was a perfectly adequate proxy for presence. This sync is what makes falsy primitives spec-valid, so the proxy stops being equivalent and starts rejecting valid wire traffic.

Why a literal port of the schema fix won't catch this

Comments #3263885960 (loosen CallToolResultSchema.structuredContent from z.record to z.unknown() in schemas.ts:1381/1566) and #3263885954 (relax ToolSchema.outputSchema away from z.literal('object')) cover the Zod-shape side. A reviewer who applies only those — loosen the schemas, leave the application-level guards alone — ships a server that throws on every falsy structured result and a client that rejects them, despite both wire types now permitting them. mcp.ts and client.ts don't import spec.types.ts, so neither tsc nor the drift guard surfaces this; the truthiness checks typecheck fine against unknown. There is no runtime test today covering a falsy structured result (it was wire-invalid pre-sync), so CI stays green.

Step-by-step proof (post companion-work that loosens the Zod schemas)

  1. Server registers a tool with outputSchema: { type: 'boolean' } whose handler returns { content: [], structuredContent: false }.
  2. tools/list advertises that schema — spec-valid post-sync.
  3. Client calls callTool({ name: 'isReady' }).
  4. Server-side: validateToolOutput() at mcp.ts:282 evaluates !false → true and throws InvalidParams: 'Tool isReady has an output schema but no structured content was provided'. The tool call fails before reaching schema validation.
  5. Even if the server were fixed: the client receives { content: [], structuredContent: false } and at client.ts:877 evaluates !false && !undefined → true, throwing InvalidRequest: 'Tool isReady has an output schema but did not return structured content'.
  6. Same sequence for structuredContent: 0 ({ type: 'number' }), '' ({ type: 'string' }), or null ({ type: 'null' }).

How to fix

Change all three sites to presence checks:

  • mcp.ts:282if (result.structuredContent === undefined)
  • client.ts:877if (result.structuredContent === undefined && !result.isError)
  • client.ts:885if (result.structuredContent !== undefined)

This preserves the "tool with an outputSchema must return structuredContent" invariant while permitting all falsy JSON values, exactly as the spec now demands. Add a runtime test exercising a falsy structured result (false/0/''/null) so this can't regress.

Comment on lines +91 to +97
* The client's capabilities for this specific request. Required.
*
* Capabilities are declared per-request rather than once at initialization;
* an empty object means the client supports no optional capabilities.
* Servers MUST NOT infer capabilities from prior requests.
*/
'io.modelcontextprotocol/clientCapabilities': ClientCapabilities;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Companion-work item: this sync adds a normative MUST-NOT clause to RequestMetaObject['io.modelcontextprotocol/clientCapabilities'] — "Capabilities are declared per-request rather than once at initialization … Servers MUST NOT infer capabilities from prior requests" — that the SDK's session-scoped Server._clientCapabilities cache (server.ts:99, written once at server.ts:424 in the now-deleted initialize handler) and the public parameter-less getClientCapabilities()/getClientVersion() getters (server.ts:444-453) cannot satisfy, silently (server.ts does not import spec.types.ts). The companion redesign needs to expose per-request clientCapabilities/clientInfo/protocolVersion on RequestHandlerExtra, deprecate the session-scoped getters (breaking change → migration.md), and rewire the 8 capability-assertion call sites (server.ts:272/279/286/343/414/493/560/568/616) to read from the current request's _meta — none of which is captured by #3223937258's "per-request _meta injection" remediation list, which never names the public getters or the per-request scoping discipline.

Extended reasoning...

What changed in the spec

This sync adds three new required io.modelcontextprotocol/* keys to RequestMetaObject. The JSDoc on 'io.modelcontextprotocol/clientCapabilities' (spec.types.ts:91-97) carries a normative clause:

The client's capabilities for this specific request. Required. Capabilities are declared per-request rather than once at initialization; an empty object means the client supports no optional capabilities. Servers MUST NOT infer capabilities from prior requests.

This is a stronger constraint than "replace the initialize handshake with per-request _meta injection" — it mandates a per-request scoping discipline on the server side: the capability set for any given assertion must come from that request's _meta, never from a cache populated by an earlier request.

What the SDK ships — a session-scoped cache and session-scoped public getters

The SDK's Server class models client capabilities and client identity as a single session-wide value:

  • Server._clientCapabilities / Server._clientVersion (server.ts:99-100) are private session-scoped fields, written once at server.ts:424-425 inside _oninitialize() — the handler for the (now-deleted) initialize request.
  • Server.getClientCapabilities() (server.ts:444-446) and Server.getClientVersion() (server.ts:451-453) are public, parameter-less getters whose JSDoc reads "After initialization has completed, this will be populated with the client's reported capabilities." Both return the session-scoped value with no per-request scope. They are consumed by packages/server/src/experimental/tasks/server.ts:121/217 and by user code following docs/server.md.
  • Eight capability-assertion call sites read this._clientCapabilities directly: server.ts:272/279/286/343/414/493/560/568/616. None reads from the current request's _meta.

server.ts does not import spec.types.ts, so neither tsc nor spec.types.test.ts flags this — it is the same silent-divergence class as #3216586348 (-32042 removal), #3246176899 (session bootstrap), and #3256562384 (logging/listChanged opt-in defaults).

Why this is not subsumed by #3223937258 (addressing the refutation)

#3223937258's remediation list says: "Replace the connect()-time initialize/initialized handshake with per-request _meta injection (protocolVersion/clientInfo/clientCapabilities) and an optional server/discover call; rip out assertInitialized() gating on the server." That directs the handshake replacement but never names getClientCapabilities()/getClientVersion(), never observes they are session-scoped public APIs, and never calls out that the per-request scoping is normative (a MUST NOT, not just a transport detail). Two concrete things follow that the existing checklist does not capture:

  1. The public getters need deprecation/migration regardless of how the rewrite goes. Even after removing the initialize handler, getClientCapabilities() and getClientVersion() remain on the public surface with JSDoc that references a deleted handshake. They are parameter-less, so there is no request scope to expose. Either they are removed (breaking → migration.md + major changeset) or they are deprecated with a pointer at the new per-request API. Neither action is in any of the existing 27 comments.

  2. A literal port of #3223937258 still violates the MUST NOT. A literal-minded reading of "per-request _meta injection" is: read each request's _meta.clientCapabilities and write it into this._clientCapabilities. That is still a session-scoped cache that gets refreshed, and (a) under concurrency, two in-flight requests with different clientCapabilities cross-contaminate — request 2's assertion can pass on request 1's capabilities — and (b) for a request whose _meta omits clientCapabilities (e.g. a back-compat path), the stale value from the prior request is read, which is precisely "inferring from prior requests."

Step-by-step proof

  1. Spec-compliant client sends tools/call (request A) with _meta['io.modelcontextprotocol/clientCapabilities'] = { sampling: {} }. The tool handler awaits ctx.sample().
  2. Concurrently (Streamable HTTP, multiple in-flight requests), the same client sends another tools/call (request B) with _meta['io.modelcontextprotocol/clientCapabilities'] = {} — it has revoked its sampling consent for this request.
  3. After a literal port that re-stamps this._clientCapabilities from each request's _meta: request A writes { sampling: {} }, then request B writes {}. Request A's ctx.sample() then runs the assertion at server.ts:272, reads this._clientCapabilities?.samplingundefined → throws McpError even though request A did declare sampling. Or, if interleaved the other way, request B's handler calls server.getClientCapabilities() and sees { sampling: {} } from request A — the server has "inferred capabilities from a prior request," violating the MUST NOT.
  4. There is no parameter on getClientCapabilities() to disambiguate which request's capabilities the caller wants, so the public API cannot express the spec's per-request semantics.

Impact

After this sync, Server._clientCapabilities is never populated (the initialize handler has no spec counterpart), so the 8 assertion sites all see undefined and reject every server-initiated sampling/elicitation/roots call — that immediate failure mode is what #3223937258 documents. Once the redesign starts injecting per-request _meta, the deeper problem is that the data model has the wrong shape: a session-scoped cache cannot satisfy a per-request normative MUST NOT, and the public getters cannot expose a per-request value without a new parameter or a new home (e.g., RequestHandlerExtra).

How to fix (companion-redesign scope)

  • Expose per-request clientCapabilities / clientInfo / protocolVersion on RequestHandlerExtra so handlers and capability assertions read the current request's _meta, not a cache.
  • Deprecate the session-scoped Server.getClientCapabilities() / Server.getClientVersion() (breaking change → migration.md entry + changeset). Update packages/server/src/experimental/tasks/server.ts:121/217 and docs/server.md to read from the per-request source.
  • Rewire the 8 capability-assertion call sites (server.ts:272/279/286/343/414/493/560/568/616) to take the per-request capabilities as a parameter rather than reading this._clientCapabilities.
  • Delete _clientCapabilities / _clientVersion once nothing reads them.

This is forward-looking scoping for the already-required companion redesign on an automated cron PR, not a defect this PR introduces — but it identifies a concrete public-API breaking change and a normative scoping constraint that the existing 27-comment porting checklist does not name.

@github-actions github-actions Bot force-pushed the update-spec-types branch from 1896892 to b255ba4 Compare May 21, 2026 05:24
Comment thread packages/core/src/types/spec.types.ts
Comment on lines +370 to +399
export const UNSUPPORTED_PROTOCOL_VERSION = -32004;

/**
* Returned when the request's protocol version is unknown to the server or
* unsupported (e.g., a known experimental or draft version the server has
* chosen not to implement). For HTTP, the response status code MUST be
* `400 Bad Request`.
*
* @internal
* @example Unsupported protocol version
* {@includeCode ./examples/UnsupportedProtocolVersionError/unsupported-version.json}
*
* @category Errors
*/
export interface UnsupportedProtocolVersionError extends Omit<JSONRPCErrorResponse, 'error'> {
error: Error & {
code: typeof UNSUPPORTED_PROTOCOL_VERSION;
data: {
/**
* Protocol versions the server supports. The client should choose a
* mutually supported version from this list and retry.
*/
supported: string[];
/**
* The protocol version that was requested by the client.
*/
requested: string;
};
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Companion-work item supplementing #3223937253: this revision gives UnsupportedProtocolVersionError its own dedicated constant UNSUPPORTED_PROTOCOL_VERSION = -32004 (replacing the earlier draft's code: typeof INVALID_PARAMS framing that #3223937253 was written against), but packages/core/src/types/enums.ts ProtocolErrorCode has no member for -32004 (alongside the already-flagged missing -32003 and the now-deleted -32042 UrlElicitationRequired member that should be removed). Separately, the Streamable HTTP server transport's existing protocol-version-rejection path at packages/server/src/server/streamableHttp.ts:889-898 (validateProtocolVersion()) already returns HTTP 400 for an unsupported MCP-Protocol-Version header but emits generic code -32_000 with the supported/requested versions only flattened into the message string — wire-divergent from the spec's required -32004 + structured data: { supported: string[]; requested: string } payload, so a spec-compliant client cannot programmatically pick a mutually-supported version and retry.

Extended reasoning...

What changed in the spec

This revision (c47bd846) replaces the earlier draft's UnsupportedProtocolVersionError shape (which used code: typeof INVALID_PARAMS per the existing comment #3223937253) with a dedicated error-code constant:

export const UNSUPPORTED_PROTOCOL_VERSION = -32004;

export interface UnsupportedProtocolVersionError extends Omit<JSONRPCErrorResponse, 'error'> {
    error: Error & {
        code: typeof UNSUPPORTED_PROTOCOL_VERSION;
        data: {
            supported: string[];
            requested: string;
        };
    };
}

This means the existing comment #3223937253 — which only flags MISSING_REQUIRED_CLIENT_CAPABILITY = -32003 as needing a ProtocolErrorCode member and explicitly characterizes UnsupportedProtocolVersionError as carrying code: INVALID_PARAMS — is now stale on this point and omits a second required constant.

Gap 1: no ProtocolErrorCode member for -32004

packages/core/src/types/enums.ts currently defines:

export enum ProtocolErrorCode {
    ParseError = -32_700,
    InvalidRequest = -32_600,
    MethodNotFound = -32_601,
    InvalidParams = -32_602,
    InternalError = -32_603,
    ResourceNotFound = -32_002,
    UrlElicitationRequired = -32_042   // ← spec constant deleted in this same diff
}

There is no member for -32003 (already flagged) and no member for -32004 (not yet flagged). The companion redesign that wires UnsupportedProtocolVersionError into the Protocol→transport HTTP-400 hook (per #3239359153) will have no named SDK constant to use, and ProtocolError.fromError() / catch-clause mappings have nothing to switch on.

Gap 2: validateProtocolVersion() is wire-divergent from the new error shape

packages/server/src/server/streamableHttp.ts:889-898 already rejects an unsupported MCP-Protocol-Version header with HTTP 400 — but the JSON body it emits is:

return this.createJsonErrorResponse(400, -32_000, error);
//                                       ^^^^^^^ generic, not -32_004
// where `error` is a string interpolating the supported/requested versions

The spec's UnsupportedProtocolVersionError envelope requires code: -32_004 and a structured data: { supported: string[]; requested: string } payload so the client can programmatically pick a mutually-supported version and retry. The transport's current response carries the version list only inside the human-readable message string, so a spec-compliant client looking for error.data.supported / error.data.requested gets undefined and would have to regex-parse the message.

createJsonErrorResponse() (streamableHttp.ts:284-288) does already accept an optional data? parameter, but it is typed string — so the fix is a small type-widening (allow an object payload), not a new parameter.

Why nothing in CI surfaces it

Neither enums.ts nor streamableHttp.ts imports spec.types.ts, so neither tsc nor the spec.types.test.ts drift guard sees this — same silent class as #3216586348, #3239359153, and #3246176899.

Step-by-step proof

  1. Spec post-sync: UNSUPPORTED_PROTOCOL_VERSION = -32004 (spec.types.ts:~370), UnsupportedProtocolVersionError.error.code: typeof UNSUPPORTED_PROTOCOL_VERSION with data: { supported, requested } (spec.types.ts:~383-399).
  2. grep -n '32004\|32_004' packages/core/src/types/enums.ts → no match. The SDK has no name for the new error code.
  3. A client sends a POST with header MCP-Protocol-Version: 1999-01-01. validateProtocolVersion() at streamableHttp.ts:889 returns createJsonErrorResponse(400, -32_000, 'Bad Request: Unsupported protocol version (supported versions: ...)').
  4. The wire shows { error: { code: -32000, message: 'Bad Request: Unsupported protocol version (supported versions: 2025-11-07, 2025-06-18, ...)' } } — no data field at all. A spec-compliant client checking error.code === -32004 doesn't recognise it; checking error.data.supported gets undefined.

How to fix (companion work)

  • enums.ts: add ProtocolErrorCode.UnsupportedProtocolVersion = -32_004 (alongside the already-flagged MissingRequiredClientCapability = -32_003); remove the stale UrlElicitationRequired = -32_042 member whose spec constant was deleted in this same diff (see #3216586348).
  • streamableHttp.ts: change validateProtocolVersion() to emit ProtocolErrorCode.UnsupportedProtocolVersion (-32_004) and pass a structured data: { supported: this._supportedProtocolVersions, requested: protocolVersion } payload through createJsonErrorResponse(). Widen createJsonErrorResponse()'s data parameter from string to string | object (or unknown).

This is a small supplemental delta on the already-tracked #3223937253 enum-member item and the #3239359153 transport-layer hook, and the entire PR is held pending companion redesign — but the existing comments' INVALID_PARAMS framing is now factually incorrect against the current diff and -32004 is a second distinct constant requiring its own enum member, so worth recording so the companion work doesn't miss it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Status update — partially addressed on main:

Gap 1 (enum members) — done. packages/core/src/types/enums.ts now defines ProtocolErrorCode.MissingRequiredClientCapability = -32_003 and ProtocolErrorCode.UnsupportedProtocolVersion = -32_004 (both documented as protocol revision 2026-07-28). The third sub-item — removing UrlElicitationRequired = -32_042 — was evidently decided otherwise: the member is retained, consistent with the deliberately kept 2025-11-25 wire surface (spec.types.2025-11-25.ts snapshot), so no further action is suggested there.

Gap 2 (Streamable HTTP transport) — still open. validateProtocolVersion() in packages/server/src/server/streamableHttp.ts (now ~lines 906-914) still rejects an unsupported MCP-Protocol-Version header with createJsonErrorResponse(400, -32_000, message): generic code -32_000 instead of ProtocolErrorCode.UnsupportedProtocolVersion (-32_004), and the supported/requested versions remain flattened into the message string with no structured data: { supported: string[]; requested: string } payload. createJsonErrorResponse()'s data option is still typed string (line 288), so the type-widening to allow an object payload is also still pending. Nothing under packages/server/src emits -32_004 yet, so a spec-compliant client checking error.code === -32004 / error.data.supported still cannot programmatically pick a mutually-supported version and retry.

The remaining work is the small transport-layer delta: emit -32_004 from validateProtocolVersion(), pass { supported: this._supportedProtocolVersions, requested: protocolVersion } as structured data, and widen createJsonErrorResponse()'s data parameter to accept an object.

@github-actions github-actions Bot force-pushed the update-spec-types branch from b255ba4 to da9d82e Compare May 22, 2026 05:20
Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch 4 times, most recently from bd3e3e3 to 2780cbe Compare May 28, 2026 05:25
Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch from 2780cbe to 31aef57 Compare May 29, 2026 05:26
Comment thread packages/core/src/types/spec.types.ts
@github-actions github-actions Bot force-pushed the update-spec-types branch 3 times, most recently from 5af1602 to 56abf78 Compare June 1, 2026 05:37

/** @internal */
export const LATEST_PROTOCOL_VERSION = 'DRAFT-2026-v1';
export const LATEST_PROTOCOL_VERSION = '2026-07-28';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Companion-work scoping item: this sync stamps the spec's LATEST_PROTOCOL_VERSION as the concrete release version '2026-07-28' (spec.types.ts:37), but the SDK's own version constants in packages/core/src/types/constants.ts (LATEST_PROTOCOL_VERSION = '2025-11-25', SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION) have no compile-time link to spec.types.ts and nothing in CI surfaces the gap — Protocol._supportedProtocolVersions (shared/protocol.ts:351) and the Streamable HTTP transport's validateProtocolVersion() (streamableHttp.ts:889-898) would 400 any client advertising '2026-07-28', and the data.supported list for the new -32004 UnsupportedProtocolVersionError would come from the same stale constant. The bump (plus the hard-coded assertion at packages/core/test/types.test.ts:24) belongs in the same companion PR that implements the new wire behavior — bumping it alone would falsely advertise support — but none of the existing porting checklists name constants.ts at all.

Extended reasoning...

What this finding covers

This sync changes the spec mirror's LATEST_PROTOCOL_VERSION from the placeholder 'DRAFT-2026-v1' to the concrete release version '2026-07-28' (spec.types.ts:37). The SDK's own version constants live in a separate, hand-maintained file — packages/core/src/types/constants.ts:1-3 — which still declares LATEST_PROTOCOL_VERSION = '2025-11-25', DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26', and SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']. '2026-07-28' appears nowhere in that list. These constants are public API (re-exported from exports/public/index.ts) and feed two runtime gates: Protocol._supportedProtocolVersions defaults to the list (packages/core/src/shared/protocol.ts:351), and the Streamable HTTP server transport's validateProtocolVersion() (packages/server/src/server/streamableHttp.ts:259, 889-898) rejects any request whose MCP-Protocol-Version header is not in the list with HTTP 400.

Why nothing in CI surfaces it

constants.ts has no compile-time link to spec.types.ts — the only test touching the constant is packages/core/test/types.test.ts:24, which hard-asserts LATEST_PROTOCOL_VERSION === '2025-11-25' against a literal; no test compares the SDK constant to SpecTypes.LATEST_PROTOCOL_VERSION. So unlike the schema/union breakage the drift guard catches, this divergence produces zero red CI — the same silent class as the -32042 removal (#3216586348), the session bootstrap (#3246176899), and the transport-layer items (#3239359153) already accepted on this PR.

Step-by-step proof (post-companion-redesign)

  1. The companion redesign lands the new wire behavior (per-request _meta, server/discover, InputRequiredResult, etc.) but the porter follows only the existing 33 comments — none of which name constants.ts, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, or types.test.ts:24.
  2. A spec-compliant client (correctly) sends MCP-Protocol-Version: 2026-07-28 and _meta['io.modelcontextprotocol/protocolVersion'] = '2026-07-28'.
  3. validateProtocolVersion() checks the header against this._supportedProtocolVersions (defaulted from SUPPORTED_PROTOCOL_VERSIONS), finds no '2026-07-28', and returns HTTP 400 — every request from a spec-compliant client is rejected even though the SDK now implements the new behavior.
  4. Per the new RequestMetaObject JSDoc, the server MUST answer an unknown version with the new -32004 UnsupportedProtocolVersionError listing data.supported — and that supported list would be built from this same stale constant, so the error response itself advertises the wrong set of versions.
  5. Conversely, an SDK client can never negotiate or advertise '2026-07-28' because its own LATEST_PROTOCOL_VERSION is '2025-11-25'.

Addressing the refutation

One reviewer pass argued this reduces to "remember to bump the version constant when implementing the new protocol version," since (a) omitting '2026-07-28' today is correct (the SDK doesn't implement it yet) and (b) any test of the new flow would fail without the bump. Point (a) is true and is exactly how this finding is framed: the bump must land with the companion behavioral redesign, not in this PR and not before — bumping alone would falsely advertise support. Point (b) is weaker than it sounds: the new spec error path is keyed on the server's supported-versions list, so an end-to-end test could exercise the new server/discover/_meta/InputRequiredResult machinery while pinning the test client to '2025-11-25'-era constants and never notice the list is stale; and even where a test does trip, the porter still has to find constants.ts, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, the streamableHttp.ts transport option default (line 259), and the literal assertion at types.test.ts:24 — surfaces no existing comment names. The pre-existing-relationship argument (the spec mirror previously said 'DRAFT-2026-v1', equally absent) misses that this diff is what converts a placeholder draft tag into a concrete, shippable wire version a real client will start advertising — that is the moment the gap becomes consequential.

How to fix (companion-work scope)

In the same companion PR that implements the 2026-07-28 wire behavior: add '2026-07-28' to SUPPORTED_PROTOCOL_VERSIONS and bump LATEST_PROTOCOL_VERSION in packages/core/src/types/constants.ts; decide whether DEFAULT_NEGOTIATED_PROTOCOL_VERSION (still '2025-03-26') should move; update the hard-coded assertion at packages/core/test/types.test.ts:24; and consider adding a test that ties the SDK constant to SpecTypes.LATEST_PROTOCOL_VERSION (or at least to the spec snapshot) so future spec-version bumps stop being silent. Do not bump the constant in this automated sync alone — that would advertise a version the SDK does not yet implement.

@github-actions github-actions Bot force-pushed the update-spec-types branch 6 times, most recently from 0dfe972 to ef5e88c Compare June 7, 2026 05:32
Comment on lines +3005 to 3013
export type ClientNotification = CancelledNotification | ProgressNotification;

/** @internal */
export type ClientResult =
| EmptyResult
| CreateMessageResult
| ListRootsResult
| ElicitResult
| GetTaskResult
| GetTaskPayloadResult
| ListTasksResult
| CancelTaskResult;
export type ClientResult = EmptyResult;

/* Server messages */
/** @internal */
export type ServerRequest =
| PingRequest
| CreateMessageRequest
| ListRootsRequest
| ElicitRequest
| GetTaskRequest
| GetTaskPayloadRequest
| ListTasksRequest
| CancelTaskRequest;

/** @internal */
export type ServerNotification =

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream schema.ts self-inconsistency to batch with the other feedback on this PR: with ServerRequest deleted entirely (zero server→client requests remain), the rewritten direction unions keep three arms that are unreachable by their own direction semantics — ServerNotification retains CancelledNotification (a server can only cancel a request it issued "in the same direction", and it can issue none), ClientNotification retains ProgressNotification (client→server progress reports on a server-issued request, which no longer exists), and ClientResult = EmptyResult survives as a one-member alias though no message can ever carry a client→server result. Suggest upstream either drop these arms (and delete/never ClientResult) or document them as deliberate forward-compat slots for the SEP-2577 interop window, so the companion ClientNotificationSchema/ServerNotificationSchema/ClientResultSchema work in schemas.ts doesn't bake unreachable shapes into Protocol's direction typing.

Extended reasoning...

What the issue is

This sync deletes export type ServerRequest entirely — grep of the post-sync file returns zero matches, and every remaining extends JSONRPCRequest is client→server (DiscoverRequest:559, PaginatedRequest:961, ReadResourceRequest:1110, SubscriptionsListenRequest:1208, GetPromptRequest:1462, CallToolRequest:1723, CompleteRequest:2450 — all members of ClientRequest). The former server-initiated requests (CreateMessageRequest/ListRootsRequest/ElicitRequest) lost their JSONRPCRequest inheritance and survive only as InputRequest payloads embedded in InputRequiredResult — payload types, not a wire request direction, even under the SEP-2577 12-month retention.

Yet the same diff rewrites the direction unions (lines 3005-3022) to keep three arms whose own semantics presuppose server→client requests:

  1. ServerNotification includes CancelledNotification (line 3014). CancelledNotificationParams.requestId "MUST correspond to the ID of a request previously issued in the same direction" (line 520) — so a server→client cancelled notification can only cancel a server-issued request, of which none exist.
  2. ClientNotification includes ProgressNotification (line 3005). Progress flows from the receiver of a request back to the requestor, keyed on a progressToken "given in the initial request" (line 909). A client→server progress notification reports progress on a request the server issued to the client — which no longer exists. The only conceivable residual use (a client emitting progress against a progressToken found inside an embedded InputRequest's params) has no spec-defined channel or semantics: input fulfillment is returned via inputResponses on retry, not streamed, and embedded payloads are not issued requests with IDs.
  3. ClientResult = EmptyResult (line 3008). A client→server JSON-RPC result exists only as the response to a server→client request. With ServerRequest gone, no message can ever carry a ClientResult; the union is retained as a dead one-member alias rather than deleted or marked never.

Step-by-step proof (arm 1; the others are symmetric)

  1. Post-sync, the only requests in the protocol are the nine ClientRequest members — all client→server. A server holds zero outstanding request IDs of its own issuance.
  2. A server wants to emit { method: 'notifications/cancelled', params: { requestId: X } } as a ServerNotification.
  3. Per line 520, X MUST be the ID of a request "previously issued in the same direction" — i.e. server→client. No such request can exist.
  4. Therefore the ServerNotification.CancelledNotification arm can never legally appear on the wire. By the same logic, ClientNotification.ProgressNotification (no server-issued request to report progress on) and every value of ClientResult (no server-issued request to respond to) are equally uninhabitable.

The contrast confirms this is a mechanical edit rather than a design choice: the reachable mirror arms are coherent (ClientNotification.CancelledNotification — client cancels its own request; ServerNotification.ProgressNotification — server reports progress on a client request), and the same diff did deliberately prune CreateMessageResult/ListRootsResult/ElicitResult from ClientResult. It pruned union members by deleted-type-name only, leaving the direction-mirror arms of the two type-shared notifications and the now-pointless ClientResult alias behind.

Why this matters for the SDK (silent — no CI signal)

The companion union work will rewrite ClientNotificationSchema/ServerNotificationSchema/ClientResultSchema (schemas.ts ~2095-2110) to mirror the spec. Faithfully encoding these arms bakes unreachable message shapes into the public unions and into Protocol's generic direction typing (SendNotificationT/SendResultT): server-side Protocol would still type-permit sending a notifications/cancelled it can never legally send, and client-side Protocol would keep a result type with no request to respond to. None of the affected runtime files import spec.types.ts, so nothing in CI flags this — spec.types.test.ts's union checks would happily pass once the SDK mirrors the same vestigial arms.

Distinct from existing comments

#3252228068 documents the ServerRequest deletion and states "ClientResult collapses to bare EmptyResult" — but only as deletion inventory; it never observes that the retained ClientResult, the server-direction CancelledNotification arm, or the client-direction ProgressNotification arm are unreachable, and its remediation list does not touch the notification unions. #3246176908 made the unreachability argument for a prior revision's task-only ServerRequest and is resolved/superseded (those types no longer exist). No other comment discusses ClientNotification/ServerNotification arm reachability.

How to fix

Raise upstream with the batched schema.ts feedback: either (a) drop CancelledNotification from ServerNotification, drop ProgressNotification from ClientNotification, and delete ClientResult (or mark it never) until a server→client request direction exists again; or (b) if these are deliberately retained as forward-compat slots for the SEP-2577 deprecated sampling/roots interop window, say so in the union JSDoc so SDK porters know to keep them. Until settled, the companion work should not treat the current union shapes as authoritative for Protocol's direction typing.

Comment on lines 518 to 523
* The ID of the request to cancel.
*
* This MUST correspond to the ID of a request previously issued in the same direction.
* This MUST be provided for cancelling non-task requests.
* This MUST NOT be used for cancelling tasks (use the {@link CancelTaskRequest | tasks/cancel} request instead).
*/
requestId?: RequestId;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream partial-revert to batch with the other schema.ts feedback: this hunk deletes the two normative sentences that justified CancelledNotificationParams.requestId being optional ('This MUST be provided for cancelling non-task requests' / 'This MUST NOT be used for cancelling tasks…'), and the same diff deletes the entire tasks subsystem — the only mechanism that ever made omitting requestId meaningful (it was required in every pre-task spec revision) — yet the ? survives, leaving { "method": "notifications/cancelled", "params": {} } type-valid but with no spec-defined semantics. Suggest raising upstream (revert to required, matching pre-task revisions, or document omission semantics) before 2026-07-28 ships with the orphaned ?; the SDK should keep its own optional schema (schemas.ts:201, deliberately restored by #2248) through the 2025-11-25 interop window regardless, so no SDK change is needed now.

Extended reasoning...

What the issue is

This hunk (spec.types.ts:516-523 post-sync) deletes the two normative sentences from the JSDoc of CancelledNotificationParams.requestId:

  • 'This MUST be provided for cancelling non-task requests.'
  • 'This MUST NOT be used for cancelling tasks (use the tasks/cancel request instead).'

…but leaves the field declared optional:

export interface CancelledNotificationParams extends NotificationParams {
    /**
     * The ID of the request to cancel.
     *
     * This MUST correspond to the ID of a request previously issued in the same direction.
     */
    requestId?: RequestId;
    reason?: string;
}

The surviving sentence presupposes the field is present — 'This MUST correspond to the ID of a request previously issued' has nothing to correspond to when the field is omitted — and the post-sync spec defines no semantics whatsoever for omission.

Why this is an upstream slip, not intentional

requestId was required in every spec revision before tasks (e.g. the 2025-06-18 schema.ts declares requestId: RequestId with no ?). The 2025-11-25 task feature is what made it optional, paired with exactly the two MUST sentences this diff deletes — the optionality existed solely so cancellation messages in task flows were expressible (a task cancellation identified the task, not a request id). This same diff deletes the entire tasks subsystem (TaskMetadata, tasks/cancel, RelatedTaskMetadata, the related-task _meta key), i.e. the only mechanism that ever justified omitting requestId — but does not revert the ?. Classic partial revert: the prose was cleaned up, the optionality marker was missed. Same partial-migration class as the already-accepted #3246176905 (one of four notification JSDoc blocks migrated, three missed).

Step-by-step proof

  1. Pre-tasks (2025-06-18 schema.ts): CancelledNotification.params.requestId: RequestId — required. { params: { reason: 'x' } } is type-invalid.
  2. 2025-11-25 (tasks era, the snapshot this repo imported in 38d6cd2): requestId?: RequestId plus the two MUST sentences — optional, but normatively gated: it MUST be present for non-task cancellation and MUST be absent for tasks (which use tasks/cancel instead). Every wire message has defined semantics.
  3. This diff (c47bd846 → 00f8803): the tasks subsystem and both MUST sentences are deleted; requestId? survives. Now { "method": "notifications/cancelled", "params": {} } is type-valid, yet there is no task it could refer to and no rule saying what a receiver should do with it — the message is semantically void but conformant.

Why nothing in CI surfaces this

The SDK mirrors the optional shape: CancelledNotificationParamsSchema.requestId is RequestIdSchema.optional() (packages/core/src/types/schemas.ts:201 — deliberately restored by #2248 for 2025-11-25 interop), and Protocol._oncancel silently no-ops when requestId is absent (packages/core/src/shared/protocol.ts:337: if (!notification.params.requestId) { return; }). Because both sides are optional, the bidirectional CancelledNotification assignability check in spec.types.test.ts passes in both directions — so unlike most of this PR's findings, neither tsc nor the drift guard gives a porter any signal to revisit this field. Silent, same class as the accepted #3216586348 / #3246176899 findings.

How to fix

Raise upstream with the other schema.ts feedback already batched on this PR: either revert requestId to required (matching every pre-task revision, now that the sole reason for optionality is gone), or explicitly document what an omitted requestId means. Then re-run pnpm run fetch:spec-types.

No SDK change is appropriate now: schemas.ts:201 should stay optional through the 2025-11-25 interop window regardless of what upstream decides (an SDK receiver must tolerate task-era peers emitting requestId-less cancellations) — which is exactly why the upstream report needs to happen before 2026-07-28 ships with the orphaned ?, rather than waiting for the companion SDK work to trip over it.

Comment on lines 320 to 324
* - **Prompts**: Unknown prompt name or missing required arguments
* - **Pagination**: Invalid or expired cursor values
* - **Logging**: Invalid log level
* - **Tasks**: Invalid or nonexistent task ID, invalid cursor, or attempting to cancel a task already in a terminal status
* - **Elicitation**: Server requests an elicitation mode not declared in client capabilities
* - **Sampling**: Missing tool result or tool results mixed with other content

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Nit (upstream prose, batch with the other schema.ts feedback): the InvalidParamsError bullet list still routes "Elicitation: Server requests an elicitation mode not declared in client capabilities" to -32602 (line 323), but the MethodNotFoundError doc rewritten by this same sync (lines 299-301) normatively sends all client-capability misses to the new MissingRequiredClientCapabilityError (-32003) — whose single canonical example is literally missing-elicitation-capability.json. Since elicitation modes are ClientCapabilities.elicitation.{form,url} sub-keys, this bullet directly contradicts the new error's scope; suggest rewriting it upstream to point at MissingRequiredClientCapabilityError so the companion SDK work mapping the server.ts elicitation capability gates to wire codes doesn't have two conflicting spec instructions.

Extended reasoning...

What the issue is

The latest re-pull (upstream commit 14a6e3a2, part of the d6323899→00f8803 delta) leaves spec.types.ts saying three mutually inconsistent things about what error a server returns when a request needs an elicitation capability the client didn't declare:

  1. MethodNotFoundError doc (lines 299-301, rewritten by this diff): "A request that requires a client capability the client did not declare is signalled instead by {@link MissingRequiredClientCapabilityError} (-32003)." — i.e. all client-capability misses are normatively routed to -32003.
  2. MissingRequiredClientCapabilityError (added by this diff, lines 397-413): "Returned when processing a request requires a capability the client did not declare in clientCapabilities" — and its one canonical example is examples/MissingRequiredClientCapabilityError/missing-elicitation-capability.json (line 410), i.e. exactly the missing-elicitation-capability case.
  3. InvalidParamsError bullet list (line 323): still keeps "Elicitation: Server requests an elicitation mode not declared in client capabilities" under -32602.

Elicitation modes are client-capability sub-keys — ClientCapabilities.elicitation = { form?: JSONObject; url?: JSONObject } (spec.types.ts:667-670) — and -32003's data.requiredCapabilities: ClientCapabilities can express the granular requirement ({ elicitation: { url: {} } }). So "an elicitation mode not declared in client capabilities" is by definition "a capability the client did not declare," which per items 1-2 MUST be -32003 — yet item 3 says -32602.

Why this is a partial-migration slip introduced by this sync

Pre-sync the bullet was consistent: no -32003 existed, ElicitRequest was a wire request, and a mode mismatch was a plain params-validation failure. The contradiction is created by this diff, and the upstream commit demonstrably edited both surrounding sites while missing this one: it rewrote the MethodNotFoundError doc two paragraphs above and edited this exact bullet list (the hunk @@ -281,7 +320,6 deletes the Tasks bullet) — but left the sibling elicitation bullet untouched. This is the same missed-sibling pattern as the accepted stale-JSDoc findings on this PR (#3246176905, #3239359160).

The bullet is also dead-letter prose under the new model regardless: post-sync ElicitRequest no longer extends JSONRPCRequest (it is only an InputRequest payload inside InputRequiredResult), so a client cannot return -32602 to an elicitation request at all. The only surviving interpretation — a server-side capability gate rejecting the original tools/call-style request — is precisely -32003's own canonical example.

Step-by-step proof

  1. Client sends tools/call with _meta['io.modelcontextprotocol/clientCapabilities'] = { elicitation: { form: {} } } (form mode only).
  2. The tool handler needs a URL-mode elicitation. The server checks the per-request capabilities and finds elicitation.url undeclared.
  3. Per spec.types.ts:299-301 and the -32003 definition + its missing-elicitation-capability.json example, the server MUST respond with MissingRequiredClientCapabilityError (-32003, data.requiredCapabilities: { elicitation: { url: {} } }, HTTP 400).
  4. Per spec.types.ts:323, the same scenario ("elicitation mode not declared in client capabilities") is listed as InvalidParamsError (-32602).
  5. Both passages cannot be followed simultaneously — the spec contradicts itself on the wire code for this exact case.

Concrete SDK consequence

This isn't just doc pedantry: the already-mandated companion work (#3223937253, #3278874075 — add ProtocolErrorCode.MissingRequiredClientCapability = -32003 and emit it on per-request capability misses) has to map the SDK's existing elicitation gates to a wire code. Those gates sit exactly on this fault line: packages/server/src/server/server.ts:220-225 throws SdkError(CapabilityNotSupported) when _clientCapabilities.elicitation is absent, and server.ts:284-292 gates URL mode on _clientCapabilities.elicitation.url. The porter choosing between -32602 (per line 323) and -32003 (per lines 299-301/410) is making a wire-compatibility decision that is breaking to flip later. The example file and the MethodNotFoundError rescope make -32003 clearly the intended answer — the bullet is the stale outlier.

Not a duplicate

The existing -32003 comments (#3223937253: missing enum member/schemas; #3278874075: -32004 transport path and enum members) never mention the InvalidParamsError elicitation bullet or the MethodNotFoundError rescope — the contradicting text only landed upstream in commit 14a6e3a2, pulled after the last detailed review round.

How to fix

Batch with the other upstream schema.ts feedback already on this PR: delete or rewrite the elicitation bullet at spec.types.ts:323 to point at MissingRequiredClientCapabilityError (e.g. move it next to the MethodNotFoundError cross-reference), then re-run pnpm run fetch:spec-types. No change in this repo directly (the file header says DO NOT EDIT). In the companion SDK work, route elicitation-mode capability misses to -32003, matching the canonical example and the MethodNotFoundError doc — not -32602.

Comment on lines +572 to +577
export interface DiscoverResult extends CacheableResult {
/**
* The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
* MCP Protocol Versions this server supports. The client should choose a
* version from this list for use in subsequent requests.
*/
supportedVersions: string[];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Scoping correction for two existing checklists: DiscoverResult also extends CacheableResult (spec.types.ts:572), making six extenders total — but #3252228073 enumerates only the five list/read results when directing which schemas should extend CacheableResultSchema, and the #3223937253 DiscoverResultSchema porting item predates the mixin and describes DiscoverResult without ttlMs/cacheScope. The companion port should include DiscoverResultSchema among the CacheableResultSchema extenders, and the upstream ttlMs?/cacheScope? optionality feedback batch should name DiscoverResult too — a required cacheScope: 'public' | 'private' on a capabilities document that can be per-auth/per-tenant is a footgun.

Extended reasoning...

What the gap is

This revision declares export interface DiscoverResult extends CacheableResult at spec.types.ts:572, so the server/discover result requires the new ttlMs: number and cacheScope: 'public' | 'private' fields, exactly like the five list/read results. Grepping the post-sync file confirms there are exactly six CacheableResult extenders:

Line Type
572 DiscoverResult
1029 ListResourcesResult
1065 ListResourceTemplatesResult
1123 ReadResourceResult
1419 ListPromptsResult
1620 ListToolsResult

Neither existing finding records the sixth:

  • #3252228073 (the CacheableResult comment) enumerates only the five list/read results and its remediation says to have "ListResourcesResultSchema/ListResourceTemplatesResultSchema/ReadResourceResultSchema/ListPromptsResultSchema/ListToolsResultSchema extend" the new CacheableResultSchema — DiscoverResult is never mentioned.
  • #3223937253 (the "add DiscoverRequestSchema/DiscoverResultSchema" porting item, 2026-05-12) was written against revision 8e192a22, before CacheableResult existed (introduced in c47bd846, 2026-05-16). It describes DiscoverResult as { supportedVersions, capabilities, serverInfo, instructions? } — a field list that is now stale.

The concrete failure path

A porter following both checklists verbatim would (a) build DiscoverResultSchema from #3223937253's stale field list, without ttlMs/cacheScope, and (b) wire CacheableResultSchema into only the five schemas #3252228073 names. The sdkTypeChecks entry for DiscoverResult (which #3223937253 directs the porter to add, and which the coverage check forces) then fails its bidirectional spec = sdk assignability check with TS2741 "Property 'ttlMs' is missing" — plus the AssertExactKeys check once added.

Addressing the refutation

One verifier argued this is fully subsumed: the mixin-level fix "automatically covers DiscoverResult," and the failure is CI-caught, not silent. Both points are partly true but don't dissolve the finding:

  • The mixin fix is only automatic if the porter knows DiscoverResultSchema is supposed to extend the mixin. #3252228073's remediation names the five extending schemas explicitly; a porter wiring CacheableResultSchema into exactly those five and building DiscoverResultSchema from #3223937253's pre-mixin field list has followed both checklists to the letter and still mis-ported. The enumeration is the checklist, and it is incomplete.
  • "CI-caught" applies equally to the accepted #3252228073 itself — every CacheableResult finding on this PR is CI-visible, since the drift guard is the whole point of the sync. This PR's established acceptance pattern (#3254078087, #3286031387, #3322449645) treats stale-enumeration/stale-checklist corrections as valid precisely because the comments serve as the porting plan for a held PR; a red TS2741 tells the porter something is missing, not that two prior comments pointed them the wrong way.
  • The upstream-optionality extension is not subsumed: #3252228073's argument for ttlMs?/cacheScope? is the HTTP Cache-Control-is-opt-in analogy for list/read results. DiscoverResult adds a distinct and stronger argument — ServerCapabilities can be dynamic (per-auth, per-tenant), and a required cacheScope forces every server to take a caching stance on its capabilities document, where a careless 'public' on a capabilities response served behind auth lets a shared cache leak one tenant's capability surface to another. That belongs in the same upstream feedback batch and is named nowhere else on this PR.

Step-by-step proof

  1. Porter implements #3223937253: DiscoverResultSchema = ResultSchema.extend({ supportedVersions: z.array(z.string()), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, instructions: z.string().optional() }), and adds the sdkTypeChecks.DiscoverResult entry the comment calls for.
  2. Porter implements #3252228073: adds CacheableResultSchema and has the five named list/read schemas extend it.
  3. tsc --noEmit on spec.types.test.ts: the DiscoverResult check's sdk = spec direction... actually the failing direction is spec = sdk — assigning the SDK type (no ttlMs) to SpecTypes.DiscoverResult (requires ttlMs: number, cacheScope: 'public' | 'private') → TS2741: Property 'ttlMs' is missing in type '{ supportedVersions: string[]; ... }' but required in type 'DiscoverResult'. The ServerResult union check (which contains DiscoverResult) fails the same way.
  4. Porter must now discover, outside both checklists, that spec.types.ts:572 has an extends CacheableResult clause that #3252228073's enumeration omitted.

How to fix

No change to this automated sync itself. (1) In the companion port, include DiscoverResultSchema among the CacheableResultSchema extenders — i.e., read #3252228073's "five result types" as six. (2) In the upstream ttlMs?/cacheScope? optionality feedback batch already on the table from #3252228073, explicitly include DiscoverResult, with the added per-auth/per-tenant capabilities-document argument: a required cache directive on server/discover is a footgun where 'public' can leak tenant-specific capability sets through shared caches.

Filed as a nit: this PR is already held for companion work and the gap is CI-visible once the DiscoverResult type check exists — this records the connection neither existing finding names, in the same stale-enumeration-correction tier already established on this PR.

@github-actions github-actions Bot force-pushed the update-spec-types branch from ef5e88c to bab2413 Compare June 8, 2026 05:34
Comment on lines +468 to +492
* An InputRequiredResult sent by the server to indicate that additional input is needed
* before the request can be completed.
*
* At least one of `inputRequests` or `requestState` MUST be present.
* @example InputRequiredResult with elicitation and sampling input requests and request state
* {@includeCode ./examples/InputRequiredResult/input-required-result-with-elicitation-and-sampling-and-request-state.json}
*
* @example InputRequiredResult with request state only (load shedding)
* {@includeCode ./examples/InputRequiredResult/input-required-result-with-request-state-only.json}
*
* @category Multi Round-Trip
*/
export interface InputRequiredResult extends Result {
/* Requests issued by the server that must be complete before the
* client can retry the original request.
*/
inputRequests?: InputRequests;
/* Request state to be passed back to the server when the client
* retries the original request.
* Note: The client must treat this as an opaque blob; it must not
* interpret it in any way.
*/
requestState?: string;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Upstream schema.ts nit to batch with the other spec feedback: InputRequiredResult's JSDoc (line 471) says "At least one of inputRequests or requestState MUST be present", but both fields are optional, so { resultType: 'input_required' } with neither field is type-valid yet spec-invalid — and since Result carries an index signature, the degenerate payload is structurally indistinguishable from any other Result. Concrete porting note for the companion InputRequiredResultSchema demanded by #3206453749: a plain looseObject with two .optional() fields would accept the forbidden neither-field payload, and the bidirectional spec↔SDK assignability check can't express the constraint, so it must live in a runtime .refine() (precedent: Base64Schema, schemas.ts:765) unless upstream restructures the type as a two-arm union — the pattern the spec already uses for ElicitRequestParams.

Extended reasoning...

What the issue is

The new InputRequiredResult (spec.types.ts:480-491) declares both of its distinguishing fields optional:

export interface InputRequiredResult extends Result {
    inputRequests?: InputRequests;
    requestState?: string;
}

while its own JSDoc at line 471 is normative: "At least one of inputRequests or requestState MUST be present." So { resultType: 'input_required' } with neither field is type-valid but spec-invalid. And because Result carries [key: string]: unknown and both added fields are optional, the degenerate payload is structurally indistinguishable from any other Result at the type level — compounding (but distinct from) the non-narrowed-resultType finding in #3214351594.

Step-by-step proof

  1. A server returns CallToolResultResponse with result: { resultType: 'input_required' } — no inputRequests, no requestState.
  2. Against the spec types this assigns cleanly to InputRequiredResult (both fields optional) and therefore to CallToolResult | InputRequiredResult — TypeScript raises no error.
  3. Per the line-471 MUST, the payload is non-conformant: the client has neither sub-requests to fulfil nor opaque state to replay, so the "retry with inputResponses/requestState" contract is unsatisfiable. The message is semantically void but type-valid.
  4. The constraint is structurally expressible upstream: the load-shedding example at lines 475-476 (requestState only) confirms each single-field arm is independently valid, so a two-arm union — one arm requiring inputRequests, one requiring requestState — models it exactly. The spec already uses this pattern for ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams. Alternatively the generated schema.json could carry anyOf: [{required: ['inputRequests']}, {required: ['requestState']}] next to the prose.

Concrete SDK consequence (the porting note)

The companion work demanded by #3206453749 must add InputRequiredResultSchema to schemas.ts. The natural encoding — a looseObject with two .optional() fields — accepts the forbidden neither-field payload, so Protocol.request() would validate spec-invalid wire traffic as a well-formed InputRequiredResult. Encoding the constraint as a Zod union on the SDK side instead would break the spec→SDK direction of the bidirectional assignability check in spec.types.test.ts (the spec type admits neither-field; the union does not). So without an upstream fix the MUST can only live in a runtime refinement — .refine(v => v.inputRequests !== undefined || v.requestState !== undefined) — for which the SDK already has precedent (Base64Schema, schemas.ts:765). The drift guard checks shapes, not prose constraints, so nothing in CI points the porter at this.

Addressing the counter-arguments

One review pass argued this is the file's deliberate prose-normative idiom (citing e.g. ElicitResult.content and CancelledNotificationParams.requestId) and that the structural-degeneracy point overlaps #3214351594. On the first point: those cited examples are conditional constraints ("only present when action is accept", "MUST correspond to a prior request ID") that TypeScript genuinely cannot express without dependent types — whereas an at-least-one-of is a plain two-arm union the same file already uses for exactly this shape (ElicitRequestParams), so flagging it is a concrete, actionable upstream suggestion, not pedantry about every prose MUST. On the second: #3214351594 covers the non-narrowed resultType discriminant and mentions structural degeneracy only as a side observation; it never mentions the at-least-one constraint, and neither does any of the other 37 timeline comments (#3206453749 lists InputRequiredResult only as needing a schema; #3216586357 covers the missing InputResponse error arm). The residual .refine() porting note is precisely the kind of checklist item this PR's accepted comment tier exists to record — a literal port following only the existing comments would ship a validator that accepts the forbidden payload.

How to fix

Upstream in schema.ts (batch with the resultType discriminant, missing InputResponse error arm, and the other accepted schema.ts feedback): restructure InputRequiredResult as a two-arm union (one arm with required inputRequests, one with required requestState), or at minimum pair the prose MUST with an anyOf required-arms constraint in the generated schema.json. In the companion SDK work regardless: give InputRequiredResultSchema a .refine() encoding the at-least-one rule, following the Base64Schema precedent.

Comment on lines +2973 to 2982
* Parameters for a {@link ElicitationCompleteNotification | notifications/elicitation/complete} notification.
*
* @example Elicitation result response
* {@includeCode ./examples/ElicitResultResponse/elicitation-result-response.json}
*
* @category `elicitation/create`
* @category `notifications/elicitation/complete`
*/
export interface ElicitResultResponse extends JSONRPCResultResponse {
result: ElicitResult;
export interface ElicitationCompleteNotificationParams extends NotificationParams {
/**
* The ID of the elicitation that completed.
*/
elicitationId: string;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 This sync extracts the previously-inline params of notifications/elicitation/complete into a new named export ElicitationCompleteNotificationParams (line 2977), which the drift guard's coverage check picks up but which has no sdkTypeChecks entry or _K_ key-parity assertion in spec.types.test.ts — so the coverage test fails on this name. Unlike the other new types on this PR, the SDK side is already complete (ElicitationCompleteNotificationParamsSchema at schemas.ts:1916, alias at types.ts:348, registered in specTypeSchema.ts:62), so the fix is a two-line test-file addition — but none of the existing porting checklists (#3223937253's 10 additive types, #3206453749's 10 Multi Round-Trip types, #3252228073's CacheableResult) enumerate this export, so a porter working through them would still have a red coverage check.

Extended reasoning...

What the bug is

This sync restructures the previously-inline params of ElicitationCompleteNotification into a new named export:

export interface ElicitationCompleteNotificationParams extends NotificationParams {
    elicitationId: string;
}

(spec.types.ts:2977, replacing the inline params: { elicitationId: string } object literal). Because it is a new export interface, the drift guard in packages/core/test/spec.types.test.ts now requires a corresponding compatibility-test entry — and none exists.

The code path that triggers it

The drift guard works in three steps:

  1. extractExportedTypes() (spec.types.test.ts:1072-1075) regex-matches every export interface|class|type <Name> in spec.types.ts — this picks up ElicitationCompleteNotificationParams.
  2. Names are filtered by MISSING_SDK_TYPES = ['Error', 'URLElicitationRequiredError'] (lines 1066-1070) — the new name is not in the allowlist.
  3. The should have comprehensive compatibility tests test (lines 1098-1108) asserts every remaining name has an sdkTypeChecks entry, ending in expect(missingTests).toHaveLength(0).

A grep of the test file for ElicitationCompleteNotification finds entries only for the parent notification — the sdkTypeChecks.ElicitationCompleteNotification entry at lines 112-114 and the _K_ElicitationCompleteNotification key-parity assertion at lines 925-926. There is no entry for the Params type, so the coverage assertion fails listing ElicitationCompleteNotificationParams. Once the entry is added, the sibling key-parity test (lines 1110-1116) additionally requires a matching _K_ElicitationCompleteNotificationParams assertion.

Step-by-step proof

  1. Post-sync, spec.types.ts:2977 declares export interface ElicitationCompleteNotificationParams extends NotificationParams { elicitationId: string }.
  2. extractExportedTypes returns a list containing 'ElicitationCompleteNotificationParams'.
  3. typesToCheck = specTypes.filter(t => !MISSING_SDK_TYPES.includes(t)) retains it (the allowlist names only Error and URLElicitationRequiredError).
  4. sdkTypeChecks['ElicitationCompleteNotificationParams'] is undefined → the name lands in missingTests.
  5. expect(missingTests).toHaveLength(0) fails with the new name in the diff output.

Why the fix is unusually small

Unlike the other new exports on this PR, the SDK side already ships everything needed: ElicitationCompleteNotificationParamsSchema exists at packages/core/src/types/schemas.ts:1916 (and is consumed by ElicitationCompleteNotificationSchema at line 1930), the type alias ElicitationCompleteNotificationParams exists at types.ts:348, and the schema is registered in specTypeSchema.ts:62. So no schema or runtime work is required — the fix is purely a test-file addition:

ElicitationCompleteNotificationParams: (
    sdk: SDKTypes.ElicitationCompleteNotificationParams,
    spec: SpecTypes.ElicitationCompleteNotificationParams
) => { sdk = spec; spec = sdk; },
// plus:
type _K_ElicitationCompleteNotificationParams = Assert<
    AssertExactKeys<SDKTypes.ElicitationCompleteNotificationParams, SpecTypes.ElicitationCompleteNotificationParams>>;

(modulo whatever the surrounding NotificationParams-derived entries do — note the spec type's _meta divergence tracked in #3278874070 may interact with the exact-keys check.)

Why this is not a duplicate of the existing checklists

This PR's comments collectively serve as the porting checklist for the held companion work, and the established review pattern here accepts corrections for unenumerated checklist items (e.g. #3368827094 for DiscoverResult/CacheableResult). The additive-batch comment #3223937253 enumerates exactly 10 new exports (Discover*, SubscriptionFilter, SubscriptionsListen*, SubscriptionsAcknowledged*, and the two error envelopes); #3206453749 enumerates the 10 Multi Round-Trip types; #3252228073 covers CacheableResult; #3239359156 discusses ElicitationCompleteNotification only in terms of its delivery-channel gap, not its Params extraction or test coverage. None names ElicitationCompleteNotificationParams — a porter completing every enumerated item would still have a red should have comprehensive compatibility tests check on this one name.

Impact and severity

This is part of the same CI-red drift-guard class already extensively documented on this held PR (the coverage check fails for many names), so it adds no new blocking condition — but it is a distinct, unenumerated item that every existing checklist would miss. Filed as a nit in the same stale-/incomplete-checklist-correction tier already established on this PR (#3368827094, #3286031387, #3322449645).

@github-actions github-actions Bot force-pushed the update-spec-types branch 7 times, most recently from 86d0536 to fa89096 Compare June 15, 2026 05:46
@github-actions github-actions Bot force-pushed the update-spec-types branch from fa89096 to 15db7e3 Compare June 16, 2026 05:50
@github-actions github-actions Bot force-pushed the update-spec-types branch from 15db7e3 to 0435878 Compare June 17, 2026 05:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants