From ec6df14c548ef5c0bd6211879b288723b67d67a2 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Tue, 2 Jun 2026 14:56:18 +0000 Subject: [PATCH 1/3] chore(core): add per-revision spec reference types (2025-11-25 and 2026-07-28) Replace the single generated spec.types.ts with one reference file per protocol revision: - spec.types.2025-11-25.ts: the released 2025-11-25 schema, pinned at spec commit 357adac4 and frozen. - spec.types.2026-07-28.ts: the upcoming 2026-07-28 revision, pinned at spec commit 9d700ed6. Until that revision is published, its schema is fetched from the spec repository's draft directory. fetch-spec-types.ts takes the revision (and an optional commit SHA) and writes spec.types..ts; with no arguments it refreshes both. The type comparison test splits accordingly: spec.types.2025-11-25.test.ts compares the SDK against the frozen release, and spec.types.2026-07-28.test.ts pins the 2026-07-28 protocol version and the new -32003/-32004 error code constants, tracking the not-yet-implemented surface in MISSING_SDK_TYPES_2026_07_28 with completeness checks that force honest burn-down. --- .github/workflows/update-spec-types.yml | 14 +- .prettierignore | 3 +- REVIEW.md | 2 +- common/eslint-config/eslint.config.mjs | 2 +- .../core/src/types/spec.types.2025-11-25.ts | 2559 +++++++++++++++++ ...spec.types.ts => spec.types.2026-07-28.ts} | 1200 ++++---- ....test.ts => spec.types.2025-11-25.test.ts} | 277 +- .../core/test/spec.types.2026-07-28.test.ts | 508 ++++ scripts/fetch-spec-types.ts | 105 +- 9 files changed, 3688 insertions(+), 982 deletions(-) create mode 100644 packages/core/src/types/spec.types.2025-11-25.ts rename packages/core/src/types/{spec.types.ts => spec.types.2026-07-28.ts} (75%) rename packages/core/test/{spec.types.test.ts => spec.types.2025-11-25.test.ts} (79%) create mode 100644 packages/core/test/spec.types.2026-07-28.test.ts diff --git a/.github/workflows/update-spec-types.yml b/.github/workflows/update-spec-types.yml index 6f7bde8e43..482fb04213 100644 --- a/.github/workflows/update-spec-types.yml +++ b/.github/workflows/update-spec-types.yml @@ -34,16 +34,16 @@ jobs: run: pnpm install - name: Fetch latest spec types - run: pnpm run fetch:spec-types + run: pnpm run fetch:spec-types 2026-07-28 - name: Check for changes id: check_changes run: | - if git diff --quiet packages/core/src/types/spec.types.ts; then + if git diff --quiet packages/core/src/types/spec.types.2026-07-28.ts; then echo "has_changes=false" >> $GITHUB_OUTPUT else echo "has_changes=true" >> $GITHUB_OUTPUT - LATEST_SHA=$(grep "Last updated from commit:" packages/core/src/types/spec.types.ts | cut -d: -f2 | tr -d ' ') + LATEST_SHA=$(grep "Last updated from commit:" packages/core/src/types/spec.types.2026-07-28.ts | cut -d: -f2 | tr -d ' ') echo "sha=$LATEST_SHA" >> $GITHUB_OUTPUT fi @@ -59,12 +59,12 @@ jobs: git config user.email "github-actions[bot]@users.noreply.github.com" git checkout -B update-spec-types - git add packages/core/src/types/spec.types.ts - git commit -m "chore: update spec.types.ts from upstream" + git add packages/core/src/types/spec.types.2026-07-28.ts + git commit -m "chore: update spec.types.2026-07-28.ts from upstream" git push -f --no-verify origin update-spec-types # Create PR if it doesn't exist, or update if it does - PR_BODY="This PR updates \`packages/core/src/types/spec.types.ts\` from the Model Context Protocol specification. + PR_BODY="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/${{ steps.check_changes.outputs.sha }}/schema/draft/schema.ts @@ -77,7 +77,7 @@ jobs: gh pr edit "$EXISTING_PR" --body "$PR_BODY" else gh pr create \ - --title "chore: update spec.types.ts from upstream" \ + --title "chore: update spec.types.2026-07-28.ts from upstream" \ --body "$PR_BODY" \ --base main \ --head update-spec-types diff --git a/.prettierignore b/.prettierignore index 6877ccc5aa..d2fb242b9d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -10,7 +10,8 @@ node_modules pnpm-lock.yaml # Ignore generated files -src/spec.types.ts +**/src/types/spec.types.2025-11-25.ts +**/src/types/spec.types.2026-07-28.ts # Batch test cloned repos and results packages/codemod/batch-test/repos diff --git a/REVIEW.md b/REVIEW.md index ad726c762f..d210004600 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -75,7 +75,7 @@ When verifying spec compliance, consult the spec directly rather than relying on ### Schema Compliance -- When editing Zod protocol schemas in `schemas.ts`, verify unknown-key handling matches the spec `schema.ts`: if the spec type has no `additionalProperties: false`, the SDK schema must use `z.looseObject()` / `.catchall(z.unknown())` rather than implicit strict — over-strict Zod (incl. `z.literal('object')` on `type`) rejects spec-valid payloads from other SDKs. Also confirm `spec.types.test.ts` still passes bidirectionally. (#1768, #1849, #1169) +- When editing Zod protocol schemas in `schemas.ts`, verify unknown-key handling matches the spec `schema.ts`: if the spec type has no `additionalProperties: false`, the SDK schema must use `z.looseObject()` / `.catchall(z.unknown())` rather than implicit strict — over-strict Zod (incl. `z.literal('object')` on `type`) rejects spec-valid payloads from other SDKs. Also confirm the `spec.types.*.test.ts` comparisons still pass bidirectionally. (#1768, #1849, #1169) ### Async / Lifecycle diff --git a/common/eslint-config/eslint.config.mjs b/common/eslint-config/eslint.config.mjs index 32aad92752..a32b4208cc 100644 --- a/common/eslint-config/eslint.config.mjs +++ b/common/eslint-config/eslint.config.mjs @@ -96,7 +96,7 @@ export default defineConfig( }, { // Ignore generated protocol types everywhere - ignores: ['**/spec.types.ts'] + ignores: ['**/spec.types.2025-11-25.ts', '**/spec.types.2026-07-28.ts'] }, { files: ['packages/client/**/*.ts', 'packages/server/**/*.ts'], diff --git a/packages/core/src/types/spec.types.2025-11-25.ts b/packages/core/src/types/spec.types.2025-11-25.ts new file mode 100644 index 0000000000..225a53c2d7 --- /dev/null +++ b/packages/core/src/types/spec.types.2025-11-25.ts @@ -0,0 +1,2559 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/2025-11-25/schema.ts + * Last updated from commit: 357adac47ab2654b64799f994e6db8d3df4ee19d + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: pnpm run fetch:spec-types 2025-11-25 + */ /* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse; + +/** @internal */ +export const LATEST_PROTOCOL_VERSION = '2025-11-25'; +/** @internal */ +export const JSONRPC_VERSION = '2.0'; + +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; + +/** + * Common params for any task-augmented request. + * + * @internal + */ +export interface TaskAugmentedRequestParams extends RequestParams { + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task?: TaskMetadata; +} +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} + +/** @internal */ +export interface Request { + method: string; + // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** @internal */ +export interface Notification { + method: string; + // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; +} + +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResultResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; +} + +/** + * A response to a request, containing either the result or error. + * + * @category JSON-RPC + */ +export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; + +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; + +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +export const URL_ELICITATION_REQUIRED = -32042; + +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError extends Omit { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} + +/* Empty result */ +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; + +/* Cancellation */ +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +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. + * This MUST be provided for cancelling non-task requests. + * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). + */ + requestId?: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} + +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * For task cancellation, use the `tasks/cancel` request instead of this notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: 'notifications/cancelled'; + params: CancelledNotificationParams; +} + +/* Initialization */ +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} + +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: 'initialize'; + params: InitializeRequestParams; +} + +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * 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. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} + +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: 'notifications/initialized'; + params?: NotificationParams; +} + +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { form?: object; url?: object }; + + /** + * Present if the client supports task-augmented requests. + */ + tasks?: { + /** + * Whether this client supports tasks/list. + */ + list?: object; + /** + * Whether this client supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for sampling-related requests. + */ + sampling?: { + /** + * Whether the client supports task-augmented sampling/createMessage requests. + */ + createMessage?: object; + }; + /** + * Task support for elicitation-related requests. + */ + elicitation?: { + /** + * Whether the client supports task-augmented elicitation/create requests. + */ + create?: object; + }; + }; + }; +} + +/** + * 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` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; + /** + * Present if the server supports task-augmented requests. + */ + tasks?: { + /** + * Whether this server supports tasks/list. + */ + list?: object; + /** + * Whether this server supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for tool-related requests. + */ + tools?: { + /** + * Whether the server supports task-augmented tools/call requests. + */ + call?: object; + }; + }; + }; +} + +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: 'light' | 'dark'; +} + +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} + +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} + +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: 'ping'; + params?: RequestParams; +} + +/* Progress notifications */ + +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} + +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: 'notifications/progress'; + params: ProgressNotificationParams; +} + +/* Pagination */ +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} + +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} + +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: 'resources/list'; +} + +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} + +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: 'resources/templates/list'; +} + +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} + +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface ReadResourceRequestParams extends ResourceRequestParams {} + +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: 'resources/read'; + params: ReadResourceRequestParams; +} + +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: 'notifications/resources/list_changed'; + params?: NotificationParams; +} + +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface SubscribeRequestParams extends ResourceRequestParams {} + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: 'resources/subscribe'; + params: SubscribeRequestParams; +} + +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface UnsubscribeRequestParams extends ResourceRequestParams {} + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: 'resources/unsubscribe'; + params: UnsubscribeRequestParams; +} + +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: 'notifications/resources/updated'; + params: ResourceUpdatedNotificationParams; +} + +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: 'prompts/list'; +} + +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} + +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; +} + +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: 'prompts/get'; + params: GetPromptRequestParams; +} + +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = 'user' | 'assistant'; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: 'resource_link'; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: 'resource'; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: 'notifications/prompts/list_changed'; + params?: NotificationParams; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: 'tools/list'; +} + +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} + +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} + +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends TaskAugmentedRequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { [key: string]: unknown }; +} + +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: 'tools/call'; + params: CallToolRequestParams; +} + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: 'notifications/tools/list_changed'; + params?: NotificationParams; +} + +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Execution-related properties for a tool. + * + * @category `tools/list` + */ +export interface ToolExecution { + /** + * Indicates whether this tool supports task-augmented execution. + * This allows clients to handle long-running operations through polling + * the task system. + * + * - "forbidden": Tool does not support task-augmented execution (default when absent) + * - "optional": Tool may support task-augmented execution + * - "required": Tool requires task-augmented execution + * + * Default: "forbidden" + */ + taskSupport?: 'forbidden' | 'optional' | 'required'; +} + +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + $schema?: string; + type: 'object'; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Execution-related properties for this tool. + */ + execution?: ToolExecution; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + * + * 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]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/* Tasks */ + +/** + * The status of a task. + * + * @category `tasks` + */ +export type TaskStatus = + | 'working' // The request is currently being processed + | 'input_required' // The task is waiting for input (e.g., elicitation or sampling) + | 'completed' // The request completed successfully and results are available + | 'failed' // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true. + | 'cancelled'; // The request was cancelled before completion + +/** + * Metadata for augmenting a request with task execution. + * Include this in the `task` field of the request parameters. + * + * @category `tasks` + */ +export interface TaskMetadata { + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl?: number; +} + +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @category `tasks` + */ +export interface RelatedTaskMetadata { + /** + * The task identifier this message is associated with. + */ + taskId: string; +} + +/** + * Data associated with a task. + * + * @category `tasks` + */ +export interface Task { + /** + * The task identifier. + */ + taskId: string; + + /** + * Current task state. + */ + status: TaskStatus; + + /** + * Optional human-readable message describing the current task state. + * This can provide context for any status, including: + * - Reasons for "cancelled" status + * - Summaries for "completed" status + * - Diagnostic information for "failed" status (e.g., error details, what went wrong) + */ + statusMessage?: string; + + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string; + + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + + /** + * Actual retention duration from creation in milliseconds, null for unlimited. + * @nullable + */ + ttl: number | null; + + /** + * Suggested polling interval in milliseconds. + */ + pollInterval?: number; +} + +/** + * A response to a task-augmented request. + * + * @category `tasks` + */ +export interface CreateTaskResult extends Result { + task: Task; +} + +/** + * A request to retrieve the state of a task. + * + * @category `tasks/get` + */ +export interface GetTaskRequest extends JSONRPCRequest { + method: 'tasks/get'; + params: { + /** + * The task identifier to query. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/get request. + * + * @category `tasks/get` + */ +export type GetTaskResult = Result & Task; + +/** + * A request to retrieve the result of a completed task. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadRequest extends JSONRPCRequest { + method: 'tasks/result'; + params: { + /** + * The task identifier to retrieve results for. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadResult extends Result { + [key: string]: unknown; +} + +/** + * A request to cancel a task. + * + * @category `tasks/cancel` + */ +export interface CancelTaskRequest extends JSONRPCRequest { + method: 'tasks/cancel'; + params: { + /** + * The task identifier to cancel. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/cancel request. + * + * @category `tasks/cancel` + */ +export type CancelTaskResult = Result & Task; + +/** + * A request to retrieve a list of tasks. + * + * @category `tasks/list` + */ +export interface ListTasksRequest extends PaginatedRequest { + method: 'tasks/list'; +} + +/** + * The response to a tasks/list request. + * + * @category `tasks/list` + */ +export interface ListTasksResult extends PaginatedResult { + tasks: Task[]; +} + +/** + * Parameters for a `notifications/tasks/status` notification. + * + * @category `notifications/tasks/status` + */ +export type TaskStatusNotificationParams = NotificationParams & Task; + +/** + * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. + * + * @category `notifications/tasks/status` + */ +export interface TaskStatusNotification extends JSONRPCNotification { + method: 'notifications/tasks/status'; + params: TaskStatusNotificationParams; +} + +/* Logging */ + +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; +} + +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: 'logging/setLevel'; + params: SetLevelRequestParams; +} + +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} + +/** + * JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: 'notifications/message'; + params: LoggingMessageNotificationParams; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency'; + +/* Sampling */ +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: 'none' | 'thisServer' | 'allServers'; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} + +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: 'auto' | 'required' | 'none'; +} + +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: 'sampling/createMessage'; + params: CreateMessageRequestParams; +} + +/** + * The client's response to a sampling/createMessage request from the server. + * The client should inform the user before returning the sampled message, to allow them + * to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: 'endTurn' | 'stopSequence' | 'maxTokens' | 'toolUse' | string; +} + +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * @category `sampling/createMessage` + */ +export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} + +/** + * @category Content + */ +export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; + +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: 'text'; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: 'image'; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: 'audio'; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: 'tool_use'; + + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + + /** + * The name of the tool to call. + */ + name: string; + + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { [key: string]: unknown }; + + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: 'tool_result'; + + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: 'completion/complete'; + params: CompleteRequestParams; +} + +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: 'ref/resource'; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: 'ref/prompt'; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: 'roots/list'; + params?: RequestParams; +} + +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: 'notifications/roots/list_changed'; + params?: NotificationParams; +} + +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode?: 'form'; + + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: 'object'; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} + +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode: 'url'; + + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} + +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; + +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: 'elicitation/create'; + params: ElicitRequestParams; +} + +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; + +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: 'string'; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: 'email' | 'uri' | 'date' | 'date-time'; + default?: string; +} + +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: 'number' | 'integer'; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} + +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: 'boolean'; + title?: string; + description?: string; + default?: boolean; +} + +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: 'string'; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} + +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: 'string'; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Combined single selection enumeration +export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; + +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: 'array'; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: 'string'; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: 'array'; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * @category `elicitation/create` + */ +// Combined multiple selection enumeration +export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; + +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: 'string'; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Union type for all enum schemas +export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; + +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: 'accept' | 'decline' | 'cancel'; + + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { [key: string]: string | number | boolean | string[] }; +} + +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: 'notifications/elicitation/complete'; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} + +/* Client messages */ +/** @internal */ +export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; + +/** @internal */ +export type ClientNotification = + | CancelledNotification + | ProgressNotification + | InitializedNotification + | RootsListChangedNotification + | TaskStatusNotification; + +/** @internal */ +export type ClientResult = + | EmptyResult + | CreateMessageResult + | ListRootsResult + | ElicitResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; + +/* Server messages */ +/** @internal */ +export type ServerRequest = + | PingRequest + | CreateMessageRequest + | ListRootsRequest + | ElicitRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; + +/** @internal */ +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification + | ElicitationCompleteNotification + | TaskStatusNotification; + +/** @internal */ +export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; diff --git a/packages/core/src/types/spec.types.ts b/packages/core/src/types/spec.types.2026-07-28.ts similarity index 75% rename from packages/core/src/types/spec.types.ts rename to packages/core/src/types/spec.types.2026-07-28.ts index a03f21f134..7305df0462 100644 --- a/packages/core/src/types/spec.types.ts +++ b/packages/core/src/types/spec.types.2026-07-28.ts @@ -3,10 +3,10 @@ * * Source: https://github.com/modelcontextprotocol/modelcontextprotocol * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 5c25208be86db5033f644a4e0d005e08f699ef3d + * Last updated from commit: 9d700ed62dcf86cb77475c9b81930611a9182f46 * * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: pnpm run fetch:spec-types + * To update this file, run: pnpm run fetch:spec-types 2026-07-28 */ /* JSON types */ /** @@ -34,7 +34,7 @@ export type JSONArray = JSONValue[]; export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse; /** @internal */ -export const LATEST_PROTOCOL_VERSION = 'DRAFT-2026-v1'; +export const LATEST_PROTOCOL_VERSION = '2026-07-28'; /** @internal */ export const JSONRPC_VERSION = '2.0'; @@ -48,7 +48,8 @@ export const JSONRPC_VERSION = '2.0'; * **Prefix:** * - Optional — if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`). * - Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`). - * - Any prefix consisting of zero or more labels, followed by `modelcontextprotocol` or `mcp`, followed by any label, is **reserved** for MCP use. For example: `modelcontextprotocol.io/`, `mcp.dev/`, `api.modelcontextprotocol.org/`, and `tools.mcp.com/` are all reserved. + * - Implementations SHOULD use reverse DNS notation (e.g., `com.example/` rather than `example.com/`). + * - Any prefix where the second label is `modelcontextprotocol` or `mcp` is **reserved** for MCP use. For example: `io.modelcontextprotocol/`, `dev.mcp/`, `org.modelcontextprotocol.api/`, and `com.mcp.tools/` are all reserved. However, `com.example.mcp/` is NOT reserved, as the second label is `example`. * * **Name:** * - Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`). @@ -71,6 +72,42 @@ export interface RequestMetaObject extends MetaObject { * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotification | notifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. */ progressToken?: ProgressToken; + /** + * The MCP Protocol Version being used for this request. Required. + * + * For the HTTP transport, this value MUST match the `MCP-Protocol-Version` + * header; otherwise the server MUST return a `400 Bad Request`. If the + * server does not support the requested version, it MUST return an + * {@link UnsupportedProtocolVersionError}. + */ + 'io.modelcontextprotocol/protocolVersion': string; + /** + * Identifies the client software making the request. Required. + * + * The {@link Implementation} schema requires `name` and `version`; other + * fields are optional. + */ + 'io.modelcontextprotocol/clientInfo': Implementation; + /** + * 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; + /** + * 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. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains in the specification for at least twelve months; see the + * deprecated features registry. + */ + 'io.modelcontextprotocol/logLevel'?: LoggingLevel; } /** @@ -87,30 +124,13 @@ export type ProgressToken = string | number; */ export type Cursor = string; -/** - * Common params for any task-augmented request. - * - * @internal - */ -export interface TaskAugmentedRequestParams extends RequestParams { - /** - * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a {@link CreateTaskResult} immediately, and the actual result can be - * retrieved later via {@link GetTaskPayloadRequest | tasks/result}. - * - * Task augmentation is subject to capability negotiation - receivers MUST declare support - * for task augmentation of specific request types in their capabilities. - */ - task?: TaskMetadata; -} - /** * Common params for any request. * * @category Common Types */ export interface RequestParams { - _meta?: RequestMetaObject; + _meta: RequestMetaObject; } /** @internal */ @@ -138,6 +158,16 @@ export interface Notification { params?: { [key: string]: any }; } +/** + * Indicates the type of a {@link Result} object, allowing the client to + * determine how to parse the response. + * + * complete - the request completed successfully and the result contains the final content. + * input_required - the request requires additional input and the result contains an {@link InputRequiredResult} object with instructions for the client to provide additional input before retrying the original request. + * @category Common Types + */ +export type ResultType = 'complete' | 'input_required' | string; + /** * Common result fields. * @@ -145,6 +175,16 @@ export interface Notification { */ export interface Result { _meta?: MetaObject; + /** + * Indicates the type of the result, which allows the client to determine + * how to parse the result object. + * + * Servers implementing this protocol version MUST include this field. + * For backward compatibility, when a client receives a result from a + * server implementing an earlier protocol version (which does not include + * `resultType`), the client MUST treat the absent field as `"complete"`. + */ + resultType: ResultType; [key: string]: unknown; } @@ -256,15 +296,14 @@ export interface InvalidRequestError extends Error { /** * A JSON-RPC error indicating that the requested method does not exist or is not available. * - * In MCP, this error is returned when a request is made for a method that requires a capability that has not been declared. This can occur in either direction: + * In MCP, a server returns this error when a client invokes a method the server does not implement — either a genuinely unknown method, or one gated behind a server capability the server did not advertise (e.g., calling `prompts/list` when the `prompts` capability was not advertised). * - * - A server returning this error when the client requests a capability it doesn't support (e.g., requesting completions when the `completions` capability was not advertised) - * - A client returning this error when the server requests a capability it doesn't support (e.g., requesting roots when the client did not declare the `roots` capability) + * A request that requires a client capability the client did not declare is signalled instead by {@link MissingRequiredClientCapabilityError} (`-32003`). * * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} * - * @example Roots not supported - * {@includeCode ./examples/MethodNotFoundError/roots-not-supported.json} + * @example Prompts not supported + * {@includeCode ./examples/MethodNotFoundError/prompts-not-supported.json} * * @category Errors */ @@ -281,7 +320,6 @@ export interface MethodNotFoundError extends Error { * - **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 * @@ -319,24 +357,68 @@ export interface InternalError extends Error { code: typeof INTERNAL_ERROR; } -// Implementation-specific JSON-RPC error codes [-32000, -32099] -/** @internal */ -export const URL_ELICITATION_REQUIRED = -32042; +/** + * Error code returned when a server requires a client capability that was + * not declared in the request's `clientCapabilities`. + * + * @category Errors + */ +export const MISSING_REQUIRED_CLIENT_CAPABILITY = -32003; /** - * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * Error code returned when the request's protocol version is not supported + * by the server. * - * @example Authorization required - * {@includeCode ./examples/URLElicitationRequiredError/authorization-required.json} + * @category Errors + */ +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 URLElicitationRequiredError extends Omit { +export interface UnsupportedProtocolVersionError extends Omit { error: Error & { - code: typeof URL_ELICITATION_REQUIRED; + code: typeof UNSUPPORTED_PROTOCOL_VERSION; data: { - elicitations: ElicitRequestURLParams[]; - [key: string]: unknown; + /** + * 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; + }; + }; +} + +/** + * Returned when processing a request requires a capability the client did not + * declare in `clientCapabilities`. For HTTP, the response status code MUST be + * `400 Bad Request`. + * + * @example Missing elicitation capability + * {@includeCode ./examples/MissingRequiredClientCapabilityError/missing-elicitation-capability.json} + * + * @category Errors + */ +export interface MissingRequiredClientCapabilityError extends Omit { + error: Error & { + code: typeof MISSING_REQUIRED_CLIENT_CAPABILITY; + data: { + /** + * The capabilities the server requires from the client to process this request. + */ + requiredCapabilities: ClientCapabilities; }; }; } @@ -349,6 +431,79 @@ export interface URLElicitationRequiredError extends Omit = T & { jsonrpc: '2.0' }; // Adds the `jsonrpc` and `id` properties to a type, to match the on-wire format of requests. type WithJSONRPCRequest = T & { jsonrpc: '2.0'; id: SDKTypes.RequestId }; -// The spec defines typed *ResultResponse interfaces (e.g. InitializeResultResponse) that pair a -// JSONRPCResultResponse envelope with a specific result type. The SDK doesn't export these because -// nothing in the SDK needs the combined type — Protocol._onresponse() unwraps the envelope and -// validates the inner result separately. We define this locally to verify the composition still -// type-checks against the spec without polluting the SDK's public API. -type TypedResultResponse = SDKTypes.JSONRPCResultResponse & { result: R }; - const sdkTypeChecks = { RequestParams: (sdk: SDKTypes.RequestParams, spec: SpecTypes.RequestParams) => { sdk = spec; @@ -40,6 +37,7 @@ const sdkTypeChecks = { spec = sdk; }, InitializeRequestParams: (sdk: SDKTypes.InitializeRequestParams, spec: SpecTypes.InitializeRequestParams) => { + // @ts-expect-error 2025-11-25 types capabilities.experimental values as `object`; the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; spec = sdk; }, @@ -90,7 +88,9 @@ const sdkTypeChecks = { spec = sdk; }, CreateMessageRequestParams: (sdk: SDKTypes.CreateMessageRequestParams, spec: SpecTypes.CreateMessageRequestParams) => { + // @ts-expect-error 2025-11-25 types `metadata` as `object`; the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; + // @ts-expect-error the SDK's JSONValue-typed tool inputSchema properties are not assignable to 2025-11-25's `object` spec = sdk; }, CompleteRequestParams: (sdk: SDKTypes.CompleteRequestParams, spec: SpecTypes.CompleteRequestParams) => { @@ -245,7 +245,9 @@ const sdkTypeChecks = { spec = sdk; }, Tool: (sdk: SDKTypes.Tool, spec: SpecTypes.Tool) => { + // @ts-expect-error 2025-11-25 types inputSchema/outputSchema properties as `object`; the SDK follows the 2026-07-28 schema's JSONValue sdk = spec; + // @ts-expect-error the SDK's JSONValue-typed inputSchema/outputSchema properties are not assignable to 2025-11-25's `object` spec = sdk; }, ListToolsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListToolsRequest) => { @@ -253,7 +255,9 @@ const sdkTypeChecks = { spec = sdk; }, ListToolsResult: (sdk: SDKTypes.ListToolsResult, spec: SpecTypes.ListToolsResult) => { + // @ts-expect-error 2025-11-25 vs 2026-07-28 Tool typing; see the Tool check above sdk = spec; + // @ts-expect-error 2025-11-25 vs 2026-07-28 Tool typing; see the Tool check above spec = sdk; }, CallToolResult: (sdk: SDKTypes.CallToolResult, spec: SpecTypes.CallToolResult) => { @@ -473,31 +477,40 @@ const sdkTypeChecks = { spec = sdk; }, CreateMessageRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CreateMessageRequest) => { + // @ts-expect-error 2025-11-25 vs 2026-07-28 typing of params metadata/tools; see the CreateMessageRequestParams check above sdk = spec; + // @ts-expect-error 2025-11-25 vs 2026-07-28 typing of params metadata/tools; see the CreateMessageRequestParams check above spec = sdk; }, InitializeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.InitializeRequest) => { + // @ts-expect-error 2025-11-25 types capabilities.experimental values as `object`; the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; spec = sdk; }, InitializeResult: (sdk: SDKTypes.InitializeResult, spec: SpecTypes.InitializeResult) => { + // @ts-expect-error 2025-11-25 types capabilities.experimental values as `object`; the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; spec = sdk; }, ClientCapabilities: (sdk: SDKTypes.ClientCapabilities, spec: SpecTypes.ClientCapabilities) => { + // @ts-expect-error 2025-11-25 types experimental/sampling/elicitation/tasks blobs as `object`; the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; spec = sdk; }, ServerCapabilities: (sdk: SDKTypes.ServerCapabilities, spec: SpecTypes.ServerCapabilities) => { + // @ts-expect-error 2025-11-25 types experimental/logging/completions/tasks blobs as `object`; the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; spec = sdk; }, ClientRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ClientRequest) => { + // @ts-expect-error 2025-11-25 types capabilities.experimental values as `object` (via the InitializeRequest member); the SDK follows the 2026-07-28 schema's JSONObject sdk = spec; spec = sdk; }, ServerRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ServerRequest) => { + // @ts-expect-error 2025-11-25 vs 2026-07-28 typing of CreateMessageRequest params; see the CreateMessageRequestParams check above sdk = spec; + // @ts-expect-error 2025-11-25 vs 2026-07-28 typing of CreateMessageRequest params; see the CreateMessageRequestParams check above spec = sdk; }, LoggingMessageNotification: (sdk: WithJSONRPC, spec: SpecTypes.LoggingMessageNotification) => { @@ -552,10 +565,6 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - TaskAugmentedRequestParams: (sdk: SDKTypes.TaskAugmentedRequestParams, spec: SpecTypes.TaskAugmentedRequestParams) => { - sdk = spec; - spec = sdk; - }, ToolExecution: (sdk: SDKTypes.ToolExecution, spec: SpecTypes.ToolExecution) => { sdk = spec; spec = sdk; @@ -572,35 +581,15 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - Task: (sdk: SDKTypes.Task, spec: SpecTypes.Task) => { - sdk = spec; - spec = sdk; - }, - CreateTaskResult: (sdk: SDKTypes.CreateTaskResult, spec: SpecTypes.CreateTaskResult) => { - sdk = spec; - spec = sdk; - }, - GetTaskResult: (sdk: SDKTypes.GetTaskResult, spec: SpecTypes.GetTaskResult) => { - sdk = spec; - spec = sdk; - }, - GetTaskPayloadRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetTaskPayloadRequest) => { - sdk = spec; - spec = sdk; - }, - ListTasksRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListTasksRequest) => { - sdk = spec; - spec = sdk; - }, - ListTasksResult: (sdk: SDKTypes.ListTasksResult, spec: SpecTypes.ListTasksResult) => { + TaskAugmentedRequestParams: (sdk: SDKTypes.TaskAugmentedRequestParams, spec: SpecTypes.TaskAugmentedRequestParams) => { sdk = spec; spec = sdk; }, - CancelTaskRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CancelTaskRequest) => { + Task: (sdk: SDKTypes.Task, spec: SpecTypes.Task) => { sdk = spec; spec = sdk; }, - CancelTaskResult: (sdk: SDKTypes.CancelTaskResult, spec: SpecTypes.CancelTaskResult) => { + CreateTaskResult: (sdk: SDKTypes.CreateTaskResult, spec: SpecTypes.CreateTaskResult) => { sdk = spec; spec = sdk; }, @@ -608,156 +597,39 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - GetTaskPayloadResult: (sdk: SDKTypes.GetTaskPayloadResult, spec: SpecTypes.GetTaskPayloadResult) => { - sdk = spec; - spec = sdk; - }, - TaskStatusNotificationParams: (sdk: SDKTypes.TaskStatusNotificationParams, spec: SpecTypes.TaskStatusNotificationParams) => { - sdk = spec; - spec = sdk; - }, - TaskStatusNotification: (sdk: WithJSONRPC, spec: SpecTypes.TaskStatusNotification) => { - sdk = spec; - spec = sdk; - }, - - /* JSON primitives */ - JSONValue: (sdk: SDKTypes.JSONValue, spec: SpecTypes.JSONValue) => { - sdk = spec; - spec = sdk; - }, - JSONObject: (sdk: SDKTypes.JSONObject, spec: SpecTypes.JSONObject) => { - sdk = spec; - spec = sdk; - }, - JSONArray: (sdk: SDKTypes.JSONArray, spec: SpecTypes.JSONArray) => { - sdk = spec; - spec = sdk; - }, - - /* Meta types */ - MetaObject: (sdk: SDKTypes.MetaObject, spec: SpecTypes.MetaObject) => { - sdk = spec; - spec = sdk; - }, - RequestMetaObject: (sdk: SDKTypes.RequestMetaObject, spec: SpecTypes.RequestMetaObject) => { - sdk = spec; - spec = sdk; - }, - - /* Error types */ - ParseError: (sdk: SDKTypes.ParseError, spec: SpecTypes.ParseError) => { - sdk = spec; - spec = sdk; - }, - InvalidRequestError: (sdk: SDKTypes.InvalidRequestError, spec: SpecTypes.InvalidRequestError) => { - sdk = spec; - spec = sdk; - }, - MethodNotFoundError: (sdk: SDKTypes.MethodNotFoundError, spec: SpecTypes.MethodNotFoundError) => { - sdk = spec; - spec = sdk; - }, - InvalidParamsError: (sdk: SDKTypes.InvalidParamsError, spec: SpecTypes.InvalidParamsError) => { - sdk = spec; - spec = sdk; - }, - InternalError: (sdk: SDKTypes.InternalError, spec: SpecTypes.InternalError) => { - sdk = spec; - spec = sdk; - }, - - /* ResultResponse types — see TypedResultResponse comment above */ - InitializeResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.InitializeResultResponse) => { - sdk = spec; - spec = sdk; - }, - PingResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.PingResultResponse) => { - sdk = spec; - spec = sdk; - }, - ListResourcesResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ListResourcesResultResponse) => { - sdk = spec; - spec = sdk; - }, - ListResourceTemplatesResultResponse: ( - sdk: TypedResultResponse, - spec: SpecTypes.ListResourceTemplatesResultResponse - ) => { - sdk = spec; - spec = sdk; - }, - ReadResourceResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ReadResourceResultResponse) => { - sdk = spec; - spec = sdk; - }, - SubscribeResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.SubscribeResultResponse) => { - sdk = spec; - spec = sdk; - }, - UnsubscribeResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.UnsubscribeResultResponse) => { - sdk = spec; - spec = sdk; - }, - ListPromptsResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ListPromptsResultResponse) => { - sdk = spec; - spec = sdk; - }, - GetPromptResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.GetPromptResultResponse) => { - sdk = spec; - spec = sdk; - }, - ListToolsResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ListToolsResultResponse) => { - sdk = spec; - spec = sdk; - }, - CallToolResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.CallToolResultResponse) => { - sdk = spec; - spec = sdk; - }, - CreateTaskResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.CreateTaskResultResponse) => { - sdk = spec; - spec = sdk; - }, - GetTaskResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.GetTaskResultResponse) => { + GetTaskResult: (sdk: SDKTypes.GetTaskResult, spec: SpecTypes.GetTaskResult) => { sdk = spec; spec = sdk; }, - GetTaskPayloadResultResponse: ( - sdk: TypedResultResponse, - spec: SpecTypes.GetTaskPayloadResultResponse - ) => { + GetTaskPayloadRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetTaskPayloadRequest) => { sdk = spec; spec = sdk; }, - CancelTaskResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.CancelTaskResultResponse) => { + GetTaskPayloadResult: (sdk: SDKTypes.GetTaskPayloadResult, spec: SpecTypes.GetTaskPayloadResult) => { sdk = spec; spec = sdk; }, - ListTasksResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ListTasksResultResponse) => { + ListTasksRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListTasksRequest) => { sdk = spec; spec = sdk; }, - SetLevelResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.SetLevelResultResponse) => { + ListTasksResult: (sdk: SDKTypes.ListTasksResult, spec: SpecTypes.ListTasksResult) => { sdk = spec; spec = sdk; }, - CreateMessageResultResponse: ( - sdk: TypedResultResponse, - spec: SpecTypes.CreateMessageResultResponse - ) => { + CancelTaskRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CancelTaskRequest) => { sdk = spec; spec = sdk; }, - CompleteResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.CompleteResultResponse) => { + CancelTaskResult: (sdk: SDKTypes.CancelTaskResult, spec: SpecTypes.CancelTaskResult) => { sdk = spec; spec = sdk; }, - ListRootsResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ListRootsResultResponse) => { + TaskStatusNotificationParams: (sdk: SDKTypes.TaskStatusNotificationParams, spec: SpecTypes.TaskStatusNotificationParams) => { sdk = spec; spec = sdk; }, - ElicitResultResponse: (sdk: TypedResultResponse, spec: SpecTypes.ElicitResultResponse) => { + TaskStatusNotification: (sdk: WithJSONRPC, spec: SpecTypes.TaskStatusNotification) => { sdk = spec; spec = sdk; } @@ -791,7 +663,7 @@ type AssertExactKeys< type Assert = T; /* - * Excluded from key-level assertions (23 entries): + * Excluded from key-level assertions (21 entries): * * Union types — KnownKeys cannot meaningfully enumerate their members (15): * ClientRequest, ServerRequest, ClientNotification, ServerNotification, @@ -799,12 +671,11 @@ type Assert = T; * SamplingMessageContentBlock, ElicitRequestParams, PrimitiveSchemaDefinition, * SingleSelectEnumSchema, MultiSelectEnumSchema, EnumSchema * - * Primitive type aliases — no object keys to compare (8): - * JSONValue, JSONArray, Role, LoggingLevel, ProgressToken, RequestId, - * Cursor, TaskStatus + * Primitive type aliases — no object keys to compare (6): + * Role, LoggingLevel, ProgressToken, RequestId, Cursor, TaskStatus */ -// -- Simple types (96) -- +// -- Simple types (88) -- type _K_RequestParams = Assert>; type _K_NotificationParams = Assert>; @@ -884,7 +755,9 @@ type _K_LegacyTitledEnumSchema = Assert>; type _K_JSONRPCResultResponse = Assert>; type _K_InitializeResult = Assert>; +// @ts-expect-error SDK follows the 2026-07-28 schema's `extensions` capability key; not in released 2025-11-25 type _K_ClientCapabilities = Assert>; +// @ts-expect-error SDK follows the 2026-07-28 schema's `extensions` capability key; not in released 2025-11-25 type _K_ServerCapabilities = Assert>; type _K_SamplingMessage = Assert>; type _K_Icon = Assert>; @@ -895,28 +768,19 @@ type _K_ToolChoice = Assert>; type _K_ToolResultContent = Assert>; type _K_Annotations = Assert>; -type _K_TaskAugmentedRequestParams = Assert>; type _K_ToolExecution = Assert>; type _K_TaskMetadata = Assert>; type _K_RelatedTaskMetadata = Assert>; +type _K_TaskAugmentedRequestParams = Assert>; type _K_Task = Assert>; type _K_CreateTaskResult = Assert>; type _K_GetTaskResult = Assert>; +type _K_GetTaskPayloadResult = Assert>; type _K_ListTasksResult = Assert>; type _K_CancelTaskResult = Assert>; -type _K_GetTaskPayloadResult = Assert>; type _K_TaskStatusNotificationParams = Assert< AssertExactKeys >; -type _K_JSONObject = Assert>; -type _K_MetaObject = Assert>; -// @ts-expect-error Genuine mismatch: SDK RequestMetaObject has extra 'io.modelcontextprotocol/related-task' not in spec -type _K_RequestMetaObject = Assert>; -type _K_ParseError = Assert>; -type _K_InvalidRequestError = Assert>; -type _K_MethodNotFoundError = Assert>; -type _K_InvalidParamsError = Assert>; -type _K_InternalError = Assert>; // -- WithJSONRPC-wrapped notification types (11) -- // SDK notification types do not include `jsonrpc` — the spec types do. We wrap @@ -971,57 +835,12 @@ type _K_ListPromptsRequest = Assert, SpecTypes.GetPromptRequest>>; type _K_CreateMessageRequest = Assert, SpecTypes.CreateMessageRequest>>; type _K_InitializeRequest = Assert, SpecTypes.InitializeRequest>>; +type _K_GetTaskRequest = Assert, SpecTypes.GetTaskRequest>>; type _K_GetTaskPayloadRequest = Assert< AssertExactKeys, SpecTypes.GetTaskPayloadRequest> >; type _K_ListTasksRequest = Assert, SpecTypes.ListTasksRequest>>; type _K_CancelTaskRequest = Assert, SpecTypes.CancelTaskRequest>>; -type _K_GetTaskRequest = Assert, SpecTypes.GetTaskRequest>>; - -// -- TypedResultResponse-wrapped types (21) -- -// The spec defines typed *ResultResponse interfaces that pair JSONRPCResultResponse -// with a specific result. We compare TypedResultResponse against the -// spec's combined type. - -type _K_InitializeResultResponse = Assert< - AssertExactKeys, SpecTypes.InitializeResultResponse> ->; -type _K_PingResultResponse = Assert, SpecTypes.PingResultResponse>>; -type _K_ListResourcesResultResponse = Assert< - AssertExactKeys, SpecTypes.ListResourcesResultResponse> ->; -type _K_ListResourceTemplatesResultResponse = Assert< - AssertExactKeys, SpecTypes.ListResourceTemplatesResultResponse> ->; -type _K_ReadResourceResultResponse = Assert< - AssertExactKeys, SpecTypes.ReadResourceResultResponse> ->; -type _K_SubscribeResultResponse = Assert, SpecTypes.SubscribeResultResponse>>; -type _K_UnsubscribeResultResponse = Assert, SpecTypes.UnsubscribeResultResponse>>; -type _K_ListPromptsResultResponse = Assert< - AssertExactKeys, SpecTypes.ListPromptsResultResponse> ->; -type _K_GetPromptResultResponse = Assert, SpecTypes.GetPromptResultResponse>>; -type _K_ListToolsResultResponse = Assert, SpecTypes.ListToolsResultResponse>>; -type _K_CallToolResultResponse = Assert, SpecTypes.CallToolResultResponse>>; -type _K_CreateTaskResultResponse = Assert< - AssertExactKeys, SpecTypes.CreateTaskResultResponse> ->; -type _K_GetTaskResultResponse = Assert, SpecTypes.GetTaskResultResponse>>; -type _K_GetTaskPayloadResultResponse = Assert< - AssertExactKeys, SpecTypes.GetTaskPayloadResultResponse> ->; -type _K_CancelTaskResultResponse = Assert< - AssertExactKeys, SpecTypes.CancelTaskResultResponse> ->; -type _K_ListTasksResultResponse = Assert, SpecTypes.ListTasksResultResponse>>; -type _K_SetLevelResultResponse = Assert, SpecTypes.SetLevelResultResponse>>; -type _K_CreateMessageResultResponse = Assert< - AssertExactKeys, SpecTypes.CreateMessageResultResponse> ->; -type _K_CompleteResultResponse = Assert, SpecTypes.CompleteResultResponse>>; -type _K_ListRootsResultResponse = Assert, SpecTypes.ListRootsResultResponse>>; -type _K_ElicitResultResponse = Assert, SpecTypes.ElicitResultResponse>>; // -- Name mismatches (2) -- // SDK exports these under different names than the spec. @@ -1048,9 +867,7 @@ const KEY_PARITY_EXCLUDED = [ 'SingleSelectEnumSchema', 'MultiSelectEnumSchema', 'EnumSchema', - // Primitive aliases (8) - 'JSONValue', - 'JSONArray', + // Primitive aliases (6) 'Role', 'LoggingLevel', 'ProgressToken', @@ -1059,8 +876,8 @@ const KEY_PARITY_EXCLUDED = [ 'TaskStatus' ]; -// This file is .gitignore'd, and fetched by `npm run fetch:spec-types` (called by `npm run test`) -const SPEC_TYPES_FILE = path.resolve(__dirname, '../src/types/spec.types.ts'); +// Generated from the frozen 2025-11-25 release schema by `pnpm run fetch:spec-types 2025-11-25`. +const SPEC_TYPES_FILE = path.resolve(__dirname, '../src/types/spec.types.2025-11-25.ts'); const SDK_TYPES_FILE = path.resolve(__dirname, '../src/types/types.ts'); const MISSING_SDK_TYPES = [ @@ -1078,7 +895,7 @@ function extractKeyParityTypes(source: string): string[] { return [...source.matchAll(/^type _K_(\w+)\s*=/gm)].map(m => m[1]!); } -describe('Spec Types', () => { +describe('Spec Types (2025-11-25)', () => { const specTypes = extractExportedTypes(fs.readFileSync(SPEC_TYPES_FILE, 'utf8')); const sdkTypes = extractExportedTypes(fs.readFileSync(SDK_TYPES_FILE, 'utf8')); const typesToCheck = specTypes.filter(type => !MISSING_SDK_TYPES.includes(type)); @@ -1086,7 +903,7 @@ describe('Spec Types', () => { it('should define some expected types', () => { expect(specTypes).toContain('JSONRPCNotification'); expect(specTypes).toContain('ElicitResult'); - expect(specTypes).toHaveLength(176); + expect(specTypes).toHaveLength(145); }); it('should have up to date list of missing sdk types', () => { diff --git a/packages/core/test/spec.types.2026-07-28.test.ts b/packages/core/test/spec.types.2026-07-28.test.ts new file mode 100644 index 0000000000..0a8c418c97 --- /dev/null +++ b/packages/core/test/spec.types.2026-07-28.test.ts @@ -0,0 +1,508 @@ +/** + * Compares the SDK's types against the upcoming 2026-07-28 schema (spec.types.2026-07-28.ts). + * The frozen-release comparison lives in spec.types.2025-11-25.test.ts. + * + * The SDK does not implement the 2026-07-28 surface yet: every 2026-07-28 type whose shape the SDK + * does not (yet) match is listed in MISSING_SDK_TYPES_2026_07_28 below. Removing a name from + * that list forces a real mutual-assignability check to be added to sdkTypeChecks (the + * completeness tests below fail otherwise) — implementation work burns the list down. + * + * Unlike MISSING_SDK_TYPES in the 2025-11-25 comparison, names in this list may well + * exist in the SDK (e.g. RequestParams) — they are listed because the 2026-07-28 revision changed + * their shape, not necessarily because the SDK lacks them. + */ +import fs from 'node:fs'; +import path from 'node:path'; + +import { + LATEST_PROTOCOL_VERSION, + MISSING_REQUIRED_CLIENT_CAPABILITY, + UNSUPPORTED_PROTOCOL_VERSION +} from '../src/types/spec.types.2026-07-28.js'; +import type * as SpecTypes from '../src/types/spec.types.2026-07-28.js'; +import type * as SDKTypes from '../src/types/index.js'; + +/* eslint-disable @typescript-eslint/no-unused-vars */ + +// Adds the `jsonrpc` property to a type, to match the on-wire format of notifications. +type WithJSONRPC = T & { jsonrpc: '2.0' }; + +// Adds the `jsonrpc` and `id` properties to a type, to match the on-wire format of requests. +type WithJSONRPCRequest = T & { jsonrpc: '2.0'; id: SDKTypes.RequestId }; + +const sdkTypeChecks = { + JSONValue: (sdk: SDKTypes.JSONValue, spec: SpecTypes.JSONValue) => { + sdk = spec; + spec = sdk; + }, + JSONObject: (sdk: SDKTypes.JSONObject, spec: SpecTypes.JSONObject) => { + sdk = spec; + spec = sdk; + }, + JSONArray: (sdk: SDKTypes.JSONArray, spec: SpecTypes.JSONArray) => { + sdk = spec; + spec = sdk; + }, + MetaObject: (sdk: SDKTypes.MetaObject, spec: SpecTypes.MetaObject) => { + sdk = spec; + spec = sdk; + }, + ProgressToken: (sdk: SDKTypes.ProgressToken, spec: SpecTypes.ProgressToken) => { + sdk = spec; + spec = sdk; + }, + Cursor: (sdk: SDKTypes.Cursor, spec: SpecTypes.Cursor) => { + sdk = spec; + spec = sdk; + }, + Request: (sdk: SDKTypes.Request, spec: SpecTypes.Request) => { + sdk = spec; + spec = sdk; + }, + NotificationParams: (sdk: SDKTypes.NotificationParams, spec: SpecTypes.NotificationParams) => { + sdk = spec; + spec = sdk; + }, + RequestId: (sdk: SDKTypes.RequestId, spec: SpecTypes.RequestId) => { + sdk = spec; + spec = sdk; + }, + JSONRPCRequest: (sdk: SDKTypes.JSONRPCRequest, spec: SpecTypes.JSONRPCRequest) => { + sdk = spec; + spec = sdk; + }, + JSONRPCNotification: (sdk: WithJSONRPC, spec: SpecTypes.JSONRPCNotification) => { + sdk = spec; + spec = sdk; + }, + JSONRPCErrorResponse: (sdk: SDKTypes.JSONRPCErrorResponse, spec: SpecTypes.JSONRPCErrorResponse) => { + sdk = spec; + spec = sdk; + }, + ParseError: (sdk: SDKTypes.ParseError, spec: SpecTypes.ParseError) => { + sdk = spec; + spec = sdk; + }, + InvalidRequestError: (sdk: SDKTypes.InvalidRequestError, spec: SpecTypes.InvalidRequestError) => { + sdk = spec; + spec = sdk; + }, + MethodNotFoundError: (sdk: SDKTypes.MethodNotFoundError, spec: SpecTypes.MethodNotFoundError) => { + sdk = spec; + spec = sdk; + }, + InvalidParamsError: (sdk: SDKTypes.InvalidParamsError, spec: SpecTypes.InvalidParamsError) => { + sdk = spec; + spec = sdk; + }, + InternalError: (sdk: SDKTypes.InternalError, spec: SpecTypes.InternalError) => { + sdk = spec; + spec = sdk; + }, + CancelledNotificationParams: (sdk: SDKTypes.CancelledNotificationParams, spec: SpecTypes.CancelledNotificationParams) => { + sdk = spec; + spec = sdk; + }, + CancelledNotification: (sdk: WithJSONRPC, spec: SpecTypes.CancelledNotification) => { + sdk = spec; + spec = sdk; + }, + ClientCapabilities: (sdk: SDKTypes.ClientCapabilities, spec: SpecTypes.ClientCapabilities) => { + sdk = spec; + spec = sdk; + }, + ServerCapabilities: (sdk: SDKTypes.ServerCapabilities, spec: SpecTypes.ServerCapabilities) => { + sdk = spec; + spec = sdk; + }, + Icon: (sdk: SDKTypes.Icon, spec: SpecTypes.Icon) => { + sdk = spec; + spec = sdk; + }, + Icons: (sdk: SDKTypes.Icons, spec: SpecTypes.Icons) => { + sdk = spec; + spec = sdk; + }, + BaseMetadata: (sdk: SDKTypes.BaseMetadata, spec: SpecTypes.BaseMetadata) => { + sdk = spec; + spec = sdk; + }, + Implementation: (sdk: SDKTypes.Implementation, spec: SpecTypes.Implementation) => { + sdk = spec; + spec = sdk; + }, + ProgressNotificationParams: (sdk: SDKTypes.ProgressNotificationParams, spec: SpecTypes.ProgressNotificationParams) => { + sdk = spec; + spec = sdk; + }, + ProgressNotification: (sdk: WithJSONRPC, spec: SpecTypes.ProgressNotification) => { + sdk = spec; + spec = sdk; + }, + ResourceListChangedNotification: ( + sdk: WithJSONRPC, + spec: SpecTypes.ResourceListChangedNotification + ) => { + sdk = spec; + spec = sdk; + }, + ResourceUpdatedNotificationParams: ( + sdk: SDKTypes.ResourceUpdatedNotificationParams, + spec: SpecTypes.ResourceUpdatedNotificationParams + ) => { + sdk = spec; + spec = sdk; + }, + ResourceUpdatedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ResourceUpdatedNotification) => { + sdk = spec; + spec = sdk; + }, + Resource: (sdk: SDKTypes.Resource, spec: SpecTypes.Resource) => { + sdk = spec; + spec = sdk; + }, + ResourceTemplate: (sdk: SDKTypes.ResourceTemplateType, spec: SpecTypes.ResourceTemplate) => { + sdk = spec; + spec = sdk; + }, + ResourceContents: (sdk: SDKTypes.ResourceContents, spec: SpecTypes.ResourceContents) => { + sdk = spec; + spec = sdk; + }, + TextResourceContents: (sdk: SDKTypes.TextResourceContents, spec: SpecTypes.TextResourceContents) => { + sdk = spec; + spec = sdk; + }, + BlobResourceContents: (sdk: SDKTypes.BlobResourceContents, spec: SpecTypes.BlobResourceContents) => { + sdk = spec; + spec = sdk; + }, + Prompt: (sdk: SDKTypes.Prompt, spec: SpecTypes.Prompt) => { + sdk = spec; + spec = sdk; + }, + PromptArgument: (sdk: SDKTypes.PromptArgument, spec: SpecTypes.PromptArgument) => { + sdk = spec; + spec = sdk; + }, + Role: (sdk: SDKTypes.Role, spec: SpecTypes.Role) => { + sdk = spec; + spec = sdk; + }, + PromptMessage: (sdk: SDKTypes.PromptMessage, spec: SpecTypes.PromptMessage) => { + sdk = spec; + spec = sdk; + }, + ResourceLink: (sdk: SDKTypes.ResourceLink, spec: SpecTypes.ResourceLink) => { + sdk = spec; + spec = sdk; + }, + EmbeddedResource: (sdk: SDKTypes.EmbeddedResource, spec: SpecTypes.EmbeddedResource) => { + sdk = spec; + spec = sdk; + }, + PromptListChangedNotification: ( + sdk: WithJSONRPC, + spec: SpecTypes.PromptListChangedNotification + ) => { + sdk = spec; + spec = sdk; + }, + ToolListChangedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ToolListChangedNotification) => { + sdk = spec; + spec = sdk; + }, + ToolAnnotations: (sdk: SDKTypes.ToolAnnotations, spec: SpecTypes.ToolAnnotations) => { + sdk = spec; + spec = sdk; + }, + LoggingMessageNotificationParams: ( + sdk: SDKTypes.LoggingMessageNotificationParams, + spec: SpecTypes.LoggingMessageNotificationParams + ) => { + sdk = spec; + spec = sdk; + }, + LoggingMessageNotification: (sdk: WithJSONRPC, spec: SpecTypes.LoggingMessageNotification) => { + sdk = spec; + spec = sdk; + }, + LoggingLevel: (sdk: SDKTypes.LoggingLevel, spec: SpecTypes.LoggingLevel) => { + sdk = spec; + spec = sdk; + }, + ToolChoice: (sdk: SDKTypes.ToolChoice, spec: SpecTypes.ToolChoice) => { + sdk = spec; + spec = sdk; + }, + Annotations: (sdk: SDKTypes.Annotations, spec: SpecTypes.Annotations) => { + sdk = spec; + spec = sdk; + }, + ContentBlock: (sdk: SDKTypes.ContentBlock, spec: SpecTypes.ContentBlock) => { + sdk = spec; + spec = sdk; + }, + TextContent: (sdk: SDKTypes.TextContent, spec: SpecTypes.TextContent) => { + sdk = spec; + spec = sdk; + }, + ImageContent: (sdk: SDKTypes.ImageContent, spec: SpecTypes.ImageContent) => { + sdk = spec; + spec = sdk; + }, + AudioContent: (sdk: SDKTypes.AudioContent, spec: SpecTypes.AudioContent) => { + sdk = spec; + spec = sdk; + }, + ToolUseContent: (sdk: SDKTypes.ToolUseContent, spec: SpecTypes.ToolUseContent) => { + sdk = spec; + spec = sdk; + }, + ModelPreferences: (sdk: SDKTypes.ModelPreferences, spec: SpecTypes.ModelPreferences) => { + sdk = spec; + spec = sdk; + }, + ModelHint: (sdk: SDKTypes.ModelHint, spec: SpecTypes.ModelHint) => { + sdk = spec; + spec = sdk; + }, + ResourceTemplateReference: (sdk: SDKTypes.ResourceTemplateReference, spec: SpecTypes.ResourceTemplateReference) => { + sdk = spec; + spec = sdk; + }, + PromptReference: (sdk: SDKTypes.PromptReference, spec: SpecTypes.PromptReference) => { + sdk = spec; + spec = sdk; + }, + Root: (sdk: SDKTypes.Root, spec: SpecTypes.Root) => { + sdk = spec; + spec = sdk; + }, + ElicitRequestFormParams: (sdk: SDKTypes.ElicitRequestFormParams, spec: SpecTypes.ElicitRequestFormParams) => { + sdk = spec; + spec = sdk; + }, + ElicitRequestURLParams: (sdk: SDKTypes.ElicitRequestURLParams, spec: SpecTypes.ElicitRequestURLParams) => { + sdk = spec; + spec = sdk; + }, + ElicitRequestParams: (sdk: SDKTypes.ElicitRequestParams, spec: SpecTypes.ElicitRequestParams) => { + sdk = spec; + spec = sdk; + }, + ElicitRequest: (sdk: SDKTypes.ElicitRequest, spec: SpecTypes.ElicitRequest) => { + sdk = spec; + spec = sdk; + }, + PrimitiveSchemaDefinition: (sdk: SDKTypes.PrimitiveSchemaDefinition, spec: SpecTypes.PrimitiveSchemaDefinition) => { + sdk = spec; + spec = sdk; + }, + StringSchema: (sdk: SDKTypes.StringSchema, spec: SpecTypes.StringSchema) => { + sdk = spec; + spec = sdk; + }, + NumberSchema: (sdk: SDKTypes.NumberSchema, spec: SpecTypes.NumberSchema) => { + sdk = spec; + spec = sdk; + }, + BooleanSchema: (sdk: SDKTypes.BooleanSchema, spec: SpecTypes.BooleanSchema) => { + sdk = spec; + spec = sdk; + }, + UntitledSingleSelectEnumSchema: (sdk: SDKTypes.UntitledSingleSelectEnumSchema, spec: SpecTypes.UntitledSingleSelectEnumSchema) => { + sdk = spec; + spec = sdk; + }, + TitledSingleSelectEnumSchema: (sdk: SDKTypes.TitledSingleSelectEnumSchema, spec: SpecTypes.TitledSingleSelectEnumSchema) => { + sdk = spec; + spec = sdk; + }, + SingleSelectEnumSchema: (sdk: SDKTypes.SingleSelectEnumSchema, spec: SpecTypes.SingleSelectEnumSchema) => { + sdk = spec; + spec = sdk; + }, + UntitledMultiSelectEnumSchema: (sdk: SDKTypes.UntitledMultiSelectEnumSchema, spec: SpecTypes.UntitledMultiSelectEnumSchema) => { + sdk = spec; + spec = sdk; + }, + TitledMultiSelectEnumSchema: (sdk: SDKTypes.TitledMultiSelectEnumSchema, spec: SpecTypes.TitledMultiSelectEnumSchema) => { + sdk = spec; + spec = sdk; + }, + MultiSelectEnumSchema: (sdk: SDKTypes.MultiSelectEnumSchema, spec: SpecTypes.MultiSelectEnumSchema) => { + sdk = spec; + spec = sdk; + }, + LegacyTitledEnumSchema: (sdk: SDKTypes.LegacyTitledEnumSchema, spec: SpecTypes.LegacyTitledEnumSchema) => { + sdk = spec; + spec = sdk; + }, + EnumSchema: (sdk: SDKTypes.EnumSchema, spec: SpecTypes.EnumSchema) => { + sdk = spec; + spec = sdk; + }, + ElicitationCompleteNotification: ( + sdk: WithJSONRPC, + spec: SpecTypes.ElicitationCompleteNotification + ) => { + sdk = spec; + spec = sdk; + }, + ClientNotification: (sdk: WithJSONRPC, spec: SpecTypes.ClientNotification) => { + sdk = spec; + spec = sdk; + } +}; + +// Generated from the 2026-07-28 schema by `pnpm run fetch:spec-types 2026-07-28 `. +const SPEC_TYPES_FILE = path.resolve(__dirname, '../src/types/spec.types.2026-07-28.ts'); + +/** + * 2026-07-28 spec types the SDK does not match yet. Spec-implementation work for the + * 2026-07-28 release removes entries from this list as the SDK adopts each shape. + */ +const MISSING_SDK_TYPES_2026_07_28 = [ + // Inlined in the SDK (same as the 2025-11-25 comparison): + 'Error', // The inner error object of a JSONRPCError + + // SEP-2260 per-request envelope: 2026-07-28 requests carry a required `_meta` envelope + // (`io.modelcontextprotocol/protocolVersion`, clientInfo, clientCapabilities); the SDK + // still implements the 2025-11-25 request shapes. + 'RequestParams', + 'RequestMetaObject', + 'PaginatedRequestParams', + 'ResourceRequestParams', + 'CallToolRequestParams', + 'CompleteRequestParams', + 'GetPromptRequestParams', + 'ReadResourceRequestParams', + 'CreateMessageRequestParams', + 'PaginatedRequest', + 'CallToolRequest', + 'CompleteRequest', + 'GetPromptRequest', + 'ListPromptsRequest', + 'ListResourceTemplatesRequest', + 'ListResourcesRequest', + 'ListRootsRequest', + 'ListToolsRequest', + 'ReadResourceRequest', + 'CreateMessageRequest', + 'ClientRequest', + + // SEP-2322 (MRTR): 2026-07-28 results carry a required `resultType` discriminator; the SDK + // still implements the 2025-11-25 result shapes. + 'Result', + 'EmptyResult', + 'PaginatedResult', + 'CallToolResult', + 'CompleteResult', + 'ElicitResult', + 'GetPromptResult', + 'ListPromptsResult', + 'ListResourceTemplatesResult', + 'ListResourcesResult', + 'ListRootsResult', + 'ListToolsResult', + 'ReadResourceResult', + 'CreateMessageResult', + 'ClientResult', + 'ServerResult', + 'ResultType', + 'CacheableResult', + + // Response envelopes embedding the changed Result shape: + 'JSONRPCResultResponse', + 'JSONRPCResponse', + 'JSONRPCMessage', + 'CallToolResultResponse', + 'CompleteResultResponse', + 'GetPromptResultResponse', + 'ListPromptsResultResponse', + 'ListResourceTemplatesResultResponse', + 'ListResourcesResultResponse', + 'ListToolsResultResponse', + 'ReadResourceResultResponse', + + // SEP-2575 sessionless discovery (new surface): + 'DiscoverRequest', + 'DiscoverResult', + 'DiscoverResultResponse', + + // SEP-2567 input requests/responses (new surface): + 'InputRequest', + 'InputRequests', + 'InputRequiredResult', + 'InputResponse', + 'InputResponseRequestParams', + 'InputResponses', + + // 2026-07-28 subscriptions surface (new): + 'SubscriptionFilter', + 'SubscriptionsAcknowledgedNotification', + 'SubscriptionsAcknowledgedNotificationParams', + 'SubscriptionsListenRequest', + 'SubscriptionsListenRequestParams', + + // New typed protocol errors (-32003 / -32004): + 'MissingRequiredClientCapabilityError', + 'UnsupportedProtocolVersionError', + + // Other shapes changed in the 2026-07-28 schema (sampling content, open tool schemas, + // loosened Notification.params, server notification union): + 'SamplingMessage', + 'SamplingMessageContentBlock', + 'ToolResultContent', + 'Tool', + 'Notification', + 'ServerNotification' +]; + +function extractExportedTypes(source: string): string[] { + const matches = [...source.matchAll(/export\s+(?:interface|class|type)\s+(\w+)\b/g)]; + return matches.map(m => m[1]!); +} + +describe('Spec Types (2026-07-28)', () => { + const specTypes = extractExportedTypes(fs.readFileSync(SPEC_TYPES_FILE, 'utf8')); + const typesToCheck = specTypes.filter(type => !MISSING_SDK_TYPES_2026_07_28.includes(type)); + + it('pins the 2026-07-28 protocol version and the new error codes', () => { + expect(LATEST_PROTOCOL_VERSION).toBe('2026-07-28'); + expect(MISSING_REQUIRED_CLIENT_CAPABILITY).toBe(-32003); + expect(UNSUPPORTED_PROTOCOL_VERSION).toBe(-32004); + }); + + it('should define some expected types', () => { + expect(specTypes).toContain('DiscoverRequest'); + expect(specTypes).toContain('InputRequiredResult'); + expect(specTypes).toContain('SubscriptionsListenRequest'); + expect(specTypes).toHaveLength(150); + }); + + it('should only allowlist types that exist in the 2026-07-28 schema', () => { + for (const typeName of MISSING_SDK_TYPES_2026_07_28) { + expect(specTypes).toContain(typeName); + } + }); + + it('should have comprehensive compatibility tests', () => { + const missingTests = []; + + for (const typeName of typesToCheck) { + if (!sdkTypeChecks[typeName as keyof typeof sdkTypeChecks]) { + missingTests.push(typeName); + } + } + + expect(missingTests).toHaveLength(0); + }); + + describe('Missing SDK Types', () => { + it.each(MISSING_SDK_TYPES_2026_07_28)('%s should not be present in MISSING_SDK_TYPES_2026_07_28 if it has a compatibility test', type => { + expect(sdkTypeChecks[type as keyof typeof sdkTypeChecks]).toBeUndefined(); + }); + }); +}); diff --git a/scripts/fetch-spec-types.ts b/scripts/fetch-spec-types.ts index cd0e26f5f5..b0db8d486f 100644 --- a/scripts/fetch-spec-types.ts +++ b/scripts/fetch-spec-types.ts @@ -7,12 +7,32 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const PROJECT_ROOT = join(__dirname, '..'); +/** + * The protocol revisions the SDK keeps reference types for: + * - `2025-11-25`: the frozen, released schema. + * - `2026-07-28`: the upcoming protocol revision. + * + * Each is written to `packages/core/src/types/spec.types..ts`. + */ +const SUPPORTED_VERSIONS = ['2025-11-25', '2026-07-28'] as const; +type SpecVersion = (typeof SUPPORTED_VERSIONS)[number]; + +/** + * Upstream schema directory per revision. Until the 2026-07-28 revision is + * published, its schema lives in the spec repository's draft directory; this + * mapping drops once `schema/2026-07-28/` exists upstream. + */ +const UPSTREAM_SCHEMA_DIRS: Record = { + '2025-11-25': '2025-11-25', + '2026-07-28': 'draft' +}; + interface GitHubCommit { sha: string; } -async function fetchLatestSHA(): Promise { - const url = 'https://api.github.com/repos/modelcontextprotocol/modelcontextprotocol/commits?path=schema/draft/schema.ts&per_page=1'; +async function fetchLatestSHA(version: SpecVersion): Promise { + const url = `https://api.github.com/repos/modelcontextprotocol/modelcontextprotocol/commits?path=schema/${UPSTREAM_SCHEMA_DIRS[version]}/schema.ts&per_page=1`; const response = await fetch(url); if (!response.ok) { @@ -27,8 +47,8 @@ async function fetchLatestSHA(): Promise { return commits[0].sha; } -async function fetchSpecTypes(sha: string): Promise { - const url = `https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/${sha}/schema/draft/schema.ts`; +async function fetchSpecTypes(version: SpecVersion, sha: string): Promise { + const url = `https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/${sha}/schema/${UPSTREAM_SCHEMA_DIRS[version]}/schema.ts`; const response = await fetch(url); if (!response.ok) { @@ -38,49 +58,70 @@ async function fetchSpecTypes(sha: string): Promise { return await response.text(); } -async function main() { - try { - // Check if SHA is provided as command line argument - const providedSHA = process.argv[2]; - - let latestSHA: string; - if (providedSHA) { - console.log(`Using provided SHA: ${providedSHA}`); - latestSHA = providedSHA; - } else { - console.log('Fetching latest commit SHA...'); - latestSHA = await fetchLatestSHA(); - } +async function updateSpecTypes(version: SpecVersion, providedSHA?: string): Promise { + let sha: string; + if (providedSHA) { + console.log(`[${version}] Using provided SHA: ${providedSHA}`); + sha = providedSHA; + } else { + console.log(`[${version}] Fetching latest commit SHA...`); + sha = await fetchLatestSHA(version); + } - console.log(`Fetching spec.types.ts from commit: ${latestSHA}`); + console.log(`[${version}] Fetching schema.ts from commit: ${sha}`); - const specContent = await fetchSpecTypes(latestSHA); + const specContent = await fetchSpecTypes(version, sha); - // Read header template - const headerTemplate = `/** + // Read header template + const headerTemplate = `/** * This file is automatically generated from the Model Context Protocol specification. * * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/{SCHEMA_DIR}/schema.ts * Last updated from commit: {SHA} * * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: pnpm run fetch:spec-types + * To update this file, run: pnpm run fetch:spec-types {VERSION} */`; - const header = headerTemplate.replace('{SHA}', latestSHA); + const header = headerTemplate.replaceAll('{VERSION}', version).replaceAll('{SCHEMA_DIR}', UPSTREAM_SCHEMA_DIRS[version]).replace('{SHA}', sha); + + // Combine header and content + const fullContent = header + specContent; + + // Format with prettier using the project's config so the output passes lint + const outputPath = join(PROJECT_ROOT, 'packages', 'core', 'src', 'types', `spec.types.${version}.ts`); + const prettierConfig = await prettier.resolveConfig(outputPath); + const formatted = await prettier.format(fullContent, { ...prettierConfig, filepath: outputPath }); - // Combine header and content - const fullContent = header + specContent; + writeFileSync(outputPath, formatted, 'utf-8'); - // Format with prettier using the project's config so the output passes lint - const outputPath = join(PROJECT_ROOT, 'packages', 'core', 'src', 'types', 'spec.types.ts'); - const prettierConfig = await prettier.resolveConfig(outputPath); - const formatted = await prettier.format(fullContent, { ...prettierConfig, filepath: outputPath }); + console.log(`[${version}] Successfully updated packages/core/src/types/spec.types.${version}.ts`); +} + +function isSupportedVersion(value: string): value is SpecVersion { + return (SUPPORTED_VERSIONS as readonly string[]).includes(value); +} + +async function main() { + try { + // Usage: fetch-spec-types.ts [version] [sha] + // With no version, all supported versions are fetched at their latest upstream SHA. + const providedVersion = process.argv[2]; + const providedSHA = process.argv[3]; + + if (providedVersion === undefined) { + for (const version of SUPPORTED_VERSIONS) { + await updateSpecTypes(version); + } + return; + } - writeFileSync(outputPath, formatted, 'utf-8'); + if (!isSupportedVersion(providedVersion)) { + throw new Error(`Unsupported version "${providedVersion}". Supported versions: ${SUPPORTED_VERSIONS.join(', ')}`); + } - console.log('Successfully updated packages/core/src/types/spec.types.ts'); + await updateSpecTypes(providedVersion, providedSHA); } catch (error) { console.error('Error:', error instanceof Error ? error.message : String(error)); process.exit(1); From a09f142c0aee539d6c04c5245d4fc0cd5fab86c9 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Tue, 2 Jun 2026 15:51:00 +0000 Subject: [PATCH 2/3] feat(core): add the 2026-07-28 wire contract surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the 2026-07-28 wire shapes needed for per-request, sessionless operation (SEP-2575 / SEP-2567), plus a SEP-2322 forward-compatibility guard. Types and constants only — no dispatch, negotiation, or transport behavior yet: - Reserved `_meta` envelope key constants (protocolVersion, clientInfo, clientCapabilities, logLevel) plus RequestMetaEnvelopeSchema modeling the complete envelope; the logLevel key carries the spec's SEP-2577 deprecation tag. The base request schemas stay lenient so the same wire schemas parse requests from earlier protocol revisions; envelope requiredness is enforced at dispatch when that lands. - server/discover request and result schemas and types. - ProtocolErrorCode.UnsupportedProtocolVersion (-32004) with a typed UnsupportedProtocolVersionError carrying the spec's { supported, requested } error data, materialized by ProtocolError.fromError, and ProtocolErrorCode.MissingRequiredClientCapability (-32003). - An optional resultType passthrough on the base result schema (absent means "complete"), so results from 2026-07-28 servers parse without per-result modeling (SEP-2322). The 2026-07-28 type-comparison allowlist burns RequestMetaObject — now genuinely modeled, with the mutual-assignability check doubling as a pin on the meta-key strings — and re-annotates the remaining deferred groups with the work that will burn them. The frozen 2025-11-25 key-parity checks tolerate exactly the new resultType key via a dedicated assertion helper so every other key stays strictly checked. --- .../codemod/src/generated/specSchemaMap.ts | 3 + packages/core/src/exports/public/index.ts | 6 +- packages/core/src/types/constants.ts | 33 +++++ packages/core/src/types/enums.ts | 10 ++ packages/core/src/types/errors.ts | 38 +++++- packages/core/src/types/schemas.ts | 97 +++++++++++++- packages/core/src/types/specTypeSchema.ts | 3 + packages/core/src/types/types.ts | 28 ++++ .../core/test/spec.types.2025-11-25.test.ts | 50 ++++--- .../core/test/spec.types.2026-07-28.test.ts | 74 ++++++++--- packages/core/test/types.test.ts | 123 ++++++++++++++++++ packages/core/test/types/errors.test.ts | 44 +++++++ 12 files changed, 469 insertions(+), 40 deletions(-) create mode 100644 packages/core/test/types/errors.test.ts diff --git a/packages/codemod/src/generated/specSchemaMap.ts b/packages/codemod/src/generated/specSchemaMap.ts index 2536456fb8..77f3d3dfc8 100644 --- a/packages/codemod/src/generated/specSchemaMap.ts +++ b/packages/codemod/src/generated/specSchemaMap.ts @@ -27,6 +27,8 @@ export const SPEC_SCHEMA_NAMES: ReadonlySet = new Set([ 'CreateMessageResultWithToolsSchema', 'CreateTaskResultSchema', 'CursorSchema', + 'DiscoverRequestSchema', + 'DiscoverResultSchema', 'ElicitRequestFormParamsSchema', 'ElicitRequestParamsSchema', 'ElicitRequestSchema', @@ -112,6 +114,7 @@ export const SPEC_SCHEMA_NAMES: ReadonlySet = new Set([ 'ReadResourceResultSchema', 'RelatedTaskMetadataSchema', 'RequestIdSchema', + 'RequestMetaEnvelopeSchema', 'RequestMetaSchema', 'RequestSchema', 'ResourceContentsSchema', diff --git a/packages/core/src/exports/public/index.ts b/packages/core/src/exports/public/index.ts index 729144f1a3..a3c98da6fe 100644 --- a/packages/core/src/exports/public/index.ts +++ b/packages/core/src/exports/public/index.ts @@ -71,14 +71,18 @@ export * from '../../types/types.js'; // Constants export { + CLIENT_CAPABILITIES_META_KEY, + CLIENT_INFO_META_KEY, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, JSONRPC_VERSION, LATEST_PROTOCOL_VERSION, + LOG_LEVEL_META_KEY, METHOD_NOT_FOUND, PARSE_ERROR, + PROTOCOL_VERSION_META_KEY, RELATED_TASK_META_KEY, SUPPORTED_PROTOCOL_VERSIONS } from '../../types/constants.js'; @@ -87,7 +91,7 @@ export { export { ProtocolErrorCode } from '../../types/enums.js'; // Error classes -export { ProtocolError, UrlElicitationRequiredError } from '../../types/errors.js'; +export { ProtocolError, UnsupportedProtocolVersionError, UrlElicitationRequiredError } from '../../types/errors.js'; // Type guards and message parsing export { diff --git a/packages/core/src/types/constants.ts b/packages/core/src/types/constants.ts index 878d5111cf..d51fe926cc 100644 --- a/packages/core/src/types/constants.ts +++ b/packages/core/src/types/constants.ts @@ -4,6 +4,39 @@ export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18 export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; +/* Reserved `_meta` keys for the per-request envelope (protocol revision 2026-07-28) */ + +/** + * `_meta` key carrying the MCP protocol version governing a request. + * + * For the HTTP transport, the value must match the `MCP-Protocol-Version` header. + */ +export const PROTOCOL_VERSION_META_KEY = 'io.modelcontextprotocol/protocolVersion'; + +/** + * `_meta` key identifying the client software making a request. + */ +export const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; + +/** + * `_meta` key carrying the client's capabilities for a request. + * + * Capabilities are declared per request rather than once at initialization; + * servers must not infer capabilities from prior requests. + */ +export const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities'; + +/** + * `_meta` key carrying the desired log level for a request. + * + * When absent, the server must not send `notifications/message` notifications + * for the request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. + */ +export const LOG_LEVEL_META_KEY = 'io.modelcontextprotocol/logLevel'; + /* JSON-RPC types */ export const JSONRPC_VERSION = '2.0'; diff --git a/packages/core/src/types/enums.ts b/packages/core/src/types/enums.ts index 0d80242a86..0e3b65f9f0 100644 --- a/packages/core/src/types/enums.ts +++ b/packages/core/src/types/enums.ts @@ -12,5 +12,15 @@ export enum ProtocolErrorCode { // MCP-specific error codes ResourceNotFound = -32_002, + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + MissingRequiredClientCapability = -32_003, + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + UnsupportedProtocolVersion = -32_004, UrlElicitationRequired = -32_042 } diff --git a/packages/core/src/types/errors.ts b/packages/core/src/types/errors.ts index 796c0d2bc5..a175686d13 100644 --- a/packages/core/src/types/errors.ts +++ b/packages/core/src/types/errors.ts @@ -1,5 +1,5 @@ import { ProtocolErrorCode } from './enums.js'; -import type { ElicitRequestURLParams } from './types.js'; +import type { ElicitRequestURLParams, UnsupportedProtocolVersionErrorData } from './types.js'; /** * Protocol errors are JSON-RPC errors that cross the wire as error responses. @@ -27,6 +27,13 @@ export class ProtocolError extends Error { } } + if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data as Partial; + if (Array.isArray(errorData.supported) && typeof errorData.requested === 'string') { + return new UnsupportedProtocolVersionError({ supported: errorData.supported, requested: errorData.requested }, message); + } + } + // Default to generic ProtocolError return new ProtocolError(code, message, data); } @@ -47,3 +54,32 @@ export class UrlElicitationRequiredError extends ProtocolError { return (this.data as { elicitations: ElicitRequestURLParams[] })?.elicitations ?? []; } } + +/** + * Error type for the `-32004` UnsupportedProtocolVersion protocol error (protocol + * revision 2026-07-28): the request's protocol version is unknown to the server or + * unsupported by it. + * + * The error data lists the protocol versions the receiver supports (`supported`), + * so the sender can choose a mutually supported version and retry, and echoes the + * version that was requested (`requested`). + */ +export class UnsupportedProtocolVersionError extends ProtocolError { + constructor(data: UnsupportedProtocolVersionErrorData, message: string = `Unsupported protocol version: ${data.requested}`) { + super(ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + + /** + * Protocol versions the receiver supports. + */ + get supported(): string[] { + return (this.data as UnsupportedProtocolVersionErrorData).supported; + } + + /** + * The protocol version that was requested. + */ + get requested(): string { + return (this.data as UnsupportedProtocolVersionErrorData).requested; + } +} diff --git a/packages/core/src/types/schemas.ts b/packages/core/src/types/schemas.ts index a243c1b829..f472a36ff9 100644 --- a/packages/core/src/types/schemas.ts +++ b/packages/core/src/types/schemas.ts @@ -1,6 +1,13 @@ import * as z from 'zod/v4'; -import { JSONRPC_VERSION, RELATED_TASK_META_KEY } from './constants.js'; +import { + CLIENT_CAPABILITIES_META_KEY, + CLIENT_INFO_META_KEY, + JSONRPC_VERSION, + LOG_LEVEL_META_KEY, + PROTOCOL_VERSION_META_KEY, + RELATED_TASK_META_KEY +} from './constants.js'; import type { JSONArray, JSONObject, @@ -113,7 +120,14 @@ export const ResultSchema = z.looseObject({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on `_meta` usage. */ - _meta: RequestMetaSchema.optional() + _meta: RequestMetaSchema.optional(), + /** + * Indicates the type of the result, allowing the receiver to determine how to + * parse the result object. Servers implementing protocol revision 2026-07-28 or + * later always include this field; results from earlier revisions omit it, and + * an absent value must be treated as `"complete"`. + */ + resultType: z.string().optional() }); /** @@ -552,6 +566,43 @@ export const InitializedNotificationSchema = NotificationSchema.extend({ params: NotificationsParamsSchema.optional() }); +/* Discovery */ +/** + * A request from the client asking the server to advertise its supported protocol + * versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers + * MUST implement `server/discover`. Clients MAY call it but are not required to — + * version negotiation can also happen inline via the per-request `_meta` envelope. + */ +export const DiscoverRequestSchema = RequestSchema.extend({ + method: z.literal('server/discover'), + params: BaseRequestParamsSchema.optional() +}); + +/** + * The result returned by the server for a `server/discover` request. + */ +export const DiscoverResultSchema = ResultSchema.extend({ + /** + * MCP protocol versions this server supports. The client should choose a + * version from this list for use in subsequent requests. + */ + supportedVersions: z.array(z.string()), + /** + * The capabilities of the server. + */ + capabilities: ServerCapabilitiesSchema, + /** + * Information about the server software implementation. + */ + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); + /* Ping */ /** * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. @@ -1509,6 +1560,48 @@ export const LoggingMessageNotificationSchema = NotificationSchema.extend({ params: LoggingMessageNotificationParamsSchema }); +/* Per-request `_meta` envelope */ +/** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own. The base request schemas + * ({@linkcode RequestMetaSchema}) deliberately stay lenient so the same wire schemas + * parse requests from earlier protocol revisions (no envelope) as well; envelope + * requiredness is enforced per request at dispatch time, not here. + */ +export const RequestMetaEnvelopeSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * The MCP protocol version being used for this request. For the HTTP transport, + * the value must match the `MCP-Protocol-Version` header. + */ + [PROTOCOL_VERSION_META_KEY]: z.string(), + /** + * Identifies the client software making the request. + */ + [CLIENT_INFO_META_KEY]: ImplementationSchema, + /** + * The client's capabilities for this specific request. An empty object means the + * client supports no optional capabilities. Servers must not infer capabilities + * from prior requests. + */ + [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilitiesSchema, + /** + * The desired log level for this request. When absent, the server must not send + * `notifications/message` notifications for the request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. + */ + [LOG_LEVEL_META_KEY]: LoggingLevelSchema.optional() +}); + /* Sampling */ /** * Hints to use for model selection. diff --git a/packages/core/src/types/specTypeSchema.ts b/packages/core/src/types/specTypeSchema.ts index 477d61a55a..e538da8fa5 100644 --- a/packages/core/src/types/specTypeSchema.ts +++ b/packages/core/src/types/specTypeSchema.ts @@ -58,6 +58,8 @@ const SPEC_SCHEMA_KEYS = [ 'CreateMessageResultWithToolsSchema', 'CreateTaskResultSchema', 'CursorSchema', + 'DiscoverRequestSchema', + 'DiscoverResultSchema', 'ElicitationCompleteNotificationSchema', 'ElicitationCompleteNotificationParamsSchema', 'ElicitRequestSchema', @@ -133,6 +135,7 @@ const SPEC_SCHEMA_KEYS = [ 'RelatedTaskMetadataSchema', 'RequestSchema', 'RequestIdSchema', + 'RequestMetaEnvelopeSchema', 'RequestMetaSchema', 'ResourceSchema', 'ResourceContentsSchema', diff --git a/packages/core/src/types/types.ts b/packages/core/src/types/types.ts index a92deec8e1..123de7fe84 100644 --- a/packages/core/src/types/types.ts +++ b/packages/core/src/types/types.ts @@ -34,6 +34,8 @@ import type { CreateMessageResultWithToolsSchema, CreateTaskResultSchema, CursorSchema, + DiscoverRequestSchema, + DiscoverResultSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitRequestFormParamsSchema, @@ -106,6 +108,7 @@ import type { ReadResourceResultSchema, RelatedTaskMetadataSchema, RequestIdSchema, + RequestMetaEnvelopeSchema, RequestMetaSchema, RequestSchema, ResourceContentsSchema, @@ -200,6 +203,11 @@ export type JSONRPCResultResponse = Infer; export type JSONRPCMessage = Infer; export type RequestParams = Infer; export type NotificationParams = Infer; +/** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28 (protocol version, client info, client capabilities, optional log level). + */ +export type RequestMetaEnvelope = Infer; /* Empty result */ export type EmptyResult = Infer; @@ -224,6 +232,10 @@ export type ServerCapabilities = Infer; export type InitializeResult = Infer; export type InitializedNotification = Infer; +/* Discovery */ +export type DiscoverRequest = Infer; +export type DiscoverResult = Infer; + /* Ping */ export type PingRequest = Infer; @@ -458,6 +470,22 @@ export interface InternalError extends JSONRPCErrorObject { code: typeof INTERNAL_ERROR; } +/** + * Data carried by a `-32004` UnsupportedProtocolVersion protocol error + * (protocol revision 2026-07-28). + */ +export interface UnsupportedProtocolVersionErrorData { + /** + * Protocol versions the receiver supports. The sender should choose a + * mutually supported version from this list and retry. + */ + supported: string[]; + /** + * The protocol version that was requested. + */ + requested: string; +} + /** * Callback type for list changed notifications. */ diff --git a/packages/core/test/spec.types.2025-11-25.test.ts b/packages/core/test/spec.types.2025-11-25.test.ts index 45adde80e2..bf0903cd1a 100644 --- a/packages/core/test/spec.types.2025-11-25.test.ts +++ b/packages/core/test/spec.types.2025-11-25.test.ts @@ -662,6 +662,14 @@ type AssertExactKeys< /** Constraint: T must resolve to `true`. */ type Assert = T; +/** + * Same as {@link AssertExactKeys}, but tolerates the SDK's `resultType` key on + * result shapes: the SDK follows the 2026-07-28 schema's optional `resultType` + * passthrough (absent means "complete"), which is not in released 2025-11-25. + * Every other key still has to match exactly. + */ +type AssertExactKeysWithResultType = AssertExactKeys; + /* * Excluded from key-level assertions (21 entries): * @@ -702,27 +710,29 @@ type _K_ElicitRequestURLParams = Assert>; type _K_BaseMetadata = Assert>; type _K_Implementation = Assert>; -type _K_PaginatedResult = Assert>; -type _K_ListRootsResult = Assert>; +type _K_PaginatedResult = Assert>; +type _K_ListRootsResult = Assert>; type _K_Root = Assert>; -type _K_ElicitResult = Assert>; -type _K_CompleteResult = Assert>; +type _K_ElicitResult = Assert>; +type _K_CompleteResult = Assert>; type _K_Request = Assert>; -type _K_Result = Assert>; +type _K_Result = Assert>; type _K_JSONRPCRequest = Assert>; type _K_JSONRPCNotification = Assert>; -type _K_EmptyResult = Assert>; +type _K_EmptyResult = Assert>; type _K_Notification = Assert>; type _K_ResourceTemplateReference = Assert>; // @ts-expect-error Genuine mismatch: SDK PromptReference is missing 'title' from spec type _K_PromptReference = Assert>; type _K_ToolAnnotations = Assert>; type _K_Tool = Assert>; -type _K_ListToolsResult = Assert>; -type _K_CallToolResult = Assert>; -type _K_ListResourcesResult = Assert>; -type _K_ListResourceTemplatesResult = Assert>; -type _K_ReadResourceResult = Assert>; +type _K_ListToolsResult = Assert>; +type _K_CallToolResult = Assert>; +type _K_ListResourcesResult = Assert>; +type _K_ListResourceTemplatesResult = Assert< + AssertExactKeysWithResultType +>; +type _K_ReadResourceResult = Assert>; type _K_ResourceContents = Assert>; type _K_TextResourceContents = Assert>; type _K_BlobResourceContents = Assert>; @@ -730,8 +740,8 @@ type _K_Resource = Assert // @ts-expect-error Genuine mismatch: SDK PromptArgument is missing 'title' from spec type _K_PromptArgument = Assert>; type _K_Prompt = Assert>; -type _K_ListPromptsResult = Assert>; -type _K_GetPromptResult = Assert>; +type _K_ListPromptsResult = Assert>; +type _K_GetPromptResult = Assert>; type _K_TextContent = Assert>; type _K_ImageContent = Assert>; type _K_AudioContent = Assert>; @@ -754,7 +764,7 @@ type _K_TitledMultiSelectEnumSchema = Assert>; type _K_JSONRPCErrorResponse = Assert>; type _K_JSONRPCResultResponse = Assert>; -type _K_InitializeResult = Assert>; +type _K_InitializeResult = Assert>; // @ts-expect-error SDK follows the 2026-07-28 schema's `extensions` capability key; not in released 2025-11-25 type _K_ClientCapabilities = Assert>; // @ts-expect-error SDK follows the 2026-07-28 schema's `extensions` capability key; not in released 2025-11-25 @@ -773,11 +783,11 @@ type _K_TaskMetadata = Assert>; type _K_TaskAugmentedRequestParams = Assert>; type _K_Task = Assert>; -type _K_CreateTaskResult = Assert>; -type _K_GetTaskResult = Assert>; -type _K_GetTaskPayloadResult = Assert>; -type _K_ListTasksResult = Assert>; -type _K_CancelTaskResult = Assert>; +type _K_CreateTaskResult = Assert>; +type _K_GetTaskResult = Assert>; +type _K_GetTaskPayloadResult = Assert>; +type _K_ListTasksResult = Assert>; +type _K_CancelTaskResult = Assert>; type _K_TaskStatusNotificationParams = Assert< AssertExactKeys >; @@ -845,7 +855,7 @@ type _K_CancelTaskRequest = Assert>; +type _K_CreateMessageResult = Assert>; type _K_ResourceTemplate = Assert>; // Types excluded from the key-parity completeness guard: union types and primitive aliases diff --git a/packages/core/test/spec.types.2026-07-28.test.ts b/packages/core/test/spec.types.2026-07-28.test.ts index 0a8c418c97..064221963a 100644 --- a/packages/core/test/spec.types.2026-07-28.test.ts +++ b/packages/core/test/spec.types.2026-07-28.test.ts @@ -21,6 +21,13 @@ import { } from '../src/types/spec.types.2026-07-28.js'; import type * as SpecTypes from '../src/types/spec.types.2026-07-28.js'; import type * as SDKTypes from '../src/types/index.js'; +import { + CLIENT_CAPABILITIES_META_KEY, + CLIENT_INFO_META_KEY, + LOG_LEVEL_META_KEY, + PROTOCOL_VERSION_META_KEY, + ProtocolErrorCode +} from '../src/types/index.js'; /* eslint-disable @typescript-eslint/no-unused-vars */ @@ -47,6 +54,14 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, + // The SDK models the 2026-07-28 revision's required per-request `_meta` envelope as + // RequestMetaEnvelope (the base request schemas stay lenient; envelope + // requiredness is enforced at dispatch). This check also pins the + // *_META_KEY constants: a drifted key name breaks mutual assignability. + RequestMetaObject: (sdk: SDKTypes.RequestMetaEnvelope, spec: SpecTypes.RequestMetaObject) => { + sdk = spec; + spec = sdk; + }, ProgressToken: (sdk: SDKTypes.ProgressToken, spec: SpecTypes.ProgressToken) => { sdk = spec; spec = sdk; @@ -367,11 +382,14 @@ const MISSING_SDK_TYPES_2026_07_28 = [ // Inlined in the SDK (same as the 2025-11-25 comparison): 'Error', // The inner error object of a JSONRPCError - // SEP-2260 per-request envelope: 2026-07-28 requests carry a required `_meta` envelope - // (`io.modelcontextprotocol/protocolVersion`, clientInfo, clientCapabilities); the SDK - // still implements the 2025-11-25 request shapes. + // SEP-2575 per-request envelope: 2026-07-28 requests REQUIRE a `_meta` envelope + // (`io.modelcontextprotocol/protocolVersion`, clientInfo, clientCapabilities). The + // envelope itself is modeled by RequestMetaEnvelope (see sdkTypeChecks above); the + // request shapes below stay here because the SDK wire schemas deliberately keep + // `_meta` lenient — the same schemas parse pre-2026 requests (no envelope) and 2026 + // requests, with envelope requiredness enforced per request at dispatch. They burn + // only if the SDK ever models era-specific request types. 'RequestParams', - 'RequestMetaObject', 'PaginatedRequestParams', 'ResourceRequestParams', 'CallToolRequestParams', @@ -392,8 +410,9 @@ const MISSING_SDK_TYPES_2026_07_28 = [ 'CreateMessageRequest', 'ClientRequest', - // SEP-2322 (MRTR): 2026-07-28 results carry a required `resultType` discriminator; the SDK - // still implements the 2025-11-25 result shapes. + // SEP-2322 (MRTR) → PR for MRTR: 2026-07-28 results carry a required `resultType` + // discriminator. The SDK base result schema carries `resultType` as an optional + // passthrough only (absent means "complete"); per-result modeling lands with MRTR. 'Result', 'EmptyResult', 'PaginatedResult', @@ -411,9 +430,12 @@ const MISSING_SDK_TYPES_2026_07_28 = [ 'ClientResult', 'ServerResult', 'ResultType', + + // SEP-2549 cacheable results: `ttlMs`/`cacheScope` caching hints on the list/read + // result shapes → PR for SEP-2549: 'CacheableResult', - // Response envelopes embedding the changed Result shape: + // Response envelopes embedding the changed Result shape → PR for MRTR: 'JSONRPCResultResponse', 'JSONRPCResponse', 'JSONRPCMessage', @@ -426,12 +448,15 @@ const MISSING_SDK_TYPES_2026_07_28 = [ 'ListToolsResultResponse', 'ReadResourceResultResponse', - // SEP-2575 sessionless discovery (new surface): + // SEP-2575 sessionless discovery: the SDK ships the wire shapes + // (DiscoverRequestSchema / DiscoverResultSchema), but the 2026-07-28 shapes embed the + // required `_meta` envelope (request) and required `resultType` (result → MRTR PR), + // so they do not match yet; DiscoverResultResponse is a response wrapper (→ MRTR PR): 'DiscoverRequest', 'DiscoverResult', 'DiscoverResultResponse', - // SEP-2567 input requests/responses (new surface): + // SEP-2567 input requests/responses (new surface) → PR for MRTR: 'InputRequest', 'InputRequests', 'InputRequiredResult', @@ -439,19 +464,24 @@ const MISSING_SDK_TYPES_2026_07_28 = [ 'InputResponseRequestParams', 'InputResponses', - // 2026-07-28 subscriptions surface (new): + // 2026-07-28 subscriptions surface (new) → PR for subscriptions/listen: 'SubscriptionFilter', 'SubscriptionsAcknowledgedNotification', 'SubscriptionsAcknowledgedNotificationParams', 'SubscriptionsListenRequest', 'SubscriptionsListenRequestParams', - // New typed protocol errors (-32003 / -32004): + // New typed protocol errors: the SDK ships -32003/-32004 as ProtocolErrorCode + // entries plus the UnsupportedProtocolVersionError class (errors.ts); the spec's + // per-code error *response envelope* interfaces are not modeled as wire types: 'MissingRequiredClientCapabilityError', 'UnsupportedProtocolVersionError', - // Other shapes changed in the 2026-07-28 schema (sampling content, open tool schemas, - // loosened Notification.params, server notification union): + // Other shapes changed in the 2026-07-28 schema: sampling content changes (SamplingMessage, + // SamplingMessageContentBlock, ToolResultContent) → backchannel PR; open tool + // input/output schema typing (Tool); loosened Notification.params (Notification); + // server notification union, which gains the subscriptions ack (ServerNotification → + // PR for subscriptions/listen): 'SamplingMessage', 'SamplingMessageContentBlock', 'ToolResultContent', @@ -473,6 +503,15 @@ describe('Spec Types (2026-07-28)', () => { expect(LATEST_PROTOCOL_VERSION).toBe('2026-07-28'); expect(MISSING_REQUIRED_CLIENT_CAPABILITY).toBe(-32003); expect(UNSUPPORTED_PROTOCOL_VERSION).toBe(-32004); + expect(ProtocolErrorCode.MissingRequiredClientCapability).toBe(MISSING_REQUIRED_CLIENT_CAPABILITY); + expect(ProtocolErrorCode.UnsupportedProtocolVersion).toBe(UNSUPPORTED_PROTOCOL_VERSION); + }); + + it('pins the per-request _meta envelope keys to the 2026-07-28 schema', () => { + expect(PROTOCOL_VERSION_META_KEY).toBe('io.modelcontextprotocol/protocolVersion'); + expect(CLIENT_INFO_META_KEY).toBe('io.modelcontextprotocol/clientInfo'); + expect(CLIENT_CAPABILITIES_META_KEY).toBe('io.modelcontextprotocol/clientCapabilities'); + expect(LOG_LEVEL_META_KEY).toBe('io.modelcontextprotocol/logLevel'); }); it('should define some expected types', () => { @@ -501,8 +540,11 @@ describe('Spec Types (2026-07-28)', () => { }); describe('Missing SDK Types', () => { - it.each(MISSING_SDK_TYPES_2026_07_28)('%s should not be present in MISSING_SDK_TYPES_2026_07_28 if it has a compatibility test', type => { - expect(sdkTypeChecks[type as keyof typeof sdkTypeChecks]).toBeUndefined(); - }); + it.each(MISSING_SDK_TYPES_2026_07_28)( + '%s should not be present in MISSING_SDK_TYPES_2026_07_28 if it has a compatibility test', + type => { + expect(sdkTypeChecks[type as keyof typeof sdkTypeChecks]).toBeUndefined(); + } + ); }); }); diff --git a/packages/core/test/types.test.ts b/packages/core/test/types.test.ts index 280f2ede9f..a92615bceb 100644 --- a/packages/core/test/types.test.ts +++ b/packages/core/test/types.test.ts @@ -1,6 +1,8 @@ import { CallToolRequestSchema, CallToolResultSchema, + CLIENT_CAPABILITIES_META_KEY, + CLIENT_INFO_META_KEY, ClientCapabilitiesSchema, ClientRequestSchema, CompleteRequestSchema, @@ -8,10 +10,17 @@ import { CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, + DiscoverRequestSchema, + DiscoverResultSchema, ElicitRequestFormParamsSchema, + EmptyResultSchema, LATEST_PROTOCOL_VERSION, + LOG_LEVEL_META_KEY, PromptMessageSchema, + PROTOCOL_VERSION_META_KEY, + RequestMetaEnvelopeSchema, ResourceLinkSchema, + ResultSchema, SamplingMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, ToolChoiceSchema, @@ -1049,3 +1058,117 @@ describe('2025-11-25 task wire interop (task feature removed; wire types remain) } }); }); + +describe('2026-07-28 wire shapes', () => { + describe('RequestMetaEnvelope', () => { + const envelope = { + [PROTOCOL_VERSION_META_KEY]: '2026-07-28', + [CLIENT_INFO_META_KEY]: { name: 'test-client', version: '1.0.0' }, + [CLIENT_CAPABILITIES_META_KEY]: {} + }; + + test('accepts a complete envelope', () => { + const result = RequestMetaEnvelopeSchema.safeParse(envelope); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data[PROTOCOL_VERSION_META_KEY]).toBe('2026-07-28'); + expect(result.data[CLIENT_INFO_META_KEY]).toEqual({ name: 'test-client', version: '1.0.0' }); + expect(result.data[CLIENT_CAPABILITIES_META_KEY]).toEqual({}); + } + }); + + test('accepts the optional log level, progress token, and unknown keys', () => { + const result = RequestMetaEnvelopeSchema.safeParse({ + ...envelope, + [LOG_LEVEL_META_KEY]: 'warning', + progressToken: 'token-1', + 'com.example/custom': { anything: true } + }); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data[LOG_LEVEL_META_KEY]).toBe('warning'); + expect(result.data.progressToken).toBe('token-1'); + expect(result.data['com.example/custom']).toEqual({ anything: true }); + } + }); + + test.each([PROTOCOL_VERSION_META_KEY, CLIENT_INFO_META_KEY, CLIENT_CAPABILITIES_META_KEY])( + 'rejects an envelope missing %s', + key => { + const incomplete: Record = { ...envelope }; + delete incomplete[key]; + expect(RequestMetaEnvelopeSchema.safeParse(incomplete).success).toBe(false); + } + ); + + test('rejects an invalid log level', () => { + const result = RequestMetaEnvelopeSchema.safeParse({ ...envelope, [LOG_LEVEL_META_KEY]: 'loud' }); + expect(result.success).toBe(false); + }); + }); + + describe('DiscoverRequest', () => { + test('parses a discover request with and without params', () => { + expect(DiscoverRequestSchema.safeParse({ method: 'server/discover' }).success).toBe(true); + expect( + DiscoverRequestSchema.safeParse({ + method: 'server/discover', + params: { _meta: { [PROTOCOL_VERSION_META_KEY]: '2026-07-28' } } + }).success + ).toBe(true); + }); + + test('rejects other methods', () => { + expect(DiscoverRequestSchema.safeParse({ method: 'initialize' }).success).toBe(false); + }); + }); + + describe('DiscoverResult', () => { + const result = { + supportedVersions: ['2026-07-28'], + capabilities: { tools: { listChanged: true } }, + serverInfo: { name: 'test-server', version: '1.0.0' } + }; + + test('parses a discover result', () => { + const parsed = DiscoverResultSchema.safeParse({ ...result, resultType: 'complete', instructions: 'Use the echo tool.' }); + expect(parsed.success).toBe(true); + if (parsed.success) { + expect(parsed.data.supportedVersions).toEqual(['2026-07-28']); + expect(parsed.data.capabilities).toEqual({ tools: { listChanged: true } }); + expect(parsed.data.serverInfo).toEqual({ name: 'test-server', version: '1.0.0' }); + expect(parsed.data.instructions).toBe('Use the echo tool.'); + } + }); + + test.each(['supportedVersions', 'capabilities', 'serverInfo'])('rejects a discover result missing %s', key => { + const incomplete: Record = { ...result }; + delete incomplete[key]; + expect(DiscoverResultSchema.safeParse(incomplete).success).toBe(false); + }); + }); + + describe('Result resultType passthrough', () => { + test('accepts results with and without resultType (absent means "complete")', () => { + const withIt = ResultSchema.safeParse({ resultType: 'complete' }); + expect(withIt.success).toBe(true); + if (withIt.success) { + expect(withIt.data.resultType).toBe('complete'); + } + const withoutIt = ResultSchema.safeParse({}); + expect(withoutIt.success).toBe(true); + if (withoutIt.success) { + expect(withoutIt.data.resultType).toBeUndefined(); + } + }); + + test('rejects a non-string resultType', () => { + expect(ResultSchema.safeParse({ resultType: 42 }).success).toBe(false); + }); + + test('EmptyResult accepts resultType but still rejects unknown keys', () => { + expect(EmptyResultSchema.safeParse({ resultType: 'complete' }).success).toBe(true); + expect(EmptyResultSchema.safeParse({ unexpected: true }).success).toBe(false); + }); + }); +}); diff --git a/packages/core/test/types/errors.test.ts b/packages/core/test/types/errors.test.ts new file mode 100644 index 0000000000..b908dfb397 --- /dev/null +++ b/packages/core/test/types/errors.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; + +import { ProtocolErrorCode } from '../../src/types/enums.js'; +import { ProtocolError, UnsupportedProtocolVersionError } from '../../src/types/errors.js'; + +describe('UnsupportedProtocolVersionError', () => { + const data = { supported: ['2025-11-25', '2025-06-18'], requested: '2026-07-28' }; + + it('carries code -32004 and the supported/requested data', () => { + const error = new UnsupportedProtocolVersionError(data); + expect(error.code).toBe(ProtocolErrorCode.UnsupportedProtocolVersion); + expect(error.code).toBe(-32004); + expect(error.supported).toEqual(['2025-11-25', '2025-06-18']); + expect(error.requested).toBe('2026-07-28'); + expect(error.data).toEqual(data); + }); + + it('defaults the message from the requested version', () => { + const error = new UnsupportedProtocolVersionError(data); + expect(error.message).toBe('Unsupported protocol version: 2026-07-28'); + const custom = new UnsupportedProtocolVersionError(data, 'try another version'); + expect(custom.message).toBe('try another version'); + }); + + it('is materialized by ProtocolError.fromError', () => { + const error = ProtocolError.fromError(-32004, 'Unsupported protocol version: 2026-07-28', data); + expect(error).toBeInstanceOf(UnsupportedProtocolVersionError); + if (error instanceof UnsupportedProtocolVersionError) { + expect(error.supported).toEqual(['2025-11-25', '2025-06-18']); + expect(error.requested).toBe('2026-07-28'); + } + expect(error.message).toBe('Unsupported protocol version: 2026-07-28'); + }); + + it('falls back to a generic ProtocolError when the data is missing or malformed', () => { + for (const malformed of [undefined, {}, { supported: 'not-an-array', requested: '2026-07-28' }, { supported: ['2025-11-25'] }]) { + const error = ProtocolError.fromError(-32004, 'unsupported', malformed); + expect(error).toBeInstanceOf(ProtocolError); + expect(error).not.toBeInstanceOf(UnsupportedProtocolVersionError); + expect(error.code).toBe(-32004); + expect(error.data).toEqual(malformed); + } + }); +}); From f123c816a7a9a956ba7b6a2aa027ae099a6257f1 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Wed, 3 Jun 2026 15:14:17 +0000 Subject: [PATCH 3/3] chore: add changeset --- .changeset/spec-reference-types-2026-07-28.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/spec-reference-types-2026-07-28.md diff --git a/.changeset/spec-reference-types-2026-07-28.md b/.changeset/spec-reference-types-2026-07-28.md new file mode 100644 index 0000000000..df0101e05f --- /dev/null +++ b/.changeset/spec-reference-types-2026-07-28.md @@ -0,0 +1,6 @@ +--- +'@modelcontextprotocol/core': patch +'@modelcontextprotocol/codemod': patch +--- + +Add per-revision spec reference types (2025-11-25 and 2026-07-28) with split comparison tests, and the 2026-07-28 wire contract surface: request-meta key constants, `RequestMetaEnvelopeSchema`, `server/discover` shapes, the typed `-32004` error, the `-32003` code constant, and a `resultType` passthrough on the base result. Types and constants only — no behavior changes.