diff --git a/.changeset/lazy-era-wire-schemas.md b/.changeset/lazy-era-wire-schemas.md new file mode 100644 index 0000000000..b49b5ea659 --- /dev/null +++ b/.changeset/lazy-era-wire-schemas.md @@ -0,0 +1,7 @@ +--- +'@modelcontextprotocol/client': patch +'@modelcontextprotocol/server': patch +'@modelcontextprotocol/server-legacy': patch +--- + +Build protocol-revision wire schemas lazily on first validation instead of at import. Each revision's schema set is now constructed by a module-level memoized factory, so importing the client or server package no longer pays the construction cost of both frozen wire-schema graphs up front. Method membership in the revision registries stays static, the schemas themselves are unchanged, and registry lookups keep returning reference-identical schema objects. diff --git a/packages/core-internal/src/wire/rev2025-11-25/buildSchemas.ts b/packages/core-internal/src/wire/rev2025-11-25/buildSchemas.ts new file mode 100644 index 0000000000..3538fd02bd --- /dev/null +++ b/packages/core-internal/src/wire/rev2025-11-25/buildSchemas.ts @@ -0,0 +1,2432 @@ +/** + * Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from + * the public/neutral types/schemas.ts. The neutral layer is the public-API + * superset and is free to evolve (e.g., SEP-2106 widening); this file is the + * 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. + * + * This is the era's complete frozen wire-parse contract — both the 2025-only + * delta (the deprecated task family, the era role unions) AND frozen copies of + * every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, + * prompts/resources/completion/elicitation, …). The 2026-era codec + * (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. + * + * The 2025-only delta (the task message surface, restored types-only by #2248 + * for interop with task-capable 2025 peers) is parsed ONLY through this era's + * registry; the deprecated Task* schemas also live (marked `@deprecated`) in + * the neutral schema layer so the public types stay nameable without a + * cross-layer import — nameability is constant, runtime availability is + * version-keyed — but appear in no API signature. Q1 increment 2 — deletions + * are physical: the + * 2026-era REGISTRY has no Task* methods (its frozen building-block copies do + * carry the deprecated Task* sub-schemas by composition — soft contamination, + * tracked for anchor-exactness adjudication). + * + * The only cross-layer dependency is `import type { JSONObject, JSONValue }` + * from the neutral types barrel — pure structural type aliases with no parse + * behavior. No runtime schema is shared with the neutral layer. + */ +import * as z from 'zod/v4'; + +import type { JSONObject, JSONValue } from '../../types/types'; +import { normalizeContentlessToolResult, TOOL_RESULT_FOREIGN_FAMILY_KEYS } from '../resultFamilies'; + +function build() { + /* ─────────────────────────────────────────────────────────────────────────── + * Building blocks + * ─────────────────────────────────────────────────────────────────────────── */ + + const JSONValueSchema: z.ZodType = z.lazy(() => + z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)]) + ); + const JSONObjectSchema: z.ZodType = z.record(z.string(), JSONValueSchema); + + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema = z.union([z.string(), z.number().int()]); + + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema = z.string(); + + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema = z.object({ + ttl: z.number().optional() + }); + + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema = z.object({ + taskId: z.string() + }); + + const RequestMetaSchema = 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(), + /** + * If specified, this request is related to the provided task. + */ + 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional() + }); + + /** + * Common params for any request. + */ + const BaseRequestParamsSchema = z.object({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() + }); + + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * 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: TaskMetadataSchema.optional() + }); + + const RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.loose().optional() + }); + + const NotificationsParamsSchema = z.object({ + /** + * 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() + }); + + const NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.loose().optional() + }); + + 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() + }); + + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema = z.union([z.string(), z.number().int()]); + + /* Empty result */ + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema = ResultSchema.strict(); + + const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional() + }); + /* Cancellation */ + /** + * 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 {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/cancelled'), + params: CancelledNotificationParamsSchema + }); + + /* Base Metadata */ + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema = z.object({ + /** + * URL or data URI for the icon. + */ + src: z.string(), + /** + * Optional MIME type for the icon. + */ + mimeType: z.string().optional(), + /** + * 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: z.array(z.string()).optional(), + /** + * 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: z.enum(['light', 'dark']).optional() + }); + + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema = z.object({ + /** + * 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: z.array(IconSchema).optional() + }); + + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.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: z.string().optional() + }); + + /* Initialization */ + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: z.string(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: z.string().optional(), + + /** + * 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: z.string().optional() + }); + + const FormElicitationCapabilitySchema = z.intersection( + z.object({ + applyDefaults: z.boolean().optional() + }), + JSONObjectSchema + ); + + const ElicitationCapabilitySchema = z.preprocess( + value => { + if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record).length === 0) { + return { form: {} }; + } + return value; + }, + z.intersection( + z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() + }), + JSONObjectSchema.optional() + ) + ); + + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema = z.looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: JSONObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: JSONObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for sampling requests. + */ + sampling: z + .looseObject({ + createMessage: JSONObjectSchema.optional() + }) + .optional(), + /** + * Task support for elicitation requests. + */ + elicitation: z + .looseObject({ + create: JSONObjectSchema.optional() + }) + .optional() + }) + .optional() + }); + + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema = z.looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: JSONObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: JSONObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for tool requests. + */ + tools: z + .looseObject({ + call: JSONObjectSchema.optional() + }) + .optional() + }) + .optional() + }); + + /** + * 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. + */ + const ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), JSONObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + sampling: z + .object({ + /** + * Present if the client supports context inclusion via `includeContext` parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: JSONObjectSchema.optional(), + /** + * Present if the client supports tool use via `tools` and `toolChoice` parameters. + */ + tools: JSONObjectSchema.optional() + }) + .optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + roots: z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the client supports task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it. + */ + tasks: ClientTasksCapabilitySchema.optional(), + /** + * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: z.record(z.string(), JSONObjectSchema).optional() + }); + + const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema = RequestSchema.extend({ + method: z.literal('initialize'), + params: InitializeRequestParamsSchema + }); + + /** + * 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. + */ + const ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), JSONObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + logging: JSONObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: JSONObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server supports task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it. + */ + tasks: ServerTasksCapabilitySchema.optional(), + /** + * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: z.record(z.string(), JSONObjectSchema).optional() + }); + + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema = ResultSchema.extend({ + /** + * 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: z.string(), + capabilities: ServerCapabilitiesSchema, + 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() + }); + + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/initialized'), + params: NotificationsParamsSchema.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. + */ + const PingRequestSchema = RequestSchema.extend({ + method: z.literal('ping'), + params: BaseRequestParamsSchema.optional() + }); + + /* Progress notifications */ + const ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) + }); + + const ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: ProgressNotificationParamsSchema + }); + + const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() + }); + + /* Pagination */ + const PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() + }); + + const PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() + }); + + /* Resources */ + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema = z.object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string() + }); + + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = z.string().refine( + val => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } catch { + return false; + } + }, + { message: 'Invalid Base64 string' } + ); + + const BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema + }); + + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema = z.enum(['user', 'assistant']); + + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema = z.object({ + /** + * Intended audience(s) for the resource. + */ + audience: z.array(RoleSchema).optional(), + + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: z.number().min(0).max(1).optional(), + + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: z.iso.datetime({ offset: true }).optional() + }); + + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: z.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: z.optional(z.string()), + + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + + /** + * 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: z.optional(z.number()), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.optional(z.looseObject({})) + }); + + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.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: z.optional(z.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: z.optional(z.string()), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.optional(z.looseObject({})) + }); + + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/list') + }); + + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: z.array(ResourceSchema) + }); + + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') + }); + + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: z.array(ResourceTemplateSchema) + }); + + const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() + }); + + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; + + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema = RequestSchema.extend({ + method: z.literal('resources/read'), + params: ReadResourceRequestParamsSchema + }); + + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema = ResultSchema.extend({ + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) + }); + + /** + * 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. + */ + const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: SubscribeRequestParamsSchema + }); + + const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: UnsubscribeRequestParamsSchema + }); + + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.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 {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: ResourceUpdatedNotificationParamsSchema + }); + + /* Prompts */ + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) + }); + + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.optional(z.looseObject({})) + }); + + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') + }); + + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: z.array(PromptSchema) + }); + + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema = RequestSchema.extend({ + method: z.literal('prompts/get'), + params: GetPromptRequestParamsSchema + }); + + /** + * Text provided to or from an LLM. + */ + const TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema = z.object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with `ToolResultContent` in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's `inputSchema`. + */ + input: z.record(z.string(), z.unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * 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 {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema = ResourceSchema.extend({ + type: z.literal('resource_link') + }); + + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema + ]); + + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema = z.object({ + role: RoleSchema, + content: ContentBlockSchema + }); + + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.string().optional(), + messages: z.array(PromptMessageSchema) + }); + + /** + * 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. + */ + const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + /* Tools */ + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode 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. + */ + const ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + + /** + * If `true`, the tool does not modify its environment. + * + * Default: `false` + */ + readOnlyHint: z.boolean().optional(), + + /** + * 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: z.boolean().optional(), + + /** + * 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: z.boolean().optional(), + + /** + * 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: z.boolean().optional() + }); + + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema = z.object({ + /** + * Indicates the tool's preference for task-augmented execution. + * - `"required"`: Clients MUST invoke the tool as a task + * - `"optional"`: Clients MAY invoke the tool as a task or normal request + * - `"forbidden"`: Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to `"forbidden"`. + */ + taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() + }); + + /** + * Definition for a tool the client can call. + */ + const ToolSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have `type: 'object'` at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), JSONValueSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the `structuredContent` field of a `CallToolResult`. + * Must have `type: 'object'` at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), JSONValueSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tools/list') + }); + + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: z.array(ToolSchema) + }); + + /** + * The server's response to a tool call. + */ + const CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the `Tool` does not define an outputSchema, this field MUST be present in the result. + * Required on the wire per the specification (it may be an empty array). + */ + content: z.array(ContentBlockSchema), + + /** + * An object containing structured tool output. + * + * If the `Tool` defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + + /** + * 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: z.boolean().optional() + }); + + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.record(z.string(), z.unknown()).optional() + }); + + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema = RequestSchema.extend({ + method: z.literal('tools/call'), + params: CallToolRequestParamsSchema + }); + + /** + * 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. + */ + const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + /* Logging */ + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); + + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * 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/logging/message`. + */ + level: LoggingLevelSchema + }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema = RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: SetLevelRequestParamsSchema + }); + + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.string().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown() + }); + /** + * Notification 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. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: LoggingMessageNotificationParamsSchema + }); + + /* Sampling */ + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema = z.object({ + /** + * A hint for a model name. + */ + name: z.string().optional() + }); + + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.number().min(0).max(1).optional() + }); + + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema = z.object({ + /** + * Controls when tools are used: + * - `"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: z.enum(['auto', 'required', 'none']).optional() + }); + + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema = z.object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(ContentBlockSchema), + structuredContent: z.object({}).loose().optional(), + isError: z.boolean().optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); + + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema + ]); + + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema = z.object({ + role: RoleSchema, + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: z.array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.string().optional(), + /** + * 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"`. The values `"thisServer"` and `"allServers"` are deprecated (SEP-2596): servers SHOULD + * omit this field or use `"none"`, and SHOULD only use the deprecated values if the client declares + * `ClientCapabilities`.`sampling.context`. + * + * @deprecated The `"thisServer"` and `"allServers"` values are deprecated as of protocol version 2025-11-25 + * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `"none"`. + */ + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + /** + * 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: z.number().int(), + stopSequences: z.array(z.string()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: JSONObjectSchema.optional(), + /** + * 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: z.array(ToolSchema).optional(), + /** + * 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: ToolChoiceSchema.optional() + }); + /** + * 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. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema = RequestSchema.extend({ + method: z.literal('sampling/createMessage'), + params: CreateMessageRequestParamsSchema + }); + + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.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 + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema + }); + + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.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: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include `ToolUseContent` if `stopReason` is `"toolUse"`. + */ + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) + }); + + /* Elicitation */ + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() + }); + + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() + }); + + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() + }); + + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() + }); + + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array( + z.object({ + const: z.string(), + title: z.string() + }) + ), + default: z.string().optional() + }); + + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() + }); + + // Combined single selection enumeration + const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); + + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() + }); + + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array( + z.object({ + const: z.string(), + title: z.string() + }) + ) + }), + default: z.array(z.string()).optional() + }); + + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); + + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); + + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); + + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing `mode` as `"form"`. + */ + mode: z.literal('form').optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: z.string(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + }); + + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.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: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() + }); + + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); + + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: ElicitRequestParamsSchema + }); + + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() + }); + + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: ElicitationCompleteNotificationParamsSchema + }); + + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - `"accept"`: User submitted the form/confirmed the action + * - `"decline"`: User explicitly declined the action + * - `"cancel"`: User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is `"accept"`. + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize `null` to `undefined` for leniency while maintaining type compatibility. + */ + content: z.preprocess( + val => (val === null ? undefined : val), + z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() + ) + }); + + /* Autocomplete */ + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() + }); + + /** + * Identifies a prompt. + */ + const PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() + }); + + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema = RequestSchema.extend({ + method: z.literal('completion/complete'), + params: CompleteRequestParamsSchema + }); + + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema = ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) + }); + + /* Roots */ + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema = z.object({ + /** + * The URI identifying the root. This *must* start with `file://` for now. + */ + uri: z.string().startsWith('file://'), + /** + * An optional name for the root. + */ + name: z.string().optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema = RequestSchema.extend({ + method: z.literal('roots/list'), + params: BaseRequestParamsSchema.optional() + }); + + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema = ResultSchema.extend({ + roots: z.array(RootSchema) + }); + + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + /* ─────────────────────────────────────────────────────────────────────────── + * Tasks (2025-11-25 wire vocabulary; restored types-only by #2248 for interop + * with task-capable 2025 peers — parsed ONLY through this era's registry). + * ─────────────────────────────────────────────────────────────────────────── */ + + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema = z.looseObject({ + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl: z.number().optional(), + + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.number().optional() + }); + + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); + + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema = z.object({ + taskId: z.string(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If `null`, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: z.string(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: z.string(), + pollInterval: z.optional(z.number()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: z.optional(z.string()) + }); + + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema + }); + + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); + + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tasks/status'), + params: TaskStatusNotificationParamsSchema + }); + + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/get'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) + }); + + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema = ResultSchema.merge(TaskSchema); + + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/result'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) + }); + + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema = ResultSchema.loose(); + + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tasks/list') + }); + + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: z.array(TaskSchema) + }); + + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/cancel'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) + }); + + /** + * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); + + /* ─────────────────────────────────────────────────────────────────────────── + * The 2025-era wire role unions: the era-faithful aggregates (what a + * 2025-11-25 peer may legally put on the wire, per role) and the source the + * era registry is built from. Member order preserves the pre-split unions + * (task members last for requests/results; notification members are + * method-discriminated, so ordering is not observable). + * ─────────────────────────────────────────────────────────────────────────── */ + + const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema + ]); + + const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema + ]); + + const ClientResultSchema = z.union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema + ]); + + const ServerRequestSchema = z.union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema + ]); + + const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema + ]); + + const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema + ]); + + /** + * Wire seam: owns both halves of the v1-parity ruling — the guard (a content-less body + * carrying another result family's keys fails loudly; the era is frozen so the key list is + * complete) and the tolerance (`content` defaults to `[]`). The era file stays twin-conformant. + * Definition verbatim from the pre-lazy registry.ts; it lives with the era schemas so the + * registry's lazy result map and the eager shim serve the SAME object through the memo. + */ + const CallToolResultWireSchema = z + .unknown() + .superRefine((value, ctx) => { + // content === undefined covers both an absent key and an explicit + // undefined from server-side authoring objects. + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + (value as Record).content !== undefined + ) + return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) { + if (key in value) { + ctx.addIssue({ + code: 'custom', + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + } + }) + .transform(normalizeContentlessToolResult) + .pipe(CallToolResultSchema); + + return { + JSONValueSchema, + JSONObjectSchema, + ProgressTokenSchema, + CursorSchema, + TaskMetadataSchema, + RelatedTaskMetadataSchema, + RequestMetaSchema, + BaseRequestParamsSchema, + TaskAugmentedRequestParamsSchema, + RequestSchema, + NotificationsParamsSchema, + NotificationSchema, + ResultSchema, + RequestIdSchema, + EmptyResultSchema, + CancelledNotificationParamsSchema, + CancelledNotificationSchema, + IconSchema, + IconsSchema, + BaseMetadataSchema, + ImplementationSchema, + ClientTasksCapabilitySchema, + ServerTasksCapabilitySchema, + ClientCapabilitiesSchema, + InitializeRequestParamsSchema, + InitializeRequestSchema, + ServerCapabilitiesSchema, + InitializeResultSchema, + InitializedNotificationSchema, + PingRequestSchema, + ProgressSchema, + ProgressNotificationParamsSchema, + ProgressNotificationSchema, + PaginatedRequestParamsSchema, + PaginatedRequestSchema, + PaginatedResultSchema, + ResourceContentsSchema, + TextResourceContentsSchema, + BlobResourceContentsSchema, + RoleSchema, + AnnotationsSchema, + ResourceSchema, + ResourceTemplateSchema, + ListResourcesRequestSchema, + ListResourcesResultSchema, + ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema, + ResourceRequestParamsSchema, + ReadResourceRequestParamsSchema, + ReadResourceRequestSchema, + ReadResourceResultSchema, + ResourceListChangedNotificationSchema, + SubscribeRequestParamsSchema, + SubscribeRequestSchema, + UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema, + ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema, + PromptArgumentSchema, + PromptSchema, + ListPromptsRequestSchema, + ListPromptsResultSchema, + GetPromptRequestParamsSchema, + GetPromptRequestSchema, + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + EmbeddedResourceSchema, + ResourceLinkSchema, + ContentBlockSchema, + PromptMessageSchema, + GetPromptResultSchema, + PromptListChangedNotificationSchema, + ToolAnnotationsSchema, + ToolExecutionSchema, + ToolSchema, + ListToolsRequestSchema, + ListToolsResultSchema, + CallToolResultSchema, + CallToolRequestParamsSchema, + CallToolRequestSchema, + ToolListChangedNotificationSchema, + LoggingLevelSchema, + SetLevelRequestParamsSchema, + SetLevelRequestSchema, + LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema, + ModelHintSchema, + ModelPreferencesSchema, + ToolChoiceSchema, + ToolResultContentSchema, + SamplingContentSchema, + SamplingMessageContentBlockSchema, + SamplingMessageSchema, + CreateMessageRequestParamsSchema, + CreateMessageRequestSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + UntitledMultiSelectEnumSchemaSchema, + TitledMultiSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema, + EnumSchemaSchema, + PrimitiveSchemaDefinitionSchema, + ElicitRequestFormParamsSchema, + ElicitRequestURLParamsSchema, + ElicitRequestParamsSchema, + ElicitRequestSchema, + ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema, + ElicitResultSchema, + ResourceTemplateReferenceSchema, + PromptReferenceSchema, + CompleteRequestParamsSchema, + CompleteRequestSchema, + CompleteResultSchema, + RootSchema, + ListRootsRequestSchema, + ListRootsResultSchema, + RootsListChangedNotificationSchema, + TaskCreationParamsSchema, + TaskStatusSchema, + TaskSchema, + CreateTaskResultSchema, + TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema, + GetTaskRequestSchema, + GetTaskResultSchema, + GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema, + ListTasksRequestSchema, + ListTasksResultSchema, + CancelTaskRequestSchema, + CancelTaskResultSchema, + ClientRequestSchema, + ClientNotificationSchema, + ClientResultSchema, + ServerRequestSchema, + ServerNotificationSchema, + ServerResultSchema, + CallToolResultWireSchema + }; +} + +/** The full set of frozen 2025-11-25 wire schemas, as one built object (the memo target). */ +export type Rev2025WireSchemas = ReturnType; + +let memo: Rev2025WireSchemas | undefined; + +/** + * Builds the era wire-schema set on first call and returns the same object + * thereafter. Module evaluation stays construction-free so importing the + * era codec/registry costs nothing until the first validation actually + * needs a schema; the registry, the codec, and the eager `schemas.ts` + * shim all pull through this memo, so reference identity holds across + * every consumer. + */ +export function buildSchemas2025(): Rev2025WireSchemas { + return (memo ??= build()); +} diff --git a/packages/core-internal/src/wire/rev2025-11-25/codec.ts b/packages/core-internal/src/wire/rev2025-11-25/codec.ts index de39f8b21a..4be008a883 100644 --- a/packages/core-internal/src/wire/rev2025-11-25/codec.ts +++ b/packages/core-internal/src/wire/rev2025-11-25/codec.ts @@ -31,9 +31,9 @@ import type * as z from 'zod/v4'; import type { CallToolResult, Result } from '../../types/types'; import type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec'; import { appendTextFallbackForNonObject } from '../textFallback'; +import { buildSchemas2025 } from './buildSchemas'; import { isNonObjectJsonSchemaRoot, wrapOutputSchemaForLegacy } from './legacyWrap'; import { getNotificationSchema, getRequestSchema, getResultSchema, hasNotificationMethod2025, hasRequestMethod2025 } from './registry'; -import { CreateMessageResultSchema, CreateMessageResultWithToolsSchema } from './schemas'; function isPlainObject(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); @@ -75,9 +75,13 @@ export const rev2025Codec: WireCodec = { validateInputResponse: (): ValidateOutcome => NOT_IN_ERA, // Arrow literals can't carry overload signatures; the cast is sound (the - // boolean dispatches to exactly the schema each overload names). - samplingResultVariant: ((hasTools: boolean, raw: unknown) => - triState(hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema, raw)) as WireCodec['samplingResultVariant'], + // boolean dispatches to exactly the schema each overload names). The + // schemas are pulled through the era's memo so the codec module itself + // stays construction-free at import time. + samplingResultVariant: ((hasTools: boolean, raw: unknown) => { + const s = buildSchemas2025(); + return triState(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }) as WireCodec['samplingResultVariant'], // The 2025 era carries no per-request `_meta` envelope — legacy wire // bytes stay identical (the never-stamp guarantee, outbound-request half). diff --git a/packages/core-internal/src/wire/rev2025-11-25/registry.ts b/packages/core-internal/src/wire/rev2025-11-25/registry.ts index fb582559f9..96d04b4db9 100644 --- a/packages/core-internal/src/wire/rev2025-11-25/registry.ts +++ b/packages/core-internal/src/wire/rev2025-11-25/registry.ts @@ -20,67 +20,29 @@ * 2026-only vocabulary (`server/discover`, `subscriptions/listen`, the MRTR * shells, `resultType`, the `_meta` envelope) has NO entry and NO code path * here — the inverse-leak guarantee is physical absence, not discipline. + * + * LAZY SCHEMA CONSTRUCTION: method membership and the exported method lists + * are static (null-valued key objects below — the mapped-type keying keeps + * the both-direction drift guard), while the schema VALUES are pulled through + * the era's memoized `buildSchemas2025()` factory on first lookup. Importing + * this module therefore constructs no zod schemas; the first validation does, + * once, and every consumer (registry, codec, the eager `schemas.ts` shim) + * sees the same objects, so the by-reference pins keep holding. */ -import * as z from 'zod/v4'; +import type * as z from 'zod/v4'; import type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types'; -import { normalizeContentlessToolResult, TOOL_RESULT_FOREIGN_FAMILY_KEYS } from '../resultFamilies'; -import type { ClientNotificationSchema, ClientRequestSchema, ServerNotificationSchema, ServerRequestSchema } from './schemas'; -import { - CallToolRequestSchema, - CallToolResultSchema, - CancelledNotificationSchema, - CancelTaskRequestSchema, - CompleteRequestSchema, - CompleteResultSchema, - CreateMessageRequestSchema, - CreateMessageResultWithToolsSchema, - ElicitationCompleteNotificationSchema, - ElicitRequestSchema, - ElicitResultSchema, - EmptyResultSchema, - GetPromptRequestSchema, - GetPromptResultSchema, - GetTaskPayloadRequestSchema, - GetTaskRequestSchema, - InitializedNotificationSchema, - InitializeRequestSchema, - InitializeResultSchema, - ListPromptsRequestSchema, - ListPromptsResultSchema, - ListResourcesRequestSchema, - ListResourcesResultSchema, - ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema, - ListRootsRequestSchema, - ListRootsResultSchema, - ListTasksRequestSchema, - ListToolsRequestSchema, - ListToolsResultSchema, - LoggingMessageNotificationSchema, - PingRequestSchema, - ProgressNotificationSchema, - PromptListChangedNotificationSchema, - ReadResourceRequestSchema, - ReadResourceResultSchema, - ResourceListChangedNotificationSchema, - ResourceUpdatedNotificationSchema, - RootsListChangedNotificationSchema, - SetLevelRequestSchema, - SubscribeRequestSchema, - TaskStatusNotificationSchema, - ToolListChangedNotificationSchema, - UnsubscribeRequestSchema -} from './schemas'; +import type { Rev2025WireSchemas } from './buildSchemas'; +import { buildSchemas2025 } from './buildSchemas'; /* The era's wire vocabulary, derived from the wire role unions in - * `./schemas.ts` (the same unions the registries used to be built from at - * runtime). Keying the maps by these derived unions makes drift a compile + * `./buildSchemas.ts` (the same unions the registries used to be built from + * at runtime). Keying the maps by these derived unions makes drift a compile * error in BOTH directions: a union member without a map entry, a map entry * the unions do not know, and an entry pointing at a different method's * schema all fail to typecheck. */ -type WireRequest = z.output | z.output; -type WireNotification = z.output | z.output; +type WireRequest = z.output | z.output; +type WireNotification = z.output | z.output; /** Every request method in the 2025-era wire vocabulary (the typed `RequestMethod` surface plus the task family). */ export type Rev2025RequestMethod = WireRequest['method']; @@ -98,115 +60,171 @@ export type Rev2025NotificationMethod = WireNotification['method']; */ type Rev2025TypedRequestMethod = Extract; -/* Runtime schema lookup — result schemas by method */ -// Keyed by the era's typed-method subset and valued by -// `z.ZodType` so the runtime map and the typed -// `ResultTypeMap` cannot drift: a missing entry, an extra key, or an entry -// that does not parse to the typed map's result type is a compile error. No -// entry may be looser than the typed map (no task-result union members) and -// no key may fall outside it (no `tasks/*` entries — the task methods are -// 2025-11-25 wire vocabulary with no SDK runtime; callers needing task -// interop pass an explicit schema). -/** - * Wire seam: owns both halves of the v1-parity ruling — the guard (a content-less body - * carrying another result family's keys fails loudly; the era is frozen so the key list is - * complete) and the tolerance (`content` defaults to `[]`). The era file stays twin-conformant. - */ -export const CallToolResultWireSchema = z - .unknown() - .superRefine((value, ctx) => { - // content === undefined covers both an absent key and an explicit - // undefined from server-side authoring objects. - if (typeof value !== 'object' || value === null || Array.isArray(value) || (value as Record).content !== undefined) - return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) { - if (key in value) { - ctx.addIssue({ - code: 'custom', - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - } - }) - .transform(normalizeContentlessToolResult) - .pipe(CallToolResultSchema); - -const resultSchemas: { readonly [M in Rev2025TypedRequestMethod]: z.ZodType } = { - ping: EmptyResultSchema, - initialize: InitializeResultSchema, - 'completion/complete': CompleteResultSchema, - 'logging/setLevel': EmptyResultSchema, - 'prompts/get': GetPromptResultSchema, - 'prompts/list': ListPromptsResultSchema, - 'resources/list': ListResourcesResultSchema, - 'resources/templates/list': ListResourceTemplatesResultSchema, - 'resources/read': ReadResourceResultSchema, - 'resources/subscribe': EmptyResultSchema, - 'resources/unsubscribe': EmptyResultSchema, - 'tools/call': CallToolResultWireSchema, - 'tools/list': ListToolsResultSchema, - 'sampling/createMessage': CreateMessageResultWithToolsSchema, - 'elicitation/create': ElicitResultSchema, - 'roots/list': ListRootsResultSchema +/* Static method membership — the schema-free half of the registry. + * + * These null-valued objects carry ONLY the method keys, in the same order the + * eager schema maps used to declare them (so the exported method lists stay + * byte-identical to the pre-lazy builder). The mapped-type keying preserves + * the both-direction drift guard: a union member without a key, or a key the + * union does not know, is a compile error. Membership checks and the exported + * lists read these objects and never touch the schema memo. */ +const requestMethodKeys: { readonly [M in Rev2025RequestMethod]: null } = { + ping: null, + initialize: null, + 'completion/complete': null, + 'logging/setLevel': null, + 'prompts/get': null, + 'prompts/list': null, + 'resources/list': null, + 'resources/templates/list': null, + 'resources/read': null, + 'resources/subscribe': null, + 'resources/unsubscribe': null, + 'tools/call': null, + 'tools/list': null, + 'tasks/get': null, + 'tasks/result': null, + 'tasks/list': null, + 'tasks/cancel': null, + 'sampling/createMessage': null, + 'elicitation/create': null, + 'roots/list': null }; -/* Runtime schema lookup — request and notification schemas by method. - * - * The entries are the SAME schema objects the wire role unions are built - * from (reference identity is pinned by `test/types/registryPins.test.ts`), - * and the key order preserves the pre-split union iteration order so the - * exported method lists are byte-identical to the builder they replace. */ -const requestSchemas: { readonly [M in Rev2025RequestMethod]: z.ZodType> } = { - ping: PingRequestSchema, - initialize: InitializeRequestSchema, - 'completion/complete': CompleteRequestSchema, - 'logging/setLevel': SetLevelRequestSchema, - 'prompts/get': GetPromptRequestSchema, - 'prompts/list': ListPromptsRequestSchema, - 'resources/list': ListResourcesRequestSchema, - 'resources/templates/list': ListResourceTemplatesRequestSchema, - 'resources/read': ReadResourceRequestSchema, - 'resources/subscribe': SubscribeRequestSchema, - 'resources/unsubscribe': UnsubscribeRequestSchema, - 'tools/call': CallToolRequestSchema, - 'tools/list': ListToolsRequestSchema, - 'tasks/get': GetTaskRequestSchema, - 'tasks/result': GetTaskPayloadRequestSchema, - 'tasks/list': ListTasksRequestSchema, - 'tasks/cancel': CancelTaskRequestSchema, - 'sampling/createMessage': CreateMessageRequestSchema, - 'elicitation/create': ElicitRequestSchema, - 'roots/list': ListRootsRequestSchema +const notificationMethodKeys: { readonly [M in Rev2025NotificationMethod]: null } = { + 'notifications/cancelled': null, + 'notifications/progress': null, + 'notifications/initialized': null, + 'notifications/roots/list_changed': null, + 'notifications/tasks/status': null, + 'notifications/message': null, + 'notifications/resources/updated': null, + 'notifications/resources/list_changed': null, + 'notifications/tools/list_changed': null, + 'notifications/prompts/list_changed': null, + 'notifications/elicitation/complete': null }; -const notificationSchemas: { readonly [M in Rev2025NotificationMethod]: z.ZodType> } = { - 'notifications/cancelled': CancelledNotificationSchema, - 'notifications/progress': ProgressNotificationSchema, - 'notifications/initialized': InitializedNotificationSchema, - 'notifications/roots/list_changed': RootsListChangedNotificationSchema, - 'notifications/tasks/status': TaskStatusNotificationSchema, - 'notifications/message': LoggingMessageNotificationSchema, - 'notifications/resources/updated': ResourceUpdatedNotificationSchema, - 'notifications/resources/list_changed': ResourceListChangedNotificationSchema, - 'notifications/tools/list_changed': ToolListChangedNotificationSchema, - 'notifications/prompts/list_changed': PromptListChangedNotificationSchema, - 'notifications/elicitation/complete': ElicitationCompleteNotificationSchema +const resultMethodKeys: { readonly [M in Rev2025TypedRequestMethod]: null } = { + ping: null, + initialize: null, + 'completion/complete': null, + 'logging/setLevel': null, + 'prompts/get': null, + 'prompts/list': null, + 'resources/list': null, + 'resources/templates/list': null, + 'resources/read': null, + 'resources/subscribe': null, + 'resources/unsubscribe': null, + 'tools/call': null, + 'tools/list': null, + 'sampling/createMessage': null, + 'elicitation/create': null, + 'roots/list': null }; +/* Lazy schema maps — built once, on the first schema lookup, from the era's + * memoized schema factory. The entries are the SAME schema objects the wire + * role unions are built from (reference identity is pinned by + * `test/types/registryPins.test.ts`), and the key order preserves the + * pre-split union iteration order. The mapped types below are unchanged from + * the eager maps, so the drift guards still apply entry by entry. */ +interface RegistryMaps { + /* Runtime schema lookup — request and notification schemas by method. */ + readonly requestSchemas: { readonly [M in Rev2025RequestMethod]: z.ZodType> }; + readonly notificationSchemas: { readonly [M in Rev2025NotificationMethod]: z.ZodType> }; + /* Runtime schema lookup — result schemas by method. + * + * Keyed by the era's typed-method subset and valued by + * `z.ZodType` so the runtime map and the typed + * `ResultTypeMap` cannot drift: a missing entry, an extra key, or an entry + * that does not parse to the typed map's result type is a compile error. No + * entry may be looser than the typed map (no task-result union members) and + * no key may fall outside it (no `tasks/*` entries — the task methods are + * 2025-11-25 wire vocabulary with no SDK runtime; callers needing task + * interop pass an explicit schema). The `tools/call` entry is the wire-seam + * wrapper `CallToolResultWireSchema` (content-default guard + tolerance), + * which lives with the era schemas in `./buildSchemas.ts`. */ + readonly resultSchemas: { readonly [M in Rev2025TypedRequestMethod]: z.ZodType }; +} + +let maps: RegistryMaps | undefined; + +function registryMaps(): RegistryMaps { + if (maps) return maps; + const s = buildSchemas2025(); + maps = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + 'completion/complete': s.CompleteRequestSchema, + 'logging/setLevel': s.SetLevelRequestSchema, + 'prompts/get': s.GetPromptRequestSchema, + 'prompts/list': s.ListPromptsRequestSchema, + 'resources/list': s.ListResourcesRequestSchema, + 'resources/templates/list': s.ListResourceTemplatesRequestSchema, + 'resources/read': s.ReadResourceRequestSchema, + 'resources/subscribe': s.SubscribeRequestSchema, + 'resources/unsubscribe': s.UnsubscribeRequestSchema, + 'tools/call': s.CallToolRequestSchema, + 'tools/list': s.ListToolsRequestSchema, + 'tasks/get': s.GetTaskRequestSchema, + 'tasks/result': s.GetTaskPayloadRequestSchema, + 'tasks/list': s.ListTasksRequestSchema, + 'tasks/cancel': s.CancelTaskRequestSchema, + 'sampling/createMessage': s.CreateMessageRequestSchema, + 'elicitation/create': s.ElicitRequestSchema, + 'roots/list': s.ListRootsRequestSchema + }, + notificationSchemas: { + 'notifications/cancelled': s.CancelledNotificationSchema, + 'notifications/progress': s.ProgressNotificationSchema, + 'notifications/initialized': s.InitializedNotificationSchema, + 'notifications/roots/list_changed': s.RootsListChangedNotificationSchema, + 'notifications/tasks/status': s.TaskStatusNotificationSchema, + 'notifications/message': s.LoggingMessageNotificationSchema, + 'notifications/resources/updated': s.ResourceUpdatedNotificationSchema, + 'notifications/resources/list_changed': s.ResourceListChangedNotificationSchema, + 'notifications/tools/list_changed': s.ToolListChangedNotificationSchema, + 'notifications/prompts/list_changed': s.PromptListChangedNotificationSchema, + 'notifications/elicitation/complete': s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + 'completion/complete': s.CompleteResultSchema, + 'logging/setLevel': s.EmptyResultSchema, + 'prompts/get': s.GetPromptResultSchema, + 'prompts/list': s.ListPromptsResultSchema, + 'resources/list': s.ListResourcesResultSchema, + 'resources/templates/list': s.ListResourceTemplatesResultSchema, + 'resources/read': s.ReadResourceResultSchema, + 'resources/subscribe': s.EmptyResultSchema, + 'resources/unsubscribe': s.EmptyResultSchema, + 'tools/call': s.CallToolResultWireSchema, + 'tools/list': s.ListToolsResultSchema, + 'sampling/createMessage': s.CreateMessageResultWithToolsSchema, + 'elicitation/create': s.ElicitResultSchema, + 'roots/list': s.ListRootsResultSchema + } + }; + return maps; +} + /** The 2025-era request-method set (registry membership = the deletion story). */ export function hasRequestMethod2025(method: string): method is Rev2025RequestMethod { - return Object.prototype.hasOwnProperty.call(requestSchemas, method); + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); } /** The 2025-era notification-method set. */ export function hasNotificationMethod2025(method: string): method is Rev2025NotificationMethod { - return Object.prototype.hasOwnProperty.call(notificationSchemas, method); + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); } /** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ function hasResultMethod(method: string): method is Rev2025TypedRequestMethod { - return Object.prototype.hasOwnProperty.call(resultSchemas, method); + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); } /** @@ -219,7 +237,7 @@ function hasResultMethod(method: string): method is Rev2025TypedRequestMethod { export function getResultSchema(method: M): z.ZodType; export function getResultSchema(method: string): z.ZodType | undefined; export function getResultSchema(method: string): z.ZodType | undefined { - return hasResultMethod(method) ? resultSchemas[method] : undefined; + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : undefined; } /** @@ -231,7 +249,7 @@ export function getResultSchema(method: string): z.ZodType | undefined { export function getRequestSchema(method: M): z.ZodType; export function getRequestSchema(method: string): z.ZodType | undefined; export function getRequestSchema(method: string): z.ZodType | undefined { - return hasRequestMethod2025(method) ? requestSchemas[method] : undefined; + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : undefined; } /** @@ -242,9 +260,9 @@ export function getRequestSchema(method: string): z.ZodType | undefined { export function getNotificationSchema(method: M): z.ZodType; export function getNotificationSchema(method: string): z.ZodType | undefined; export function getNotificationSchema(method: string): z.ZodType | undefined { - return hasNotificationMethod2025(method) ? notificationSchemas[method] : undefined; + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : undefined; } /** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -export const rev2025RequestMethods: readonly string[] = Object.keys(requestSchemas); -export const rev2025NotificationMethods: readonly string[] = Object.keys(notificationSchemas); +export const rev2025RequestMethods: readonly string[] = Object.keys(requestMethodKeys); +export const rev2025NotificationMethods: readonly string[] = Object.keys(notificationMethodKeys); diff --git a/packages/core-internal/src/wire/rev2025-11-25/schemas.ts b/packages/core-internal/src/wire/rev2025-11-25/schemas.ts index 935e3b74cc..76f4d7296b 100644 --- a/packages/core-internal/src/wire/rev2025-11-25/schemas.ts +++ b/packages/core-internal/src/wire/rev2025-11-25/schemas.ts @@ -1,992 +1,92 @@ /** - * Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from - * the public/neutral types/schemas.ts. The neutral layer is the public-API - * superset and is free to evolve (e.g., SEP-2106 widening); this file is the - * 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. - * - * This is the era's complete frozen wire-parse contract — both the 2025-only - * delta (the deprecated task family, the era role unions) AND frozen copies of - * every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, - * prompts/resources/completion/elicitation, …). The 2026-era codec - * (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. - * - * The 2025-only delta (the task message surface, restored types-only by #2248 - * for interop with task-capable 2025 peers) is parsed ONLY through this era's - * registry; the deprecated Task* schemas also live (marked `@deprecated`) in - * the neutral schema layer so the public types stay nameable without a - * cross-layer import — nameability is constant, runtime availability is - * version-keyed — but appear in no API signature. Q1 increment 2 — deletions - * are physical: the - * 2026-era REGISTRY has no Task* methods (its frozen building-block copies do - * carry the deprecated Task* sub-schemas by composition — soft contamination, - * tracked for anchor-exactness adjudication). - * - * The only cross-layer dependency is `import type { JSONObject, JSONValue }` - * from the neutral types barrel — pure structural type aliases with no parse - * behavior. No runtime schema is shared with the neutral layer. - */ -import * as z from 'zod/v4'; - -import type { JSONObject, JSONValue } from '../../types/types'; - -/* ─────────────────────────────────────────────────────────────────────────── - * Building blocks - * ─────────────────────────────────────────────────────────────────────────── */ - -export const JSONValueSchema: z.ZodType = z.lazy(() => - z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)]) -); -export const JSONObjectSchema: z.ZodType = z.record(z.string(), JSONValueSchema); - -/** - * A progress token, used to associate progress notifications with the original request. - */ -export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); - -/** - * An opaque token used to represent a cursor for pagination. - */ -export const CursorSchema = z.string(); - -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -export const TaskMetadataSchema = z.object({ - ttl: z.number().optional() -}); - -/** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const RelatedTaskMetadataSchema = z.object({ - taskId: z.string() -}); - -export const RequestMetaSchema = 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(), - /** - * If specified, this request is related to the provided task. - */ - 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional() -}); - -/** - * Common params for any request. - */ -export const BaseRequestParamsSchema = z.object({ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); - -/** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * 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: TaskMetadataSchema.optional() -}); - -export const RequestSchema = z.object({ - method: z.string(), - params: BaseRequestParamsSchema.loose().optional() -}); - -export const NotificationsParamsSchema = z.object({ - /** - * 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() -}); - -export const NotificationSchema = z.object({ - method: z.string(), - params: NotificationsParamsSchema.loose().optional() -}); - -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() -}); - -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); - -/* Empty result */ -/** - * A response that indicates success but carries no data. - */ -export const EmptyResultSchema = ResultSchema.strict(); - -export const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestIdSchema.optional(), - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: z.string().optional() -}); -/* Cancellation */ -/** - * 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 {@linkcode InitializeRequest | initialize} request. - */ -export const CancelledNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/cancelled'), - params: CancelledNotificationParamsSchema -}); - -/* Base Metadata */ -/** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ -export const IconSchema = z.object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), - /** - * Optional MIME type for the icon. - */ - mimeType: z.string().optional(), - /** - * 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: z.array(z.string()).optional(), - /** - * 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: z.enum(['light', 'dark']).optional() -}); - -/** - * Base schema to add `icons` property. - * - */ -export const IconsSchema = z.object({ - /** - * 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: z.array(IconSchema).optional() -}); - -/** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ -export const BaseMetadataSchema = z.object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: z.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: z.string().optional() -}); - -/* Initialization */ -/** - * Describes the name and version of an MCP implementation. - */ -export const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: z.string(), - /** - * An optional URL of the website for this implementation. - */ - websiteUrl: z.string().optional(), - - /** - * 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: z.string().optional() -}); - -const FormElicitationCapabilitySchema = z.intersection( - z.object({ - applyDefaults: z.boolean().optional() - }), - JSONObjectSchema -); - -const ElicitationCapabilitySchema = z.preprocess( - value => { - if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record).length === 0) { - return { form: {} }; - } - return value; - }, - z.intersection( - z.object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() - }), - JSONObjectSchema.optional() - ) -); - -/** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const ClientTasksCapabilitySchema = z.looseObject({ - /** - * Present if the client supports listing tasks. - */ - list: JSONObjectSchema.optional(), - /** - * Present if the client supports cancelling tasks. - */ - cancel: JSONObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: z - .looseObject({ - /** - * Task support for sampling requests. - */ - sampling: z - .looseObject({ - createMessage: JSONObjectSchema.optional() - }) - .optional(), - /** - * Task support for elicitation requests. - */ - elicitation: z - .looseObject({ - create: JSONObjectSchema.optional() - }) - .optional() - }) - .optional() -}); - -/** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const ServerTasksCapabilitySchema = z.looseObject({ - /** - * Present if the server supports listing tasks. - */ - list: JSONObjectSchema.optional(), - /** - * Present if the server supports cancelling tasks. - */ - cancel: JSONObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: z - .looseObject({ - /** - * Task support for tool requests. - */ - tools: z - .looseObject({ - call: JSONObjectSchema.optional() - }) - .optional() - }) - .optional() -}); - -/** - * 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. - */ -export const ClientCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: z.record(z.string(), JSONObjectSchema).optional(), - /** - * Present if the client supports sampling from an LLM. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - sampling: z - .object({ - /** - * Present if the client supports context inclusion via `includeContext` parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context: JSONObjectSchema.optional(), - /** - * Present if the client supports tool use via `tools` and `toolChoice` parameters. - */ - tools: JSONObjectSchema.optional() - }) - .optional(), - /** - * Present if the client supports eliciting user input. - */ - elicitation: ElicitationCapabilitySchema.optional(), - /** - * Present if the client supports listing roots. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - roots: z - .object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the client supports task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it. - */ - tasks: ClientTasksCapabilitySchema.optional(), - /** - * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). - */ - extensions: z.record(z.string(), JSONObjectSchema).optional() -}); - -export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: z.string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -export const InitializeRequestSchema = RequestSchema.extend({ - method: z.literal('initialize'), - params: InitializeRequestParamsSchema -}); - -/** - * 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. - */ -export const ServerCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: z.record(z.string(), JSONObjectSchema).optional(), - /** - * Present if the server supports sending log messages to the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - logging: JSONObjectSchema.optional(), - /** - * Present if the server supports sending completions to the client. - */ - completions: JSONObjectSchema.optional(), - /** - * Present if the server offers any prompt templates. - */ - prompts: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any resources to read. - */ - resources: z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.boolean().optional(), - - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any tools to call. - */ - tools: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server supports task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it. - */ - tasks: ServerTasksCapabilitySchema.optional(), - /** - * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). - */ - extensions: z.record(z.string(), JSONObjectSchema).optional() -}); - -/** - * After receiving an initialize request from the client, the server sends this response. - */ -export const InitializeResultSchema = ResultSchema.extend({ - /** - * 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: z.string(), - capabilities: ServerCapabilitiesSchema, - 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() -}); - -/** - * This notification is sent from the client to the server after initialization has finished. - */ -export const InitializedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/initialized'), - params: NotificationsParamsSchema.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. - */ -export const PingRequestSchema = RequestSchema.extend({ - method: z.literal('ping'), - params: BaseRequestParamsSchema.optional() -}); - -/* Progress notifications */ -export const ProgressSchema = z.object({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: z.number(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: z.optional(z.number()), - /** - * An optional message describing the current progress. - */ - message: z.optional(z.string()) -}); - -export const ProgressNotificationParamsSchema = z.object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema -}); -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ -export const ProgressNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/progress'), - params: ProgressNotificationParamsSchema -}); - -export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: CursorSchema.optional() -}); - -/* Pagination */ -export const PaginatedRequestSchema = RequestSchema.extend({ - params: PaginatedRequestParamsSchema.optional() -}); - -export const PaginatedResultSchema = ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: CursorSchema.optional() -}); - -/* Resources */ -/** - * The contents of a specific resource or sub-resource. - */ -export const ResourceContentsSchema = z.object({ - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const TextResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: z.string() -}); - -/** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ -const Base64Schema = z.string().refine( - val => { - try { - // atob throws a DOMException if the string contains characters - // that are not part of the Base64 character set. - atob(val); - return true; - } catch { - return false; - } - }, - { message: 'Invalid Base64 string' } -); - -export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: Base64Schema -}); - -/** - * The sender or recipient of messages and data in a conversation. - */ -export const RoleSchema = z.enum(['user', 'assistant']); - -/** - * Optional annotations providing clients additional context about a resource. - */ -export const AnnotationsSchema = z.object({ - /** - * Intended audience(s) for the resource. - */ - audience: z.array(RoleSchema).optional(), - - /** - * Importance hint for the resource, from 0 (least) to 1 (most). - */ - priority: z.number().min(0).max(1).optional(), - - /** - * ISO 8601 timestamp for the most recent modification. - */ - lastModified: z.iso.datetime({ offset: true }).optional() -}); - -/** - * A known resource that the server is capable of reading. - */ -export const ResourceSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * The URI of this resource. - */ - uri: z.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: z.optional(z.string()), - - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - - /** - * 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: z.optional(z.number()), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.optional(z.looseObject({})) -}); - -/** - * A template description for resources available on the server. - */ -export const ResourceTemplateSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: z.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: z.optional(z.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: z.optional(z.string()), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.optional(z.looseObject({})) -}); - -/** - * Sent from the client to request a list of resources the server has. - */ -export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/list') -}); - -/** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ -export const ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: z.array(ResourceSchema) -}); - -/** - * Sent from the client to request a list of resource templates the server has. - */ -export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/templates/list') -}); - -/** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ -export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: z.array(ResourceTemplateSchema) -}); - -export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: z.string() -}); - -/** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ -export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; - -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export const ReadResourceRequestSchema = RequestSchema.extend({ - method: z.literal('resources/read'), - params: ReadResourceRequestParamsSchema -}); - -/** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ -export const ReadResourceResultSchema = ResultSchema.extend({ - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); - -/** - * 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. - */ -export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ -export const SubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/subscribe'), - params: SubscribeRequestParamsSchema -}); - -export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ -export const UnsubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/unsubscribe'), - params: UnsubscribeRequestParamsSchema -}); - -/** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ -export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: z.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 {@linkcode SubscribeRequest | resources/subscribe} request. - */ -export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: ResourceUpdatedNotificationParamsSchema -}); - -/* Prompts */ -/** - * Describes an argument that a prompt can accept. - */ -export const PromptArgumentSchema = z.object({ - /** - * The name of the argument. - */ - name: z.string(), - /** - * A human-readable description of the argument. - */ - description: z.optional(z.string()), - /** - * Whether this argument must be provided. - */ - required: z.optional(z.boolean()) -}); - -/** - * A prompt or prompt template that the server offers. - */ -export const PromptSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * An optional description of what this prompt provides - */ - description: z.optional(z.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: z.optional(z.array(PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.optional(z.looseObject({})) -}); - -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('prompts/list') -}); - -/** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ -export const ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: z.array(PromptSchema) -}); - -/** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ -export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.record(z.string(), z.string()).optional() -}); -/** - * Used by the client to get a prompt provided by the server. - */ -export const GetPromptRequestSchema = RequestSchema.extend({ - method: z.literal('prompts/get'), - params: GetPromptRequestParamsSchema -}); - -/** - * Text provided to or from an LLM. - */ -export const TextContentSchema = z.object({ - type: z.literal('text'), - /** - * The text content of the message. - */ - text: z.string(), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * An image provided to or from an LLM. - */ -export const ImageContentSchema = z.object({ - type: z.literal('image'), - /** - * The base64-encoded image data. - */ - data: Base64Schema, - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: z.string(), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * Audio content provided to or from an LLM. - */ -export const AudioContentSchema = z.object({ - type: z.literal('audio'), - /** - * The base64-encoded audio data. - */ - data: Base64Schema, - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: z.string(), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - + * Eager named-export surface for the era wire schemas. + * + * The schema DEFINITIONS live in `./buildSchemas.ts`, wrapped in a memoized + * factory so the runtime graph (codec/registry) defers zod construction to + * the first validation. This module keeps the historical per-name import + * surface for tests and tooling: importing it warms the memo, and every + * export is the SAME object the registry serves (reference identity through + * the shared memo). + * + * Runtime modules must import `buildSchemas` instead — a runtime import of + * this shim would re-eagerize construction. + */ +import { buildSchemas2025 } from './buildSchemas'; + +const s = buildSchemas2025(); + +export const JSONValueSchema = s.JSONValueSchema; +export const JSONObjectSchema = s.JSONObjectSchema; +export const ProgressTokenSchema = s.ProgressTokenSchema; +export const CursorSchema = s.CursorSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskMetadataSchema = s.TaskMetadataSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const RelatedTaskMetadataSchema = s.RelatedTaskMetadataSchema; +export const RequestMetaSchema = s.RequestMetaSchema; +export const BaseRequestParamsSchema = s.BaseRequestParamsSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskAugmentedRequestParamsSchema = s.TaskAugmentedRequestParamsSchema; +export const RequestSchema = s.RequestSchema; +export const NotificationsParamsSchema = s.NotificationsParamsSchema; +export const NotificationSchema = s.NotificationSchema; +export const ResultSchema = s.ResultSchema; +export const RequestIdSchema = s.RequestIdSchema; +export const EmptyResultSchema = s.EmptyResultSchema; +export const CancelledNotificationParamsSchema = s.CancelledNotificationParamsSchema; +export const CancelledNotificationSchema = s.CancelledNotificationSchema; +export const IconSchema = s.IconSchema; +export const IconsSchema = s.IconsSchema; +export const BaseMetadataSchema = s.BaseMetadataSchema; +export const ImplementationSchema = s.ImplementationSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const ClientTasksCapabilitySchema = s.ClientTasksCapabilitySchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const ServerTasksCapabilitySchema = s.ServerTasksCapabilitySchema; +export const ClientCapabilitiesSchema = s.ClientCapabilitiesSchema; +export const InitializeRequestParamsSchema = s.InitializeRequestParamsSchema; +export const InitializeRequestSchema = s.InitializeRequestSchema; +export const ServerCapabilitiesSchema = s.ServerCapabilitiesSchema; +export const InitializeResultSchema = s.InitializeResultSchema; +export const InitializedNotificationSchema = s.InitializedNotificationSchema; +export const PingRequestSchema = s.PingRequestSchema; +export const ProgressSchema = s.ProgressSchema; +export const ProgressNotificationParamsSchema = s.ProgressNotificationParamsSchema; +export const ProgressNotificationSchema = s.ProgressNotificationSchema; +export const PaginatedRequestParamsSchema = s.PaginatedRequestParamsSchema; +export const PaginatedRequestSchema = s.PaginatedRequestSchema; +export const PaginatedResultSchema = s.PaginatedResultSchema; +export const ResourceContentsSchema = s.ResourceContentsSchema; +export const TextResourceContentsSchema = s.TextResourceContentsSchema; +export const BlobResourceContentsSchema = s.BlobResourceContentsSchema; +export const RoleSchema = s.RoleSchema; +export const AnnotationsSchema = s.AnnotationsSchema; +export const ResourceSchema = s.ResourceSchema; +export const ResourceTemplateSchema = s.ResourceTemplateSchema; +export const ListResourcesRequestSchema = s.ListResourcesRequestSchema; +export const ListResourcesResultSchema = s.ListResourcesResultSchema; +export const ListResourceTemplatesRequestSchema = s.ListResourceTemplatesRequestSchema; +export const ListResourceTemplatesResultSchema = s.ListResourceTemplatesResultSchema; +export const ResourceRequestParamsSchema = s.ResourceRequestParamsSchema; +export const ReadResourceRequestParamsSchema = s.ReadResourceRequestParamsSchema; +export const ReadResourceRequestSchema = s.ReadResourceRequestSchema; +export const ReadResourceResultSchema = s.ReadResourceResultSchema; +export const ResourceListChangedNotificationSchema = s.ResourceListChangedNotificationSchema; +export const SubscribeRequestParamsSchema = s.SubscribeRequestParamsSchema; +export const SubscribeRequestSchema = s.SubscribeRequestSchema; +export const UnsubscribeRequestParamsSchema = s.UnsubscribeRequestParamsSchema; +export const UnsubscribeRequestSchema = s.UnsubscribeRequestSchema; +export const ResourceUpdatedNotificationParamsSchema = s.ResourceUpdatedNotificationParamsSchema; +export const ResourceUpdatedNotificationSchema = s.ResourceUpdatedNotificationSchema; +export const PromptArgumentSchema = s.PromptArgumentSchema; +export const PromptSchema = s.PromptSchema; +export const ListPromptsRequestSchema = s.ListPromptsRequestSchema; +export const ListPromptsResultSchema = s.ListPromptsResultSchema; +export const GetPromptRequestParamsSchema = s.GetPromptRequestParamsSchema; +export const GetPromptRequestSchema = s.GetPromptRequestSchema; +export const TextContentSchema = s.TextContentSchema; +export const ImageContentSchema = s.ImageContentSchema; +export const AudioContentSchema = s.AudioContentSchema; /** * A tool call request from an assistant (LLM). * Represents the assistant's request to use a tool. @@ -995,295 +95,22 @@ export const AudioContentSchema = z.object({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const ToolUseContentSchema = z.object({ - type: z.literal('tool_use'), - /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. - */ - name: z.string(), - /** - * Unique identifier for this tool call. - * Used to correlate with `ToolResultContent` in subsequent messages. - */ - id: z.string(), - /** - * Arguments to pass to the tool. - * Must conform to the tool's `inputSchema`. - */ - input: z.record(z.string(), z.unknown()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -export const EmbeddedResourceSchema = z.object({ - type: z.literal('resource'), - resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * 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 {@linkcode ListResourcesRequest | resources/list} requests. - */ -export const ResourceLinkSchema = ResourceSchema.extend({ - type: z.literal('resource_link') -}); - -/** - * A content block that can be used in prompts and tool results. - */ -export const ContentBlockSchema = z.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); - -/** - * Describes a message returned as part of a prompt. - */ -export const PromptMessageSchema = z.object({ - role: RoleSchema, - content: ContentBlockSchema -}); - -/** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ -export const GetPromptResultSchema = ResultSchema.extend({ - /** - * An optional description for the prompt. - */ - description: z.string().optional(), - messages: z.array(PromptMessageSchema) -}); - -/** - * 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. - */ -export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -/* Tools */ -/** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode 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. - */ -export const ToolAnnotationsSchema = z.object({ - /** - * A human-readable title for the tool. - */ - title: z.string().optional(), - - /** - * If `true`, the tool does not modify its environment. - * - * Default: `false` - */ - readOnlyHint: z.boolean().optional(), - - /** - * 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: z.boolean().optional(), - - /** - * 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: z.boolean().optional(), - - /** - * 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: z.boolean().optional() -}); - -/** - * Execution-related properties for a tool. - */ -export const ToolExecutionSchema = z.object({ - /** - * Indicates the tool's preference for task-augmented execution. - * - `"required"`: Clients MUST invoke the tool as a task - * - `"optional"`: Clients MAY invoke the tool as a task or normal request - * - `"forbidden"`: Clients MUST NOT attempt to invoke the tool as a task - * - * If not present, defaults to `"forbidden"`. - */ - taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() -}); - -/** - * Definition for a tool the client can call. - */ -export const ToolSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A human-readable description of the tool. - */ - description: z.string().optional(), - /** - * A JSON Schema 2020-12 object defining the expected parameters for the tool. - * Must have `type: 'object'` at the root level per MCP spec. - */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), JSONValueSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()), - /** - * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the `structuredContent` field of a `CallToolResult`. - * Must have `type: 'object'` at the root level per MCP spec. - */ - outputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), JSONValueSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) - .optional(), - /** - * Optional additional tool information. - */ - annotations: ToolAnnotationsSchema.optional(), - /** - * Execution-related properties for this tool. - */ - execution: ToolExecutionSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * Sent from the client to request a list of tools the server has. - */ -export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tools/list') -}); - -/** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ -export const ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: z.array(ToolSchema) -}); - -/** - * The server's response to a tool call. - */ -export const CallToolResultSchema = ResultSchema.extend({ - /** - * A list of content objects that represent the result of the tool call. - * - * If the `Tool` does not define an outputSchema, this field MUST be present in the result. - * Required on the wire per the specification (it may be an empty array). - */ - content: z.array(ContentBlockSchema), - - /** - * An object containing structured tool output. - * - * If the `Tool` defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. - */ - structuredContent: z.record(z.string(), z.unknown()).optional(), - - /** - * 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: z.boolean().optional() -}); - -/** - * Parameters for a `tools/call` request. - */ -export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The name of the tool to call. - */ - name: z.string(), - /** - * Arguments to pass to the tool. - */ - arguments: z.record(z.string(), z.unknown()).optional() -}); - -/** - * Used by the client to invoke a tool provided by the server. - */ -export const CallToolRequestSchema = RequestSchema.extend({ - method: z.literal('tools/call'), - params: CallToolRequestParamsSchema -}); - -/** - * 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. - */ -export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -/* Logging */ +export const ToolUseContentSchema = s.ToolUseContentSchema; +export const EmbeddedResourceSchema = s.EmbeddedResourceSchema; +export const ResourceLinkSchema = s.ResourceLinkSchema; +export const ContentBlockSchema = s.ContentBlockSchema; +export const PromptMessageSchema = s.PromptMessageSchema; +export const GetPromptResultSchema = s.GetPromptResultSchema; +export const PromptListChangedNotificationSchema = s.PromptListChangedNotificationSchema; +export const ToolAnnotationsSchema = s.ToolAnnotationsSchema; +export const ToolExecutionSchema = s.ToolExecutionSchema; +export const ToolSchema = s.ToolSchema; +export const ListToolsRequestSchema = s.ListToolsRequestSchema; +export const ListToolsResultSchema = s.ListToolsResultSchema; +export const CallToolResultSchema = s.CallToolResultSchema; +export const CallToolRequestParamsSchema = s.CallToolRequestParamsSchema; +export const CallToolRequestSchema = s.CallToolRequestSchema; +export const ToolListChangedNotificationSchema = s.ToolListChangedNotificationSchema; /** * The severity of a log message. * @@ -1291,8 +118,7 @@ export const ToolListChangedNotificationSchema = NotificationSchema.extend({ * in the specification for at least twelve months. Migrate to stderr logging * (STDIO servers) or OpenTelemetry. */ -export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); - +export const LoggingLevelSchema = s.LoggingLevelSchema; /** * Parameters for a `logging/setLevel` request. * @@ -1300,12 +126,7 @@ export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', * in the specification for at least twelve months. Migrate to stderr logging * (STDIO servers) or OpenTelemetry. */ -export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * 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/logging/message`. - */ - level: LoggingLevelSchema -}); +export const SetLevelRequestParamsSchema = s.SetLevelRequestParamsSchema; /** * A request from the client to the server, to enable or adjust logging. * @@ -1313,11 +134,7 @@ export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ * in the specification for at least twelve months. Migrate to stderr logging * (STDIO servers) or OpenTelemetry. */ -export const SetLevelRequestSchema = RequestSchema.extend({ - method: z.literal('logging/setLevel'), - params: SetLevelRequestParamsSchema -}); - +export const SetLevelRequestSchema = s.SetLevelRequestSchema; /** * Parameters for a `notifications/message` notification. * @@ -1325,20 +142,7 @@ export const SetLevelRequestSchema = RequestSchema.extend({ * in the specification for at least twelve months. Migrate to stderr logging * (STDIO servers) or OpenTelemetry. */ -export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: z.string().optional(), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: z.unknown() -}); +export const LoggingMessageNotificationParamsSchema = s.LoggingMessageNotificationParamsSchema; /** * Notification 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. * @@ -1346,12 +150,7 @@ export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema. * in the specification for at least twelve months. Migrate to stderr logging * (STDIO servers) or OpenTelemetry. */ -export const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: LoggingMessageNotificationParamsSchema -}); - -/* Sampling */ +export const LoggingMessageNotificationSchema = s.LoggingMessageNotificationSchema; /** * Hints to use for model selection. * @@ -1359,13 +158,7 @@ export const LoggingMessageNotificationSchema = NotificationSchema.extend({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const ModelHintSchema = z.object({ - /** - * A hint for a model name. - */ - name: z.string().optional() -}); - +export const ModelHintSchema = s.ModelHintSchema; /** * The server's preferences for model selection, requested of the client during sampling. * @@ -1373,25 +166,7 @@ export const ModelHintSchema = z.object({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const ModelPreferencesSchema = z.object({ - /** - * Optional hints to use for model selection. - */ - hints: z.array(ModelHintSchema).optional(), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: z.number().min(0).max(1).optional(), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: z.number().min(0).max(1).optional(), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: z.number().min(0).max(1).optional() -}); - +export const ModelPreferencesSchema = s.ModelPreferencesSchema; /** * Controls tool usage behavior in sampling requests. * @@ -1399,16 +174,7 @@ export const ModelPreferencesSchema = z.object({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const ToolChoiceSchema = z.object({ - /** - * Controls when tools are used: - * - `"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: z.enum(['auto', 'required', 'none']).optional() -}); - +export const ToolChoiceSchema = s.ToolChoiceSchema; /** * The result of a tool execution, provided by the user (server). * Represents the outcome of invoking a tool requested via `ToolUseContent`. @@ -1417,20 +183,7 @@ export const ToolChoiceSchema = z.object({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const ToolResultContentSchema = z.object({ - type: z.literal('tool_result'), - toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), - content: z.array(ContentBlockSchema), - structuredContent: z.object({}).loose().optional(), - isError: z.boolean().optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - +export const ToolResultContentSchema = s.ToolResultContentSchema; /** * Basic content types for sampling responses (without tool use). * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. @@ -1439,8 +192,7 @@ export const ToolResultContentSchema = z.object({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); - +export const SamplingContentSchema = s.SamplingContentSchema; /** * Content block types allowed in sampling messages. * This includes text, image, audio, tool use requests, and tool results. @@ -1449,14 +201,7 @@ export const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSc * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); - +export const SamplingMessageContentBlockSchema = s.SamplingMessageContentBlockSchema; /** * Describes a message issued to or received from an LLM API. * @@ -1464,16 +209,7 @@ export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const SamplingMessageSchema = z.object({ - role: RoleSchema, - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - +export const SamplingMessageSchema = s.SamplingMessageSchema; /** * Parameters for a `sampling/createMessage` request. * @@ -1481,52 +217,7 @@ export const SamplingMessageSchema = z.object({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - messages: z.array(SamplingMessageSchema), - /** - * The server's preferences for which model to select. The client MAY modify or omit this request. - */ - modelPreferences: ModelPreferencesSchema.optional(), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: z.string().optional(), - /** - * 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"`. The values `"thisServer"` and `"allServers"` are deprecated (SEP-2596): servers SHOULD - * omit this field or use `"none"`, and SHOULD only use the deprecated values if the client declares - * `ClientCapabilities`.`sampling.context`. - * - * @deprecated The `"thisServer"` and `"allServers"` values are deprecated as of protocol version 2025-11-25 - * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `"none"`. - */ - includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), - temperature: z.number().optional(), - /** - * 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: z.number().int(), - stopSequences: z.array(z.string()).optional(), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: JSONObjectSchema.optional(), - /** - * 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: z.array(ToolSchema).optional(), - /** - * 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: ToolChoiceSchema.optional() -}); +export const CreateMessageRequestParamsSchema = s.CreateMessageRequestParamsSchema; /** * 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. * @@ -1534,11 +225,7 @@ export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const CreateMessageRequestSchema = RequestSchema.extend({ - method: z.literal('sampling/createMessage'), - params: CreateMessageRequestParamsSchema -}); - +export const CreateMessageRequestSchema = s.CreateMessageRequestSchema; /** * The client's response to a `sampling/create_message` request from the server. * This is the backwards-compatible version that returns single content (no arrays). @@ -1548,29 +235,7 @@ export const CreateMessageRequestSchema = RequestSchema.extend({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const CreateMessageResultSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.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 - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), - role: RoleSchema, - /** - * Response content. Single content block (text, image, or audio). - */ - content: SamplingContentSchema -}); - +export const CreateMessageResultSchema = s.CreateMessageResultSchema; /** * The client's response to a `sampling/create_message` request when tools were provided. * This version supports array content for tool use flows. @@ -1579,349 +244,31 @@ export const CreateMessageResultSchema = ResultSchema.extend({ * in the specification for at least twelve months. Migrate to calling LLM * provider APIs directly. */ -export const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.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: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), - role: RoleSchema, - /** - * Response content. May be a single block or array. May include `ToolUseContent` if `stopReason` is `"toolUse"`. - */ - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) -}); - -/* Elicitation */ -/** - * Primitive schema definition for boolean fields. - */ -export const BooleanSchemaSchema = z.object({ - type: z.literal('boolean'), - title: z.string().optional(), - description: z.string().optional(), - default: z.boolean().optional() -}); - -/** - * Primitive schema definition for string fields. - */ -export const StringSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - minLength: z.number().optional(), - maxLength: z.number().optional(), - format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), - default: z.string().optional() -}); - -/** - * Primitive schema definition for number fields. - */ -export const NumberSchemaSchema = z.object({ - type: z.enum(['number', 'integer']), - title: z.string().optional(), - description: z.string().optional(), - minimum: z.number().optional(), - maximum: z.number().optional(), - default: z.number().optional() -}); - -/** - * Schema for single-selection enumeration without display titles for options. - */ -export const UntitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - default: z.string().optional() -}); - -/** - * Schema for single-selection enumeration with display titles for each option. - */ -export const TitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - oneOf: z.array( - z.object({ - const: z.string(), - title: z.string() - }) - ), - default: z.string().optional() -}); - -/** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ -export const LegacyTitledEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - enumNames: z.array(z.string()).optional(), - default: z.string().optional() -}); - -// Combined single selection enumeration -export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); - -/** - * Schema for multiple-selection enumeration without display titles for options. - */ -export const UntitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - type: z.literal('string'), - enum: z.array(z.string()) - }), - default: z.array(z.string()).optional() -}); - -/** - * Schema for multiple-selection enumeration with display titles for each option. - */ -export const TitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - anyOf: z.array( - z.object({ - const: z.string(), - title: z.string() - }) - ) - }), - default: z.array(z.string()).optional() -}); - -/** - * Combined schema for multiple-selection enumeration - */ -export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); - -/** - * Primitive schema definition for enum fields. - */ -export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); - -/** - * Union of all primitive schema definitions. - */ -export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); - -/** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ -export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The elicitation mode. - * - * Optional for backward compatibility. Clients MUST treat missing `mode` as `"form"`. - */ - mode: z.literal('form').optional(), - /** - * The message to present to the user describing what information is being requested. - */ - message: z.string(), - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) -}); - -/** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ -export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('url'), - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: z.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: z.string(), - /** - * The URL that the user should navigate to. - */ - url: z.string().url() -}); - -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); - -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -export const ElicitRequestSchema = RequestSchema.extend({ - method: z.literal('elicitation/create'), - params: ElicitRequestParamsSchema -}); - -/** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the elicitation that completed. - */ - elicitationId: z.string() -}); - -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/elicitation/complete'), - params: ElicitationCompleteNotificationParamsSchema -}); - -/** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ -export const ElicitResultSchema = ResultSchema.extend({ - /** - * The user action in response to the elicitation. - * - `"accept"`: User submitted the form/confirmed the action - * - `"decline"`: User explicitly declined the action - * - `"cancel"`: User dismissed without making an explicit choice - */ - action: z.enum(['accept', 'decline', 'cancel']), - /** - * The submitted form data, only present when action is `"accept"`. - * Contains values matching the requested schema. - * Per MCP spec, content is "typically omitted" for decline/cancel actions. - * We normalize `null` to `undefined` for leniency while maintaining type compatibility. - */ - content: z.preprocess( - val => (val === null ? undefined : val), - z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() - ) -}); - -/* Autocomplete */ -/** - * A reference to a resource or resource template definition. - */ -export const ResourceTemplateReferenceSchema = z.object({ - type: z.literal('ref/resource'), - /** - * The URI or URI template of the resource. - */ - uri: z.string() -}); - -/** - * Identifies a prompt. - */ -export const PromptReferenceSchema = z.object({ - type: z.literal('ref/prompt'), - /** - * The name of the prompt or prompt template - */ - name: z.string() -}); - -/** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ -export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: z.object({ - /** - * The name of the argument - */ - name: z.string(), - /** - * The value of the argument to use for completion matching. - */ - value: z.string() - }), - context: z - .object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.record(z.string(), z.string()).optional() - }) - .optional() -}); -/** - * A request from the client to the server, to ask for completion options. - */ -export const CompleteRequestSchema = RequestSchema.extend({ - method: z.literal('completion/complete'), - params: CompleteRequestParamsSchema -}); - -/** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ -export const CompleteResultSchema = ResultSchema.extend({ - completion: z.looseObject({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.array(z.string()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.optional(z.number().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.optional(z.boolean()) - }) -}); - -/* Roots */ +export const CreateMessageResultWithToolsSchema = s.CreateMessageResultWithToolsSchema; +export const BooleanSchemaSchema = s.BooleanSchemaSchema; +export const StringSchemaSchema = s.StringSchemaSchema; +export const NumberSchemaSchema = s.NumberSchemaSchema; +export const UntitledSingleSelectEnumSchemaSchema = s.UntitledSingleSelectEnumSchemaSchema; +export const TitledSingleSelectEnumSchemaSchema = s.TitledSingleSelectEnumSchemaSchema; +export const LegacyTitledEnumSchemaSchema = s.LegacyTitledEnumSchemaSchema; +export const SingleSelectEnumSchemaSchema = s.SingleSelectEnumSchemaSchema; +export const UntitledMultiSelectEnumSchemaSchema = s.UntitledMultiSelectEnumSchemaSchema; +export const TitledMultiSelectEnumSchemaSchema = s.TitledMultiSelectEnumSchemaSchema; +export const MultiSelectEnumSchemaSchema = s.MultiSelectEnumSchemaSchema; +export const EnumSchemaSchema = s.EnumSchemaSchema; +export const PrimitiveSchemaDefinitionSchema = s.PrimitiveSchemaDefinitionSchema; +export const ElicitRequestFormParamsSchema = s.ElicitRequestFormParamsSchema; +export const ElicitRequestURLParamsSchema = s.ElicitRequestURLParamsSchema; +export const ElicitRequestParamsSchema = s.ElicitRequestParamsSchema; +export const ElicitRequestSchema = s.ElicitRequestSchema; +export const ElicitationCompleteNotificationParamsSchema = s.ElicitationCompleteNotificationParamsSchema; +export const ElicitationCompleteNotificationSchema = s.ElicitationCompleteNotificationSchema; +export const ElicitResultSchema = s.ElicitResultSchema; +export const ResourceTemplateReferenceSchema = s.ResourceTemplateReferenceSchema; +export const PromptReferenceSchema = s.PromptReferenceSchema; +export const CompleteRequestParamsSchema = s.CompleteRequestParamsSchema; +export const CompleteRequestSchema = s.CompleteRequestSchema; +export const CompleteResultSchema = s.CompleteResultSchema; /** * Represents a root directory or file that the server can operate on. * @@ -1929,23 +276,7 @@ export const CompleteResultSchema = ResultSchema.extend({ * in the specification for at least twelve months. Migrate to passing paths via * tool parameters, resource URIs, or configuration. */ -export const RootSchema = z.object({ - /** - * The URI identifying the root. This *must* start with `file://` for now. - */ - uri: z.string().startsWith('file://'), - /** - * An optional name for the root. - */ - name: z.string().optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - +export const RootSchema = s.RootSchema; /** * Sent from the server to request a list of root URIs from the client. * @@ -1953,11 +284,7 @@ export const RootSchema = z.object({ * in the specification for at least twelve months. Migrate to passing paths via * tool parameters, resource URIs, or configuration. */ -export const ListRootsRequestSchema = RequestSchema.extend({ - method: z.literal('roots/list'), - params: BaseRequestParamsSchema.optional() -}); - +export const ListRootsRequestSchema = s.ListRootsRequestSchema; /** * The client's response to a `roots/list` request from the server. * @@ -1965,10 +292,7 @@ export const ListRootsRequestSchema = RequestSchema.extend({ * in the specification for at least twelve months. Migrate to passing paths via * tool parameters, resource URIs, or configuration. */ -export const ListRootsResultSchema = ResultSchema.extend({ - roots: z.array(RootSchema) -}); - +export const ListRootsResultSchema = s.ListRootsResultSchema; /** * A notification from the client to the server, informing it that the list of roots has changed. * @@ -1976,254 +300,39 @@ export const ListRootsResultSchema = ResultSchema.extend({ * in the specification for at least twelve months. Migrate to passing paths via * tool parameters, resource URIs, or configuration. */ -export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -/* ─────────────────────────────────────────────────────────────────────────── - * Tasks (2025-11-25 wire vocabulary; restored types-only by #2248 for interop - * with task-capable 2025 peers — parsed ONLY through this era's registry). - * ─────────────────────────────────────────────────────────────────────────── */ - -/** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const TaskCreationParamsSchema = z.looseObject({ - /** - * Requested duration in milliseconds to retain task from creation. - */ - ttl: z.number().optional(), - - /** - * Time in milliseconds to wait between task status requests. - */ - pollInterval: z.number().optional() -}); - -/** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); - -/** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const TaskSchema = z.object({ - taskId: z.string(), - status: TaskStatusSchema, - /** - * Time in milliseconds to keep task results available after completion. - * If `null`, the task has unlimited lifetime until manually cleaned up. - */ - ttl: z.union([z.number(), z.null()]), - /** - * ISO 8601 timestamp when the task was created. - */ - createdAt: z.string(), - /** - * ISO 8601 timestamp when the task was last updated. - */ - lastUpdatedAt: z.string(), - pollInterval: z.optional(z.number()), - /** - * Optional diagnostic message for failed tasks or other status information. - */ - statusMessage: z.optional(z.string()) -}); - -/** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const CreateTaskResultSchema = ResultSchema.extend({ - task: TaskSchema -}); - -/** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); - -/** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tasks/status'), - params: TaskStatusNotificationParamsSchema -}); - -/** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const GetTaskRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/get'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); - -/** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const GetTaskResultSchema = ResultSchema.merge(TaskSchema); - -/** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/result'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); - -/** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const GetTaskPayloadResultSchema = ResultSchema.loose(); - -/** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const ListTasksRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tasks/list') -}); - -/** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const ListTasksResultSchema = PaginatedResultSchema.extend({ - tasks: z.array(TaskSchema) -}); - -/** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const CancelTaskRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/cancel'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); - -/** - * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); - -/* ─────────────────────────────────────────────────────────────────────────── - * The 2025-era wire role unions: the era-faithful aggregates (what a - * 2025-11-25 peer may legally put on the wire, per role) and the source the - * era registry is built from. Member order preserves the pre-split unions - * (task members last for requests/results; notification members are - * method-discriminated, so ordering is not observable). - * ─────────────────────────────────────────────────────────────────────────── */ - -export const ClientRequestSchema = z.union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); - -export const ClientNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema, - TaskStatusNotificationSchema -]); - -export const ClientResultSchema = z.union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); - -export const ServerRequestSchema = z.union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); - -export const ServerNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - TaskStatusNotificationSchema, - ElicitationCompleteNotificationSchema -]); - -export const ServerResultSchema = z.union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); +export const RootsListChangedNotificationSchema = s.RootsListChangedNotificationSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskCreationParamsSchema = s.TaskCreationParamsSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskStatusSchema = s.TaskStatusSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskSchema = s.TaskSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const CreateTaskResultSchema = s.CreateTaskResultSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskStatusNotificationParamsSchema = s.TaskStatusNotificationParamsSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskStatusNotificationSchema = s.TaskStatusNotificationSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const GetTaskRequestSchema = s.GetTaskRequestSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const GetTaskResultSchema = s.GetTaskResultSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const GetTaskPayloadRequestSchema = s.GetTaskPayloadRequestSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const GetTaskPayloadResultSchema = s.GetTaskPayloadResultSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const ListTasksRequestSchema = s.ListTasksRequestSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const ListTasksResultSchema = s.ListTasksResultSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const CancelTaskRequestSchema = s.CancelTaskRequestSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const CancelTaskResultSchema = s.CancelTaskResultSchema; +export const ClientRequestSchema = s.ClientRequestSchema; +export const ClientNotificationSchema = s.ClientNotificationSchema; +export const ClientResultSchema = s.ClientResultSchema; +export const ServerRequestSchema = s.ServerRequestSchema; +export const ServerNotificationSchema = s.ServerNotificationSchema; +export const ServerResultSchema = s.ServerResultSchema; +export const CallToolResultWireSchema = s.CallToolResultWireSchema; diff --git a/packages/core-internal/src/wire/rev2026-07-28/buildSchemas.ts b/packages/core-internal/src/wire/rev2026-07-28/buildSchemas.ts new file mode 100644 index 0000000000..a8aa6b7262 --- /dev/null +++ b/packages/core-internal/src/wire/rev2026-07-28/buildSchemas.ts @@ -0,0 +1,1399 @@ +/** + * 2026-era wire schemas (protocol revision 2026-07-28). + * + * Fully self-contained — no runtime imports from types/schemas.ts. The + * neutral types/schemas.ts layer is the public-API superset and is free to + * evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN + * against the 2026-07-28 anchor. Every era-shared building block (content + * blocks, resources, prompts, capabilities, notifications, …) that the wire + * shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at + * the point this revision was sealed, dependencies first. The only cross-layer + * dependency is `import type { JSONObject, JSONValue }` from the neutral types + * barrel — pure structural type aliases with no parse behavior. + * + * This module is the only place the per-request `_meta` envelope is modeled. + * The envelope is wire-only vocabulary: the protocol layer lifts it off + * inbound requests before any handler runs and surfaces it at + * `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at + * dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc + * deferral ("enforced per request at dispatch time, not here") is now + * discharged by that codec step. + * + * No 2025-era traffic ever touches this module, so requiredness here is + * bare and spec-exact (the shared-schema `.catch` hazards do not apply). + */ +import * as z from 'zod/v4'; + +import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, PROTOCOL_VERSION_META_KEY } from '../../types/constants'; +import type { JSONObject, JSONValue } from '../../types/types'; + +/** + * The 2026-era request-method set — the hand-registry seed (see registry.ts + * for the seed decisions). The dispatch maps below are mapped types over this + * union, so a missing entry, an extra entry, or an entry pointing at another + * method's schema is a compile error; the CI registry-diff oracle pins the + * same set against the anchor at runtime. + */ +export type Rev2026RequestMethod = + | 'tools/call' + | 'tools/list' + | 'prompts/get' + | 'prompts/list' + | 'resources/list' + | 'resources/templates/list' + | 'resources/read' + | 'completion/complete' + | 'server/discover' + | 'subscriptions/listen'; + +/** The 2026-era notification-method set (the hand-registry seed; see the deletion list above). */ +export type Rev2026NotificationMethod = + | 'notifications/cancelled' + | 'notifications/progress' + | 'notifications/message' + | 'notifications/resources/updated' + | 'notifications/resources/list_changed' + | 'notifications/tools/list_changed' + | 'notifications/prompts/list_changed' + | 'notifications/subscriptions/acknowledged'; + +function build() { + /* ════════════════════════════════════════════════════════════════════════════ + * Frozen neutral-layer building blocks + * + * Everything from this point until the next ═-banner is a verbatim frozen + * copy of a schema that, at the time this revision was sealed, lived in the + * neutral types/schemas.ts. They are copied dependencies-first so no forward + * references exist. They are NOT re-derived from the public layer at runtime — + * a widening or tightening landed on types/schemas.ts has no effect here until + * a deliberate per-revision re-freeze. + * ════════════════════════════════════════════════════════════════════════════ */ + + const JSONValueSchema: z.ZodType = z.lazy(() => + z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)]) + ); + const JSONObjectSchema: z.ZodType = z.record(z.string(), JSONValueSchema); + + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema = z.union([z.string(), z.number().int()]); + + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema = z.string(); + + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema = z.union([z.string(), z.number().int()]); + + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema = z.enum(['user', 'assistant']); + + /** + * The severity of a log message. + */ + const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); + + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = z.string().refine( + val => { + try { + atob(val); + return true; + } catch { + return false; + } + }, + { message: 'Invalid Base64 string' } + ); + + /* ─── Request/notification meta and base params ─── */ + + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema = z.object({ + ttl: z.number().optional() + }); + + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema = z.object({ + taskId: z.string() + }); + + const RequestMetaSchema = 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(), + /** + * If specified, this request is related to the provided task. + */ + 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional() + }); + + const BaseRequestParamsSchema = z.object({ + _meta: RequestMetaSchema.optional() + }); + + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + task: TaskMetadataSchema.optional() + }); + + const NotificationsParamsSchema = z.object({ + _meta: RequestMetaSchema.optional() + }); + + const NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.loose().optional() + }); + + /* ─── Icons / base metadata / implementation ─── */ + + const IconSchema = z.object({ + src: z.string(), + mimeType: z.string().optional(), + sizes: z.array(z.string()).optional(), + theme: z.enum(['light', 'dark']).optional() + }); + + const IconsSchema = z.object({ + icons: z.array(IconSchema).optional() + }); + + const BaseMetadataSchema = z.object({ + name: z.string(), + title: z.string().optional() + }); + + const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: z.string(), + websiteUrl: z.string().optional(), + description: z.string().optional() + }); + + /* ─── Capability schemas ─── */ + + const FormElicitationCapabilitySchema = z.intersection( + z.object({ + applyDefaults: z.boolean().optional() + }), + JSONObjectSchema + ); + + const ElicitationCapabilitySchema = z.preprocess( + value => { + if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record).length === 0) { + return { form: {} }; + } + return value; + }, + z.intersection( + z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() + }), + JSONObjectSchema.optional() + ) + ); + + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema = z.looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: z + .looseObject({ + sampling: z + .looseObject({ + createMessage: JSONObjectSchema.optional() + }) + .optional(), + elicitation: z + .looseObject({ + create: JSONObjectSchema.optional() + }) + .optional() + }) + .optional() + }); + + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema = z.looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: z + .looseObject({ + tools: z + .looseObject({ + call: JSONObjectSchema.optional() + }) + .optional() + }) + .optional() + }); + + const ClientCapabilitiesSchema = z.object({ + experimental: z.record(z.string(), JSONObjectSchema).optional(), + sampling: z + .object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }) + .optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: z + .object({ + listChanged: z.boolean().optional() + }) + .optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: z.record(z.string(), JSONObjectSchema).optional() + }); + + const ServerCapabilitiesSchema = z.object({ + experimental: z.record(z.string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: z + .object({ + listChanged: z.boolean().optional() + }) + .optional(), + resources: z + .object({ + subscribe: z.boolean().optional(), + listChanged: z.boolean().optional() + }) + .optional(), + tools: z + .object({ + listChanged: z.boolean().optional() + }) + .optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: z.record(z.string(), JSONObjectSchema).optional() + }); + + /* ─── Progress / logging notifications ─── */ + + const ProgressSchema = z.object({ + progress: z.number(), + total: z.optional(z.number()), + message: z.optional(z.string()) + }); + + const ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema + }); + + const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: ProgressNotificationParamsSchema + }); + + const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: z.string().optional(), + data: z.unknown() + }); + + const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: LoggingMessageNotificationParamsSchema + }); + + /* ─── Resource contents / annotations ─── */ + + const ResourceContentsSchema = z.object({ + uri: z.string(), + mimeType: z.optional(z.string()), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const TextResourceContentsSchema = ResourceContentsSchema.extend({ + text: z.string() + }); + + const BlobResourceContentsSchema = ResourceContentsSchema.extend({ + blob: Base64Schema + }); + + const AnnotationsSchema = z.object({ + audience: z.array(RoleSchema).optional(), + priority: z.number().min(0).max(1).optional(), + lastModified: z.iso.datetime({ offset: true }).optional() + }); + + /* ─── Resources / templates / list-changed notifications ─── */ + + const ResourceSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: z.string(), + description: z.optional(z.string()), + mimeType: z.optional(z.string()), + size: z.optional(z.number()), + annotations: AnnotationsSchema.optional(), + _meta: z.optional(z.looseObject({})) + }); + + const ResourceTemplateSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: z.string(), + description: z.optional(z.string()), + mimeType: z.optional(z.string()), + annotations: AnnotationsSchema.optional(), + _meta: z.optional(z.looseObject({})) + }); + + const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + uri: z.string() + }); + + const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: ResourceUpdatedNotificationParamsSchema + }); + + /* ─── Prompts / content blocks ─── */ + + const PromptArgumentSchema = z.object({ + name: z.string(), + description: z.optional(z.string()), + required: z.optional(z.boolean()) + }); + + const PromptSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: z.optional(z.string()), + arguments: z.optional(z.array(PromptArgumentSchema)), + _meta: z.optional(z.looseObject({})) + }); + + const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + const TextContentSchema = z.object({ + type: z.literal('text'), + text: z.string(), + annotations: AnnotationsSchema.optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const ImageContentSchema = z.object({ + type: z.literal('image'), + data: Base64Schema, + mimeType: z.string(), + annotations: AnnotationsSchema.optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const AudioContentSchema = z.object({ + type: z.literal('audio'), + data: Base64Schema, + mimeType: z.string(), + annotations: AnnotationsSchema.optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const ToolUseContentSchema = z.object({ + type: z.literal('tool_use'), + name: z.string(), + id: z.string(), + input: z.record(z.string(), z.unknown()), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + const ResourceLinkSchema = ResourceSchema.extend({ + type: z.literal('resource_link') + }); + + const ContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema + ]); + + const PromptMessageSchema = z.object({ + role: RoleSchema, + content: ContentBlockSchema + }); + + /* ─── Tool annotations / tool list-changed / sampling primitives ─── */ + + const ToolAnnotationsSchema = z.object({ + title: z.string().optional(), + readOnlyHint: z.boolean().optional(), + destructiveHint: z.boolean().optional(), + idempotentHint: z.boolean().optional(), + openWorldHint: z.boolean().optional() + }); + + const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed'), + params: NotificationsParamsSchema.optional() + }); + + const ModelHintSchema = z.object({ + name: z.string().optional() + }); + + const ModelPreferencesSchema = z.object({ + hints: z.array(ModelHintSchema).optional(), + costPriority: z.number().min(0).max(1).optional(), + speedPriority: z.number().min(0).max(1).optional(), + intelligencePriority: z.number().min(0).max(1).optional() + }); + + const ToolChoiceSchema = z.object({ + mode: z.enum(['auto', 'required', 'none']).optional() + }); + + /* ─── Elicitation primitive-schema vocabulary ─── */ + + const BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() + }); + + const StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() + }); + + const NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() + }); + + const UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() + }); + + const TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array( + z.object({ + const: z.string(), + title: z.string() + }) + ), + default: z.string().optional() + }); + + const LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() + }); + + const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); + + const UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() + }); + + const TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array( + z.object({ + const: z.string(), + title: z.string() + }) + ) + }), + default: z.array(z.string()).optional() + }); + + const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); + + const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); + + const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); + + const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + mode: z.literal('form').optional(), + message: z.string(), + requestedSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + }); + + /* ─── Completion references / roots ─── */ + + const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + uri: z.string() + }); + + const PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + name: z.string() + }); + + const RootSchema = z.object({ + uri: z.string().startsWith('file://'), + name: z.string().optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /* ════════════════════════════════════════════════════════════════════════════ + * End of frozen neutral-layer building blocks. Everything below is the + * 2026-07-28 wire-specific vocabulary (envelope, forks, results, requests, + * notifications) composed against the frozen copies above. + * ════════════════════════════════════════════════════════════════════════════ */ + + /* 2026-era capability forks (defined ahead of the envelope, which composes + * the client fork). The frozen shapes minus the deleted `tasks` key: `tasks` + * is 2025-only vocabulary with no slot on this revision, consistent with the + * encode-side deletion (Q1-SD3 iii). + * + * Both forks list their members EXPLICITLY (composing the frozen member + * schemas by reference) rather than using `.omit()`: the envelope schema + * below reaches the bundled package declarations, and an `.omit()` inference + * is a mapped type whose printed member order is unstable across dts-rollup + * builds (api-report flap). The explicit list doubles as the fork's deletion + * statement — a member added to the frozen shape must be re-adjudicated here. */ + const sharedClientCapabilityShape = ClientCapabilitiesSchema.shape; + const ClientCapabilities2026Schema = z.object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema.shape; + const ServerCapabilities2026Schema = z.object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + + /* 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 (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + 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. Validated with the 2026 fork: `tasks` has no slot on + * this revision (deleted vocabulary), matching the server-side fork wired + * into `DiscoverResultSchema`. + */ + [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + /** + * 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() + }); + + /* ------------------------------------------------------------------------ * + * Forked payload vocabulary (shared-tier admission rule, ATK-B section 1): + * `Tool` and `SamplingMessage` are bidirectionally incomparable between the + * 2025-11-25 and 2026-07-28 anchors, so they FORK per wire module instead of + * sitting in the shared tier. The forks below are 2026-anchor-exact: + * - Tool (2026) has NO `execution` member (ToolExecution and its + * `taskSupport` carrier are deleted vocabulary) — a 2026 peer's tool that + * carries one is stripped on parse, and the encode side strips it from + * outbound tools (Q1-SD3 iii). + * - SamplingMessage (2026) is composed against the 2026 anchor shape. + * ------------------------------------------------------------------------ */ + + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: z.string().optional(), + // Anchor-exact: { $schema?: string; type: 'object'; [key: string]: unknown } + inputSchema: z.looseObject({ + $schema: z.string().optional(), + type: z.literal('object') + }), + // Anchor-exact: { $schema?: string; [key: string]: unknown } + outputSchema: z + .looseObject({ + $schema: z.string().optional() + }) + .optional(), + annotations: ToolAnnotationsSchema.optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema = z.object({ + type: z.literal('tool_result'), + toolUseId: z.string(), + content: z.array(ContentBlockSchema), + structuredContent: z.unknown().optional(), + isError: z.boolean().optional(), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema + ]); + + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema = z.object({ + role: RoleSchema, + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + _meta: z.record(z.string(), z.unknown()).optional() + }); + + /* ------------------------------------------------------------------------ * + * Result side. `resultType` is a sender obligation (spec.types.2026-07-28 + * Result.resultType: "Servers implementing this protocol version MUST + * include this field") and a receiver default (schema.ts:208 — clients MUST + * treat absent `resultType` as 'complete'). These are the WIRE-TRUE + * artifacts — the corpus and the parity suite parse them; `decodeResult` + * parses with them and then LIFTS (drops resultType) to the neutral shape. + * Sender-side requiredness is enforced by construction (`encodeResult` + * stamps it), so the parse side carries the receiver default. + * ------------------------------------------------------------------------ */ + + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = z.string(); + + const wireMeta = z.record(z.string(), z.unknown()).optional(); + + function wireResult(shape: T) { + return z.looseObject({ + _meta: wireMeta, + /** Sender MUST set; receiver defaults absent → 'complete' (spec receiver leniency). */ + resultType: ResultTypeSchema.default('complete'), + ...shape + }); + } + + const ResultSchema = wireResult({}); + + const PaginatedResultSchema = wireResult({ + nextCursor: CursorSchema.optional() + }); + + const CallToolResultSchema = wireResult({ + content: z.array(ContentBlockSchema), + structuredContent: z.unknown().optional(), + isError: z.boolean().optional() + }); + + const ListToolsResultSchema = wireResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + tools: z.array(ToolSchema), + nextCursor: CursorSchema.optional() + }); + + const ListPromptsResultSchema = wireResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + prompts: z.array(PromptSchema), + nextCursor: CursorSchema.optional() + }); + + const GetPromptResultSchema = wireResult({ + description: z.string().optional(), + messages: z.array(PromptMessageSchema) + }); + + const ListResourcesResultSchema = wireResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + resources: z.array(ResourceSchema), + nextCursor: CursorSchema.optional() + }); + + const ListResourceTemplatesResultSchema = wireResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + resourceTemplates: z.array(ResourceTemplateSchema), + nextCursor: CursorSchema.optional() + }); + + const ReadResourceResultSchema = wireResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) + }); + + const CompleteResultSchema = wireResult({ + completion: z + .object({ + values: z.array(z.string()).max(100), + total: z.number().int().optional(), + hasMore: z.boolean().optional() + }) + .loose() + }); + + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']) + }); + + const DiscoverResultSchema = wireResult({ + // Receiver-side leniency per caching.mdx:56-58 — the probe classifier must + // accept a DiscoverResult that omits OR malforms the cache hints (spec: + // "if ttlMs is negative, clients SHOULD ignore it and treat it as 0"). + // `.catch()` returns the fallback for both absence and parse failure; + // sender obligation is enforced by `encodeResult`, not by parse. + // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise + ttlMs: z.number().int().min(0).catch(0), + // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise + cacheScope: z.enum(['public', 'private']).catch('private'), + supportedVersions: z.array(z.string()), + capabilities: ServerCapabilities2026Schema, + serverInfo: ImplementationSchema, + instructions: z.string().optional() + }); + + /* ------------------------------------------------------------------------ * + * Multi round-trip requests (SEP-2322). The in-band vocabulary of this + * revision: server→client interactions are carried as de-JSON-RPC'd embedded + * requests inside an `input_required` result, fulfilled by the client, and + * echoed back as embedded responses on the retry. The shapes below are + * anchor-exact wire artifacts (corpus + parity); the lenient dispatch-time + * schemas the multi-round-trip driver parses embedded requests with live in + * `inputRequired.ts`. + * + * The sampling shapes fork here (they compose the forked SamplingMessage / + * Tool payloads); the URL-mode elicitation params fork here (the draft + * removed `elicitationId`; the shared schema keeps it because it is required + * on the frozen 2025-11-25 revision); form-mode elicitation params are + * revision-identical and are composed by reference from the shared schema. + * ------------------------------------------------------------------------ */ + + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema = z.object({ + messages: z.array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: z.string().optional(), + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + maxTokens: z.number().int(), + stopSequences: z.array(z.string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: z.array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() + }); + + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema = z.object({ + method: z.literal('sampling/createMessage'), + params: CreateMessageRequestParamsSchema + }); + + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema = z.object({ + method: z.literal('roots/list'), + params: z.object({ _meta: z.record(z.string(), z.unknown()).optional() }).optional() + }); + + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema = z.object({ + ...SamplingMessageSchema.shape, + model: z.string(), + stopReason: z.string().optional() + }); + + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema = z.object({ + roots: z.array(RootSchema) + }); + + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema = z.object({ + action: z.enum(['accept', 'decline', 'cancel']), + content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() + }); + + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema = z.object({ + mode: z.literal('url'), + message: z.string(), + url: z.string().url() + }); + + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); + + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema = z.object({ + method: z.literal('elicitation/create'), + params: ElicitRequestParamsSchema + }); + + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = z.union([CreateMessageRequestSchema, ListRootsRequestSchema, ElicitRequestSchema]); + + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = z.union([CreateMessageResultSchema, ListRootsResultSchema, ElicitResultSchema]); + + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = z.record(z.string(), InputRequestSchema); + + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = z.record(z.string(), InputResponseSchema); + + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: z.string().optional() + }); + + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: z.string().optional() + }; + + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = z.object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + + /* ------------------------------------------------------------------------ * + * Request side. Two views per method: + * - WIRE-TRUE (`RequestSchema`): params `_meta` carries the REQUIRED + * envelope (anchor RequestParams._meta is required). The corpus and parity + * suite consume these. + * - DISPATCH (post-lift, internal to the registry): the protocol layer's + * universal lift has already extracted the envelope, so dispatch parses a + * 2025-like shape with optional `_meta` (progressToken/extension keys + * only) and NO 2025-only members (`task` is undeclared and strips — + * payload-level deletion is physical on this leg). + * ------------------------------------------------------------------------ */ + + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = z.looseObject({ + progressToken: ProgressTokenSchema.optional() + }); + + function wireRequest(method: M, paramsShape: T) { + return z.object({ + method: z.literal(method), + params: z.object({ _meta: RequestMetaEnvelopeSchema, ...paramsShape }) + }); + } + + function dispatchRequest(method: M, paramsShape: T) { + return z.object({ + method: z.literal(method), + params: z.object({ _meta: DispatchRequestMetaSchema.optional(), ...paramsShape }).optional() + }); + } + + const callToolParamsShape = { + name: z.string(), + arguments: z.record(z.string(), z.unknown()).optional(), + // Multi-round-trip retry channel (the wire-true view models it; dispatch + // never sees it — the protocol layer lifts it before any handler runs). + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema.optional() }; + + const CallToolRequestSchema = wireRequest('tools/call', callToolParamsShape); + const ListToolsRequestSchema = wireRequest('tools/list', paginatedParamsShape); + const ListPromptsRequestSchema = wireRequest('prompts/list', paginatedParamsShape); + const GetPromptRequestSchema = wireRequest('prompts/get', { + name: z.string(), + arguments: z.record(z.string(), z.string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema = wireRequest('resources/list', paginatedParamsShape); + const ListResourceTemplatesRequestSchema = wireRequest('resources/templates/list', paginatedParamsShape); + const ReadResourceRequestSchema = wireRequest('resources/read', { uri: z.string(), ...retryParamsShape }); + const completeParamsShape = { + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: z.object({ name: z.string(), value: z.string() }), + context: z.object({ arguments: z.record(z.string(), z.string()).optional() }).optional() + }; + const CompleteRequestSchema = wireRequest('completion/complete', completeParamsShape); + const DiscoverRequestSchema = wireRequest('server/discover', {}); + + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema = z.object({ + toolsListChanged: z.boolean().optional(), + promptsListChanged: z.boolean().optional(), + resourcesListChanged: z.boolean().optional(), + resourceSubscriptions: z.array(z.string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema }; + const SubscriptionsListenRequestSchema = wireRequest('subscriptions/listen', subscriptionsListenParamsShape); + + /** Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on the graceful-close result. */ + const SubscriptionsListenResultMetaSchema = z.looseObject({ + 'io.modelcontextprotocol/subscriptionId': RequestIdSchema + }); + + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema = z.looseObject({ + /** Required `_meta` (the subscriptionId stamp); the result body is otherwise empty. */ + _meta: SubscriptionsListenResultMetaSchema, + resultType: ResultTypeSchema.default('complete') + }); + + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> } = { + 'tools/call': dispatchRequest('tools/call', callToolParamsShape), + 'tools/list': dispatchRequest('tools/list', paginatedParamsShape), + 'prompts/get': dispatchRequest('prompts/get', { + name: z.string(), + arguments: z.record(z.string(), z.string()).optional() + }), + 'prompts/list': dispatchRequest('prompts/list', paginatedParamsShape), + 'resources/list': dispatchRequest('resources/list', paginatedParamsShape), + 'resources/templates/list': dispatchRequest('resources/templates/list', paginatedParamsShape), + 'resources/read': dispatchRequest('resources/read', { uri: z.string() }), + 'completion/complete': dispatchRequest('completion/complete', completeParamsShape), + 'server/discover': dispatchRequest('server/discover', {}), + 'subscriptions/listen': dispatchRequest('subscriptions/listen', subscriptionsListenParamsShape) + }; + + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape: T) { + return z.looseObject({ _meta: wireMeta, ...shape }); + } + + const dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType } = { + 'tools/call': liftedResult({ + content: z.array(ContentBlockSchema), + structuredContent: z.unknown().optional(), + isError: z.boolean().optional() + }), + 'tools/list': liftedResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + tools: z.array(ToolSchema), + nextCursor: CursorSchema.optional() + }), + 'prompts/get': liftedResult({ + description: z.string().optional(), + messages: z.array(PromptMessageSchema) + }), + 'prompts/list': liftedResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + prompts: z.array(PromptSchema), + nextCursor: CursorSchema.optional() + }), + 'resources/list': liftedResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + resources: z.array(ResourceSchema), + nextCursor: CursorSchema.optional() + }), + 'resources/templates/list': liftedResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + resourceTemplates: z.array(ResourceTemplateSchema), + nextCursor: CursorSchema.optional() + }), + 'resources/read': liftedResult({ + ttlMs: z.number().int().min(0), + cacheScope: z.enum(['public', 'private']), + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) + }), + 'completion/complete': liftedResult({ + completion: z + .object({ + values: z.array(z.string()).max(100), + total: z.number().int().optional(), + hasMore: z.boolean().optional() + }) + .loose() + }), + 'server/discover': liftedResult({ + // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise + ttlMs: z.number().int().min(0).catch(0), + // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise + cacheScope: z.enum(['public', 'private']).catch('private'), + supportedVersions: z.array(z.string()), + capabilities: ServerCapabilities2026Schema, + serverInfo: ImplementationSchema, + instructions: z.string().optional() + }), + // `subscriptions/listen` receives a JSON-RPC result only on a server-side + // graceful close (the empty `SubscriptionsListenResult` — `_meta` carries + // the subscriptionId stamp). The dispatch result schema stays the lifted + // empty body so the mapped type is total; the listen-response demux is + // entry-layer (`Client._onresponse`) and never reaches `decodeResult`. + 'subscriptions/listen': liftedResult({}) + }; + + /* ------------------------------------------------------------------------ * + * Notifications. The 2026 notification set: cancelled, progress, message, + * resources/updated, resources/list_changed, tools/list_changed, + * prompts/list_changed. Deleted: initialized, roots/list_changed, + * tasks/status, elicitation/complete (removed from the draft together with + * URL-elicitation's elicitationId — both remain 2025-11-25 vocabulary only). + * The shapes are revision-identical to the shared schemas, which are + * composed by reference, EXCEPT cancelled (forks below: this revision + * requires `requestId`) and the 2026-only subscriptions/acknowledged. + * ------------------------------------------------------------------------ */ + + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = z.looseObject({ + /** + * The JSON-RPC ID of the `subscriptions/listen` request that opened the + * stream a notification was delivered on; absent on notifications not + * delivered via a subscription stream. + */ + 'io.modelcontextprotocol/subscriptionId': RequestIdSchema.optional() + }); + + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema = z.object({ + method: z.literal('notifications/subscriptions/acknowledged'), + params: z.object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema + }) + }); + + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema = z.object({ + _meta: NotificationMetaSchema.optional(), + /** + * The ID of the request to cancel. This MUST correspond to the ID of a + * request the client previously issued. + */ + requestId: RequestIdSchema, + /** + * An optional string describing the reason for the cancellation. This MAY + * be logged or presented to the user. + */ + reason: z.string().optional() + }); + + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema = z.object({ + method: z.literal('notifications/cancelled'), + params: CancelledNotificationParamsSchema + }); + + const notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> } = { + 'notifications/cancelled': CancelledNotificationSchema, + 'notifications/progress': ProgressNotificationSchema, + 'notifications/message': LoggingMessageNotificationSchema, + 'notifications/resources/updated': ResourceUpdatedNotificationSchema, + 'notifications/resources/list_changed': ResourceListChangedNotificationSchema, + 'notifications/tools/list_changed': ToolListChangedNotificationSchema, + 'notifications/prompts/list_changed': PromptListChangedNotificationSchema, + 'notifications/subscriptions/acknowledged': SubscriptionsAcknowledgedNotificationSchema + }; + + /* ------------------------------------------------------------------------ * + * Response envelopes (wire-true; parity/corpus artifacts). + * ------------------------------------------------------------------------ */ + const wireResultResponse = (result: T) => + z + .object({ + jsonrpc: z.literal('2.0'), + id: z.union([z.string(), z.number().int()]), + result + }) + .strict(); + + const JSONRPCResultResponseSchema = wireResultResponse(ResultSchema); + // The multi-round-trip methods may answer with either their final result or an + // InputRequiredResult (anchor: `result: CallToolResult | InputRequiredResult`). + const CallToolResultResponseSchema = wireResultResponse(z.union([CallToolResultSchema, InputRequiredResultSchema])); + const ListToolsResultResponseSchema = wireResultResponse(ListToolsResultSchema); + const ListPromptsResultResponseSchema = wireResultResponse(ListPromptsResultSchema); + const GetPromptResultResponseSchema = wireResultResponse(z.union([GetPromptResultSchema, InputRequiredResultSchema])); + const ListResourcesResultResponseSchema = wireResultResponse(ListResourcesResultSchema); + const ListResourceTemplatesResultResponseSchema = wireResultResponse(ListResourceTemplatesResultSchema); + const ReadResourceResultResponseSchema = wireResultResponse(z.union([ReadResourceResultSchema, InputRequiredResultSchema])); + const CompleteResultResponseSchema = wireResultResponse(CompleteResultSchema); + const DiscoverResultResponseSchema = wireResultResponse(DiscoverResultSchema); + + return { + JSONValueSchema, + JSONObjectSchema, + ProgressTokenSchema, + CursorSchema, + RequestIdSchema, + RoleSchema, + LoggingLevelSchema, + TaskMetadataSchema, + RelatedTaskMetadataSchema, + RequestMetaSchema, + BaseRequestParamsSchema, + TaskAugmentedRequestParamsSchema, + NotificationsParamsSchema, + NotificationSchema, + IconSchema, + IconsSchema, + BaseMetadataSchema, + ImplementationSchema, + ClientTasksCapabilitySchema, + ServerTasksCapabilitySchema, + ClientCapabilitiesSchema, + ServerCapabilitiesSchema, + ProgressSchema, + ProgressNotificationParamsSchema, + ProgressNotificationSchema, + LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema, + ResourceContentsSchema, + TextResourceContentsSchema, + BlobResourceContentsSchema, + AnnotationsSchema, + ResourceSchema, + ResourceTemplateSchema, + ResourceListChangedNotificationSchema, + ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema, + PromptArgumentSchema, + PromptSchema, + PromptListChangedNotificationSchema, + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + EmbeddedResourceSchema, + ResourceLinkSchema, + ContentBlockSchema, + PromptMessageSchema, + ToolAnnotationsSchema, + ToolListChangedNotificationSchema, + ModelHintSchema, + ModelPreferencesSchema, + ToolChoiceSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + UntitledMultiSelectEnumSchemaSchema, + TitledMultiSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema, + EnumSchemaSchema, + PrimitiveSchemaDefinitionSchema, + ElicitRequestFormParamsSchema, + ResourceTemplateReferenceSchema, + PromptReferenceSchema, + RootSchema, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema, + ToolResultContentSchema, + SamplingMessageContentBlockSchema, + SamplingMessageSchema, + ResultTypeSchema, + ResultSchema, + PaginatedResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + ListPromptsResultSchema, + GetPromptResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CompleteResultSchema, + CacheableResultSchema, + DiscoverResultSchema, + CreateMessageRequestParamsSchema, + CreateMessageRequestSchema, + ListRootsRequestSchema, + CreateMessageResultSchema, + ListRootsResultSchema, + ElicitResultSchema, + ElicitRequestURLParamsSchema, + ElicitRequestParamsSchema, + ElicitRequestSchema, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + ListPromptsRequestSchema, + GetPromptRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + CompleteRequestSchema, + DiscoverRequestSchema, + SubscriptionFilterSchema, + SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema, + CancelledNotificationParamsSchema, + CancelledNotificationSchema, + notificationSchemas2026, + JSONRPCResultResponseSchema, + CallToolResultResponseSchema, + ListToolsResultResponseSchema, + ListPromptsResultResponseSchema, + GetPromptResultResponseSchema, + ListResourcesResultResponseSchema, + ListResourceTemplatesResultResponseSchema, + ReadResourceResultResponseSchema, + CompleteResultResponseSchema, + DiscoverResultResponseSchema + }; +} + +/** The full set of frozen 2026-07-28 wire schemas, as one built object (the memo target). */ +export type Rev2026WireSchemas = ReturnType; + +let memo: Rev2026WireSchemas | undefined; + +/** + * Builds the era wire-schema set on first call and returns the same object + * thereafter. Module evaluation stays construction-free so importing the + * era codec/registry costs nothing until the first validation actually + * needs a schema; the registry, the codec, and the eager `schemas.ts` + * shim all pull through this memo, so reference identity holds across + * every consumer. + */ +export function buildSchemas2026(): Rev2026WireSchemas { + return (memo ??= build()); +} diff --git a/packages/core-internal/src/wire/rev2026-07-28/codec.ts b/packages/core-internal/src/wire/rev2026-07-28/codec.ts index d76d41024e..5af749378f 100644 --- a/packages/core-internal/src/wire/rev2026-07-28/codec.ts +++ b/packages/core-internal/src/wire/rev2026-07-28/codec.ts @@ -32,6 +32,7 @@ import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, import type { CallToolResult, Result } from '../../types/types'; import type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec'; import { appendTextFallbackForNonObject } from '../textFallback'; +import { buildSchemas2026 } from './buildSchemas'; import { fillCacheFields, stampResultType } from './encodeContract'; import { getInputRequestSchema2026, getInputResponseSchema2026 } from './inputRequired'; import { @@ -41,18 +42,6 @@ import { hasNotificationMethod2026, hasRequestMethod2026 } from './registry'; -import { - CallToolResultSchema, - CompleteResultSchema, - DiscoverResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ListToolsResultSchema, - ReadResourceResultSchema, - RequestMetaEnvelopeSchema -} from './schemas'; function isPlainObject(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); @@ -146,7 +135,7 @@ export const rev2026Codec: WireCodec & { for (const key of REQUIRED_ENVELOPE_KEYS) { if (!(key in meta)) issues.push({ key, problem: 'missing' }); } - const parsed = RequestMetaEnvelopeSchema.safeParse(meta); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); if (!parsed.success) { for (const issue of parsed.error.issues) { const path = issue.path.map(String); @@ -244,7 +233,8 @@ export const rev2026Codec: WireCodec & { // Own-key lookup: `method` is peer-influenced on related-request // paths, and a prototype-chain hit (e.g. 'constructor') must not // masquerade as a schema and throw out of the decode hop. - const wireSchema = Object.hasOwn(WIRE_RESULT_SCHEMAS, method) ? WIRE_RESULT_SCHEMAS[method] : undefined; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : undefined; if (wireSchema !== undefined) { const parsed = wireSchema.safeParse(raw); if (!parsed.success) { @@ -280,7 +270,7 @@ export const rev2026Codec: WireCodec & { '(io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo, io.modelcontextprotocol/clientCapabilities)' ); } - const parsed = RequestMetaEnvelopeSchema.safeParse(material.envelope); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); if (!parsed.success) { return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue => issue.message).join('; ')}`; } @@ -288,15 +278,23 @@ export const rev2026Codec: WireCodec & { } }; -/** Wire-true result wrappers consulted by decode step 2, keyed by method. */ -const WIRE_RESULT_SCHEMAS: Record = { - 'tools/call': CallToolResultSchema, - 'tools/list': ListToolsResultSchema, - 'prompts/get': GetPromptResultSchema, - 'prompts/list': ListPromptsResultSchema, - 'resources/list': ListResourcesResultSchema, - 'resources/templates/list': ListResourceTemplatesResultSchema, - 'resources/read': ReadResourceResultSchema, - 'completion/complete': CompleteResultSchema, - 'server/discover': DiscoverResultSchema -}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — + * built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo: Record | undefined; + +function getWireResultSchemas(): Record { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + 'tools/call': s.CallToolResultSchema, + 'tools/list': s.ListToolsResultSchema, + 'prompts/get': s.GetPromptResultSchema, + 'prompts/list': s.ListPromptsResultSchema, + 'resources/list': s.ListResourcesResultSchema, + 'resources/templates/list': s.ListResourceTemplatesResultSchema, + 'resources/read': s.ReadResourceResultSchema, + 'completion/complete': s.CompleteResultSchema, + 'server/discover': s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} diff --git a/packages/core-internal/src/wire/rev2026-07-28/inputRequired.ts b/packages/core-internal/src/wire/rev2026-07-28/inputRequired.ts index 615cf5fd38..83c9ab9769 100644 --- a/packages/core-internal/src/wire/rev2026-07-28/inputRequired.ts +++ b/packages/core-internal/src/wire/rev2026-07-28/inputRequired.ts @@ -21,41 +21,51 @@ import * as z from 'zod/v4'; import type { RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types'; -import { - CreateMessageRequestParamsSchema, - CreateMessageResultSchema, - ElicitRequestParamsSchema, - ElicitResultSchema, - ListRootsResultSchema -} from './schemas'; +import { buildSchemas2026 } from './buildSchemas'; /** The embedded input-request methods of the 2026-07-28 revision. */ export const INPUT_REQUEST_METHODS_2026 = ['elicitation/create', 'sampling/createMessage', 'roots/list'] as const; export type InputRequestMethod2026 = (typeof INPUT_REQUEST_METHODS_2026)[number]; -/** Dispatch-time (lenient) embedded request schemas, keyed by method. */ -const inputRequestSchemas2026: Record = { - 'elicitation/create': z.object({ - method: z.literal('elicitation/create'), - params: ElicitRequestParamsSchema - }), - 'sampling/createMessage': z.object({ - method: z.literal('sampling/createMessage'), - params: CreateMessageRequestParamsSchema - }), - 'roots/list': z.object({ - method: z.literal('roots/list'), - params: z.looseObject({}).optional() - }) -}; +/* The embedded-request maps are built lazily through the era's memoized + * schema factory (`buildSchemas2026`) so importing this module constructs no + * zod schemas; the maps themselves are memoized alongside. */ +interface InputSchemaMaps { + /** Dispatch-time (lenient) embedded request schemas, keyed by method. */ + readonly request: Record; + /** Embedded (bare) response schemas, keyed by the request method they answer. */ + readonly response: Record; +} + +let maps: InputSchemaMaps | undefined; -/** Embedded (bare) response schemas, keyed by the request method they answer. */ -const inputResponseSchemas2026: Record = { - 'elicitation/create': ElicitResultSchema, - 'sampling/createMessage': CreateMessageResultSchema, - 'roots/list': ListRootsResultSchema -}; +function inputSchemaMaps(): InputSchemaMaps { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + 'elicitation/create': z.object({ + method: z.literal('elicitation/create'), + params: s.ElicitRequestParamsSchema + }), + 'sampling/createMessage': z.object({ + method: z.literal('sampling/createMessage'), + params: s.CreateMessageRequestParamsSchema + }), + 'roots/list': z.object({ + method: z.literal('roots/list'), + params: z.looseObject({}).optional() + }) + }, + response: { + 'elicitation/create': s.ElicitResultSchema, + 'sampling/createMessage': s.CreateMessageResultSchema, + 'roots/list': s.ListRootsResultSchema + } + }; + return maps; +} export function isInputRequestMethod2026(method: string): method is InputRequestMethod2026 { return (INPUT_REQUEST_METHODS_2026 as readonly string[]).includes(method); @@ -69,7 +79,7 @@ export function isInputRequestMethod2026(method: string): method is InputRequest export function getInputRequestSchema2026(method: M): z.ZodType | undefined; export function getInputRequestSchema2026(method: string): z.ZodType | undefined; export function getInputRequestSchema2026(method: string): z.ZodType | undefined { - return isInputRequestMethod2026(method) ? inputRequestSchemas2026[method] : undefined; + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : undefined; } /** @@ -79,5 +89,5 @@ export function getInputRequestSchema2026(method: string): z.ZodType | undefined export function getInputResponseSchema2026(method: M): z.ZodType | undefined; export function getInputResponseSchema2026(method: string): z.ZodType | undefined; export function getInputResponseSchema2026(method: string): z.ZodType | undefined { - return isInputRequestMethod2026(method) ? inputResponseSchemas2026[method] : undefined; + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : undefined; } diff --git a/packages/core-internal/src/wire/rev2026-07-28/registry.ts b/packages/core-internal/src/wire/rev2026-07-28/registry.ts index c515b58a4e..3319051f76 100644 --- a/packages/core-internal/src/wire/rev2026-07-28/registry.ts +++ b/packages/core-internal/src/wire/rev2026-07-28/registry.ts @@ -26,26 +26,59 @@ * and own ack/filter/stamp/teardown themselves; on the client side * `Client.listen()` sends directly on the transport (string-typed * request id, transport-level demux) rather than via `request()`. + * + * LAZY SCHEMA CONSTRUCTION: method membership and the exported method lists + * are static (null-valued key objects below, mapped over the hand-registry + * unions so drift is a compile error in both directions), while the dispatch + * schema maps are pulled through the era's memoized `buildSchemas2026()` + * factory on first lookup — importing this module constructs no zod schemas. */ import type * as z from 'zod/v4'; import type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types'; -import type { Rev2026NotificationMethod, Rev2026RequestMethod } from './schemas'; -import { dispatchRequestSchemas, dispatchResultSchemas, notificationSchemas2026 } from './schemas'; +import type { Rev2026NotificationMethod, Rev2026RequestMethod } from './buildSchemas'; +import { buildSchemas2026 } from './buildSchemas'; + +/* Static method membership — the schema-free half of the registry. Key order + * matches the dispatch maps in `./buildSchemas.ts` so the exported method + * lists are byte-identical to the pre-lazy `Object.keys(map)` derivation. */ +const requestMethodKeys: { readonly [M in Rev2026RequestMethod]: null } = { + 'tools/call': null, + 'tools/list': null, + 'prompts/get': null, + 'prompts/list': null, + 'resources/list': null, + 'resources/templates/list': null, + 'resources/read': null, + 'completion/complete': null, + 'server/discover': null, + 'subscriptions/listen': null +}; + +const notificationMethodKeys: { readonly [M in Rev2026NotificationMethod]: null } = { + 'notifications/cancelled': null, + 'notifications/progress': null, + 'notifications/message': null, + 'notifications/resources/updated': null, + 'notifications/resources/list_changed': null, + 'notifications/tools/list_changed': null, + 'notifications/prompts/list_changed': null, + 'notifications/subscriptions/acknowledged': null +}; /** The 2026-era request-method set (registry membership = the deletion story). */ export function hasRequestMethod2026(method: string): method is Rev2026RequestMethod { - return Object.prototype.hasOwnProperty.call(dispatchRequestSchemas, method); + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); } /** The 2026-era notification-method set. */ export function hasNotificationMethod2026(method: string): method is Rev2026NotificationMethod { - return Object.prototype.hasOwnProperty.call(notificationSchemas2026, method); + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); } /** Result-map membership (same key set as the request map on this era). */ function hasResultMethod2026(method: string): method is Rev2026RequestMethod { - return Object.prototype.hasOwnProperty.call(dispatchResultSchemas, method); + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); } /** @@ -57,7 +90,7 @@ function hasResultMethod2026(method: string): method is Rev2026RequestMethod { export function getRequestSchema2026(method: M): z.ZodType | undefined; export function getRequestSchema2026(method: string): z.ZodType | undefined; export function getRequestSchema2026(method: string): z.ZodType | undefined { - return hasRequestMethod2026(method) ? dispatchRequestSchemas[method] : undefined; + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : undefined; } /** @@ -69,7 +102,7 @@ export function getRequestSchema2026(method: string): z.ZodType | undefined { export function getResultSchema2026(method: M): z.ZodType | undefined; export function getResultSchema2026(method: string): z.ZodType | undefined; export function getResultSchema2026(method: string): z.ZodType | undefined { - return hasResultMethod2026(method) ? dispatchResultSchemas[method] : undefined; + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : undefined; } /** @@ -80,9 +113,9 @@ export function getResultSchema2026(method: string): z.ZodType | undefined { export function getNotificationSchema2026(method: M): z.ZodType | undefined; export function getNotificationSchema2026(method: string): z.ZodType | undefined; export function getNotificationSchema2026(method: string): z.ZodType | undefined { - return hasNotificationMethod2026(method) ? notificationSchemas2026[method] : undefined; + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : undefined; } /** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -export const rev2026RequestMethods: readonly string[] = Object.keys(dispatchRequestSchemas); -export const rev2026NotificationMethods: readonly string[] = Object.keys(notificationSchemas2026); +export const rev2026RequestMethods: readonly string[] = Object.keys(requestMethodKeys); +export const rev2026NotificationMethods: readonly string[] = Object.keys(notificationMethodKeys); diff --git a/packages/core-internal/src/wire/rev2026-07-28/schemas.ts b/packages/core-internal/src/wire/rev2026-07-28/schemas.ts index 02a1663142..ed545f7a99 100644 --- a/packages/core-internal/src/wire/rev2026-07-28/schemas.ts +++ b/packages/core-internal/src/wire/rev2026-07-28/schemas.ts @@ -1,1244 +1,157 @@ /** - * 2026-era wire schemas (protocol revision 2026-07-28). + * Eager named-export surface for the era wire schemas. * - * Fully self-contained — no runtime imports from types/schemas.ts. The - * neutral types/schemas.ts layer is the public-API superset and is free to - * evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN - * against the 2026-07-28 anchor. Every era-shared building block (content - * blocks, resources, prompts, capabilities, notifications, …) that the wire - * shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at - * the point this revision was sealed, dependencies first. The only cross-layer - * dependency is `import type { JSONObject, JSONValue }` from the neutral types - * barrel — pure structural type aliases with no parse behavior. + * The schema DEFINITIONS live in `./buildSchemas.ts`, wrapped in a memoized + * factory so the runtime graph (codec/registry) defers zod construction to + * the first validation. This module keeps the historical per-name import + * surface for tests and tooling: importing it warms the memo, and every + * export is the SAME object the registry serves (reference identity through + * the shared memo). * - * This module is the only place the per-request `_meta` envelope is modeled. - * The envelope is wire-only vocabulary: the protocol layer lifts it off - * inbound requests before any handler runs and surfaces it at - * `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at - * dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc - * deferral ("enforced per request at dispatch time, not here") is now - * discharged by that codec step. - * - * No 2025-era traffic ever touches this module, so requiredness here is - * bare and spec-exact (the shared-schema `.catch` hazards do not apply). - */ -import * as z from 'zod/v4'; - -import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, PROTOCOL_VERSION_META_KEY } from '../../types/constants'; -import type { JSONObject, JSONValue } from '../../types/types'; - -/* ════════════════════════════════════════════════════════════════════════════ - * Frozen neutral-layer building blocks - * - * Everything from this point until the next ═-banner is a verbatim frozen - * copy of a schema that, at the time this revision was sealed, lived in the - * neutral types/schemas.ts. They are copied dependencies-first so no forward - * references exist. They are NOT re-derived from the public layer at runtime — - * a widening or tightening landed on types/schemas.ts has no effect here until - * a deliberate per-revision re-freeze. - * ════════════════════════════════════════════════════════════════════════════ */ - -export const JSONValueSchema: z.ZodType = z.lazy(() => - z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)]) -); -export const JSONObjectSchema: z.ZodType = z.record(z.string(), JSONValueSchema); - -/** - * A progress token, used to associate progress notifications with the original request. - */ -export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); - -/** - * An opaque token used to represent a cursor for pagination. - */ -export const CursorSchema = z.string(); - -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); - -/** - * The sender or recipient of messages and data in a conversation. - */ -export const RoleSchema = z.enum(['user', 'assistant']); - -/** - * The severity of a log message. - */ -export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); - -/** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ -const Base64Schema = z.string().refine( - val => { - try { - atob(val); - return true; - } catch { - return false; - } - }, - { message: 'Invalid Base64 string' } -); - -/* ─── Request/notification meta and base params ─── */ - -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -export const TaskMetadataSchema = z.object({ - ttl: z.number().optional() -}); - -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -export const RelatedTaskMetadataSchema = z.object({ - taskId: z.string() -}); - -export const RequestMetaSchema = 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(), - /** - * If specified, this request is related to the provided task. - */ - 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional() -}); - -export const BaseRequestParamsSchema = z.object({ - _meta: RequestMetaSchema.optional() -}); - -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ - task: TaskMetadataSchema.optional() -}); - -export const NotificationsParamsSchema = z.object({ - _meta: RequestMetaSchema.optional() -}); - -export const NotificationSchema = z.object({ - method: z.string(), - params: NotificationsParamsSchema.loose().optional() -}); - -/* ─── Icons / base metadata / implementation ─── */ - -export const IconSchema = z.object({ - src: z.string(), - mimeType: z.string().optional(), - sizes: z.array(z.string()).optional(), - theme: z.enum(['light', 'dark']).optional() -}); - -export const IconsSchema = z.object({ - icons: z.array(IconSchema).optional() -}); - -export const BaseMetadataSchema = z.object({ - name: z.string(), - title: z.string().optional() -}); - -export const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: z.string(), - websiteUrl: z.string().optional(), - description: z.string().optional() -}); - -/* ─── Capability schemas ─── */ - -const FormElicitationCapabilitySchema = z.intersection( - z.object({ - applyDefaults: z.boolean().optional() - }), - JSONObjectSchema -); - -const ElicitationCapabilitySchema = z.preprocess( - value => { - if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record).length === 0) { - return { form: {} }; - } - return value; - }, - z.intersection( - z.object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() - }), - JSONObjectSchema.optional() - ) -); - -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -export const ClientTasksCapabilitySchema = z.looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: z - .looseObject({ - sampling: z - .looseObject({ - createMessage: JSONObjectSchema.optional() - }) - .optional(), - elicitation: z - .looseObject({ - create: JSONObjectSchema.optional() - }) - .optional() - }) - .optional() -}); - -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -export const ServerTasksCapabilitySchema = z.looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: z - .looseObject({ - tools: z - .looseObject({ - call: JSONObjectSchema.optional() - }) - .optional() - }) - .optional() -}); - -export const ClientCapabilitiesSchema = z.object({ - experimental: z.record(z.string(), JSONObjectSchema).optional(), - sampling: z - .object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }) - .optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: z - .object({ - listChanged: z.boolean().optional() - }) - .optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: z.record(z.string(), JSONObjectSchema).optional() -}); - -export const ServerCapabilitiesSchema = z.object({ - experimental: z.record(z.string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: z - .object({ - listChanged: z.boolean().optional() - }) - .optional(), - resources: z - .object({ - subscribe: z.boolean().optional(), - listChanged: z.boolean().optional() - }) - .optional(), - tools: z - .object({ - listChanged: z.boolean().optional() - }) - .optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: z.record(z.string(), JSONObjectSchema).optional() -}); - -/* ─── Progress / logging notifications ─── */ - -export const ProgressSchema = z.object({ - progress: z.number(), - total: z.optional(z.number()), - message: z.optional(z.string()) -}); - -export const ProgressNotificationParamsSchema = z.object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); - -export const ProgressNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/progress'), - params: ProgressNotificationParamsSchema -}); - -export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: z.string().optional(), - data: z.unknown() -}); - -export const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: LoggingMessageNotificationParamsSchema -}); - -/* ─── Resource contents / annotations ─── */ - -export const ResourceContentsSchema = z.object({ - uri: z.string(), - mimeType: z.optional(z.string()), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const TextResourceContentsSchema = ResourceContentsSchema.extend({ - text: z.string() -}); - -export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ - blob: Base64Schema -}); - -export const AnnotationsSchema = z.object({ - audience: z.array(RoleSchema).optional(), - priority: z.number().min(0).max(1).optional(), - lastModified: z.iso.datetime({ offset: true }).optional() -}); - -/* ─── Resources / templates / list-changed notifications ─── */ - -export const ResourceSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: z.string(), - description: z.optional(z.string()), - mimeType: z.optional(z.string()), - size: z.optional(z.number()), - annotations: AnnotationsSchema.optional(), - _meta: z.optional(z.looseObject({})) -}); - -export const ResourceTemplateSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: z.string(), - description: z.optional(z.string()), - mimeType: z.optional(z.string()), - annotations: AnnotationsSchema.optional(), - _meta: z.optional(z.looseObject({})) -}); - -export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - uri: z.string() -}); - -export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: ResourceUpdatedNotificationParamsSchema -}); - -/* ─── Prompts / content blocks ─── */ - -export const PromptArgumentSchema = z.object({ - name: z.string(), - description: z.optional(z.string()), - required: z.optional(z.boolean()) -}); - -export const PromptSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: z.optional(z.string()), - arguments: z.optional(z.array(PromptArgumentSchema)), - _meta: z.optional(z.looseObject({})) -}); - -export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -export const TextContentSchema = z.object({ - type: z.literal('text'), - text: z.string(), - annotations: AnnotationsSchema.optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const ImageContentSchema = z.object({ - type: z.literal('image'), - data: Base64Schema, - mimeType: z.string(), - annotations: AnnotationsSchema.optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const AudioContentSchema = z.object({ - type: z.literal('audio'), - data: Base64Schema, - mimeType: z.string(), - annotations: AnnotationsSchema.optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const ToolUseContentSchema = z.object({ - type: z.literal('tool_use'), - name: z.string(), - id: z.string(), - input: z.record(z.string(), z.unknown()), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const EmbeddedResourceSchema = z.object({ - type: z.literal('resource'), - resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -export const ResourceLinkSchema = ResourceSchema.extend({ - type: z.literal('resource_link') -}); - -export const ContentBlockSchema = z.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); - -export const PromptMessageSchema = z.object({ - role: RoleSchema, - content: ContentBlockSchema -}); - -/* ─── Tool annotations / tool list-changed / sampling primitives ─── */ - -export const ToolAnnotationsSchema = z.object({ - title: z.string().optional(), - readOnlyHint: z.boolean().optional(), - destructiveHint: z.boolean().optional(), - idempotentHint: z.boolean().optional(), - openWorldHint: z.boolean().optional() -}); - -export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -export const ModelHintSchema = z.object({ - name: z.string().optional() -}); - -export const ModelPreferencesSchema = z.object({ - hints: z.array(ModelHintSchema).optional(), - costPriority: z.number().min(0).max(1).optional(), - speedPriority: z.number().min(0).max(1).optional(), - intelligencePriority: z.number().min(0).max(1).optional() -}); - -export const ToolChoiceSchema = z.object({ - mode: z.enum(['auto', 'required', 'none']).optional() -}); - -/* ─── Elicitation primitive-schema vocabulary ─── */ - -export const BooleanSchemaSchema = z.object({ - type: z.literal('boolean'), - title: z.string().optional(), - description: z.string().optional(), - default: z.boolean().optional() -}); - -export const StringSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - minLength: z.number().optional(), - maxLength: z.number().optional(), - format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), - default: z.string().optional() -}); - -export const NumberSchemaSchema = z.object({ - type: z.enum(['number', 'integer']), - title: z.string().optional(), - description: z.string().optional(), - minimum: z.number().optional(), - maximum: z.number().optional(), - default: z.number().optional() -}); - -export const UntitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - default: z.string().optional() -}); - -export const TitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - oneOf: z.array( - z.object({ - const: z.string(), - title: z.string() - }) - ), - default: z.string().optional() -}); - -export const LegacyTitledEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - enumNames: z.array(z.string()).optional(), - default: z.string().optional() -}); - -export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); - -export const UntitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - type: z.literal('string'), - enum: z.array(z.string()) - }), - default: z.array(z.string()).optional() -}); - -export const TitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - anyOf: z.array( - z.object({ - const: z.string(), - title: z.string() - }) - ) - }), - default: z.array(z.string()).optional() -}); - -export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); - -export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); - -export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); - -export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - mode: z.literal('form').optional(), - message: z.string(), - requestedSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) -}); - -/* ─── Completion references / roots ─── */ - -export const ResourceTemplateReferenceSchema = z.object({ - type: z.literal('ref/resource'), - uri: z.string() -}); - -export const PromptReferenceSchema = z.object({ - type: z.literal('ref/prompt'), - name: z.string() -}); - -export const RootSchema = z.object({ - uri: z.string().startsWith('file://'), - name: z.string().optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/* ════════════════════════════════════════════════════════════════════════════ - * End of frozen neutral-layer building blocks. Everything below is the - * 2026-07-28 wire-specific vocabulary (envelope, forks, results, requests, - * notifications) composed against the frozen copies above. - * ════════════════════════════════════════════════════════════════════════════ */ - -/* 2026-era capability forks (defined ahead of the envelope, which composes - * the client fork). The frozen shapes minus the deleted `tasks` key: `tasks` - * is 2025-only vocabulary with no slot on this revision, consistent with the - * encode-side deletion (Q1-SD3 iii). - * - * Both forks list their members EXPLICITLY (composing the frozen member - * schemas by reference) rather than using `.omit()`: the envelope schema - * below reaches the bundled package declarations, and an `.omit()` inference - * is a mapped type whose printed member order is unstable across dts-rollup - * builds (api-report flap). The explicit list doubles as the fork's deletion - * statement — a member added to the frozen shape must be re-adjudicated here. */ -const sharedClientCapabilityShape = ClientCapabilitiesSchema.shape; -export const ClientCapabilities2026Schema = z.object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions -}); -const sharedServerCapabilityShape = ServerCapabilitiesSchema.shape; -export const ServerCapabilities2026Schema = z.object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions -}); - -/* 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 (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + * Runtime modules must import `buildSchemas` instead — a runtime import of + * this shim would re-eagerize construction. */ -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. Validated with the 2026 fork: `tasks` has no slot on - * this revision (deleted vocabulary), matching the server-side fork wired - * into `DiscoverResultSchema`. - */ - [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - /** - * 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() -}); - -/* ------------------------------------------------------------------------ * - * Forked payload vocabulary (shared-tier admission rule, ATK-B section 1): - * `Tool` and `SamplingMessage` are bidirectionally incomparable between the - * 2025-11-25 and 2026-07-28 anchors, so they FORK per wire module instead of - * sitting in the shared tier. The forks below are 2026-anchor-exact: - * - Tool (2026) has NO `execution` member (ToolExecution and its - * `taskSupport` carrier are deleted vocabulary) — a 2026 peer's tool that - * carries one is stripped on parse, and the encode side strips it from - * outbound tools (Q1-SD3 iii). - * - SamplingMessage (2026) is composed against the 2026 anchor shape. - * ------------------------------------------------------------------------ */ - -/** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ -export const ToolSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: z.string().optional(), - // Anchor-exact: { $schema?: string; type: 'object'; [key: string]: unknown } - inputSchema: z.looseObject({ - $schema: z.string().optional(), - type: z.literal('object') - }), - // Anchor-exact: { $schema?: string; [key: string]: unknown } - outputSchema: z - .looseObject({ - $schema: z.string().optional() - }) - .optional(), - annotations: ToolAnnotationsSchema.optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ -export const ToolResultContentSchema = z.object({ - type: z.literal('tool_result'), - toolUseId: z.string(), - content: z.array(ContentBlockSchema), - structuredContent: z.unknown().optional(), - isError: z.boolean().optional(), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** 2026-era sampling content union (composes the forked tool-result shape). */ -export const SamplingMessageContentBlockSchema = z.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); - -/** 2026-era SamplingMessage (anchor-exact: single block or array). */ -export const SamplingMessageSchema = z.object({ - role: RoleSchema, - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/* ------------------------------------------------------------------------ * - * Result side. `resultType` is a sender obligation (spec.types.2026-07-28 - * Result.resultType: "Servers implementing this protocol version MUST - * include this field") and a receiver default (schema.ts:208 — clients MUST - * treat absent `resultType` as 'complete'). These are the WIRE-TRUE - * artifacts — the corpus and the parity suite parse them; `decodeResult` - * parses with them and then LIFTS (drops resultType) to the neutral shape. - * Sender-side requiredness is enforced by construction (`encodeResult` - * stamps it), so the parse side carries the receiver default. - * ------------------------------------------------------------------------ */ - -/** Open union per the anchor: 'complete' | 'input_required' | string. */ -export const ResultTypeSchema = z.string(); - -const wireMeta = z.record(z.string(), z.unknown()).optional(); - -function wireResult(shape: T) { - return z.looseObject({ - _meta: wireMeta, - /** Sender MUST set; receiver defaults absent → 'complete' (spec receiver leniency). */ - resultType: ResultTypeSchema.default('complete'), - ...shape - }); -} - -export const ResultSchema = wireResult({}); - -export const PaginatedResultSchema = wireResult({ - nextCursor: CursorSchema.optional() -}); - -export const CallToolResultSchema = wireResult({ - content: z.array(ContentBlockSchema), - structuredContent: z.unknown().optional(), - isError: z.boolean().optional() -}); - -export const ListToolsResultSchema = wireResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - tools: z.array(ToolSchema), - nextCursor: CursorSchema.optional() -}); - -export const ListPromptsResultSchema = wireResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - prompts: z.array(PromptSchema), - nextCursor: CursorSchema.optional() -}); - -export const GetPromptResultSchema = wireResult({ - description: z.string().optional(), - messages: z.array(PromptMessageSchema) -}); - -export const ListResourcesResultSchema = wireResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - resources: z.array(ResourceSchema), - nextCursor: CursorSchema.optional() -}); - -export const ListResourceTemplatesResultSchema = wireResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - resourceTemplates: z.array(ResourceTemplateSchema), - nextCursor: CursorSchema.optional() -}); - -export const ReadResourceResultSchema = wireResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); - -export const CompleteResultSchema = wireResult({ - completion: z - .object({ - values: z.array(z.string()).max(100), - total: z.number().int().optional(), - hasMore: z.boolean().optional() - }) - .loose() -}); - -/** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ -export const CacheableResultSchema = wireResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']) -}); - -export const DiscoverResultSchema = wireResult({ - // Receiver-side leniency per caching.mdx:56-58 — the probe classifier must - // accept a DiscoverResult that omits OR malforms the cache hints (spec: - // "if ttlMs is negative, clients SHOULD ignore it and treat it as 0"). - // `.catch()` returns the fallback for both absence and parse failure; - // sender obligation is enforced by `encodeResult`, not by parse. - // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise - ttlMs: z.number().int().min(0).catch(0), - // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise - cacheScope: z.enum(['public', 'private']).catch('private'), - supportedVersions: z.array(z.string()), - capabilities: ServerCapabilities2026Schema, - serverInfo: ImplementationSchema, - instructions: z.string().optional() -}); - -/* ------------------------------------------------------------------------ * - * Multi round-trip requests (SEP-2322). The in-band vocabulary of this - * revision: server→client interactions are carried as de-JSON-RPC'd embedded - * requests inside an `input_required` result, fulfilled by the client, and - * echoed back as embedded responses on the retry. The shapes below are - * anchor-exact wire artifacts (corpus + parity); the lenient dispatch-time - * schemas the multi-round-trip driver parses embedded requests with live in - * `inputRequired.ts`. - * - * The sampling shapes fork here (they compose the forked SamplingMessage / - * Tool payloads); the URL-mode elicitation params fork here (the draft - * removed `elicitationId`; the shared schema keeps it because it is required - * on the frozen 2025-11-25 revision); form-mode elicitation params are - * revision-identical and are composed by reference from the shared schema. - * ------------------------------------------------------------------------ */ - -/** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ -export const CreateMessageRequestParamsSchema = z.object({ - messages: z.array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: z.string().optional(), - includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), - temperature: z.number().optional(), - maxTokens: z.number().int(), - stopSequences: z.array(z.string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: z.array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); - -/** 2026-era embedded sampling request (de-JSON-RPC'd). */ -export const CreateMessageRequestSchema = z.object({ - method: z.literal('sampling/createMessage'), - params: CreateMessageRequestParamsSchema -}); - -/** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ -export const ListRootsRequestSchema = z.object({ - method: z.literal('roots/list'), - params: z.object({ _meta: z.record(z.string(), z.unknown()).optional() }).optional() -}); - -/** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ -export const CreateMessageResultSchema = z.object({ - ...SamplingMessageSchema.shape, - model: z.string(), - stopReason: z.string().optional() -}); - -/** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ -export const ListRootsResultSchema = z.object({ - roots: z.array(RootSchema) -}); - -/** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ -export const ElicitResultSchema = z.object({ - action: z.enum(['accept', 'decline', 'cancel']), - content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() -}); - -/** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ -export const ElicitRequestURLParamsSchema = z.object({ - mode: z.literal('url'), - message: z.string(), - url: z.string().url() -}); - -/** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ -export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); - -/** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ -export const ElicitRequestSchema = z.object({ - method: z.literal('elicitation/create'), - params: ElicitRequestParamsSchema -}); - -/** A single embedded input request (one of the three demoted server→client requests). */ -export const InputRequestSchema = z.union([CreateMessageRequestSchema, ListRootsRequestSchema, ElicitRequestSchema]); - -/** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ -export const InputResponseSchema = z.union([CreateMessageResultSchema, ListRootsResultSchema, ElicitResultSchema]); - -/** Map of embedded input requests, keyed by server-assigned identifiers. */ -export const InputRequestsSchema = z.record(z.string(), InputRequestSchema); - -/** Map of embedded input responses, keyed by the corresponding request identifiers. */ -export const InputResponsesSchema = z.record(z.string(), InputResponseSchema); - -/** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ -export const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: z.string().optional() -}); - -/** The retry-channel members carried by client-initiated requests on this revision. */ -const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: z.string().optional() -}; - -/** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ -export const InputResponseRequestParamsSchema = z.object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape -}); - -/* ------------------------------------------------------------------------ * - * Request side. Two views per method: - * - WIRE-TRUE (`RequestSchema`): params `_meta` carries the REQUIRED - * envelope (anchor RequestParams._meta is required). The corpus and parity - * suite consume these. - * - DISPATCH (post-lift, internal to the registry): the protocol layer's - * universal lift has already extracted the envelope, so dispatch parses a - * 2025-like shape with optional `_meta` (progressToken/extension keys - * only) and NO 2025-only members (`task` is undeclared and strips — - * payload-level deletion is physical on this leg). - * ------------------------------------------------------------------------ */ - -/** Post-lift request `_meta` (progressToken + extension keys; loose). */ -const DispatchRequestMetaSchema = z.looseObject({ - progressToken: ProgressTokenSchema.optional() -}); - -function wireRequest(method: M, paramsShape: T) { - return z.object({ - method: z.literal(method), - params: z.object({ _meta: RequestMetaEnvelopeSchema, ...paramsShape }) - }); -} - -function dispatchRequest(method: M, paramsShape: T) { - return z.object({ - method: z.literal(method), - params: z.object({ _meta: DispatchRequestMetaSchema.optional(), ...paramsShape }).optional() - }); -} - -const callToolParamsShape = { - name: z.string(), - arguments: z.record(z.string(), z.unknown()).optional(), - // Multi-round-trip retry channel (the wire-true view models it; dispatch - // never sees it — the protocol layer lifts it before any handler runs). - ...retryParamsShape -}; -const paginatedParamsShape = { cursor: CursorSchema.optional() }; - -export const CallToolRequestSchema = wireRequest('tools/call', callToolParamsShape); -export const ListToolsRequestSchema = wireRequest('tools/list', paginatedParamsShape); -export const ListPromptsRequestSchema = wireRequest('prompts/list', paginatedParamsShape); -export const GetPromptRequestSchema = wireRequest('prompts/get', { - name: z.string(), - arguments: z.record(z.string(), z.string()).optional(), - ...retryParamsShape -}); -export const ListResourcesRequestSchema = wireRequest('resources/list', paginatedParamsShape); -export const ListResourceTemplatesRequestSchema = wireRequest('resources/templates/list', paginatedParamsShape); -export const ReadResourceRequestSchema = wireRequest('resources/read', { uri: z.string(), ...retryParamsShape }); -const completeParamsShape = { - ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: z.object({ name: z.string(), value: z.string() }), - context: z.object({ arguments: z.record(z.string(), z.string()).optional() }).optional() -}; -export const CompleteRequestSchema = wireRequest('completion/complete', completeParamsShape); -export const DiscoverRequestSchema = wireRequest('server/discover', {}); - -/** Anchor SubscriptionFilter (2026-only). */ -export const SubscriptionFilterSchema = z.object({ - toolsListChanged: z.boolean().optional(), - promptsListChanged: z.boolean().optional(), - resourcesListChanged: z.boolean().optional(), - resourceSubscriptions: z.array(z.string()).optional() -}); -const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema }; -export const SubscriptionsListenRequestSchema = wireRequest('subscriptions/listen', subscriptionsListenParamsShape); - -/** Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on the graceful-close result. */ -export const SubscriptionsListenResultMetaSchema = z.looseObject({ - 'io.modelcontextprotocol/subscriptionId': RequestIdSchema -}); - -/** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ -export const SubscriptionsListenResultSchema = z.looseObject({ - /** Required `_meta` (the subscriptionId stamp); the result body is otherwise empty. */ - _meta: SubscriptionsListenResultMetaSchema, - resultType: ResultTypeSchema.default('complete') -}); - -/** - * The 2026-era request-method set — the hand-registry seed (see registry.ts - * for the seed decisions). The dispatch maps below are mapped types over this - * union, so a missing entry, an extra entry, or an entry pointing at another - * method's schema is a compile error; the CI registry-diff oracle pins the - * same set against the anchor at runtime. - */ -export type Rev2026RequestMethod = - | 'tools/call' - | 'tools/list' - | 'prompts/get' - | 'prompts/list' - | 'resources/list' - | 'resources/templates/list' - | 'resources/read' - | 'completion/complete' - | 'server/discover' - | 'subscriptions/listen'; - -/** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ -export const dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> } = { - 'tools/call': dispatchRequest('tools/call', callToolParamsShape), - 'tools/list': dispatchRequest('tools/list', paginatedParamsShape), - 'prompts/get': dispatchRequest('prompts/get', { - name: z.string(), - arguments: z.record(z.string(), z.string()).optional() - }), - 'prompts/list': dispatchRequest('prompts/list', paginatedParamsShape), - 'resources/list': dispatchRequest('resources/list', paginatedParamsShape), - 'resources/templates/list': dispatchRequest('resources/templates/list', paginatedParamsShape), - 'resources/read': dispatchRequest('resources/read', { uri: z.string() }), - 'completion/complete': dispatchRequest('completion/complete', completeParamsShape), - 'server/discover': dispatchRequest('server/discover', {}), - 'subscriptions/listen': dispatchRequest('subscriptions/listen', subscriptionsListenParamsShape) -}; - -/** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ -function liftedResult(shape: T) { - return z.looseObject({ _meta: wireMeta, ...shape }); -} - -export const dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType } = { - 'tools/call': liftedResult({ - content: z.array(ContentBlockSchema), - structuredContent: z.unknown().optional(), - isError: z.boolean().optional() - }), - 'tools/list': liftedResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - tools: z.array(ToolSchema), - nextCursor: CursorSchema.optional() - }), - 'prompts/get': liftedResult({ - description: z.string().optional(), - messages: z.array(PromptMessageSchema) - }), - 'prompts/list': liftedResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - prompts: z.array(PromptSchema), - nextCursor: CursorSchema.optional() - }), - 'resources/list': liftedResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - resources: z.array(ResourceSchema), - nextCursor: CursorSchema.optional() - }), - 'resources/templates/list': liftedResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - resourceTemplates: z.array(ResourceTemplateSchema), - nextCursor: CursorSchema.optional() - }), - 'resources/read': liftedResult({ - ttlMs: z.number().int().min(0), - cacheScope: z.enum(['public', 'private']), - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) - }), - 'completion/complete': liftedResult({ - completion: z - .object({ - values: z.array(z.string()).max(100), - total: z.number().int().optional(), - hasMore: z.boolean().optional() - }) - .loose() - }), - 'server/discover': liftedResult({ - // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise - ttlMs: z.number().int().min(0).catch(0), - // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise - cacheScope: z.enum(['public', 'private']).catch('private'), - supportedVersions: z.array(z.string()), - capabilities: ServerCapabilities2026Schema, - serverInfo: ImplementationSchema, - instructions: z.string().optional() - }), - // `subscriptions/listen` receives a JSON-RPC result only on a server-side - // graceful close (the empty `SubscriptionsListenResult` — `_meta` carries - // the subscriptionId stamp). The dispatch result schema stays the lifted - // empty body so the mapped type is total; the listen-response demux is - // entry-layer (`Client._onresponse`) and never reaches `decodeResult`. - 'subscriptions/listen': liftedResult({}) -}; - -/* ------------------------------------------------------------------------ * - * Notifications. The 2026 notification set: cancelled, progress, message, - * resources/updated, resources/list_changed, tools/list_changed, - * prompts/list_changed. Deleted: initialized, roots/list_changed, - * tasks/status, elicitation/complete (removed from the draft together with - * URL-elicitation's elicitationId — both remain 2025-11-25 vocabulary only). - * The shapes are revision-identical to the shared schemas, which are - * composed by reference, EXCEPT cancelled (forks below: this revision - * requires `requestId`) and the 2026-only subscriptions/acknowledged. - * ------------------------------------------------------------------------ */ - -/** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ -export const NotificationMetaSchema = z.looseObject({ - /** - * The JSON-RPC ID of the `subscriptions/listen` request that opened the - * stream a notification was delivered on; absent on notifications not - * delivered via a subscription stream. - */ - 'io.modelcontextprotocol/subscriptionId': RequestIdSchema.optional() -}); - -/** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ -export const SubscriptionsAcknowledgedNotificationSchema = z.object({ - method: z.literal('notifications/subscriptions/acknowledged'), - params: z.object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema - }) -}); - -/** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ -export const CancelledNotificationParamsSchema = z.object({ - _meta: NotificationMetaSchema.optional(), - /** - * The ID of the request to cancel. This MUST correspond to the ID of a - * request the client previously issued. - */ - requestId: RequestIdSchema, - /** - * An optional string describing the reason for the cancellation. This MAY - * be logged or presented to the user. - */ - reason: z.string().optional() -}); - -/** 2026-era `notifications/cancelled` (see the params fork above). */ -export const CancelledNotificationSchema = z.object({ - method: z.literal('notifications/cancelled'), - params: CancelledNotificationParamsSchema -}); - -/** The 2026-era notification-method set (the hand-registry seed; see the deletion list above). */ -export type Rev2026NotificationMethod = - | 'notifications/cancelled' - | 'notifications/progress' - | 'notifications/message' - | 'notifications/resources/updated' - | 'notifications/resources/list_changed' - | 'notifications/tools/list_changed' - | 'notifications/prompts/list_changed' - | 'notifications/subscriptions/acknowledged'; - -export const notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> } = { - 'notifications/cancelled': CancelledNotificationSchema, - 'notifications/progress': ProgressNotificationSchema, - 'notifications/message': LoggingMessageNotificationSchema, - 'notifications/resources/updated': ResourceUpdatedNotificationSchema, - 'notifications/resources/list_changed': ResourceListChangedNotificationSchema, - 'notifications/tools/list_changed': ToolListChangedNotificationSchema, - 'notifications/prompts/list_changed': PromptListChangedNotificationSchema, - 'notifications/subscriptions/acknowledged': SubscriptionsAcknowledgedNotificationSchema -}; - -/* ------------------------------------------------------------------------ * - * Response envelopes (wire-true; parity/corpus artifacts). - * ------------------------------------------------------------------------ */ -const wireResultResponse = (result: T) => - z - .object({ - jsonrpc: z.literal('2.0'), - id: z.union([z.string(), z.number().int()]), - result - }) - .strict(); - -export const JSONRPCResultResponseSchema = wireResultResponse(ResultSchema); -// The multi-round-trip methods may answer with either their final result or an -// InputRequiredResult (anchor: `result: CallToolResult | InputRequiredResult`). -export const CallToolResultResponseSchema = wireResultResponse(z.union([CallToolResultSchema, InputRequiredResultSchema])); -export const ListToolsResultResponseSchema = wireResultResponse(ListToolsResultSchema); -export const ListPromptsResultResponseSchema = wireResultResponse(ListPromptsResultSchema); -export const GetPromptResultResponseSchema = wireResultResponse(z.union([GetPromptResultSchema, InputRequiredResultSchema])); -export const ListResourcesResultResponseSchema = wireResultResponse(ListResourcesResultSchema); -export const ListResourceTemplatesResultResponseSchema = wireResultResponse(ListResourceTemplatesResultSchema); -export const ReadResourceResultResponseSchema = wireResultResponse(z.union([ReadResourceResultSchema, InputRequiredResultSchema])); -export const CompleteResultResponseSchema = wireResultResponse(CompleteResultSchema); -export const DiscoverResultResponseSchema = wireResultResponse(DiscoverResultSchema); +import { buildSchemas2026 } from './buildSchemas'; + +export type { Rev2026NotificationMethod, Rev2026RequestMethod } from './buildSchemas'; + +const s = buildSchemas2026(); + +export const JSONValueSchema = s.JSONValueSchema; +export const JSONObjectSchema = s.JSONObjectSchema; +export const ProgressTokenSchema = s.ProgressTokenSchema; +export const CursorSchema = s.CursorSchema; +export const RequestIdSchema = s.RequestIdSchema; +export const RoleSchema = s.RoleSchema; +export const LoggingLevelSchema = s.LoggingLevelSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskMetadataSchema = s.TaskMetadataSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const RelatedTaskMetadataSchema = s.RelatedTaskMetadataSchema; +export const RequestMetaSchema = s.RequestMetaSchema; +export const BaseRequestParamsSchema = s.BaseRequestParamsSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const TaskAugmentedRequestParamsSchema = s.TaskAugmentedRequestParamsSchema; +export const NotificationsParamsSchema = s.NotificationsParamsSchema; +export const NotificationSchema = s.NotificationSchema; +export const IconSchema = s.IconSchema; +export const IconsSchema = s.IconsSchema; +export const BaseMetadataSchema = s.BaseMetadataSchema; +export const ImplementationSchema = s.ImplementationSchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const ClientTasksCapabilitySchema = s.ClientTasksCapabilitySchema; +/** @deprecated Task wire vocabulary (SEP-1686) — deprecated; see the task types in `types/types.ts`. */ +export const ServerTasksCapabilitySchema = s.ServerTasksCapabilitySchema; +export const ClientCapabilitiesSchema = s.ClientCapabilitiesSchema; +export const ServerCapabilitiesSchema = s.ServerCapabilitiesSchema; +export const ProgressSchema = s.ProgressSchema; +export const ProgressNotificationParamsSchema = s.ProgressNotificationParamsSchema; +export const ProgressNotificationSchema = s.ProgressNotificationSchema; +export const LoggingMessageNotificationParamsSchema = s.LoggingMessageNotificationParamsSchema; +export const LoggingMessageNotificationSchema = s.LoggingMessageNotificationSchema; +export const ResourceContentsSchema = s.ResourceContentsSchema; +export const TextResourceContentsSchema = s.TextResourceContentsSchema; +export const BlobResourceContentsSchema = s.BlobResourceContentsSchema; +export const AnnotationsSchema = s.AnnotationsSchema; +export const ResourceSchema = s.ResourceSchema; +export const ResourceTemplateSchema = s.ResourceTemplateSchema; +export const ResourceListChangedNotificationSchema = s.ResourceListChangedNotificationSchema; +export const ResourceUpdatedNotificationParamsSchema = s.ResourceUpdatedNotificationParamsSchema; +export const ResourceUpdatedNotificationSchema = s.ResourceUpdatedNotificationSchema; +export const PromptArgumentSchema = s.PromptArgumentSchema; +export const PromptSchema = s.PromptSchema; +export const PromptListChangedNotificationSchema = s.PromptListChangedNotificationSchema; +export const TextContentSchema = s.TextContentSchema; +export const ImageContentSchema = s.ImageContentSchema; +export const AudioContentSchema = s.AudioContentSchema; +export const ToolUseContentSchema = s.ToolUseContentSchema; +export const EmbeddedResourceSchema = s.EmbeddedResourceSchema; +export const ResourceLinkSchema = s.ResourceLinkSchema; +export const ContentBlockSchema = s.ContentBlockSchema; +export const PromptMessageSchema = s.PromptMessageSchema; +export const ToolAnnotationsSchema = s.ToolAnnotationsSchema; +export const ToolListChangedNotificationSchema = s.ToolListChangedNotificationSchema; +export const ModelHintSchema = s.ModelHintSchema; +export const ModelPreferencesSchema = s.ModelPreferencesSchema; +export const ToolChoiceSchema = s.ToolChoiceSchema; +export const BooleanSchemaSchema = s.BooleanSchemaSchema; +export const StringSchemaSchema = s.StringSchemaSchema; +export const NumberSchemaSchema = s.NumberSchemaSchema; +export const UntitledSingleSelectEnumSchemaSchema = s.UntitledSingleSelectEnumSchemaSchema; +export const TitledSingleSelectEnumSchemaSchema = s.TitledSingleSelectEnumSchemaSchema; +export const LegacyTitledEnumSchemaSchema = s.LegacyTitledEnumSchemaSchema; +export const SingleSelectEnumSchemaSchema = s.SingleSelectEnumSchemaSchema; +export const UntitledMultiSelectEnumSchemaSchema = s.UntitledMultiSelectEnumSchemaSchema; +export const TitledMultiSelectEnumSchemaSchema = s.TitledMultiSelectEnumSchemaSchema; +export const MultiSelectEnumSchemaSchema = s.MultiSelectEnumSchemaSchema; +export const EnumSchemaSchema = s.EnumSchemaSchema; +export const PrimitiveSchemaDefinitionSchema = s.PrimitiveSchemaDefinitionSchema; +export const ElicitRequestFormParamsSchema = s.ElicitRequestFormParamsSchema; +export const ResourceTemplateReferenceSchema = s.ResourceTemplateReferenceSchema; +export const PromptReferenceSchema = s.PromptReferenceSchema; +export const RootSchema = s.RootSchema; +export const ClientCapabilities2026Schema = s.ClientCapabilities2026Schema; +export const ServerCapabilities2026Schema = s.ServerCapabilities2026Schema; +export const RequestMetaEnvelopeSchema = s.RequestMetaEnvelopeSchema; +export const ToolSchema = s.ToolSchema; +export const ToolResultContentSchema = s.ToolResultContentSchema; +export const SamplingMessageContentBlockSchema = s.SamplingMessageContentBlockSchema; +export const SamplingMessageSchema = s.SamplingMessageSchema; +export const ResultTypeSchema = s.ResultTypeSchema; +export const ResultSchema = s.ResultSchema; +export const PaginatedResultSchema = s.PaginatedResultSchema; +export const CallToolResultSchema = s.CallToolResultSchema; +export const ListToolsResultSchema = s.ListToolsResultSchema; +export const ListPromptsResultSchema = s.ListPromptsResultSchema; +export const GetPromptResultSchema = s.GetPromptResultSchema; +export const ListResourcesResultSchema = s.ListResourcesResultSchema; +export const ListResourceTemplatesResultSchema = s.ListResourceTemplatesResultSchema; +export const ReadResourceResultSchema = s.ReadResourceResultSchema; +export const CompleteResultSchema = s.CompleteResultSchema; +export const CacheableResultSchema = s.CacheableResultSchema; +export const DiscoverResultSchema = s.DiscoverResultSchema; +export const CreateMessageRequestParamsSchema = s.CreateMessageRequestParamsSchema; +export const CreateMessageRequestSchema = s.CreateMessageRequestSchema; +export const ListRootsRequestSchema = s.ListRootsRequestSchema; +export const CreateMessageResultSchema = s.CreateMessageResultSchema; +export const ListRootsResultSchema = s.ListRootsResultSchema; +export const ElicitResultSchema = s.ElicitResultSchema; +export const ElicitRequestURLParamsSchema = s.ElicitRequestURLParamsSchema; +export const ElicitRequestParamsSchema = s.ElicitRequestParamsSchema; +export const ElicitRequestSchema = s.ElicitRequestSchema; +export const InputRequestSchema = s.InputRequestSchema; +export const InputResponseSchema = s.InputResponseSchema; +export const InputRequestsSchema = s.InputRequestsSchema; +export const InputResponsesSchema = s.InputResponsesSchema; +export const InputRequiredResultSchema = s.InputRequiredResultSchema; +export const InputResponseRequestParamsSchema = s.InputResponseRequestParamsSchema; +export const CallToolRequestSchema = s.CallToolRequestSchema; +export const ListToolsRequestSchema = s.ListToolsRequestSchema; +export const ListPromptsRequestSchema = s.ListPromptsRequestSchema; +export const GetPromptRequestSchema = s.GetPromptRequestSchema; +export const ListResourcesRequestSchema = s.ListResourcesRequestSchema; +export const ListResourceTemplatesRequestSchema = s.ListResourceTemplatesRequestSchema; +export const ReadResourceRequestSchema = s.ReadResourceRequestSchema; +export const CompleteRequestSchema = s.CompleteRequestSchema; +export const DiscoverRequestSchema = s.DiscoverRequestSchema; +export const SubscriptionFilterSchema = s.SubscriptionFilterSchema; +export const SubscriptionsListenRequestSchema = s.SubscriptionsListenRequestSchema; +export const SubscriptionsListenResultMetaSchema = s.SubscriptionsListenResultMetaSchema; +export const SubscriptionsListenResultSchema = s.SubscriptionsListenResultSchema; +export const dispatchRequestSchemas = s.dispatchRequestSchemas; +export const dispatchResultSchemas = s.dispatchResultSchemas; +export const NotificationMetaSchema = s.NotificationMetaSchema; +export const SubscriptionsAcknowledgedNotificationSchema = s.SubscriptionsAcknowledgedNotificationSchema; +export const CancelledNotificationParamsSchema = s.CancelledNotificationParamsSchema; +export const CancelledNotificationSchema = s.CancelledNotificationSchema; +export const notificationSchemas2026 = s.notificationSchemas2026; +export const JSONRPCResultResponseSchema = s.JSONRPCResultResponseSchema; +export const CallToolResultResponseSchema = s.CallToolResultResponseSchema; +export const ListToolsResultResponseSchema = s.ListToolsResultResponseSchema; +export const ListPromptsResultResponseSchema = s.ListPromptsResultResponseSchema; +export const GetPromptResultResponseSchema = s.GetPromptResultResponseSchema; +export const ListResourcesResultResponseSchema = s.ListResourcesResultResponseSchema; +export const ListResourceTemplatesResultResponseSchema = s.ListResourceTemplatesResultResponseSchema; +export const ReadResourceResultResponseSchema = s.ReadResourceResultResponseSchema; +export const CompleteResultResponseSchema = s.CompleteResultResponseSchema; +export const DiscoverResultResponseSchema = s.DiscoverResultResponseSchema; diff --git a/packages/core-internal/test/types/registryPins.test.ts b/packages/core-internal/test/types/registryPins.test.ts index 6e8a9d5c18..7170d523de 100644 --- a/packages/core-internal/test/types/registryPins.test.ts +++ b/packages/core-internal/test/types/registryPins.test.ts @@ -22,15 +22,21 @@ import { describe, expect, it } from 'vitest'; // Post-relocation home (Q1 increment-2 step 1): the pinned contents are // unchanged — only the module housing the registries moved. -import { getNotificationSchema, getRequestSchema, CallToolResultWireSchema, getResultSchema } from '../../src/wire/rev2025-11-25/registry'; +import { getNotificationSchema, getRequestSchema, getResultSchema } from '../../src/wire/rev2025-11-25/registry'; // The 2025 wire schemas are fully self-contained in the era's schema module: // every per-method schema the registry serves is a FROZEN 2025-11-25 copy so // the public/neutral layer can evolve (e.g. SEP-2106 widening) without // changing the 2025 wire-parse contract. The registry serves the FROZEN -// copies, so the by-reference pins target this module. +// copies, so the by-reference pins target this module. Since the lazy- +// construction change, importing this module also WARMS the era's schema +// memo (`buildSchemas2025`) at module scope — the registry pulls its maps +// through the same memo, so the by-reference pins hold under laziness. The +// wire-seam wrapper `CallToolResultWireSchema` moved here from the registry +// with that change (same object either way, via the shared memo). import { CallToolRequestSchema, CallToolResultSchema, + CallToolResultWireSchema, CancelledNotificationSchema, CancelTaskRequestSchema, CompleteRequestSchema,