From d6dc3127887825d348cea724f276e83caf9c43a7 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Tue, 7 Jul 2026 09:55:04 +0000 Subject: [PATCH 01/12] Construct the default AJV engine lazily on first validation AjvJsonSchemaValidator built its Ajv2020 instance (plus ajv-formats registration) in the constructor. Client and Server construct the default validator unconditionally, so every embedding application paid several milliseconds of AJV instantiation at startup even when no JSON Schema validation ever runs - a tax on CLI cold start in particular. Defer engine creation to the first getValidator() call via a private lazy getter. A caller-supplied engine is still used as-is from construction, the 2020-12 dialect check still fires before any engine is built, and the public API is unchanged. --- .../src/validators/ajvProvider.ts | 22 ++++--- .../test/validators/ajvLazyInit.test.ts | 57 +++++++++++++++++++ 2 files changed, 72 insertions(+), 7 deletions(-) create mode 100644 packages/core-internal/test/validators/ajvLazyInit.test.ts diff --git a/packages/core-internal/src/validators/ajvProvider.ts b/packages/core-internal/src/validators/ajvProvider.ts index 0a24fe4533..89768093a1 100644 --- a/packages/core-internal/src/validators/ajvProvider.ts +++ b/packages/core-internal/src/validators/ajvProvider.ts @@ -79,7 +79,7 @@ function createDefaultAjvInstance(): AjvLike { * ``` */ export class AjvJsonSchemaValidator implements jsonSchemaValidator { - private readonly _ajv: AjvLike; + private _ajv: AjvLike | undefined; /** True iff the constructor received a caller-supplied engine; the `$schema` check is skipped. */ private readonly _userAjv: boolean; @@ -88,12 +88,19 @@ export class AjvJsonSchemaValidator implements jsonSchemaValidator { * used for **every** schema regardless of its declared `$schema` (the caller owns dialect * choice). When omitted, the provider constructs a single `Ajv2020` instance with * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered. The parameter is typed structurally so consumers who don't pass an - * instance need not have `ajv` installed. + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. */ constructor(ajv?: AjvLike) { this._userAjv = ajv !== undefined; - this._ajv = ajv ?? createDefaultAjvInstance(); + this._ajv = ajv; + } + + /** The underlying engine — the default instance is created on first use. */ + private get ajv(): AjvLike { + return (this._ajv ??= createDefaultAjvInstance()); } getValidator(schema: JsonSchemaType): JsonSchemaValidator { @@ -113,10 +120,11 @@ export class AjvJsonSchemaValidator implements jsonSchemaValidator { ); } + const engine = this.ajv; const ajvValidator = '$id' in schema && typeof schema.$id === 'string' - ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) - : this._ajv.compile(schema); + ? (engine.getSchema(schema.$id) ?? engine.compile(schema)) + : engine.compile(schema); return (input: unknown): JsonSchemaValidatorResult => { const valid = ajvValidator(input); @@ -130,7 +138,7 @@ export class AjvJsonSchemaValidator implements jsonSchemaValidator { : { valid: false, data: undefined, - errorMessage: this._ajv.errorsText(ajvValidator.errors) + errorMessage: engine.errorsText(ajvValidator.errors) }; }; } diff --git a/packages/core-internal/test/validators/ajvLazyInit.test.ts b/packages/core-internal/test/validators/ajvLazyInit.test.ts new file mode 100644 index 0000000000..1823b60fdc --- /dev/null +++ b/packages/core-internal/test/validators/ajvLazyInit.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest'; + +import { AjvJsonSchemaValidator } from '../../src/validators/ajvProvider'; + +/** Peeks at the provider's private engine slot without triggering the lazy getter. */ +function engineSlot(provider: AjvJsonSchemaValidator): unknown { + return (provider as unknown as { _ajv: unknown })._ajv; +} + +describe('AjvJsonSchemaValidator lazy engine construction', () => { + it('does not construct the default Ajv engine until the first getValidator call', () => { + const provider = new AjvJsonSchemaValidator(); + expect(engineSlot(provider)).toBeUndefined(); + + const validate = provider.getValidator<{ a?: string }>({ type: 'object', properties: { a: { type: 'string' } } }); + expect(engineSlot(provider)).toBeDefined(); + expect(validate({ a: 'x' }).valid).toBe(true); + expect(validate({ a: 1 }).valid).toBe(false); + }); + + it('reuses one engine across getValidator calls', () => { + const provider = new AjvJsonSchemaValidator(); + provider.getValidator({ type: 'string' }); + const first = engineSlot(provider); + provider.getValidator({ type: 'number' }); + expect(engineSlot(provider)).toBe(first); + }); + + it('uses a caller-supplied engine immediately and never replaces it', () => { + let compiles = 0; + const fake = { + compile: () => { + compiles += 1; + return Object.assign(() => true, { errors: undefined }); + }, + getSchema: () => undefined, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + errorsText: (_errors?: any) => '' + }; + const provider = new AjvJsonSchemaValidator(fake); + expect(engineSlot(provider)).toBe(fake); + + const validate = provider.getValidator({ type: 'object' }); + expect(compiles).toBe(1); + expect(validate({}).valid).toBe(true); + expect(engineSlot(provider)).toBe(fake); + }); + + it('still rejects non-2020-12 $schema dialects before constructing the default engine', () => { + const provider = new AjvJsonSchemaValidator(); + expect(() => provider.getValidator({ $schema: 'http://json-schema.org/draft-07/schema#', type: 'object' })).toThrow( + /unsupported dialect/ + ); + // The dialect check fires before engine construction — no engine was built for the rejected schema. + expect(engineSlot(provider)).toBeUndefined(); + }); +}); From 262b9967f35cd161cda7b91b3d2576d316225fdd Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 14:07:26 +0000 Subject: [PATCH 02/12] Add changeset for lazy Ajv engine construction No-Verification-Needed: changeset-only commit --- .changeset/lazy-ajv-engine.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/lazy-ajv-engine.md diff --git a/.changeset/lazy-ajv-engine.md b/.changeset/lazy-ajv-engine.md new file mode 100644 index 0000000000..12ce0852ba --- /dev/null +++ b/.changeset/lazy-ajv-engine.md @@ -0,0 +1,6 @@ +--- +'@modelcontextprotocol/client': patch +'@modelcontextprotocol/server': patch +--- + +Construct the default Ajv validation engine lazily on first validation. Creating a `Client` or `Server` no longer pays the ajv + ajv-formats instantiation cost at startup when no JSON Schema validation ever runs. From 808221991498040dbfc7becb30066fb2313cc0ed Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 09:42:12 +0000 Subject: [PATCH 03/12] Build era wire schemas lazily through memoized factories Importing the client or server package used to construct both frozen era wire-schema graphs (2025-11-25 and 2026-07-28) at module evaluation, before any message was validated. Move each era's schema definitions into a buildSchemas() factory memoized at module level: - schema definitions are verbatim from the old era schemas.ts (and the CallToolResultWireSchema wire seam verbatim from the 2025 registry, which now serves it through the same memo) - registries keep method membership and the exported method lists as static null-valued key objects mapped over the same wire unions, so the both-direction drift guards remain compile errors and importing a registry constructs nothing - codecs and inputRequired pull schemas through the memo at first use - each era schemas.ts becomes an eager named-export shim over the memo for tests and tooling; the shim is not on any runtime import path and tree-shakes out of the published bundles Reference identity is preserved: registry lookups, codecs, and the shim all serve objects from one memo, so the by-reference registry pins hold (the pin test now warms the memo via the shim import). Importing client+server gets roughly a third cheaper in a scratch consumer; all package suites, the examples e2e matrix, typecheck, and lint pass unchanged. --- .changeset/lazy-era-wire-schemas.md | 7 + .../src/wire/rev2025-11-25/buildSchemas.ts | 2432 +++++++++++++++++ .../src/wire/rev2025-11-25/codec.ts | 12 +- .../src/wire/rev2025-11-25/registry.ts | 320 ++- .../src/wire/rev2025-11-25/schemas.ts | 2411 ++-------------- .../src/wire/rev2026-07-28/buildSchemas.ts | 1399 ++++++++++ .../src/wire/rev2026-07-28/codec.ts | 52 +- .../src/wire/rev2026-07-28/inputRequired.ts | 70 +- .../src/wire/rev2026-07-28/registry.ts | 53 +- .../src/wire/rev2026-07-28/schemas.ts | 1393 ++-------- .../test/types/registryPins.test.ts | 10 +- 11 files changed, 4467 insertions(+), 3692 deletions(-) create mode 100644 .changeset/lazy-era-wire-schemas.md create mode 100644 packages/core-internal/src/wire/rev2025-11-25/buildSchemas.ts create mode 100644 packages/core-internal/src/wire/rev2026-07-28/buildSchemas.ts 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..18ef8cc4b3 100644 --- a/packages/core-internal/src/wire/rev2025-11-25/schemas.ts +++ b/packages/core-internal/src/wire/rev2025-11-25/schemas.ts @@ -1,2229 +1,184 @@ /** - * 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() -}); - -/** - * 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. - */ -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 */ -/** - * 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. - */ -export 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. - */ -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 -}); -/** - * 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. - */ -export 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. - */ -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() -}); -/** - * 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. - */ -export 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. - */ -export 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. - */ -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() -}); - -/** - * 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. - */ -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() -}); - -/** - * 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. - */ -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() -}); - -/** - * 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. - */ -export 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. - */ -export 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. - */ -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() -}); - -/** - * 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. - */ -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() -}); -/** - * 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. - */ -export 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. - */ -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 -}); - -/** - * 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. - */ -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 */ -/** - * 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. - */ -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() -}); - -/** - * 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. - */ -export 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. - */ -export 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. - */ -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 -]); + * 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; +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; +export const LoggingLevelSchema = s.LoggingLevelSchema; +export const SetLevelRequestParamsSchema = s.SetLevelRequestParamsSchema; +export const SetLevelRequestSchema = s.SetLevelRequestSchema; +export const LoggingMessageNotificationParamsSchema = s.LoggingMessageNotificationParamsSchema; +export const LoggingMessageNotificationSchema = s.LoggingMessageNotificationSchema; +export const ModelHintSchema = s.ModelHintSchema; +export const ModelPreferencesSchema = s.ModelPreferencesSchema; +export const ToolChoiceSchema = s.ToolChoiceSchema; +export const ToolResultContentSchema = s.ToolResultContentSchema; +export const SamplingContentSchema = s.SamplingContentSchema; +export const SamplingMessageContentBlockSchema = s.SamplingMessageContentBlockSchema; +export const SamplingMessageSchema = s.SamplingMessageSchema; +export const CreateMessageRequestParamsSchema = s.CreateMessageRequestParamsSchema; +export const CreateMessageRequestSchema = s.CreateMessageRequestSchema; +export const CreateMessageResultSchema = s.CreateMessageResultSchema; +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; +export const RootSchema = s.RootSchema; +export const ListRootsRequestSchema = s.ListRootsRequestSchema; +export const ListRootsResultSchema = s.ListRootsResultSchema; +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, From 74f610c993e273f76bb5749861fef5e1933f8132 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 14:45:17 +0000 Subject: [PATCH 04/12] Restore deprecated JSDoc tags on the 2025 shim re-exports The shim restated the SEP-1686 task deprecations but dropped the SEP-2577 tags on the logging, sampling, and roots families; restore each block verbatim from the pre-factoring module so importers keep IDE strike-through and deprecation lint. --- .../src/wire/rev2025-11-25/schemas.ts | 154 ++++++++++++++++++ 1 file changed, 154 insertions(+) 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 18ef8cc4b3..76f4d7296b 100644 --- a/packages/core-internal/src/wire/rev2025-11-25/schemas.ts +++ b/packages/core-internal/src/wire/rev2025-11-25/schemas.ts @@ -87,6 +87,14 @@ 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. + * + * @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. + */ export const ToolUseContentSchema = s.ToolUseContentSchema; export const EmbeddedResourceSchema = s.EmbeddedResourceSchema; export const ResourceLinkSchema = s.ResourceLinkSchema; @@ -103,21 +111,139 @@ 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. + * + * @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. + */ export const LoggingLevelSchema = s.LoggingLevelSchema; +/** + * 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. + */ export const SetLevelRequestParamsSchema = s.SetLevelRequestParamsSchema; +/** + * 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. + */ export const SetLevelRequestSchema = s.SetLevelRequestSchema; +/** + * 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. + */ 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. + * + * @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. + */ export const LoggingMessageNotificationSchema = s.LoggingMessageNotificationSchema; +/** + * 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. + */ export const ModelHintSchema = s.ModelHintSchema; +/** + * 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. + */ export const ModelPreferencesSchema = s.ModelPreferencesSchema; +/** + * 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. + */ 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`. + * + * @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. + */ 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. + * + * @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. + */ export const SamplingContentSchema = s.SamplingContentSchema; +/** + * 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. + */ export const SamplingMessageContentBlockSchema = s.SamplingMessageContentBlockSchema; +/** + * 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. + */ export const SamplingMessageSchema = s.SamplingMessageSchema; +/** + * 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. + */ 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. + * + * @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. + */ 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). + * 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. + */ 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. + * + * @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. + */ export const CreateMessageResultWithToolsSchema = s.CreateMessageResultWithToolsSchema; export const BooleanSchemaSchema = s.BooleanSchemaSchema; export const StringSchemaSchema = s.StringSchemaSchema; @@ -143,9 +269,37 @@ 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. + * + * @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. + */ export const RootSchema = s.RootSchema; +/** + * 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. + */ export const ListRootsRequestSchema = s.ListRootsRequestSchema; +/** + * 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. + */ export const ListRootsResultSchema = s.ListRootsResultSchema; +/** + * 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. + */ 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; From bf993effe5b68f67a8b510367aa1134e07608e08 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 15:19:40 +0000 Subject: [PATCH 05/12] Move the neutral schema modules into @modelcontextprotocol/core MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The MCP spec schemas (types/schemas.ts), the OAuth/OpenID schemas (shared/auth.ts), the protocol constants (types/constants.ts), and the three JSON value types move verbatim from core-internal into packages/core/src — core now owns the schema sources instead of bundling them out of core-internal through build-only subpath aliases. Mechanism: - core's curated root entry re-exports the same public surface as before (unchanged 172 exports), now from its own local modules. - A new ./internal subpath re-exports the moved modules wholesale for the sibling SDK packages (internal helper schemas, auth types, constants, JSON types — names that are deliberately not public on the root entry). - core-internal keeps the old module paths as one-to-one named re-export shims, so no importer or test changes anywhere. - client/server/server-legacy declare @modelcontextprotocol/core as a real dependency; their bundles keep @modelcontextprotocol/core/internal as an external runtime import (explicit tsdown external entry) instead of carrying their own bundled schema copies. - The build-only core-internal/schemas + core-internal/auth tsconfig/tsdown aliases are deleted everywhere; the per-package tsconfigs gain a single source-first alias for @modelcontextprotocol/core/internal so typecheck and vitest stay build-order independent. Layering stays acyclic: core depends only on zod; core-internal depends on core; the wire era modules are untouched (their frozen copies and their runtime constants imports resolve through the shims unchanged). --- CLAUDE.md | 19 +- examples/client-quickstart/tsconfig.json | 3 + examples/server-quickstart/tsconfig.json | 3 + examples/shared/tsconfig.json | 3 + examples/tsconfig.json | 7 +- packages/client/package.json | 1 + packages/client/tsconfig.json | 1 + packages/client/tsdown.config.ts | 5 +- packages/core-internal/package.json | 1 + packages/core-internal/src/shared/auth.ts | 321 +- packages/core-internal/src/types/constants.ts | 126 +- packages/core-internal/src/types/schemas.ts | 2584 +---------------- packages/core-internal/src/types/types.ts | 6 +- packages/core-internal/tsconfig.json | 3 +- packages/core/package.json | 11 +- packages/core/src/auth.ts | 285 ++ packages/core/src/constants.ts | 104 + packages/core/src/index.ts | 24 +- packages/core/src/internal.ts | 16 + packages/core/src/schemas.ts | 2437 ++++++++++++++++ packages/core/src/types.ts | 4 + packages/core/tsconfig.json | 4 +- packages/core/tsdown.config.ts | 29 +- packages/middleware/express/tsconfig.json | 3 + packages/middleware/fastify/tsconfig.json | 3 + packages/middleware/hono/tsconfig.json | 3 + packages/middleware/node/tsconfig.json | 3 + packages/server-legacy/package.json | 1 + packages/server-legacy/tsconfig.json | 1 + packages/server-legacy/tsdown.config.ts | 6 +- packages/server/package.json | 1 + packages/server/tsconfig.json | 1 + packages/server/tsdown.config.ts | 5 +- pnpm-lock.yaml | 15 +- test/conformance/tsconfig.json | 3 + test/e2e/tsconfig.json | 3 + test/helpers/tsconfig.json | 3 + test/integration/tsconfig.json | 3 + 38 files changed, 3175 insertions(+), 2876 deletions(-) create mode 100644 packages/core/src/auth.ts create mode 100644 packages/core/src/constants.ts create mode 100644 packages/core/src/internal.ts create mode 100644 packages/core/src/schemas.ts create mode 100644 packages/core/src/types.ts diff --git a/CLAUDE.md b/CLAUDE.md index 4682dc362f..c7fa2357de 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -44,7 +44,7 @@ Include what changed, why, and how to migrate. Search for related sections and g ### JSDoc `@example` Code Snippets -JSDoc `@example` tags should pull type-checked code from companion `.examples.ts` files (e.g., `client.ts` → `client.examples.ts`). Use `` ```ts source="./file.examples.ts#regionName" `` fences referencing `//#region regionName` blocks; region names follow `exportedName_variant` or `ClassName_methodName_variant` pattern (e.g., `applyMiddlewares_basicUsage`, `Client_connect_basicUsage`). For whole-file inclusion (any file type), omit the `#regionName`. +JSDoc `@example` tags should pull type-checked code from companion `.examples.ts` files (e.g., `client.ts` → `client.examples.ts`). Use ` ```ts source="./file.examples.ts#regionName" ` fences referencing `//#region regionName` blocks; region names follow `exportedName_variant` or `ClassName_methodName_variant` pattern (e.g., `applyMiddlewares_basicUsage`, `Client_connect_basicUsage`). For whole-file inclusion (any file type), omit the `#regionName`. Run `pnpm sync:snippets` to sync example content into JSDoc comments and markdown files. @@ -70,9 +70,10 @@ The SDK separates internal code from the public API surface: - **`@modelcontextprotocol/core-internal`** (main entry, `packages/core-internal/src/index.ts`) — Internal barrel. Exports everything (including Zod schemas, Protocol class, stdio utils). Only consumed by sibling packages within the monorepo (`private: true`). - **`@modelcontextprotocol/core-internal/public`** (`packages/core-internal/src/exports/public/index.ts`) — Curated public API. Exports only TypeScript types, error classes, constants, and guards. Re-exported by client and server packages. - **`@modelcontextprotocol/client`** and **`@modelcontextprotocol/server`** (`packages/*/src/index.ts`) — Final public surface. Package-specific exports (named explicitly) plus re-exports from `core-internal/public`. -- **`@modelcontextprotocol/core`** (`packages/core/src/index.ts`) — Public Zod-schema package. Re-exports **only** the `*Schema` Zod constants (MCP spec + OAuth/OpenID), bundled from `core-internal` at build time. The published home for raw runtime validation (`CallToolResultSchema.parse(...)`); runtime-neutral (`zod` is its only dependency). Not consumed by the sibling packages — `client`/`server` keep their own bundled schema copies and stay Zod-free in their public surface. +- **`@modelcontextprotocol/core`** (`packages/core/src/index.ts`) — Public Zod-schema package and the canonical home of the schema source modules (`src/schemas.ts`, `src/auth.ts`, `src/constants.ts`). The root entry re-exports **only** the `*Schema` Zod constants (MCP spec + OAuth/OpenID) — the published home for raw runtime validation (`CallToolResultSchema.parse(...)`); runtime-neutral (`zod` is its only dependency). The `./internal` subpath re-exports the schema modules wholesale for the sibling packages: `core-internal` re-exports them at the old module paths, and the `client`/`server`/`server-legacy` bundles resolve `@modelcontextprotocol/core/internal` as a real external dependency instead of carrying their own schema copies (their public surfaces stay Zod-free). When modifying exports: + - Use explicit named exports, not `export *`, in package `index.ts` files and `core-internal/public`. - Adding a symbol to a package `index.ts` makes it public API — do so intentionally. - Internal helpers should stay in the core internal barrel and not be added to `core-internal/public` or package index files. @@ -197,14 +198,14 @@ The `ctx` parameter in handlers provides a structured context: - `sessionId?`: Transport session identifier - `mcpReq`: Request-level concerns - - `id`: JSON-RPC message ID - - `method`: Request method string (e.g., 'tools/call') - - `_meta?`: Request metadata - - `signal`: AbortSignal for cancellation - - `send(request, schema, options?)`: Send related request (for bidirectional flows) - - `notify(notification)`: Send related notification back + - `id`: JSON-RPC message ID + - `method`: Request method string (e.g., 'tools/call') + - `_meta?`: Request metadata + - `signal`: AbortSignal for cancellation + - `send(request, schema, options?)`: Send related request (for bidirectional flows) + - `notify(notification)`: Send related notification back - `http?`: HTTP transport info (undefined for stdio) - - `authInfo?`: Validated auth token info + - `authInfo?`: Validated auth token info **`ServerContext`** extends `BaseContext.mcpReq` and `BaseContext.http?` via type intersection: diff --git a/examples/client-quickstart/tsconfig.json b/examples/client-quickstart/tsconfig.json index cf326c78d8..b9650ed2f8 100644 --- a/examples/client-quickstart/tsconfig.json +++ b/examples/client-quickstart/tsconfig.json @@ -13,6 +13,9 @@ "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core-internal/src/index.ts" ], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ] diff --git a/examples/server-quickstart/tsconfig.json b/examples/server-quickstart/tsconfig.json index 36dccebc19..8866f024a3 100644 --- a/examples/server-quickstart/tsconfig.json +++ b/examples/server-quickstart/tsconfig.json @@ -13,6 +13,9 @@ "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/index.ts" ], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ] diff --git a/examples/shared/tsconfig.json b/examples/shared/tsconfig.json index ba240dda77..59ce27deee 100644 --- a/examples/shared/tsconfig.json +++ b/examples/shared/tsconfig.json @@ -13,6 +13,9 @@ "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/index.ts" ], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/examples/tsconfig.json b/examples/tsconfig.json index 1dcbec6899..6a35348636 100644 --- a/examples/tsconfig.json +++ b/examples/tsconfig.json @@ -22,15 +22,10 @@ "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/index.ts" ], + "@modelcontextprotocol/core/internal": ["./node_modules/@modelcontextprotocol/core/src/internal.ts"], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], - "@modelcontextprotocol/core-internal/schemas": [ - "./node_modules/@modelcontextprotocol/core/node_modules/@modelcontextprotocol/core-internal/src/types/schemas.ts" - ], - "@modelcontextprotocol/core-internal/auth": [ - "./node_modules/@modelcontextprotocol/core/node_modules/@modelcontextprotocol/core-internal/src/shared/auth.ts" - ], "@mcp-examples/shared": ["./node_modules/@mcp-examples/shared/src/index.ts"] } } diff --git a/packages/client/package.json b/packages/client/package.json index 752b5a38c3..8cfd5d4226 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -133,6 +133,7 @@ "test:watch": "vitest" }, "dependencies": { + "@modelcontextprotocol/core": "workspace:^", "cross-spawn": "catalog:runtimeClientOnly", "eventsource": "catalog:runtimeClientOnly", "eventsource-parser": "catalog:runtimeClientOnly", diff --git a/packages/client/tsconfig.json b/packages/client/tsconfig.json index f351f4cb76..8fc1de9347 100644 --- a/packages/client/tsconfig.json +++ b/packages/client/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": ["./node_modules/@modelcontextprotocol/core/src/internal.ts"], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/packages/client/tsdown.config.ts b/packages/client/tsdown.config.ts index 948cf95c88..45e0d7a28e 100644 --- a/packages/client/tsdown.config.ts +++ b/packages/client/tsdown.config.ts @@ -34,5 +34,8 @@ export default defineConfig({ } }, noExternal: ['@modelcontextprotocol/core-internal', 'ajv', 'ajv-formats', '@cfworker/json-schema'], - external: ['@modelcontextprotocol/client/_shims'] + // The schema modules live in @modelcontextprotocol/core (a real runtime dependency); the + // bundled core-internal shims import them via the './internal' subpath, which must stay an + // external import (explicit entry — the tsconfig paths alias would otherwise inline it). + external: ['@modelcontextprotocol/client/_shims', '@modelcontextprotocol/core/internal'] }); diff --git a/packages/core-internal/package.json b/packages/core-internal/package.json index f2ca34f5a2..2a26acf4bf 100644 --- a/packages/core-internal/package.json +++ b/packages/core-internal/package.json @@ -51,6 +51,7 @@ "test:watch": "vitest" }, "dependencies": { + "@modelcontextprotocol/core": "workspace:^", "content-type": "catalog:runtimeShared", "json-schema-typed": "catalog:runtimeShared", "zod": "catalog:runtimeShared" diff --git a/packages/core-internal/src/shared/auth.ts b/packages/core-internal/src/shared/auth.ts index e21076d817..d746ba0cd0 100644 --- a/packages/core-internal/src/shared/auth.ts +++ b/packages/core-internal/src/shared/auth.ts @@ -1,285 +1,36 @@ -import * as z from 'zod/v4'; - -/** - * Reusable URL validation that disallows `javascript:` scheme - */ -export const SafeUrlSchema = z - .url() - .superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'URL must be parseable', - fatal: true - }); - - return z.NEVER; - } - }) - .refine( - url => { - const u = new URL(url); - return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; - }, - { message: 'URL cannot use javascript:, data:, or vbscript: scheme' } - ); - -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -export const OAuthProtectedResourceMetadataSchema = z.looseObject({ - resource: z.string().url(), - authorization_servers: z.array(SafeUrlSchema).optional(), - jwks_uri: z.string().url().optional(), - scopes_supported: z.array(z.string()).optional(), - bearer_methods_supported: z.array(z.string()).optional(), - resource_signing_alg_values_supported: z.array(z.string()).optional(), - resource_name: z.string().optional(), - resource_documentation: z.string().optional(), - resource_policy_uri: z.string().url().optional(), - resource_tos_uri: z.string().url().optional(), - tls_client_certificate_bound_access_tokens: z.boolean().optional(), - authorization_details_types_supported: z.array(z.string()).optional(), - dpop_signing_alg_values_supported: z.array(z.string()).optional(), - dpop_bound_access_tokens_required: z.boolean().optional() -}); - -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -export const OAuthMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - introspection_endpoint: z.string().optional(), - introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - code_challenge_methods_supported: z.array(z.string()).optional(), - client_id_metadata_document_supported: z.boolean().optional(), - // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain - authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined) -}); - -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * - * @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -export const OpenIdProviderMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - acr_values_supported: z.array(z.string()).optional(), - subject_types_supported: z.array(z.string()), - id_token_signing_alg_values_supported: z.array(z.string()), - id_token_encryption_alg_values_supported: z.array(z.string()).optional(), - id_token_encryption_enc_values_supported: z.array(z.string()).optional(), - userinfo_signing_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), - request_object_signing_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_enc_values_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - display_values_supported: z.array(z.string()).optional(), - claim_types_supported: z.array(z.string()).optional(), - claims_supported: z.array(z.string()).optional(), - service_documentation: z.string().optional(), - claims_locales_supported: z.array(z.string()).optional(), - ui_locales_supported: z.array(z.string()).optional(), - claims_parameter_supported: z.boolean().optional(), - request_parameter_supported: z.boolean().optional(), - request_uri_parameter_supported: z.boolean().optional(), - require_request_uri_registration: z.boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: z.boolean().optional(), - // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain - authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined) -}); - -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -export const OpenIdProviderDiscoveryMetadataSchema = z.object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ - code_challenge_methods_supported: true - }).shape -}); - -/** - * OAuth 2.1 token response - */ -export const OAuthTokensSchema = z - .object({ - access_token: z.string(), - id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect - token_type: z.string(), - expires_in: z.coerce.number().optional(), - scope: z.string().optional(), - refresh_token: z.string().optional() - }) - .strip(); - -/** - * RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. - * - * `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when - * the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, - * so strict checking rejects conformant IdPs. - */ -export const IdJagTokenExchangeResponseSchema = z - .object({ - issued_token_type: z.literal('urn:ietf:params:oauth:token-type:id-jag'), - access_token: z.string(), - token_type: z.string().optional(), - expires_in: z.number().optional(), - scope: z.string().optional() - }) - .strip(); - -export type IdJagTokenExchangeResponse = z.infer; - -/** - * OAuth 2.1 error response - */ -export const OAuthErrorResponseSchema = z.object({ - error: z.string(), - error_description: z.string().optional(), - error_uri: z.string().optional() -}); - -/** - * Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` - */ -// eslint-disable-next-line unicorn/no-useless-undefined -export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -export const OAuthClientMetadataSchema = z - .object({ - redirect_uris: z.array(SafeUrlSchema), - token_endpoint_auth_method: z.string().optional(), - grant_types: z.array(z.string()).optional(), - response_types: z.array(z.string()).optional(), - /** - * OIDC Dynamic Client Registration `application_type`. MCP clients MUST set - * this to `'native'` or `'web'` when registering (SEP-837); the SDK defaults - * it from `redirect_uris` when omitted. Typed as `string` (not an enum) so - * that parsing an authorization server's registration response — which under - * RFC 7591 may echo extension values — never rejects the document on this - * field alone. - */ - application_type: z.string().optional(), - client_name: z.string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: z.string().optional(), - contacts: z.array(z.string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: z.string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: z.any().optional(), - software_id: z.string().optional(), - software_version: z.string().optional(), - software_statement: z.string().optional() - }) - .strip(); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -export const OAuthClientInformationSchema = z - .object({ - client_id: z.string(), - client_secret: z.string().optional(), - client_id_issued_at: z.number().optional(), - client_secret_expires_at: z.number().optional() - }) - .strip(); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -export const OAuthClientRegistrationErrorSchema = z - .object({ - error: z.string(), - error_description: z.string().optional() - }) - .strip(); - -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -export const OAuthTokenRevocationRequestSchema = z - .object({ - token: z.string(), - token_type_hint: z.string().optional() - }) - .strip(); - -export type OAuthMetadata = z.infer; -export type OpenIdProviderMetadata = z.infer; -export type OpenIdProviderDiscoveryMetadata = z.infer; - -export type OAuthTokens = z.infer; -export type OAuthErrorResponse = z.infer; -export type OAuthClientMetadata = z.infer; -export type OAuthClientInformation = z.infer; -export type OAuthClientInformationFull = z.infer; -export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; - -/** - * {@linkcode OAuthTokens} as persisted by an `OAuthClientProvider`. Adds an - * SDK-stamped authorization-server `issuer` identifier so stored tokens are - * bound to the AS that issued them. The `issuer` field is **not** part of the - * RFC 6749 wire response and is intentionally absent from the wire-response - * schema; the client SDK writes it before calling `saveTokens`. - */ -export type StoredOAuthTokens = OAuthTokens & { issuer?: string }; - -/** - * {@linkcode OAuthClientInformationMixed} as persisted by an - * `OAuthClientProvider`. Adds an SDK-stamped authorization-server `issuer` - * identifier so stored client credentials are bound to the AS that issued them. - * The `issuer` field is **not** part of the RFC 7591 wire response and is - * intentionally absent from the wire-response schema; the client SDK writes it - * before calling `saveClientInformation`. - */ -export type StoredOAuthClientInformation = OAuthClientInformationMixed & { issuer?: string }; - -export type OAuthClientRegistrationError = z.infer; -export type OAuthTokenRevocationRequest = z.infer; -export type OAuthProtectedResourceMetadata = z.infer; - -// Unified type for authorization server metadata -export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; +// Moved: the OAuth/OpenID schemas + types now live in @modelcontextprotocol/core (packages/core/src/auth.ts). +// This module re-exports them one-to-one so every existing import path keeps working. +export type { + AuthorizationServerMetadata, + IdJagTokenExchangeResponse, + OAuthClientInformation, + OAuthClientInformationFull, + OAuthClientInformationMixed, + OAuthClientMetadata, + OAuthClientRegistrationError, + OAuthErrorResponse, + OAuthMetadata, + OAuthProtectedResourceMetadata, + OAuthTokenRevocationRequest, + OAuthTokens, + OpenIdProviderDiscoveryMetadata, + OpenIdProviderMetadata, + StoredOAuthClientInformation, + StoredOAuthTokens +} from '@modelcontextprotocol/core/internal'; +export { + IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema, + OAuthClientInformationSchema, + OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema, + OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema, + OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema, + OptionalSafeUrlSchema, + SafeUrlSchema +} from '@modelcontextprotocol/core/internal'; diff --git a/packages/core-internal/src/types/constants.ts b/packages/core-internal/src/types/constants.ts index 61e6ca7f1f..b4f3f35fdc 100644 --- a/packages/core-internal/src/types/constants.ts +++ b/packages/core-internal/src/types/constants.ts @@ -1,104 +1,22 @@ -export const LATEST_PROTOCOL_VERSION = '2025-11-25'; -export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; -export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; - -/** - * `_meta` key associating a message with a 2025-11-25 task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ -export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; - -/* Reserved `_meta` keys for the per-request envelope (protocol revision 2026-07-28) */ - -/** - * `_meta` key carrying the MCP protocol version governing a request. - * - * For the HTTP transport, the value must match the `MCP-Protocol-Version` header. - */ -export const PROTOCOL_VERSION_META_KEY = 'io.modelcontextprotocol/protocolVersion'; - -/** - * `_meta` key identifying the client software making a request. - */ -export const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; - -/** - * `_meta` key carrying the client's capabilities for a request. - * - * Capabilities are declared per request rather than once at initialization; - * servers must not infer capabilities from prior requests. - */ -export const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities'; - -/** - * `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request - * that opened the stream a notification was delivered on. - * - * Stamped by the server on every notification delivered via a - * `subscriptions/listen` stream (including the leading - * `notifications/subscriptions/acknowledged`); on stdio, where all messages - * share one channel, clients use it to correlate notifications with their - * originating subscription. The value is the listen request's JSON-RPC ID - * verbatim. - */ -export const SUBSCRIPTION_ID_META_KEY = 'io.modelcontextprotocol/subscriptionId'; - -/** - * `_meta` key carrying the desired log level for a request. - * - * When absent, the server must not send `notifications/message` notifications - * for the request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. - */ -export const LOG_LEVEL_META_KEY = 'io.modelcontextprotocol/logLevel'; - -/* - * Reserved `_meta` keys for distributed trace context propagation (SEP-414). - * - * These unprefixed keys are reserved by the MCP specification as an explicit - * exception to the `_meta` key prefix rule. The SDK does not interpret them; - * they pass through `_meta` untouched for OpenTelemetry-style propagation. - */ - -/** - * `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). - * - * When present, the value MUST follow the W3C `traceparent` header format, - * e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. - * - * @see https://www.w3.org/TR/trace-context/#traceparent-header - */ -export const TRACEPARENT_META_KEY = 'traceparent'; - -/** - * `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). - * - * When present, the value MUST follow the W3C `tracestate` header format, - * e.g. `vendor1=value1,vendor2=value2`. - * - * @see https://www.w3.org/TR/trace-context/#tracestate-header - */ -export const TRACESTATE_META_KEY = 'tracestate'; - -/** - * `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). - * - * When present, the value MUST follow the W3C Baggage header format, - * e.g. `userId=alice,serverRegion=us-east-1`. - * - * @see https://www.w3.org/TR/baggage/ - */ -export const BAGGAGE_META_KEY = 'baggage'; - -/* JSON-RPC types */ -export const JSONRPC_VERSION = '2.0'; - -/* Standard JSON-RPC error code constants */ -export const PARSE_ERROR = -32_700; -export const INVALID_REQUEST = -32_600; -export const METHOD_NOT_FOUND = -32_601; -export const INVALID_PARAMS = -32_602; -export const INTERNAL_ERROR = -32_603; +// Moved: the protocol constants now live in @modelcontextprotocol/core (packages/core/src/constants.ts). +// This module re-exports them one-to-one so every existing import path keeps working. +export { + BAGGAGE_META_KEY, + CLIENT_CAPABILITIES_META_KEY, + CLIENT_INFO_META_KEY, + DEFAULT_NEGOTIATED_PROTOCOL_VERSION, + INTERNAL_ERROR, + INVALID_PARAMS, + INVALID_REQUEST, + JSONRPC_VERSION, + LATEST_PROTOCOL_VERSION, + LOG_LEVEL_META_KEY, + METHOD_NOT_FOUND, + PARSE_ERROR, + PROTOCOL_VERSION_META_KEY, + RELATED_TASK_META_KEY, + SUBSCRIPTION_ID_META_KEY, + SUPPORTED_PROTOCOL_VERSIONS, + TRACEPARENT_META_KEY, + TRACESTATE_META_KEY +} from '@modelcontextprotocol/core/internal'; diff --git a/packages/core-internal/src/types/schemas.ts b/packages/core-internal/src/types/schemas.ts index bc64597b98..c67bcb2a52 100644 --- a/packages/core-internal/src/types/schemas.ts +++ b/packages/core-internal/src/types/schemas.ts @@ -1,2437 +1,171 @@ -import * as z from 'zod/v4'; - -import { JSONRPC_VERSION, RELATED_TASK_META_KEY, SUBSCRIPTION_ID_META_KEY } from './constants'; -import type { JSONArray, JSONObject, JSONValue } from './types'; - -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); -export const JSONArraySchema: z.ZodType = z.array(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. - */ - [RELATED_TASK_META_KEY]: 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() - // `resultType` is wire-only vocabulary (protocol revision 2026-07-28) and - // is deliberately NOT modeled here: the neutral result schemas carry no - // slot for it. It exists only inside the 2026-era wire codec, which - // consumes it on decode and stamps it on encode. (Q1 increment 2 - the - // former optional member here was the masking surface that let modern - // vocabulary leak through every legacy-leg parse.) -}); - -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); - -/** - * A request that expects a response. - */ -export const JSONRPCRequestSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape - }) - .strict(); - -/** - * A notification which does not expect a response. - */ -export const JSONRPCNotificationSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - ...NotificationSchema.shape - }) - .strict(); - -/** - * A successful (non-error) response to a request. - */ -export const JSONRPCResultResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema - }) - .strict(); - -/** - * A response to a request that indicates an error occurred. - */ -export const JSONRPCErrorResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: z.object({ - /** - * The error type that occurred. - */ - code: z.number().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: z.string(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: z.unknown().optional() - }) - }) - .strict(); - -export const JSONRPCMessageSchema = z.union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); - -export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); - -/* 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() -}); - -/* Discovery */ -/** - * A request from the client asking the server to advertise its supported protocol - * versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers - * MUST implement `server/discover`. Clients MAY call it but are not required to — - * version negotiation can also happen inline via the per-request `_meta` envelope. - */ -export const DiscoverRequestSchema = RequestSchema.extend({ - method: z.literal('server/discover'), - params: BaseRequestParamsSchema.optional() -}); - -/** - * The result returned by the server for a `server/discover` request. - */ -export const DiscoverResultSchema = ResultSchema.extend({ - /** - * MCP protocol versions this server supports. The client should choose a - * version from this list for use in subsequent requests. - */ - supportedVersions: z.array(z.string()), - /** - * The capabilities of the server. - */ - capabilities: ServerCapabilitiesSchema, - /** - * Information about the server software implementation. - */ - serverInfo: ImplementationSchema, - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions: z.string().optional() -}); - -/* Ping */ -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -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 -}); - -/* Subscriptions (protocol revision 2026-07-28) */ -/** - * The set of notification types a client opts in to on a `subscriptions/listen` - * request. Each type is opt-in; the server MUST NOT send a notification type - * the client has not explicitly requested here. - */ -export const SubscriptionFilterSchema = z.object({ - /** - * If true, receive `notifications/tools/list_changed`. - */ - toolsListChanged: z.boolean().optional(), - /** - * If true, receive `notifications/prompts/list_changed`. - */ - promptsListChanged: z.boolean().optional(), - /** - * If true, receive `notifications/resources/list_changed`. - */ - resourcesListChanged: z.boolean().optional(), - /** - * Subscribe to `notifications/resources/updated` for these resource URIs. - * Replaces the former `resources/subscribe` RPC on the 2026-07-28 revision. - */ - resourceSubscriptions: z.array(z.string()).optional() -}); - -export const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The notifications the client opts in to on this stream. The server MUST - * NOT send notification types the client has not explicitly requested. - */ - notifications: SubscriptionFilterSchema -}); - -/** - * Sent from the client to open a long-lived channel for receiving notifications - * outside the context of a specific request (protocol revision 2026-07-28). - * Replaces the previous HTTP GET endpoint and `resources/subscribe`. - */ -export const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: z.literal('subscriptions/listen'), - params: SubscriptionsListenRequestParamsSchema -}); - -export const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The subset of requested notification types the server agreed to honor. - */ - notifications: SubscriptionFilterSchema -}); - -/** - * Sent by the server as the first message on a `subscriptions/listen` stream - * to acknowledge that the subscription has been established and report which - * notification types it agreed to honor (protocol revision 2026-07-28). - */ -export const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/subscriptions/acknowledged'), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); - -/** - * `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's - * JSON-RPC ID under the canonical subscription-id key (mirroring the same key - * on every notification delivered on the stream). - */ -export const SubscriptionsListenResultMetaSchema = z.looseObject({ - [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema -}); - -/** - * The response to a `subscriptions/listen` request, signalling that the - * subscription has ended gracefully (for example, during server shutdown). - * Because the listen stream is long-lived, this result is sent only when the - * server tears the subscription down; an abrupt transport close carries no - * response. The result body is otherwise empty. - */ -export const SubscriptionsListenResultSchema = ResultSchema.extend({ - _meta: SubscriptionsListenResultMetaSchema -}); - -/** - * 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() -}); - -/** - * 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. - */ -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 document describing the structure of the tool's output - * returned in the `structuredContent` field of a `CallToolResult`. - * - * SEP-2106: any JSON Schema root is permitted (e.g. `type:'array'`, `oneOf`, `$ref`). - * The 2025-11-25 wire parse retains the `type:'object'` constraint via the frozen schema in - * `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens. - */ - outputSchema: z.looseObject({ $schema: z.string().optional() }).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). - * - * Parse-tolerant: absent `content` defaults to `[]` (v1 parity — deployed - * servers omit it alongside `structuredContent`). - */ - content: z.array(ContentBlockSchema).default([]), - - /** - * Structured tool output. - * - * If the `Tool` defines an `outputSchema`, this field MUST be present in the result and - * contain a JSON value that matches the schema. - * - * SEP-2106: any JSON value is permitted (arrays, primitives, `null`). Narrow before property - * access. The 2025-11-25 wire parse retains the object-only constraint via the frozen schema - * in `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens. - */ - structuredContent: 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() -}); - -/** - * {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. - */ -export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( - ResultSchema.extend({ - toolResult: z.unknown() - }) -); - -/** - * 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() -}); - -/** - * Base schema for list changed subscription options (without callback). - * Used internally for Zod validation of `autoRefresh` and `debounceMs`. - */ -export const ListChangedOptionsBaseSchema = z.object({ - /** - * If `true`, the list will be refreshed automatically when a list changed notification is received. - * The callback will be called with the updated list. - * - * If `false`, the callback will be called with `null` items, allowing manual refresh. - * - * @default true - */ - autoRefresh: z.boolean().default(true), - /** - * Debounce time in milliseconds for list changed notification processing. - * - * Multiple notifications received within this timeframe will only trigger one refresh. - * Set to `0` to disable debouncing. - * - * @default 300 - */ - debounceMs: z.number().int().nonnegative().default(300) -}); - -/* 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. - */ -export 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. - */ -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 -}); -/** - * 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. - */ -export 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. - */ -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() -}); -/** - * 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. - */ -export 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. - */ -export 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. - */ -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() -}); - -/** - * 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. - */ -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() -}); - -/** - * 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. - */ -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), - /** - * SEP-2106: any JSON value is permitted. The 2025-11-25 wire parse retains the object-only - * constraint via the frozen schema in `wire/rev2025-11-25/schemas.ts`. - */ - structuredContent: z.unknown().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. - */ -export 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. - */ -export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ - TextContentSchema, - ImageContentSchema, +// Moved: the spec Zod schemas now live in @modelcontextprotocol/core (packages/core/src/schemas.ts). +// This module re-exports them one-to-one so every existing import path keeps working; a name +// added to core/src/schemas.ts must be added here too (specTypeSchema.ts imports through this +// module, so a missing name fails typecheck loudly). +export { + AnnotationsSchema, 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. - */ -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() -}); - -/** - * 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. - */ -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() -}); -/** - * 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. - */ -export 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. - */ -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 -}); - -/** - * 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. - */ -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. - * - * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the - * outcome of an out-of-band interaction by retrying the original request; no - * server-initiated completion signal exists in the 2026-07-28 revision. Kept here - * for the 2025-era URL-mode flow only. - */ - 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. - * - * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome - * of an out-of-band interaction by retrying the original request; no server-initiated - * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow - * only. The 2026-07-28 wire codec excludes this notification. - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the elicitation that completed. - * - * @deprecated See {@linkcode ElicitationCompleteNotificationParamsSchema}. - */ - elicitationId: z.string() -}); - -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome - * of an out-of-band interaction by retrying the original request; no server-initiated - * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow - * only. The 2026-07-28 wire codec excludes this notification. - * @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 */ -/** - * 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. - */ -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() -}); - -/** - * 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. - */ -export 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. - */ -export 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. - */ -export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -/* ─────────────────────────────────────────────────────────────────────────── - * Tasks (2025-11-25 wire vocabulary, DEPRECATED) - * - * The task message surface defined by the 2025-11-25 protocol revision. These - * schemas are kept in the neutral layer so the public Task* types stay - * nameable without a cross-layer import into wire/rev*; the wire-parse - * contract for them is the FROZEN copy in wire/rev2025-11-25/schemas.ts. - * - * They appear in NO role aggregate below and no API signature — nameable-only - * vocabulary for interop with task-capable 2025 peers (#2248). Removable at - * the major version that drops 2025-era support. - * ─────────────────────────────────────────────────────────────────────────── */ - -/** - * 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); - -/* Client messages */ -// NOTE (Q1 increment 2): the role unions below are the NEUTRAL message sets. -// The 2025-era task vocabulary (tasks/* methods, task results, the task -// status notification) is 2025-only WIRE vocabulary; the deprecated Task* -// schemas above are nameable-only and appear in NO role aggregate and no API -// signature. The era's full wire role unions live in -// `wire/rev2025-11-25/schemas.ts`. -export const ClientRequestSchema = z.union([ - PingRequestSchema, - InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, + BaseMetadataSchema, + BaseRequestParamsSchema, + BlobResourceContentsSchema, + BooleanSchemaSchema, + CallToolRequestParamsSchema, CallToolRequestSchema, - ListToolsRequestSchema -]); - -export const ClientNotificationSchema = z.union([ + CallToolResultSchema, + CancelledNotificationParamsSchema, CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); - -export const ClientResultSchema = z.union([ - EmptyResultSchema, + CancelTaskRequestSchema, + CancelTaskResultSchema, + ClientCapabilitiesSchema, + ClientNotificationSchema, + ClientRequestSchema, + ClientResultSchema, + ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema, + CompleteRequestSchema, + CompleteResultSchema, + ContentBlockSchema, + CreateMessageRequestParamsSchema, + CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, + CreateTaskResultSchema, + CursorSchema, + DiscoverRequestSchema, + DiscoverResultSchema, + ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema, + ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema, + ElicitRequestSchema, + ElicitRequestURLParamsSchema, ElicitResultSchema, - ListRootsResultSchema -]); - -/* Server messages */ -export const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]); - -export const ServerNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); - -export const ServerResultSchema = z.union([ + EmbeddedResourceSchema, EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, + EnumSchemaSchema, + GetPromptRequestParamsSchema, + GetPromptRequestSchema, GetPromptResultSchema, + GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema, + GetTaskRequestSchema, + GetTaskResultSchema, + IconSchema, + IconsSchema, + ImageContentSchema, + ImplementationSchema, + InitializedNotificationSchema, + InitializeRequestParamsSchema, + InitializeRequestSchema, + InitializeResultSchema, + JSONArraySchema, + JSONObjectSchema, + JSONRPCErrorResponseSchema, + JSONRPCMessageSchema, + JSONRPCNotificationSchema, + JSONRPCRequestSchema, + JSONRPCResponseSchema, + JSONRPCResultResponseSchema, + JSONValueSchema, + LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema, + ListPromptsRequestSchema, ListPromptsResultSchema, + ListResourcesRequestSchema, ListResourcesResultSchema, + ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, + ListRootsRequestSchema, + ListRootsResultSchema, + ListTasksRequestSchema, + ListTasksResultSchema, + ListToolsRequestSchema, ListToolsResultSchema, - SubscriptionsListenResultSchema -]); + LoggingLevelSchema, + LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema, + ModelHintSchema, + ModelPreferencesSchema, + MultiSelectEnumSchemaSchema, + NotificationSchema, + NotificationsParamsSchema, + NumberSchemaSchema, + PaginatedRequestParamsSchema, + PaginatedRequestSchema, + PaginatedResultSchema, + PingRequestSchema, + PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema, + ProgressNotificationSchema, + ProgressSchema, + ProgressTokenSchema, + PromptArgumentSchema, + PromptListChangedNotificationSchema, + PromptMessageSchema, + PromptReferenceSchema, + PromptSchema, + ReadResourceRequestParamsSchema, + ReadResourceRequestSchema, + ReadResourceResultSchema, + RelatedTaskMetadataSchema, + RequestIdSchema, + RequestMetaSchema, + RequestSchema, + ResourceContentsSchema, + ResourceLinkSchema, + ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema, + ResourceSchema, + ResourceTemplateReferenceSchema, + ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema, + ResultSchema, + RoleSchema, + RootSchema, + RootsListChangedNotificationSchema, + SamplingContentSchema, + SamplingMessageContentBlockSchema, + SamplingMessageSchema, + ServerCapabilitiesSchema, + ServerNotificationSchema, + ServerRequestSchema, + ServerResultSchema, + ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema, + SetLevelRequestSchema, + SingleSelectEnumSchemaSchema, + StringSchemaSchema, + SubscribeRequestParamsSchema, + SubscribeRequestSchema, + SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema, + TaskMetadataSchema, + TaskSchema, + TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema, + TaskStatusSchema, + TextContentSchema, + TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema, + ToolChoiceSchema, + ToolExecutionSchema, + ToolListChangedNotificationSchema, + ToolResultContentSchema, + ToolSchema, + ToolUseContentSchema, + UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema +} from '@modelcontextprotocol/core/internal'; diff --git a/packages/core-internal/src/types/types.ts b/packages/core-internal/src/types/types.ts index b16a7b5efc..f4720631c0 100644 --- a/packages/core-internal/src/types/types.ts +++ b/packages/core-internal/src/types/types.ts @@ -175,10 +175,8 @@ import type { UntitledSingleSelectEnumSchemaSchema } from './schemas'; -/* JSON types */ -export type JSONValue = string | number | boolean | null | JSONObject | JSONArray; -export type JSONObject = { [key: string]: JSONValue }; -export type JSONArray = JSONValue[]; +/* JSON types — moved to @modelcontextprotocol/core (packages/core/src/types.ts). */ +export type { JSONArray, JSONObject, JSONValue } from '@modelcontextprotocol/core/internal'; /** * Utility types diff --git a/packages/core-internal/tsconfig.json b/packages/core-internal/tsconfig.json index a6838303e4..38faa24f6e 100644 --- a/packages/core-internal/tsconfig.json +++ b/packages/core-internal/tsconfig.json @@ -6,7 +6,8 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] + "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], + "@modelcontextprotocol/core/internal": ["./node_modules/@modelcontextprotocol/core/src/internal.ts"] } } } diff --git a/packages/core/package.json b/packages/core/package.json index c6fb199708..28e89186bb 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -30,6 +30,16 @@ "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } + }, + "./internal": { + "import": { + "types": "./dist/internal.d.mts", + "default": "./dist/internal.mjs" + }, + "require": { + "types": "./dist/internal.d.cts", + "default": "./dist/internal.cjs" + } } }, "main": "./dist/index.cjs", @@ -53,7 +63,6 @@ }, "devDependencies": { "@eslint/js": "catalog:devTools", - "@modelcontextprotocol/core-internal": "workspace:^", "@modelcontextprotocol/eslint-config": "workspace:^", "@modelcontextprotocol/tsconfig": "workspace:^", "@modelcontextprotocol/vitest-config": "workspace:^", diff --git a/packages/core/src/auth.ts b/packages/core/src/auth.ts new file mode 100644 index 0000000000..e21076d817 --- /dev/null +++ b/packages/core/src/auth.ts @@ -0,0 +1,285 @@ +import * as z from 'zod/v4'; + +/** + * Reusable URL validation that disallows `javascript:` scheme + */ +export const SafeUrlSchema = z + .url() + .superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'URL must be parseable', + fatal: true + }); + + return z.NEVER; + } + }) + .refine( + url => { + const u = new URL(url); + return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; + }, + { message: 'URL cannot use javascript:, data:, or vbscript: scheme' } + ); + +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export const OAuthProtectedResourceMetadataSchema = z.looseObject({ + resource: z.string().url(), + authorization_servers: z.array(SafeUrlSchema).optional(), + jwks_uri: z.string().url().optional(), + scopes_supported: z.array(z.string()).optional(), + bearer_methods_supported: z.array(z.string()).optional(), + resource_signing_alg_values_supported: z.array(z.string()).optional(), + resource_name: z.string().optional(), + resource_documentation: z.string().optional(), + resource_policy_uri: z.string().url().optional(), + resource_tos_uri: z.string().url().optional(), + tls_client_certificate_bound_access_tokens: z.boolean().optional(), + authorization_details_types_supported: z.array(z.string()).optional(), + dpop_signing_alg_values_supported: z.array(z.string()).optional(), + dpop_bound_access_tokens_required: z.boolean().optional() +}); + +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export const OAuthMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + introspection_endpoint: z.string().optional(), + introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + code_challenge_methods_supported: z.array(z.string()).optional(), + client_id_metadata_document_supported: z.boolean().optional(), + // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain + authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined) +}); + +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * + * @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export const OpenIdProviderMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + acr_values_supported: z.array(z.string()).optional(), + subject_types_supported: z.array(z.string()), + id_token_signing_alg_values_supported: z.array(z.string()), + id_token_encryption_alg_values_supported: z.array(z.string()).optional(), + id_token_encryption_enc_values_supported: z.array(z.string()).optional(), + userinfo_signing_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), + request_object_signing_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_enc_values_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + display_values_supported: z.array(z.string()).optional(), + claim_types_supported: z.array(z.string()).optional(), + claims_supported: z.array(z.string()).optional(), + service_documentation: z.string().optional(), + claims_locales_supported: z.array(z.string()).optional(), + ui_locales_supported: z.array(z.string()).optional(), + claims_parameter_supported: z.boolean().optional(), + request_parameter_supported: z.boolean().optional(), + request_uri_parameter_supported: z.boolean().optional(), + require_request_uri_registration: z.boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: z.boolean().optional(), + // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain + authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined) +}); + +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export const OpenIdProviderDiscoveryMetadataSchema = z.object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); + +/** + * OAuth 2.1 token response + */ +export const OAuthTokensSchema = z + .object({ + access_token: z.string(), + id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: z.string(), + expires_in: z.coerce.number().optional(), + scope: z.string().optional(), + refresh_token: z.string().optional() + }) + .strip(); + +/** + * RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. + * + * `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when + * the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, + * so strict checking rejects conformant IdPs. + */ +export const IdJagTokenExchangeResponseSchema = z + .object({ + issued_token_type: z.literal('urn:ietf:params:oauth:token-type:id-jag'), + access_token: z.string(), + token_type: z.string().optional(), + expires_in: z.number().optional(), + scope: z.string().optional() + }) + .strip(); + +export type IdJagTokenExchangeResponse = z.infer; + +/** + * OAuth 2.1 error response + */ +export const OAuthErrorResponseSchema = z.object({ + error: z.string(), + error_description: z.string().optional(), + error_uri: z.string().optional() +}); + +/** + * Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` + */ +// eslint-disable-next-line unicorn/no-useless-undefined +export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); + +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export const OAuthClientMetadataSchema = z + .object({ + redirect_uris: z.array(SafeUrlSchema), + token_endpoint_auth_method: z.string().optional(), + grant_types: z.array(z.string()).optional(), + response_types: z.array(z.string()).optional(), + /** + * OIDC Dynamic Client Registration `application_type`. MCP clients MUST set + * this to `'native'` or `'web'` when registering (SEP-837); the SDK defaults + * it from `redirect_uris` when omitted. Typed as `string` (not an enum) so + * that parsing an authorization server's registration response — which under + * RFC 7591 may echo extension values — never rejects the document on this + * field alone. + */ + application_type: z.string().optional(), + client_name: z.string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: z.string().optional(), + contacts: z.array(z.string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: z.string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: z.any().optional(), + software_id: z.string().optional(), + software_version: z.string().optional(), + software_statement: z.string().optional() + }) + .strip(); + +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export const OAuthClientInformationSchema = z + .object({ + client_id: z.string(), + client_secret: z.string().optional(), + client_id_issued_at: z.number().optional(), + client_secret_expires_at: z.number().optional() + }) + .strip(); + +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); + +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export const OAuthClientRegistrationErrorSchema = z + .object({ + error: z.string(), + error_description: z.string().optional() + }) + .strip(); + +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export const OAuthTokenRevocationRequestSchema = z + .object({ + token: z.string(), + token_type_hint: z.string().optional() + }) + .strip(); + +export type OAuthMetadata = z.infer; +export type OpenIdProviderMetadata = z.infer; +export type OpenIdProviderDiscoveryMetadata = z.infer; + +export type OAuthTokens = z.infer; +export type OAuthErrorResponse = z.infer; +export type OAuthClientMetadata = z.infer; +export type OAuthClientInformation = z.infer; +export type OAuthClientInformationFull = z.infer; +export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; + +/** + * {@linkcode OAuthTokens} as persisted by an `OAuthClientProvider`. Adds an + * SDK-stamped authorization-server `issuer` identifier so stored tokens are + * bound to the AS that issued them. The `issuer` field is **not** part of the + * RFC 6749 wire response and is intentionally absent from the wire-response + * schema; the client SDK writes it before calling `saveTokens`. + */ +export type StoredOAuthTokens = OAuthTokens & { issuer?: string }; + +/** + * {@linkcode OAuthClientInformationMixed} as persisted by an + * `OAuthClientProvider`. Adds an SDK-stamped authorization-server `issuer` + * identifier so stored client credentials are bound to the AS that issued them. + * The `issuer` field is **not** part of the RFC 7591 wire response and is + * intentionally absent from the wire-response schema; the client SDK writes it + * before calling `saveClientInformation`. + */ +export type StoredOAuthClientInformation = OAuthClientInformationMixed & { issuer?: string }; + +export type OAuthClientRegistrationError = z.infer; +export type OAuthTokenRevocationRequest = z.infer; +export type OAuthProtectedResourceMetadata = z.infer; + +// Unified type for authorization server metadata +export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts new file mode 100644 index 0000000000..61e6ca7f1f --- /dev/null +++ b/packages/core/src/constants.ts @@ -0,0 +1,104 @@ +export const LATEST_PROTOCOL_VERSION = '2025-11-25'; +export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; +export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; + +/** + * `_meta` key associating a message with a 2025-11-25 task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ +export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; + +/* Reserved `_meta` keys for the per-request envelope (protocol revision 2026-07-28) */ + +/** + * `_meta` key carrying the MCP protocol version governing a request. + * + * For the HTTP transport, the value must match the `MCP-Protocol-Version` header. + */ +export const PROTOCOL_VERSION_META_KEY = 'io.modelcontextprotocol/protocolVersion'; + +/** + * `_meta` key identifying the client software making a request. + */ +export const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; + +/** + * `_meta` key carrying the client's capabilities for a request. + * + * Capabilities are declared per request rather than once at initialization; + * servers must not infer capabilities from prior requests. + */ +export const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities'; + +/** + * `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request + * that opened the stream a notification was delivered on. + * + * Stamped by the server on every notification delivered via a + * `subscriptions/listen` stream (including the leading + * `notifications/subscriptions/acknowledged`); on stdio, where all messages + * share one channel, clients use it to correlate notifications with their + * originating subscription. The value is the listen request's JSON-RPC ID + * verbatim. + */ +export const SUBSCRIPTION_ID_META_KEY = 'io.modelcontextprotocol/subscriptionId'; + +/** + * `_meta` key carrying the desired log level for a request. + * + * When absent, the server must not send `notifications/message` notifications + * for the request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. + */ +export const LOG_LEVEL_META_KEY = 'io.modelcontextprotocol/logLevel'; + +/* + * Reserved `_meta` keys for distributed trace context propagation (SEP-414). + * + * These unprefixed keys are reserved by the MCP specification as an explicit + * exception to the `_meta` key prefix rule. The SDK does not interpret them; + * they pass through `_meta` untouched for OpenTelemetry-style propagation. + */ + +/** + * `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). + * + * When present, the value MUST follow the W3C `traceparent` header format, + * e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. + * + * @see https://www.w3.org/TR/trace-context/#traceparent-header + */ +export const TRACEPARENT_META_KEY = 'traceparent'; + +/** + * `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). + * + * When present, the value MUST follow the W3C `tracestate` header format, + * e.g. `vendor1=value1,vendor2=value2`. + * + * @see https://www.w3.org/TR/trace-context/#tracestate-header + */ +export const TRACESTATE_META_KEY = 'tracestate'; + +/** + * `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). + * + * When present, the value MUST follow the W3C Baggage header format, + * e.g. `userId=alice,serverRegion=us-east-1`. + * + * @see https://www.w3.org/TR/baggage/ + */ +export const BAGGAGE_META_KEY = 'baggage'; + +/* JSON-RPC types */ +export const JSONRPC_VERSION = '2.0'; + +/* Standard JSON-RPC error code constants */ +export const PARSE_ERROR = -32_700; +export const INVALID_REQUEST = -32_600; +export const METHOD_NOT_FOUND = -32_601; +export const INVALID_PARAMS = -32_602; +export const INTERNAL_ERROR = -32_603; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2440232047..ef0be20770 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,8 +2,9 @@ // // Canonical public home for the Model Context Protocol specification + OAuth/OpenID Zod schemas. // -// These are the exact schema constants the SDK validates against internally (defined in the -// private @modelcontextprotocol/core-internal package). This package bundles core-internal and re-exports ONLY the +// These are the exact schema constants the SDK validates against internally — the schema source +// modules live in THIS package (src/schemas.ts, src/auth.ts) and the private +// @modelcontextprotocol/core-internal package re-exports them. This root entry re-exports ONLY the // `*Schema` Zod values, so consumers can validate protocol/OAuth payloads directly — e.g. // `CallToolResultSchema.parse(value)` / `.safeParse(value)` — without depending on core-internal's // barrel. @@ -11,13 +12,12 @@ // Scope: Zod schemas ONLY. The corresponding spec TypeScript types, error classes, enums, and // type guards are part of the public API of @modelcontextprotocol/server and /client. // -// Two groups, kept separate to mirror core-internal's own spec-vs-auth split, each bundled from a build-only -// subpath alias of core-internal (tsconfig.json + tsdown.config.ts): -// - SPEC schemas, from @modelcontextprotocol/core-internal/schemas (core-internal/src/types/schemas.ts): every -// `export const *Schema` EXCEPT internal helpers with no public spec type (e.g. -// BaseRequestParamsSchema). Mirrors core-internal's SPEC_SCHEMA_KEYS allowlist. -// - OAUTH/OPENID schemas, from @modelcontextprotocol/core-internal/auth (core-internal/src/shared/auth.ts). -// The coreSchemas test asserts both groups stay in sync with their core-internal source modules. +// Two groups, kept separate to mirror the SDK's own spec-vs-auth split: +// - SPEC schemas, from ./schemas (src/schemas.ts): every `export const *Schema` EXCEPT internal +// helpers with no public spec type (e.g. BaseRequestParamsSchema). Mirrors core-internal's +// SPEC_SCHEMA_KEYS allowlist. +// - OAUTH/OPENID schemas, from ./auth (src/auth.ts). +// The coreSchemas test asserts both groups stay in sync with their source modules. export { AnnotationsSchema, AudioContentSchema, @@ -179,10 +179,10 @@ export { UnsubscribeRequestSchema, UntitledMultiSelectEnumSchemaSchema, UntitledSingleSelectEnumSchemaSchema -} from '@modelcontextprotocol/core-internal/schemas'; +} from './schemas'; // Auth schemas (OAuth / OpenID / IdJag) — kept as a SEPARATE group from the MCP spec schemas above, -// mirroring core-internal's own spec-vs-auth split (these live in core-internal/src/shared/auth.ts, not types/schemas.ts, +// mirroring the SDK's own spec-vs-auth split (these live in src/auth.ts, not src/schemas.ts, // and are registered as `authSchemas` in core-internal's specTypeSchema.ts). This group is EXACTLY core-internal's // `authSchemas` set — every auth schema that has a public spec type (so `isSpecType.OAuthTokens`, // `isSpecType.IdJagTokenExchangeResponse`, etc. exist). The typeless internal URL field-validators @@ -201,4 +201,4 @@ export { OAuthTokensSchema, OpenIdProviderDiscoveryMetadataSchema, OpenIdProviderMetadataSchema -} from '@modelcontextprotocol/core-internal/auth'; +} from './auth'; diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts new file mode 100644 index 0000000000..a47e91728e --- /dev/null +++ b/packages/core/src/internal.ts @@ -0,0 +1,16 @@ +// @modelcontextprotocol/core/internal +// +// Wholesale re-export of core's schema source modules for the SDK's own packages. +// +// The curated root entry (`@modelcontextprotocol/core`) exposes ONLY the public spec + OAuth +// `*Schema` constants. The sibling SDK packages additionally need the handful of names that are +// deliberately NOT public there — internal helper schemas (e.g. BaseRequestParamsSchema, +// SafeUrlSchema), the auth `type` exports, the protocol constants, and the JSON value types — +// because core-internal's modules at the old paths re-export these modules one-to-one. +// +// This subpath is an internal seam, not public API: anything meant for consumers belongs on the +// root entry (which a drift test pins). Names here may change without notice. +export * from './auth'; +export * from './constants'; +export * from './schemas'; +export type { JSONArray, JSONObject, JSONValue } from './types'; diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.ts new file mode 100644 index 0000000000..bc64597b98 --- /dev/null +++ b/packages/core/src/schemas.ts @@ -0,0 +1,2437 @@ +import * as z from 'zod/v4'; + +import { JSONRPC_VERSION, RELATED_TASK_META_KEY, SUBSCRIPTION_ID_META_KEY } from './constants'; +import type { JSONArray, JSONObject, JSONValue } from './types'; + +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); +export const JSONArraySchema: z.ZodType = z.array(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. + */ + [RELATED_TASK_META_KEY]: 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() + // `resultType` is wire-only vocabulary (protocol revision 2026-07-28) and + // is deliberately NOT modeled here: the neutral result schemas carry no + // slot for it. It exists only inside the 2026-era wire codec, which + // consumes it on decode and stamps it on encode. (Q1 increment 2 - the + // former optional member here was the masking surface that let modern + // vocabulary leak through every legacy-leg parse.) +}); + +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export const RequestIdSchema = z.union([z.string(), z.number().int()]); + +/** + * A request that expects a response. + */ +export const JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape + }) + .strict(); + +/** + * A notification which does not expect a response. + */ +export const JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + ...NotificationSchema.shape + }) + .strict(); + +/** + * A successful (non-error) response to a request. + */ +export const JSONRPCResultResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema + }) + .strict(); + +/** + * A response to a request that indicates an error occurred. + */ +export const JSONRPCErrorResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.unknown().optional() + }) + }) + .strict(); + +export const JSONRPCMessageSchema = z.union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); + +export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); + +/* 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() +}); + +/* Discovery */ +/** + * A request from the client asking the server to advertise its supported protocol + * versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers + * MUST implement `server/discover`. Clients MAY call it but are not required to — + * version negotiation can also happen inline via the per-request `_meta` envelope. + */ +export const DiscoverRequestSchema = RequestSchema.extend({ + method: z.literal('server/discover'), + params: BaseRequestParamsSchema.optional() +}); + +/** + * The result returned by the server for a `server/discover` request. + */ +export const DiscoverResultSchema = ResultSchema.extend({ + /** + * MCP protocol versions this server supports. The client should choose a + * version from this list for use in subsequent requests. + */ + supportedVersions: z.array(z.string()), + /** + * The capabilities of the server. + */ + capabilities: ServerCapabilitiesSchema, + /** + * Information about the server software implementation. + */ + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +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 +}); + +/* Subscriptions (protocol revision 2026-07-28) */ +/** + * The set of notification types a client opts in to on a `subscriptions/listen` + * request. Each type is opt-in; the server MUST NOT send a notification type + * the client has not explicitly requested here. + */ +export const SubscriptionFilterSchema = z.object({ + /** + * If true, receive `notifications/tools/list_changed`. + */ + toolsListChanged: z.boolean().optional(), + /** + * If true, receive `notifications/prompts/list_changed`. + */ + promptsListChanged: z.boolean().optional(), + /** + * If true, receive `notifications/resources/list_changed`. + */ + resourcesListChanged: z.boolean().optional(), + /** + * Subscribe to `notifications/resources/updated` for these resource URIs. + * Replaces the former `resources/subscribe` RPC on the 2026-07-28 revision. + */ + resourceSubscriptions: z.array(z.string()).optional() +}); + +export const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The notifications the client opts in to on this stream. The server MUST + * NOT send notification types the client has not explicitly requested. + */ + notifications: SubscriptionFilterSchema +}); + +/** + * Sent from the client to open a long-lived channel for receiving notifications + * outside the context of a specific request (protocol revision 2026-07-28). + * Replaces the previous HTTP GET endpoint and `resources/subscribe`. + */ +export const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: z.literal('subscriptions/listen'), + params: SubscriptionsListenRequestParamsSchema +}); + +export const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The subset of requested notification types the server agreed to honor. + */ + notifications: SubscriptionFilterSchema +}); + +/** + * Sent by the server as the first message on a `subscriptions/listen` stream + * to acknowledge that the subscription has been established and report which + * notification types it agreed to honor (protocol revision 2026-07-28). + */ +export const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/subscriptions/acknowledged'), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); + +/** + * `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's + * JSON-RPC ID under the canonical subscription-id key (mirroring the same key + * on every notification delivered on the stream). + */ +export const SubscriptionsListenResultMetaSchema = z.looseObject({ + [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema +}); + +/** + * The response to a `subscriptions/listen` request, signalling that the + * subscription has ended gracefully (for example, during server shutdown). + * Because the listen stream is long-lived, this result is sent only when the + * server tears the subscription down; an abrupt transport close carries no + * response. The result body is otherwise empty. + */ +export const SubscriptionsListenResultSchema = ResultSchema.extend({ + _meta: SubscriptionsListenResultMetaSchema +}); + +/** + * 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() +}); + +/** + * 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. + */ +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 document describing the structure of the tool's output + * returned in the `structuredContent` field of a `CallToolResult`. + * + * SEP-2106: any JSON Schema root is permitted (e.g. `type:'array'`, `oneOf`, `$ref`). + * The 2025-11-25 wire parse retains the `type:'object'` constraint via the frozen schema in + * `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens. + */ + outputSchema: z.looseObject({ $schema: z.string().optional() }).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). + * + * Parse-tolerant: absent `content` defaults to `[]` (v1 parity — deployed + * servers omit it alongside `structuredContent`). + */ + content: z.array(ContentBlockSchema).default([]), + + /** + * Structured tool output. + * + * If the `Tool` defines an `outputSchema`, this field MUST be present in the result and + * contain a JSON value that matches the schema. + * + * SEP-2106: any JSON value is permitted (arrays, primitives, `null`). Narrow before property + * access. The 2025-11-25 wire parse retains the object-only constraint via the frozen schema + * in `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens. + */ + structuredContent: 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() +}); + +/** + * {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. + */ +export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( + ResultSchema.extend({ + toolResult: z.unknown() + }) +); + +/** + * 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() +}); + +/** + * Base schema for list changed subscription options (without callback). + * Used internally for Zod validation of `autoRefresh` and `debounceMs`. + */ +export const ListChangedOptionsBaseSchema = z.object({ + /** + * If `true`, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If `false`, the callback will be called with `null` items, allowing manual refresh. + * + * @default true + */ + autoRefresh: z.boolean().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to `0` to disable debouncing. + * + * @default 300 + */ + debounceMs: z.number().int().nonnegative().default(300) +}); + +/* 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. + */ +export 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. + */ +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 +}); +/** + * 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. + */ +export 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. + */ +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() +}); +/** + * 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. + */ +export 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. + */ +export 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. + */ +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() +}); + +/** + * 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. + */ +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() +}); + +/** + * 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. + */ +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), + /** + * SEP-2106: any JSON value is permitted. The 2025-11-25 wire parse retains the object-only + * constraint via the frozen schema in `wire/rev2025-11-25/schemas.ts`. + */ + structuredContent: z.unknown().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. + */ +export 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. + */ +export 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. + */ +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() +}); + +/** + * 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. + */ +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() +}); +/** + * 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. + */ +export 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. + */ +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 +}); + +/** + * 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. + */ +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. + * + * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the + * outcome of an out-of-band interaction by retrying the original request; no + * server-initiated completion signal exists in the 2026-07-28 revision. Kept here + * for the 2025-era URL-mode flow only. + */ + 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. + * + * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome + * of an out-of-band interaction by retrying the original request; no server-initiated + * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow + * only. The 2026-07-28 wire codec excludes this notification. + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + * + * @deprecated See {@linkcode ElicitationCompleteNotificationParamsSchema}. + */ + elicitationId: z.string() +}); + +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome + * of an out-of-band interaction by retrying the original request; no server-initiated + * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow + * only. The 2026-07-28 wire codec excludes this notification. + * @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 */ +/** + * 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. + */ +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() +}); + +/** + * 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. + */ +export 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. + */ +export 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. + */ +export const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() +}); + +/* ─────────────────────────────────────────────────────────────────────────── + * Tasks (2025-11-25 wire vocabulary, DEPRECATED) + * + * The task message surface defined by the 2025-11-25 protocol revision. These + * schemas are kept in the neutral layer so the public Task* types stay + * nameable without a cross-layer import into wire/rev*; the wire-parse + * contract for them is the FROZEN copy in wire/rev2025-11-25/schemas.ts. + * + * They appear in NO role aggregate below and no API signature — nameable-only + * vocabulary for interop with task-capable 2025 peers (#2248). Removable at + * the major version that drops 2025-era support. + * ─────────────────────────────────────────────────────────────────────────── */ + +/** + * 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); + +/* Client messages */ +// NOTE (Q1 increment 2): the role unions below are the NEUTRAL message sets. +// The 2025-era task vocabulary (tasks/* methods, task results, the task +// status notification) is 2025-only WIRE vocabulary; the deprecated Task* +// schemas above are nameable-only and appear in NO role aggregate and no API +// signature. The era's full wire role unions live in +// `wire/rev2025-11-25/schemas.ts`. +export const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); + +export const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); + +export const ClientResultSchema = z.union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); + +/* Server messages */ +export const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]); + +export const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); + +export const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts new file mode 100644 index 0000000000..3b1d4fb042 --- /dev/null +++ b/packages/core/src/types.ts @@ -0,0 +1,4 @@ +/* JSON types — the base value vocabulary the spec schemas are typed against. */ +export type JSONValue = string | number | boolean | null | JSONObject | JSONArray; +export type JSONObject = { [key: string]: JSONValue }; +export type JSONArray = JSONValue[]; diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index e150389b59..e6d8dabbf9 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -4,9 +4,7 @@ "exclude": ["node_modules", "dist"], "compilerOptions": { "paths": { - "*": ["./*"], - "@modelcontextprotocol/core-internal/schemas": ["./node_modules/@modelcontextprotocol/core-internal/src/types/schemas.ts"], - "@modelcontextprotocol/core-internal/auth": ["./node_modules/@modelcontextprotocol/core-internal/src/shared/auth.ts"] + "*": ["./*"] } } } diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.ts index b138a07cce..e947feab67 100644 --- a/packages/core/tsdown.config.ts +++ b/packages/core/tsdown.config.ts @@ -1,17 +1,14 @@ import { defineConfig } from 'tsdown'; -// core re-exports ONLY the spec + OAuth Zod schemas from @modelcontextprotocol/core-internal (private, -// unpublished). Two BUILD-ONLY subpath aliases (not real core exports) point at core-internal's two schema -// modules, kept as separate sources: -// @modelcontextprotocol/core-internal/schemas → core-internal/src/types/schemas.ts (MCP spec schemas) -// @modelcontextprotocol/core-internal/auth → core-internal/src/shared/auth.ts (OAuth/OpenID schemas) -// Aliasing to these modules rather than core-internal's barrel keeps the bundled graph to just the schemas + -// the constants they use — never Protocol, transports, stdio, or the ajv/cfWorker validators. Both -// modules import only `zod/v4`, so the graph stays runtime-neutral; `platform: 'neutral'` makes a -// node-only dependency leaking in fail the build here instead of silently shipping. +// core owns the schema source modules (src/schemas.ts, src/auth.ts, src/constants.ts) and builds +// two entries from them: +// - src/index.ts → the curated public surface (spec + OAuth `*Schema` constants only) +// - src/internal.ts → the wholesale internal seam the sibling SDK packages resolve at runtime +// All modules import only `zod/v4`, so the graph stays runtime-neutral; `platform: 'neutral'` +// makes a node-only dependency leaking in fail the build here instead of silently shipping. export default defineConfig({ failOnWarn: 'ci-only', - entry: ['src/index.ts'], + entry: ['src/index.ts', 'src/internal.ts'], format: ['esm', 'cjs'], fixedExtension: true, outDir: 'dist', @@ -20,14 +17,6 @@ export default defineConfig({ target: 'esnext', platform: 'neutral', dts: { - resolver: 'tsc', - compilerOptions: { - baseUrl: '.', - paths: { - '@modelcontextprotocol/core-internal/schemas': ['../core-internal/src/types/schemas.ts'], - '@modelcontextprotocol/core-internal/auth': ['../core-internal/src/shared/auth.ts'] - } - } - }, - noExternal: ['@modelcontextprotocol/core-internal/schemas', '@modelcontextprotocol/core-internal/auth'] + resolver: 'tsc' + } }); diff --git a/packages/middleware/express/tsconfig.json b/packages/middleware/express/tsconfig.json index 11330e7a4a..5cf75f3ba6 100644 --- a/packages/middleware/express/tsconfig.json +++ b/packages/middleware/express/tsconfig.json @@ -10,6 +10,9 @@ "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/index.ts" ], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ] diff --git a/packages/middleware/fastify/tsconfig.json b/packages/middleware/fastify/tsconfig.json index 62f257e788..7e06eb27be 100644 --- a/packages/middleware/fastify/tsconfig.json +++ b/packages/middleware/fastify/tsconfig.json @@ -9,6 +9,9 @@ "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/index.ts" + ], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/internal.ts" ] } } diff --git a/packages/middleware/hono/tsconfig.json b/packages/middleware/hono/tsconfig.json index 11330e7a4a..5cf75f3ba6 100644 --- a/packages/middleware/hono/tsconfig.json +++ b/packages/middleware/hono/tsconfig.json @@ -10,6 +10,9 @@ "@modelcontextprotocol/core-internal": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/index.ts" ], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ] diff --git a/packages/middleware/node/tsconfig.json b/packages/middleware/node/tsconfig.json index 7cd442d0d4..d0f212f4fb 100644 --- a/packages/middleware/node/tsconfig.json +++ b/packages/middleware/node/tsconfig.json @@ -8,6 +8,9 @@ "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/core-internal/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/packages/server-legacy/package.json b/packages/server-legacy/package.json index acc880f6f6..36c5583aca 100644 --- a/packages/server-legacy/package.json +++ b/packages/server-legacy/package.json @@ -83,6 +83,7 @@ "test:watch": "vitest" }, "dependencies": { + "@modelcontextprotocol/core": "workspace:^", "zod": "catalog:runtimeShared", "raw-body": "catalog:runtimeServerOnly", "content-type": "catalog:runtimeShared", diff --git a/packages/server-legacy/tsconfig.json b/packages/server-legacy/tsconfig.json index e70d31d788..e2886239b8 100644 --- a/packages/server-legacy/tsconfig.json +++ b/packages/server-legacy/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": ["./node_modules/@modelcontextprotocol/core/src/internal.ts"], "@modelcontextprotocol/core-internal/public": ["./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts"] } } diff --git a/packages/server-legacy/tsdown.config.ts b/packages/server-legacy/tsdown.config.ts index b4c2881fd1..3e2f0ced3d 100644 --- a/packages/server-legacy/tsdown.config.ts +++ b/packages/server-legacy/tsdown.config.ts @@ -21,5 +21,9 @@ export default defineConfig({ } } }, - noExternal: ['@modelcontextprotocol/core-internal'] + noExternal: ['@modelcontextprotocol/core-internal'], + // The schema modules live in @modelcontextprotocol/core (a real runtime dependency); the + // bundled core-internal shims import them via the './internal' subpath, which must stay an + // external import (explicit entry — the tsconfig paths alias would otherwise inline it). + external: ['@modelcontextprotocol/core/internal'] }); diff --git a/packages/server/package.json b/packages/server/package.json index d4a75c70fc..5a98083d13 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -133,6 +133,7 @@ "test:watch": "vitest" }, "dependencies": { + "@modelcontextprotocol/core": "workspace:^", "zod": "catalog:runtimeShared" }, "devDependencies": { diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.json index 2d8ef8ed15..184ab7a899 100644 --- a/packages/server/tsconfig.json +++ b/packages/server/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": ["./node_modules/@modelcontextprotocol/core/src/internal.ts"], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/packages/server/tsdown.config.ts b/packages/server/tsdown.config.ts index adec842c2f..d15b5de8d4 100644 --- a/packages/server/tsdown.config.ts +++ b/packages/server/tsdown.config.ts @@ -33,5 +33,8 @@ export default defineConfig({ } }, noExternal: ['@modelcontextprotocol/core-internal', 'ajv', 'ajv-formats', '@cfworker/json-schema'], - external: ['@modelcontextprotocol/server/_shims'] + // The schema modules live in @modelcontextprotocol/core (a real runtime dependency); the + // bundled core-internal shims import them via the './internal' subpath, which must stay an + // external import (explicit entry — the tsconfig paths alias would otherwise inline it). + external: ['@modelcontextprotocol/server/_shims', '@modelcontextprotocol/core/internal'] }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 82fdee06b0..be2b3c58c1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1290,6 +1290,9 @@ importers: packages/client: dependencies: + '@modelcontextprotocol/core': + specifier: workspace:^ + version: link:../core cross-spawn: specifier: catalog:runtimeClientOnly version: 7.0.6 @@ -1437,9 +1440,6 @@ importers: '@eslint/js': specifier: catalog:devTools version: 9.39.4 - '@modelcontextprotocol/core-internal': - specifier: workspace:^ - version: link:../core-internal '@modelcontextprotocol/eslint-config': specifier: workspace:^ version: link:../../common/eslint-config @@ -1479,6 +1479,9 @@ importers: packages/core-internal: dependencies: + '@modelcontextprotocol/core': + specifier: workspace:^ + version: link:../core content-type: specifier: catalog:runtimeShared version: 1.0.5 @@ -1778,6 +1781,9 @@ importers: packages/server: dependencies: + '@modelcontextprotocol/core': + specifier: workspace:^ + version: link:../core zod: specifier: catalog:runtimeShared version: 4.3.6 @@ -1845,6 +1851,9 @@ importers: packages/server-legacy: dependencies: + '@modelcontextprotocol/core': + specifier: workspace:^ + version: link:../core content-type: specifier: catalog:runtimeShared version: 1.0.5 diff --git a/test/conformance/tsconfig.json b/test/conformance/tsconfig.json index dffb32355b..b424eb35ec 100644 --- a/test/conformance/tsconfig.json +++ b/test/conformance/tsconfig.json @@ -6,6 +6,9 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/core-internal/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/test/e2e/tsconfig.json b/test/e2e/tsconfig.json index a4eaba6bd6..c4e5ba6f4a 100644 --- a/test/e2e/tsconfig.json +++ b/test/e2e/tsconfig.json @@ -6,6 +6,9 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/core-internal/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/test/helpers/tsconfig.json b/test/helpers/tsconfig.json index 18809d7ac8..781d610820 100644 --- a/test/helpers/tsconfig.json +++ b/test/helpers/tsconfig.json @@ -6,6 +6,9 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/core-internal/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], diff --git a/test/integration/tsconfig.json b/test/integration/tsconfig.json index 4764fcfc84..2b016fd288 100644 --- a/test/integration/tsconfig.json +++ b/test/integration/tsconfig.json @@ -6,6 +6,9 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core-internal": ["./node_modules/@modelcontextprotocol/core-internal/src/index.ts"], + "@modelcontextprotocol/core/internal": [ + "./node_modules/@modelcontextprotocol/core-internal/node_modules/@modelcontextprotocol/core/src/internal.ts" + ], "@modelcontextprotocol/core-internal/public": [ "./node_modules/@modelcontextprotocol/core-internal/src/exports/public/index.ts" ], From 25ba63bc109f55df6f1cae6cf95c0b123892c758 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 15:19:49 +0000 Subject: [PATCH 06/12] Update drift guards and the workers test for the schema modules' new home MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test-only adaptations to the schema-source move; each guard keeps pinning the same invariant, only pointed at the new canonical location: - packageTopologyPins: pin @modelcontextprotocol/core's export map as ['.', './internal'] — the internal seam is deliberate, not public API. - coreSchemas: read the spec-schema source from core's own src/schemas.ts (the auth group still reads core-internal's authSchemas registry). - wireOnlyHiding: read the @deprecated task-schema and constants sources from packages/core/src (the old paths are now re-export shims with no doc comments to scan). - codemod authSchemaNames: core's barrel now ends its auth block with "} from './auth'" instead of the deleted build-only alias specifier. - cloudflareWorkers: generalize packServerPackage to packWorkspacePackage and install the workspace core tarball alongside the server tarball — the packed server resolves @modelcontextprotocol/core/internal at runtime, which the registry copy of core does not carry yet. --- .../test/v1-to-v2/authSchemaNames.test.ts | 4 +-- .../test/packageTopologyPins.test.ts | 5 +++- .../test/types/wireOnlyHiding.test.ts | 5 ++-- packages/core/test/coreSchemas.test.ts | 11 ++++---- .../test/server/cloudflareWorkers.test.ts | 27 +++++++++++-------- 5 files changed, 31 insertions(+), 21 deletions(-) diff --git a/packages/codemod/test/v1-to-v2/authSchemaNames.test.ts b/packages/codemod/test/v1-to-v2/authSchemaNames.test.ts index 2fd4631c2d..97044c3b8c 100644 --- a/packages/codemod/test/v1-to-v2/authSchemaNames.test.ts +++ b/packages/codemod/test/v1-to-v2/authSchemaNames.test.ts @@ -12,9 +12,9 @@ describe('AUTH_SCHEMA_NAMES (codemod auth schema-routing allowlist)', () => { // the rewritten import would have no exported member. AUTH_SCHEMA_NAMES is the v1 auth-schema set, // a SUBSET of core's auth exports: core may export more (v2-only schemas such as // IdJagTokenExchangeResponseSchema) that v1 never had and the codemod never encounters. Read - // core's barrel directly (the `export { … } from '…/core-internal/auth'` block) so they cannot drift. + // core's barrel directly (the `export { … } from './auth'` block) so they cannot drift. const src = readFileSync(fileURLToPath(new URL('../../../core/src/index.ts', import.meta.url)), 'utf8'); - const closeIdx = src.indexOf("} from '@modelcontextprotocol/core-internal/auth'"); + const closeIdx = src.indexOf("} from './auth'"); const openIdx = src.lastIndexOf('export {', closeIdx); const block = src.slice(openIdx + 'export {'.length, closeIdx); const coreAuthExports = new Set([...block.matchAll(/\b(\w+Schema)\b/g)].map(m => m[1])); diff --git a/packages/core-internal/test/packageTopologyPins.test.ts b/packages/core-internal/test/packageTopologyPins.test.ts index e6f16758f1..979ff15070 100644 --- a/packages/core-internal/test/packageTopologyPins.test.ts +++ b/packages/core-internal/test/packageTopologyPins.test.ts @@ -53,7 +53,10 @@ const PUBLIC_PACKAGES: Record { // codec split (Q1 increment 2); the param-side carriers stay in the // neutral file. Both homes are scanned — the combined surface is the // same ≥19 schemas the docs claim covers. - const neutral = readFileSync(join(__dirname, '..', '..', 'src', 'types', 'schemas.ts'), 'utf8'); + // The neutral schema source moved to @modelcontextprotocol/core (the old path is a re-export shim). + const neutral = readFileSync(join(__dirname, '..', '..', '..', 'core', 'src', 'schemas.ts'), 'utf8'); const wire2025 = readFileSync(join(__dirname, '..', '..', 'src', 'wire', 'rev2025-11-25', 'schemas.ts'), 'utf8'); let total = 0; for (const schemas of [neutral, wire2025]) { @@ -159,7 +160,7 @@ describe('task vocabulary is importable but in no API signature', () => { ); } - const constants = readFileSync(join(__dirname, '..', '..', 'src', 'types', 'constants.ts'), 'utf8'); + const constants = readFileSync(join(__dirname, '..', '..', '..', 'core', 'src', 'constants.ts'), 'utf8'); const keyDecl = constants.indexOf('export const RELATED_TASK_META_KEY'); expect(constants.slice(Math.max(0, keyDecl - 300), keyDecl)).toContain('@deprecated'); }); diff --git a/packages/core/test/coreSchemas.test.ts b/packages/core/test/coreSchemas.test.ts index 85a0e08a09..3efcfdbd79 100644 --- a/packages/core/test/coreSchemas.test.ts +++ b/packages/core/test/coreSchemas.test.ts @@ -33,7 +33,9 @@ describe('@modelcontextprotocol/core', () => { // name prefix) is the source of truth, so a new auth schema added to core-internal is required here // automatically; typeless internal helpers (SafeUrlSchema, OptionalSafeUrlSchema) stay out // because they are not in `authSchemas`. - // Read the core-internal sources directly so the groups cannot silently drift. + // Read the schema source modules directly so the groups cannot silently drift: the spec + // group against core's own src/schemas.ts (the canonical home since the move), the auth + // group against core-internal's `authSchemas` registry (specTypeSchema.ts stays there). const SPEC_INTERNAL_HELPERS = [ 'BaseRequestParamsSchema', 'ClientTasksCapabilitySchema', @@ -41,10 +43,9 @@ describe('@modelcontextprotocol/core', () => { 'NotificationsParamsSchema', 'ServerTasksCapabilitySchema' ]; - const specSchemas = exportedSchemaConsts( - readCore('../../core-internal/src/types/schemas.ts'), - /^export const (\w+Schema)\b/gm - ).filter(name => !SPEC_INTERNAL_HELPERS.includes(name)); + const specSchemas = exportedSchemaConsts(readCore('../src/schemas.ts'), /^export const (\w+Schema)\b/gm).filter( + name => !SPEC_INTERNAL_HELPERS.includes(name) + ); const specTypeSrc = readCore('../../core-internal/src/types/specTypeSchema.ts'); const authStart = specTypeSrc.indexOf('const authSchemas = {'); const authObj = specTypeSrc.slice(authStart, specTypeSrc.indexOf('} as const', authStart)); diff --git a/test/integration/test/server/cloudflareWorkers.test.ts b/test/integration/test/server/cloudflareWorkers.test.ts index 44af77575a..02add64201 100644 --- a/test/integration/test/server/cloudflareWorkers.test.ts +++ b/test/integration/test/server/cloudflareWorkers.test.ts @@ -41,9 +41,9 @@ const WRANGLER_BIN = (() => { })(); /** - * Create an installable tarball of `@modelcontextprotocol/server` without mutating the workspace. + * Create an installable tarball of a workspace package without mutating the workspace. * - * Running `pnpm pack` inside `packages/server` is not an option here: its `prepack` hook rebuilds + * Running `pnpm pack` inside the package is not an option here: its `prepack` hook rebuilds * the package in place (tsdown with `clean: true`), deleting and rewriting `packages/server/dist` * while the rest of the test run is still going. Anything that node-resolves the workspace * packages at that moment — most notably suites that spawn child processes importing @@ -53,15 +53,15 @@ const WRANGLER_BIN = (() => { * * Returns the tarball's file name; the tarball itself is written into `tempDir`. */ -function packServerPackage(tempDir: string): string { - const serverPkgPath = path.resolve(__dirname, '../../../../packages/server'); - const stagingDir = path.join(tempDir, 'package-staging'); +function packWorkspacePackage(tempDir: string, packageDirName: string): string { + const pkgPath = path.resolve(__dirname, `../../../../packages/${packageDirName}`); + const stagingDir = path.join(tempDir, `package-staging-${packageDirName}`); fs.mkdirSync(stagingDir, { recursive: true }); // Build the publishable bundle with its output redirected away from the workspace's - // packages/server/dist (the CLI flag overrides `outDir` from tsdown.config.ts). + // own dist/ (the CLI flag overrides `outDir` from tsdown.config.ts). execSync(`pnpm exec tsdown --out-dir "${path.join(stagingDir, 'dist')}"`, { - cwd: serverPkgPath, + cwd: pkgPath, stdio: 'pipe', timeout: 60_000 }); @@ -69,7 +69,7 @@ function packServerPackage(tempDir: string): string { // Write a publish-shaped manifest into the staging dir: drop lifecycle scripts and // devDependencies, and resolve pnpm-only `catalog:`/`workspace:` specifiers to the versions // installed in the workspace — the same substitution `pnpm pack` performs when publishing. - const manifest = JSON.parse(fs.readFileSync(path.join(serverPkgPath, 'package.json'), 'utf8')) as { + const manifest = JSON.parse(fs.readFileSync(path.join(pkgPath, 'package.json'), 'utf8')) as { scripts?: unknown; devDependencies?: unknown; dependencies?: Record; @@ -79,7 +79,7 @@ function packServerPackage(tempDir: string): string { const dependencies = manifest.dependencies ?? {}; for (const [name, spec] of Object.entries(dependencies)) { if (spec.startsWith('catalog:') || spec.startsWith('workspace:')) { - const installed = JSON.parse(fs.readFileSync(path.join(serverPkgPath, 'node_modules', name, 'package.json'), 'utf8')) as { + const installed = JSON.parse(fs.readFileSync(path.join(pkgPath, 'node_modules', name, 'package.json'), 'utf8')) as { version: string; }; dependencies[name] = installed.version; @@ -270,8 +270,12 @@ describe('Cloudflare Workers compatibility (no nodejs_compat)', () => { try { // Pack the server package into the temp dir without touching the workspace's own - // dist/ — see packServerPackage for why the plain `pnpm pack` route is unsafe here. - const tarballName = packServerPackage(tempDir); + // dist/ — see packWorkspacePackage for why the plain `pnpm pack` route is unsafe here. + // Also pack @modelcontextprotocol/core from the workspace: the packed server resolves + // `@modelcontextprotocol/core/internal` at runtime, and the registry copy of core may + // not carry that subpath yet — the test must exercise the workspace pair together. + const tarballName = packWorkspacePackage(tempDir, 'server'); + const coreTarballName = packWorkspacePackage(tempDir, 'core'); // Write package.json const pkgJson = { @@ -279,6 +283,7 @@ describe('Cloudflare Workers compatibility (no nodejs_compat)', () => { private: true, type: 'module', dependencies: { + '@modelcontextprotocol/core': `file:./${coreTarballName}`, '@modelcontextprotocol/server': `file:./${tarballName}` } }; From f906078b30e1df3f1e01b019d5badcaecfd68f9a Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 17:16:07 +0000 Subject: [PATCH 07/12] Guard the schema-module boundary against skew, drift, and re-inlining MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The schema sources moved into @modelcontextprotocol/core with the sibling packages resolving @modelcontextprotocol/core/internal at runtime. That seam can rot in ways no existing test catches; this locks it down: - Exact sibling pins: client/server/server-legacy (and core-internal, for consistency) depend on core via workspace:* so pnpm publishes an exact version pin instead of a caret range. The ./internal surface is only guaranteed for the core version each sibling was built against, so a caret range would let installs mix skewed versions. - Changesets fixed group for core + client + server + server-legacy, keeping the pinned versions releasable in lockstep. - ./internal is labeled as an SDK-internal contract in its header, with @internal JSDoc on the re-exports (source-level only: the dts bundler flattens the re-exports and drops statement-level comments, so the built declarations do not carry the tag). - A client boundary test parses the built dists in both directions: every name the client bundle imports or re-exports from core must resolve against core's built entry export lists (skew), and sentinel schemas that exist only in core's modules must never appear as definitions in the client bundle (re-inlining via lost external config or eager aliases). - A core-internal shim-purity test pins the old schema/auth/constants module paths as pure re-export forwards: no zod import, no local definitions, imports only from @modelcontextprotocol/core/internal — so new schemas can't accrete at the old paths and silently miss core's published entries. The shim headers now state that rule, and the type-only JSON value re-export in types.ts is pinned as erasable. No-Verification-Needed: tests, manifest pins, release config, and comments only — no runtime surface change --- .changeset/config.json | 9 +- packages/client/package.json | 2 +- .../client/test/client/coreBoundary.test.ts | 166 ++++++++++++++++++ packages/core-internal/package.json | 2 +- packages/core-internal/src/shared/auth.ts | 3 + packages/core-internal/src/types/constants.ts | 3 + packages/core-internal/src/types/schemas.ts | 3 + .../core-internal/test/schemaShims.test.ts | 59 +++++++ packages/core/src/internal.ts | 26 ++- packages/server-legacy/package.json | 2 +- packages/server/package.json | 2 +- pnpm-lock.yaml | 8 +- 12 files changed, 268 insertions(+), 17 deletions(-) create mode 100644 packages/client/test/client/coreBoundary.test.ts create mode 100644 packages/core-internal/test/schemaShims.test.ts diff --git a/.changeset/config.json b/.changeset/config.json index 0154d8a2b8..3edc6b4c29 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -2,7 +2,14 @@ "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json", "changelog": ["@changesets/changelog-github", { "repo": "modelcontextprotocol/typescript-sdk" }], "commit": false, - "fixed": [], + "fixed": [ + [ + "@modelcontextprotocol/core", + "@modelcontextprotocol/client", + "@modelcontextprotocol/server", + "@modelcontextprotocol/server-legacy" + ] + ], "linked": [], "access": "public", "baseBranch": "main", diff --git a/packages/client/package.json b/packages/client/package.json index 8cfd5d4226..baab123c72 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -133,7 +133,7 @@ "test:watch": "vitest" }, "dependencies": { - "@modelcontextprotocol/core": "workspace:^", + "@modelcontextprotocol/core": "workspace:*", "cross-spawn": "catalog:runtimeClientOnly", "eventsource": "catalog:runtimeClientOnly", "eventsource-parser": "catalog:runtimeClientOnly", diff --git a/packages/client/test/client/coreBoundary.test.ts b/packages/client/test/client/coreBoundary.test.ts new file mode 100644 index 0000000000..856cd11add --- /dev/null +++ b/packages/client/test/client/coreBoundary.test.ts @@ -0,0 +1,166 @@ +/** + * Schema-module boundary pins: the built client resolves its schemas from + * @modelcontextprotocol/core instead of carrying its own copies. + * + * The client bundle keeps `@modelcontextprotocol/core/internal` as an external + * runtime import (see tsdown.config.ts), so two things can silently go wrong: + * + * 1. Skew — the client dist imports a name that core's built entries no longer + * export (e.g. a schema added to core-internal's shims without adding it to + * core, or a rename that only landed on one side). That fails at consumer + * runtime, not at build time. + * 2. Re-inlining — a config change (dropping the `external` entry, a paths + * alias resolving too early) makes the bundler inline the schema sources + * again, duplicating hundreds of Zod schemas into every sibling package. + * + * Both directions are asserted against the real build outputs. Only the ESM + * chunks are parsed; the CJS build is produced from the same module graph, so + * skew shows up identically in both. + */ +import { execFileSync } from 'node:child_process'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { beforeAll, describe, expect, test } from 'vitest'; + +const clientPkgDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); +const clientDistDir = join(clientPkgDir, 'dist'); +const corePkgDir = join(clientPkgDir, '..', 'core'); +const coreDistDir = join(corePkgDir, 'dist'); + +/** Built core entry file per import specifier the client may use. */ +const CORE_ENTRIES: Record = { + '@modelcontextprotocol/core': 'index.mjs', + '@modelcontextprotocol/core/internal': 'internal.mjs' +}; + +/** + * Sentinel schemas that exist ONLY in core's source modules. The frozen + * wire-era modules (bundled into the client on purpose) define their own + * copies of many spec schema names, but not these — so a `const` definition + * of any of them inside the client dist can only mean the neutral schema + * modules got re-inlined. The first two are names the client actually uses, + * so they must also show up as imports; SafeUrlSchema is unused by the client + * (legitimately tree-shaken away) and is pinned as never-defined only. + */ +const IMPORTED_SENTINELS = ['OAuthMetadataSchema', 'JSONRPCMessageSchema']; +const NEVER_DEFINED_SENTINELS = [...IMPORTED_SENTINELS, 'SafeUrlSchema']; + +function buildIfMissing(pkgDir: string, sentinelFile: string): void { + if (!existsSync(join(pkgDir, 'dist', sentinelFile))) { + execFileSync('pnpm', ['build'], { cwd: pkgDir, stdio: 'inherit' }); + } +} + +function clientChunks(): string[] { + return readdirSync(clientDistDir).filter(f => f.endsWith('.mjs')); +} + +/** Exported names of a built core entry (its trailing `export { a, b as c };` blocks). */ +function coreExportedNames(entryFile: string): Set { + const src = readFileSync(join(coreDistDir, entryFile), 'utf8'); + const blocks = [...src.matchAll(/export \{([\s\S]*?)\}/g)]; + expect(blocks.length, `no export block found in core dist/${entryFile}`).toBeGreaterThan(0); + const names = new Set(); + for (const block of blocks) { + for (const entry of block[1]!.split(',')) { + const name = entry + .trim() + .split(/\s+as\s+/) + .pop() + ?.trim(); + if (name) { + names.add(name); + } + } + } + return names; +} + +/** All names a client chunk pulls from a core specifier, keyed by specifier. */ +function coreImportsOf(chunkSource: string): Map> { + const imports = new Map>(); + // import { A, B as C } from "@modelcontextprotocol/core[/internal]" + // export { A, B as C } from "@modelcontextprotocol/core[/internal]" + for (const m of chunkSource.matchAll( + /(?:import|export)\s*\{([^}]*)\}\s*from\s*["'](@modelcontextprotocol\/core(?:\/internal)?)["']/g + )) { + const names = imports.get(m[2]!) ?? new Set(); + for (const entry of m[1]!.split(',')) { + // In both clause forms the name resolved against core is the one BEFORE `as`. + const name = entry + .trim() + .split(/\s+as\s+/)[0] + ?.trim(); + if (name) { + names.add(name); + } + } + imports.set(m[2]!, names); + } + return imports; +} + +describe('@modelcontextprotocol/client ↔ core schema boundary', () => { + beforeAll(() => { + buildIfMissing(corePkgDir, 'internal.mjs'); + buildIfMissing(clientPkgDir, 'index.mjs'); + }, 240_000); + + test('every name the client dist imports from core resolves against core’s built exports', () => { + let sawCoreImport = false; + for (const chunk of clientChunks()) { + const source = readFileSync(join(clientDistDir, chunk), 'utf8'); + for (const [specifier, names] of coreImportsOf(source)) { + sawCoreImport = true; + const entryFile = CORE_ENTRIES[specifier]; + expect(entryFile, `client dist/${chunk} imports unknown core subpath ${specifier}`).toBeDefined(); + const exported = coreExportedNames(entryFile!); + const missing = [...names].filter(name => !exported.has(name)); + expect( + missing, + `client dist/${chunk} imports names from ${specifier} that core's built ${entryFile} does not export` + ).toEqual([]); + } + // Non-named forms (namespace/default/bare imports, `export *`) would dodge the check above. + expect( + source, + `client dist/${chunk} uses a non-named import/re-export of @modelcontextprotocol/core — update this test to cover it` + ).not.toMatch(/(?:import|export)\s+(?!\{)[^;]*?from\s*["']@modelcontextprotocol\/core(?:\/internal)?["']/); + } + expect(sawCoreImport, 'no client chunk imports @modelcontextprotocol/core at all — external wiring changed?').toBe(true); + }); + + test('the neutral schema bodies stay OUT of the client dist (imported, never re-inlined)', () => { + const sources = clientChunks().map(chunk => ({ + chunk, + source: readFileSync(join(clientDistDir, chunk), 'utf8') + })); + + const importedNames = new Set(); + for (const { source } of sources) { + for (const names of coreImportsOf(source).values()) { + for (const name of names) { + importedNames.add(name); + } + } + } + + for (const sentinel of IMPORTED_SENTINELS) { + expect(importedNames.has(sentinel), `${sentinel} is not imported from core by any client chunk`).toBe(true); + } + + for (const sentinel of NEVER_DEFINED_SENTINELS) { + // `$N` suffix included: a re-inlined copy colliding with the import gets renamed by the + // bundler. The `[=(]` tail covers both plain bindings and function-form definitions. + const definition = new RegExp(`\\b(?:const|let|var|function)\\s+${sentinel}(?:\\$\\d+)?\\s*[=(]`); + for (const { chunk, source } of sources) { + expect( + source, + `client dist/${chunk} DEFINES ${sentinel} instead of importing it from @modelcontextprotocol/core — the neutral schema modules were re-inlined` + ).not.toMatch(definition); + } + } + }); +}); diff --git a/packages/core-internal/package.json b/packages/core-internal/package.json index 2a26acf4bf..6a83a51f2d 100644 --- a/packages/core-internal/package.json +++ b/packages/core-internal/package.json @@ -51,7 +51,7 @@ "test:watch": "vitest" }, "dependencies": { - "@modelcontextprotocol/core": "workspace:^", + "@modelcontextprotocol/core": "workspace:*", "content-type": "catalog:runtimeShared", "json-schema-typed": "catalog:runtimeShared", "zod": "catalog:runtimeShared" diff --git a/packages/core-internal/src/shared/auth.ts b/packages/core-internal/src/shared/auth.ts index d746ba0cd0..62995b8f65 100644 --- a/packages/core-internal/src/shared/auth.ts +++ b/packages/core-internal/src/shared/auth.ts @@ -1,5 +1,8 @@ // Moved: the OAuth/OpenID schemas + types now live in @modelcontextprotocol/core (packages/core/src/auth.ts). // This module re-exports them one-to-one so every existing import path keeps working. +// +// Add new schemas in packages/core/src/auth.ts, never here — this file only forwards, and +// core-internal's schemaShims test enforces that it stays free of zod imports and definitions. export type { AuthorizationServerMetadata, IdJagTokenExchangeResponse, diff --git a/packages/core-internal/src/types/constants.ts b/packages/core-internal/src/types/constants.ts index b4f3f35fdc..28df24d505 100644 --- a/packages/core-internal/src/types/constants.ts +++ b/packages/core-internal/src/types/constants.ts @@ -1,5 +1,8 @@ // Moved: the protocol constants now live in @modelcontextprotocol/core (packages/core/src/constants.ts). // This module re-exports them one-to-one so every existing import path keeps working. +// +// Add new constants in packages/core/src/constants.ts, never here — this file only forwards, and +// core-internal's schemaShims test enforces that it stays free of zod imports and definitions. export { BAGGAGE_META_KEY, CLIENT_CAPABILITIES_META_KEY, diff --git a/packages/core-internal/src/types/schemas.ts b/packages/core-internal/src/types/schemas.ts index c67bcb2a52..5e1c1e14b6 100644 --- a/packages/core-internal/src/types/schemas.ts +++ b/packages/core-internal/src/types/schemas.ts @@ -2,6 +2,9 @@ // This module re-exports them one-to-one so every existing import path keeps working; a name // added to core/src/schemas.ts must be added here too (specTypeSchema.ts imports through this // module, so a missing name fails typecheck loudly). +// +// Add new schemas in packages/core/src/schemas.ts, never here — this file only forwards, and +// core-internal's schemaShims test enforces that it stays free of zod imports and definitions. export { AnnotationsSchema, AudioContentSchema, diff --git a/packages/core-internal/test/schemaShims.test.ts b/packages/core-internal/test/schemaShims.test.ts new file mode 100644 index 0000000000..5e89bb5e7f --- /dev/null +++ b/packages/core-internal/test/schemaShims.test.ts @@ -0,0 +1,59 @@ +/** + * Shim purity pins: the schema-module re-export shims stay forwarding-only. + * + * The neutral schema sources live in @modelcontextprotocol/core + * (packages/core/src/{schemas,auth,constants}.ts); core-internal keeps the old + * module paths only as one-to-one re-export shims. If someone adds a new Zod + * schema to a shim instead of to core, the name exists at the old path but + * never reaches core's published entries — the exact drift the move was meant + * to end. This pins the shims to pure forwarding: no zod import, no schema or + * constant definitions, imports only from @modelcontextprotocol/core/internal. + */ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { describe, expect, test } from 'vitest'; + +const srcDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'src'); + +const SHIMS = ['types/schemas.ts', 'shared/auth.ts', 'types/constants.ts']; + +const NEW_HOME = 'new schemas/constants belong in packages/core/src (schemas.ts, auth.ts, constants.ts), not in the re-export shims'; + +/** Drop comments so header prose (which may mention `const`, zod, etc.) can't trip the code checks. */ +function stripComments(source: string): string { + return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, ''); +} + +describe('core-internal schema shims only forward to @modelcontextprotocol/core', () => { + for (const shim of SHIMS) { + describe(shim, () => { + const source = stripComments(readFileSync(join(srcDir, shim), 'utf8')); + + test('does not import zod', () => { + expect(source, `${shim} imports zod — ${NEW_HOME}`).not.toMatch(/from\s+['"]zod/); + }); + + test('defines no schemas or constants', () => { + expect(source, `${shim} builds a Zod schema — ${NEW_HOME}`).not.toMatch(/\bz\s*\.\s*[a-zA-Z]/); + expect(source, `${shim} declares a local binding — ${NEW_HOME}`).not.toMatch( + /\b(?:const|let|var|function|class|enum|interface)\s/ + ); + }); + + test('imports only from @modelcontextprotocol/core/internal', () => { + for (const m of source.matchAll(/from\s+['"]([^'"]+)['"]/g)) { + expect(m[1], `${shim} forwards from an unexpected module — ${NEW_HOME}`).toBe('@modelcontextprotocol/core/internal'); + } + }); + }); + } + + test('types.ts re-exports the JSON value types from core as type-only', () => { + const source = readFileSync(join(srcDir, 'types/types.ts'), 'utf8'); + expect(source).toMatch(/export type \{ JSONArray, JSONObject, JSONValue \} from '@modelcontextprotocol\/core\/internal';/); + // A value re-export would make types.ts depend on core's runtime; keep it erasable. + expect(source).not.toMatch(/export \{[^}]*JSON(?:Array|Object|Value)\b[^}]*\} from/); + }); +}); diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts index a47e91728e..8c06b9afab 100644 --- a/packages/core/src/internal.ts +++ b/packages/core/src/internal.ts @@ -1,16 +1,26 @@ // @modelcontextprotocol/core/internal // -// Wholesale re-export of core's schema source modules for the SDK's own packages. +// ⚠️ SDK-INTERNAL CONTRACT — NOT PUBLIC API. // -// The curated root entry (`@modelcontextprotocol/core`) exposes ONLY the public spec + OAuth -// `*Schema` constants. The sibling SDK packages additionally need the handful of names that are -// deliberately NOT public there — internal helper schemas (e.g. BaseRequestParamsSchema, -// SafeUrlSchema), the auth `type` exports, the protocol constants, and the JSON value types — -// because core-internal's modules at the old paths re-export these modules one-to-one. +// This subpath is a private seam between the @modelcontextprotocol packages: core-internal's +// re-export shims resolve their old module paths through it, and the client/server/server-legacy +// bundles import it as a real external dependency instead of carrying their own schema copies. +// Its surface is whatever the sibling packages need in lockstep with this exact core version — +// it may change in ANY release, including patches, with no deprecation cycle. // -// This subpath is an internal seam, not public API: anything meant for consumers belongs on the -// root entry (which a drift test pins). Names here may change without notice. +// Do not import from this subpath in application code. Everything meant for consumers is on the +// package's public root entry (`@modelcontextprotocol/core`), which a drift test pins. +// +// Why the split: the curated root entry exposes ONLY the public spec + OAuth `*Schema` constants. +// The sibling SDK packages additionally need the handful of names that are deliberately NOT +// public there — internal helper schemas (e.g. BaseRequestParamsSchema, SafeUrlSchema), the auth +// `type` exports, the protocol constants, and the JSON value types. + +/** @internal */ export * from './auth'; +/** @internal */ export * from './constants'; +/** @internal */ export * from './schemas'; +/** @internal */ export type { JSONArray, JSONObject, JSONValue } from './types'; diff --git a/packages/server-legacy/package.json b/packages/server-legacy/package.json index 36c5583aca..5dd08dea85 100644 --- a/packages/server-legacy/package.json +++ b/packages/server-legacy/package.json @@ -83,7 +83,7 @@ "test:watch": "vitest" }, "dependencies": { - "@modelcontextprotocol/core": "workspace:^", + "@modelcontextprotocol/core": "workspace:*", "zod": "catalog:runtimeShared", "raw-body": "catalog:runtimeServerOnly", "content-type": "catalog:runtimeShared", diff --git a/packages/server/package.json b/packages/server/package.json index 5a98083d13..173eaf7f2b 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -133,7 +133,7 @@ "test:watch": "vitest" }, "dependencies": { - "@modelcontextprotocol/core": "workspace:^", + "@modelcontextprotocol/core": "workspace:*", "zod": "catalog:runtimeShared" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be2b3c58c1..7f5941b410 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1291,7 +1291,7 @@ importers: packages/client: dependencies: '@modelcontextprotocol/core': - specifier: workspace:^ + specifier: workspace:* version: link:../core cross-spawn: specifier: catalog:runtimeClientOnly @@ -1480,7 +1480,7 @@ importers: packages/core-internal: dependencies: '@modelcontextprotocol/core': - specifier: workspace:^ + specifier: workspace:* version: link:../core content-type: specifier: catalog:runtimeShared @@ -1782,7 +1782,7 @@ importers: packages/server: dependencies: '@modelcontextprotocol/core': - specifier: workspace:^ + specifier: workspace:* version: link:../core zod: specifier: catalog:runtimeShared @@ -1852,7 +1852,7 @@ importers: packages/server-legacy: dependencies: '@modelcontextprotocol/core': - specifier: workspace:^ + specifier: workspace:* version: link:../core content-type: specifier: catalog:runtimeShared From e55dc27f520c32cf7d3f19c21870f0f891b7dfb5 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 17:17:26 +0000 Subject: [PATCH 08/12] Add changeset for the schema source move No-Verification-Needed: release-metadata-only change --- .changeset/schemas-source-home.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .changeset/schemas-source-home.md diff --git a/.changeset/schemas-source-home.md b/.changeset/schemas-source-home.md new file mode 100644 index 0000000000..d08753f8ec --- /dev/null +++ b/.changeset/schemas-source-home.md @@ -0,0 +1,8 @@ +--- +'@modelcontextprotocol/core': minor +'@modelcontextprotocol/client': minor +'@modelcontextprotocol/server': minor +'@modelcontextprotocol/server-legacy': minor +--- + +Move the schema source modules (spec schemas, OAuth schemas, protocol constants) into `@modelcontextprotocol/core` and resolve them from there as a regular runtime dependency instead of bundling a private copy into each package. An application importing more than one of the packages now evaluates a single shared schema graph with shared object identity. `@modelcontextprotocol/core` gains a `./internal` subpath (SDK-internal contract; may change in any release) and the four packages now version together. From edb1ab0353532df32f0e6528158f6cad7495ffd8 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 17:31:29 +0000 Subject: [PATCH 09/12] Serialize on-demand dist builds across parallel test workers barrelClean and coreBoundary each rebuilt a missing dist from their own beforeAll; vitest runs test files in separate workers, so a cold checkout raced two pnpm builds in the same package and the clean step deleted files under the other worker's reader. Route both through a shared single-flight helper: an atomic mkdir lock with one canonical sentinel set per package, a stale-lock steal for holders that died without cleanup, an async build bounded by a timeout so the worker's event loop and vitest's hook timer stay live, and only EEXIST treated as contention. No-Verification-Needed: test-only change, no runtime surface --- .../client/test/client/barrelClean.test.ts | 13 ++- .../client/test/client/coreBoundary.test.ts | 19 ++-- packages/client/test/helpers/ensureBuilt.ts | 93 +++++++++++++++++++ 3 files changed, 106 insertions(+), 19 deletions(-) create mode 100644 packages/client/test/helpers/ensureBuilt.ts diff --git a/packages/client/test/client/barrelClean.test.ts b/packages/client/test/client/barrelClean.test.ts index a218c49a0c..cd44eb31f8 100644 --- a/packages/client/test/client/barrelClean.test.ts +++ b/packages/client/test/client/barrelClean.test.ts @@ -1,11 +1,12 @@ -import { execFileSync } from 'node:child_process'; -import { existsSync, readFileSync } from 'node:fs'; +import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { beforeAll, describe, expect, test } from 'vitest'; +import { ensureBuilt } from '../helpers/ensureBuilt'; + const pkgDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); const distDir = join(pkgDir, 'dist'); const requireDist = createRequire(join(pkgDir, 'package.json')); @@ -37,11 +38,9 @@ function rootExportBlockOf(content: string): string { } describe('@modelcontextprotocol/client root entry is browser-safe', () => { - beforeAll(() => { - if (!existsSync(join(distDir, 'index.mjs')) || !existsSync(join(distDir, 'stdio.mjs'))) { - execFileSync('pnpm', ['build'], { cwd: pkgDir, stdio: 'inherit' }); - } - }, 60_000); + beforeAll(async () => { + await ensureBuilt(pkgDir); + }, 480_000); test('dist/index.mjs contains no process-spawning runtime imports', () => { const entry = join(distDir, 'index.mjs'); diff --git a/packages/client/test/client/coreBoundary.test.ts b/packages/client/test/client/coreBoundary.test.ts index 856cd11add..caca61ac47 100644 --- a/packages/client/test/client/coreBoundary.test.ts +++ b/packages/client/test/client/coreBoundary.test.ts @@ -17,13 +17,14 @@ * chunks are parsed; the CJS build is produced from the same module graph, so * skew shows up identically in both. */ -import { execFileSync } from 'node:child_process'; -import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { readdirSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { beforeAll, describe, expect, test } from 'vitest'; +import { ensureBuilt } from '../helpers/ensureBuilt'; + const clientPkgDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); const clientDistDir = join(clientPkgDir, 'dist'); const corePkgDir = join(clientPkgDir, '..', 'core'); @@ -47,12 +48,6 @@ const CORE_ENTRIES: Record = { const IMPORTED_SENTINELS = ['OAuthMetadataSchema', 'JSONRPCMessageSchema']; const NEVER_DEFINED_SENTINELS = [...IMPORTED_SENTINELS, 'SafeUrlSchema']; -function buildIfMissing(pkgDir: string, sentinelFile: string): void { - if (!existsSync(join(pkgDir, 'dist', sentinelFile))) { - execFileSync('pnpm', ['build'], { cwd: pkgDir, stdio: 'inherit' }); - } -} - function clientChunks(): string[] { return readdirSync(clientDistDir).filter(f => f.endsWith('.mjs')); } @@ -103,10 +98,10 @@ function coreImportsOf(chunkSource: string): Map> { } describe('@modelcontextprotocol/client ↔ core schema boundary', () => { - beforeAll(() => { - buildIfMissing(corePkgDir, 'internal.mjs'); - buildIfMissing(clientPkgDir, 'index.mjs'); - }, 240_000); + beforeAll(async () => { + await ensureBuilt(corePkgDir); + await ensureBuilt(clientPkgDir); + }, 480_000); test('every name the client dist imports from core resolves against core’s built exports', () => { let sawCoreImport = false; diff --git a/packages/client/test/helpers/ensureBuilt.ts b/packages/client/test/helpers/ensureBuilt.ts new file mode 100644 index 0000000000..6f6115e89b --- /dev/null +++ b/packages/client/test/helpers/ensureBuilt.ts @@ -0,0 +1,93 @@ +import { execFile } from 'node:child_process'; +import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +/** + * Canonical dist sentinels per package. Every caller waits on the same + * complete set: if callers checked their own subsets, a partial dist (from an + * interrupted build) could satisfy one caller's fast path while another still + * rebuilds — and the rebuild's clean step would wipe files under the first + * caller's running tests, which is exactly the race this helper exists to + * prevent. + */ +const DIST_SENTINELS: Record = { + client: ['index.mjs', 'stdio.mjs'], + core: ['index.mjs', 'internal.mjs'] +}; + +/** The build is killed after this long; execFile's kill still runs our finally. */ +const BUILD_TIMEOUT_MS = 180_000; +/** How long a waiter polls for another worker's build — outlasts BUILD_TIMEOUT_MS. */ +const WAIT_DEADLINE_MS = 210_000; +/** A lock older than this belongs to a dead worker (finally never ran) — steal it. */ +const STALE_LOCK_MS = 240_000; + +/** + * Build a package's dist on demand, safely across parallel vitest workers. + * + * Vitest runs test files in separate worker processes, so two files that each + * "build if dist is missing" can race on a cold checkout: both see no dist, + * both spawn `pnpm build`, and tsdown's clean step deletes files out from + * under whichever worker is already reading them. This helper makes the build + * single-flight with an atomic mkdir lock: the first worker builds, everyone + * else waits for the sentinel files to appear and the lock to clear, and once + * the dist exists nobody ever rebuilds (so no later clean can wipe it + * mid-read). + */ +export async function ensureBuilt(pkgDir: string): Promise { + const sentinels = DIST_SENTINELS[basename(pkgDir)]; + if (!sentinels) { + throw new Error(`No dist sentinels registered for ${pkgDir} — add the package to DIST_SENTINELS`); + } + const lockDir = join(pkgDir, '.dist-build-lock'); + const haveAll = () => sentinels.every(s => existsSync(join(pkgDir, 'dist', s))); + const deadline = Date.now() + WAIT_DEADLINE_MS; + for (;;) { + if (haveAll() && !existsSync(lockDir)) return; + try { + mkdirSync(lockDir); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err; + // Another worker holds the lock. If the holder died without its + // finally running (SIGKILL/OOM), the lock never clears — steal it + // once it is older than any live build could be. + try { + if (Date.now() - statSync(lockDir).mtimeMs > STALE_LOCK_MS) { + rmSync(lockDir, { recursive: true, force: true }); + continue; + } + } catch { + continue; // lock vanished between mkdir and stat — re-check now + } + if (Date.now() > deadline) { + throw new Error( + `Timed out waiting for ${pkgDir}/dist (${sentinels.join(', ')}) ` + + `while another worker held the build lock at ${lockDir}` + ); + } + await sleep(250); + continue; + } + try { + if (!haveAll()) { + try { + await execFileAsync('pnpm', ['build'], { + cwd: pkgDir, + timeout: BUILD_TIMEOUT_MS, + maxBuffer: 16 * 1024 * 1024 + }); + } catch (err) { + const stderr = (err as { stderr?: string }).stderr ?? ''; + throw new Error(`pnpm build failed in ${pkgDir}: ${(err as Error).message}\n${stderr.slice(-2000)}`); + } + } + return; + } finally { + rmSync(lockDir, { recursive: true, force: true }); + } + } +} From 64c83df0ceb1655118042552831800aafe6ecca5 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 17:38:21 +0000 Subject: [PATCH 10/12] Scale the dist-build timeout ladder to observed build times The builds take seconds; the previous bounds were sized by stacking worst cases on worst cases. Keep the ordering invariant (build kill < waiter deadline < stale-lock steal < hook timeout) at realistic magnitudes: 60s/90s/120s with 180s and 240s hooks. No-Verification-Needed: test-only timeout constants --- packages/client/test/client/barrelClean.test.ts | 2 +- packages/client/test/client/coreBoundary.test.ts | 2 +- packages/client/test/helpers/ensureBuilt.ts | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/client/test/client/barrelClean.test.ts b/packages/client/test/client/barrelClean.test.ts index cd44eb31f8..567543deed 100644 --- a/packages/client/test/client/barrelClean.test.ts +++ b/packages/client/test/client/barrelClean.test.ts @@ -40,7 +40,7 @@ function rootExportBlockOf(content: string): string { describe('@modelcontextprotocol/client root entry is browser-safe', () => { beforeAll(async () => { await ensureBuilt(pkgDir); - }, 480_000); + }, 180_000); test('dist/index.mjs contains no process-spawning runtime imports', () => { const entry = join(distDir, 'index.mjs'); diff --git a/packages/client/test/client/coreBoundary.test.ts b/packages/client/test/client/coreBoundary.test.ts index caca61ac47..3d2f18c16c 100644 --- a/packages/client/test/client/coreBoundary.test.ts +++ b/packages/client/test/client/coreBoundary.test.ts @@ -101,7 +101,7 @@ describe('@modelcontextprotocol/client ↔ core schema boundary', () => { beforeAll(async () => { await ensureBuilt(corePkgDir); await ensureBuilt(clientPkgDir); - }, 480_000); + }, 240_000); test('every name the client dist imports from core resolves against core’s built exports', () => { let sawCoreImport = false; diff --git a/packages/client/test/helpers/ensureBuilt.ts b/packages/client/test/helpers/ensureBuilt.ts index 6f6115e89b..c0721f615f 100644 --- a/packages/client/test/helpers/ensureBuilt.ts +++ b/packages/client/test/helpers/ensureBuilt.ts @@ -20,11 +20,11 @@ const DIST_SENTINELS: Record = { }; /** The build is killed after this long; execFile's kill still runs our finally. */ -const BUILD_TIMEOUT_MS = 180_000; +const BUILD_TIMEOUT_MS = 60_000; /** How long a waiter polls for another worker's build — outlasts BUILD_TIMEOUT_MS. */ -const WAIT_DEADLINE_MS = 210_000; +const WAIT_DEADLINE_MS = 90_000; /** A lock older than this belongs to a dead worker (finally never ran) — steal it. */ -const STALE_LOCK_MS = 240_000; +const STALE_LOCK_MS = 120_000; /** * Build a package's dist on demand, safely across parallel vitest workers. From 68688c9f2b8fdb7099635201e627c8651eca3959 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 17:47:13 +0000 Subject: [PATCH 11/12] Address review: node10 types resolution, docs topology, boundary test blind spots - Add typesVersions for the ./internal subpath so moduleResolution:node10 consumers resolve its declarations (exports maps are invisible there) - Update wire-schemas and packages docs: core now arrives transitively as the shared runtime schema graph of client/server/server-legacy - Boundary test: scan dist recursively (validators/ chunks were excluded) and reject bare side-effect imports of core, which have no from-clause --- docs/advanced/wire-schemas.md | 3 ++- docs/get-started/packages.md | 2 +- packages/client/test/client/coreBoundary.test.ts | 9 ++++++++- packages/core/package.json | 7 +++++++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/docs/advanced/wire-schemas.md b/docs/advanced/wire-schemas.md index d9a535627c..8ce47bda53 100644 --- a/docs/advanced/wire-schemas.md +++ b/docs/advanced/wire-schemas.md @@ -1,6 +1,7 @@ --- shape: how-to --- + # Wire schemas `@modelcontextprotocol/core` exports the **wire schemas** — the exact Zod constants the SDK validates protocol and OAuth payloads against — for code that holds raw JSON instead of SDK objects. @@ -56,7 +57,7 @@ These are the `*Schema` constants v1 exported from `@modelcontextprotocol/sdk/ty If you build with `McpServer` or `Client`, skip this package: [tools](../servers/tools.md) arrive in your handler already validated, and [tool calls](../clients/calling.md) come back as typed results. Reach for `@modelcontextprotocol/core` when nothing stands between you and the JSON — gateways, proxies, test harnesses, [worker fleets](./gateway.md). -Install it separately (`npm install @modelcontextprotocol/core`) — `@modelcontextprotocol/server` and `@modelcontextprotocol/client` keep a Zod-free public surface and never depend on it. The package is runtime-neutral; `zod` is its only dependency. +`@modelcontextprotocol/server` and `@modelcontextprotocol/client` keep a Zod-free public surface, but they resolve their shared schema graph from this package at runtime, so it already arrives transitively in your tree. Add it to your own `dependencies` (`npm install @modelcontextprotocol/core`) when you import from it directly. The package is runtime-neutral; `zod` is its only dependency. ## Pick the schema for the message you hold diff --git a/docs/get-started/packages.md b/docs/get-started/packages.md index b4eea130ac..40de2c6741 100644 --- a/docs/get-started/packages.md +++ b/docs/get-started/packages.md @@ -66,7 +66,7 @@ Four adapters exist: `@modelcontextprotocol/node` for Node's built-in `http` ser ## Reach for `core` only to validate raw wire JSON -`@modelcontextprotocol/core` exports the Zod schema constants the SDK validates protocol payloads against, for code that handles raw JSON-RPC payloads itself — gateways, proxies, log pipelines. Neither `server` nor `client` exports a Zod schema, and the matching TypeScript types ship with both, so if you only call `registerTool` and `callTool` you never install it. [Wire schemas](../advanced/wire-schemas.md) is the how-to. +`@modelcontextprotocol/core` exports the Zod schema constants the SDK validates protocol payloads against, for code that handles raw JSON-RPC payloads itself — gateways, proxies, log pipelines. Neither `server` nor `client` exports a Zod schema, and the matching TypeScript types ship with both, so if you only call `registerTool` and `callTool` you never import it directly — it arrives transitively, since `server` and `client` resolve their shared schema graph from it at runtime. [Wire schemas](../advanced/wire-schemas.md) is the how-to. ## Leave `server-legacy` and `codemod` to the migration guide diff --git a/packages/client/test/client/coreBoundary.test.ts b/packages/client/test/client/coreBoundary.test.ts index 3d2f18c16c..d99cfec50e 100644 --- a/packages/client/test/client/coreBoundary.test.ts +++ b/packages/client/test/client/coreBoundary.test.ts @@ -49,7 +49,9 @@ const IMPORTED_SENTINELS = ['OAuthMetadataSchema', 'JSONRPCMessageSchema']; const NEVER_DEFINED_SENTINELS = [...IMPORTED_SENTINELS, 'SafeUrlSchema']; function clientChunks(): string[] { - return readdirSync(clientDistDir).filter(f => f.endsWith('.mjs')); + return readdirSync(clientDistDir, { recursive: true }) + .map(String) + .filter(f => f.endsWith('.mjs')); } /** Exported names of a built core entry (its trailing `export { a, b as c };` blocks). */ @@ -123,6 +125,11 @@ describe('@modelcontextprotocol/client ↔ core schema boundary', () => { source, `client dist/${chunk} uses a non-named import/re-export of @modelcontextprotocol/core — update this test to cover it` ).not.toMatch(/(?:import|export)\s+(?!\{)[^;]*?from\s*["']@modelcontextprotocol\/core(?:\/internal)?["']/); + // Bare side-effect imports have no `from` clause and would dodge the pattern above. + expect( + source, + `client dist/${chunk} uses a bare side-effect import of @modelcontextprotocol/core — update this test to cover it` + ).not.toMatch(/import\s*["']@modelcontextprotocol\/core(?:\/internal)?["']/); } expect(sawCoreImport, 'no client chunk imports @modelcontextprotocol/core at all — external wiring changed?').toBe(true); }); diff --git a/packages/core/package.json b/packages/core/package.json index 28e89186bb..1a6977660f 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -42,6 +42,13 @@ } } }, + "typesVersions": { + "*": { + "internal": [ + "dist/internal.d.mts" + ] + } + }, "main": "./dist/index.cjs", "types": "./dist/index.d.mts", "files": [ From 60d7f1f78a49857b9ea916695d35be4f44a229d2 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Mon, 13 Jul 2026 11:19:05 +0000 Subject: [PATCH 12/12] Add preloadSchemas() and warm wire schemas eagerly on workerd The wire schemas are built lazily since the memoized-factory change, which is the right default on process-per-invocation runtimes where module evaluation is boot latency. On isolate-based serverless platforms the accounting inverts: module scope evaluates during deployment/isolate warm-up outside any request's billed CPU, so lazy construction lands inside the first request each fresh isolate serves - observable in production as a per-request CPU regression with a fresh-isolate-first-request signature. - preloadSchemas() (core-internal wire/preload.ts): synchronous, idempotent; forces both era schema factories and every memoized lookup layer above them (the 2025 registry maps, the 2026 in-band input-request maps, the 2026 wire-result wrappers), so post-preload validation constructs nothing. Exported as public API from the client and server package roots for platforms that bill request CPU but not module evaluation. - The workerd shims call it at module scope, so Cloudflare Workers deployments get eager construction automatically. Node and browser builds stay lazy; the server package gains a dedicated browser shim (its browser export condition previously reused the workerd shim, which would have leaked the eager call into browser bundles). - Dist-level pins in both packages: the workerd entries must carry the module-scope call, node/browser entries must not, and the shim must import preloadSchemas from the same shared chunk as the root entry (a duplicated definition would warm a twin module graph and leave the real one cold). - The server dist suites now share a single-flight build helper so two test files cannot race tsdown's clean step on a cold checkout; the client helper's dist sentinels now cover the shim entries. Verified against packed tarballs in a scratch consumer: a bare import constructs nothing (first preloadSchemas call does the work, second is free); a wrangler bundle resolves shimsWorkerd and contains exactly one module-scope call; an esbuild browser bundle resolves shimsBrowser and contains none; the Cloudflare Workers integration test stays green. --- .changeset/workerd-schema-preload.md | 6 + packages/client/src/index.ts | 6 + packages/client/src/shimsWorkerd.ts | 9 ++ .../test/client/workerdSchemaPreload.test.ts | 90 +++++++++++++++ packages/client/test/helpers/ensureBuilt.ts | 13 ++- packages/core-internal/eslint.config.mjs | 3 +- packages/core-internal/src/index.ts | 6 + packages/core-internal/src/wire/preload.ts | 57 ++++++++++ .../src/wire/rev2025-11-25/registry.ts | 8 ++ .../src/wire/rev2026-07-28/codec.ts | 8 ++ .../src/wire/rev2026-07-28/inputRequired.ts | 8 ++ .../core-internal/test/wire/preload.test.ts | 84 ++++++++++++++ packages/server/package.json | 8 +- packages/server/src/index.ts | 6 + packages/server/src/shimsBrowser.ts | 27 +++++ packages/server/src/shimsWorkerd.ts | 9 ++ packages/server/test/helpers/ensureBuilt.ts | 105 ++++++++++++++++++ .../server/test/server/barrelClean.test.ts | 18 +-- .../test/server/workerdSchemaPreload.test.ts | 90 +++++++++++++++ packages/server/tsdown.config.ts | 1 + 20 files changed, 548 insertions(+), 14 deletions(-) create mode 100644 .changeset/workerd-schema-preload.md create mode 100644 packages/client/test/client/workerdSchemaPreload.test.ts create mode 100644 packages/core-internal/src/wire/preload.ts create mode 100644 packages/core-internal/test/wire/preload.test.ts create mode 100644 packages/server/src/shimsBrowser.ts create mode 100644 packages/server/test/helpers/ensureBuilt.ts create mode 100644 packages/server/test/server/workerdSchemaPreload.test.ts diff --git a/.changeset/workerd-schema-preload.md b/.changeset/workerd-schema-preload.md new file mode 100644 index 0000000000..c0fc376c28 --- /dev/null +++ b/.changeset/workerd-schema-preload.md @@ -0,0 +1,6 @@ +--- +'@modelcontextprotocol/client': minor +'@modelcontextprotocol/server': minor +--- + +Add `preloadSchemas()`, an explicit opt-in to eager wire-schema construction, and call it automatically in the Cloudflare Workers builds. The wire schemas are built lazily by default, which is the right trade on process-per-invocation runtimes — but on isolate platforms that bill request CPU while module evaluation runs during isolate warm-up, laziness moves construction into the first request each fresh isolate serves. Calling `preloadSchemas()` at module scope (it is synchronous and idempotent) moves that one-time cost back to module evaluation; the packages' workerd export condition now does this automatically, while the Node and browser builds stay lazy. The server package gains a dedicated browser shim for this (its `browser` condition previously reused the workerd shim), so browser bundles keep lazy construction. diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index c9088fc499..2c9bcaaa9e 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -106,5 +106,11 @@ export { fromJsonSchema } from './fromJsonSchema'; export type { InputRequiredOptions } from '@modelcontextprotocol/core-internal'; export { withInputRequired } from '@modelcontextprotocol/core-internal'; +// Explicit opt-in to eager wire-schema construction, for platforms that bill +// request CPU but not module evaluation (isolate-based edge/serverless +// runtimes). The package's workerd build calls it automatically at module +// scope; other builds stay lazy unless the application calls it itself. +export { preloadSchemas } from '@modelcontextprotocol/core-internal'; + // re-export curated public API from core export * from '@modelcontextprotocol/core-internal/public'; diff --git a/packages/client/src/shimsWorkerd.ts b/packages/client/src/shimsWorkerd.ts index bd680e4358..1ac1e65321 100644 --- a/packages/client/src/shimsWorkerd.ts +++ b/packages/client/src/shimsWorkerd.ts @@ -3,8 +3,17 @@ * * This file is selected via package.json export conditions when running in workerd. */ +import { preloadSchemas } from '@modelcontextprotocol/core-internal'; + export { CfWorkerJsonSchemaValidator as DefaultJsonSchemaValidator } from '@modelcontextprotocol/core-internal/validators/cfWorker'; +// Platform asymmetry: isolate platforms like workerd evaluate module scope +// during deployment/isolate warm-up, outside any request's billed CPU, while +// lazy construction would land inside the first request each fresh isolate +// serves. Node and browser shims stay lazy — there, module evaluation is +// process/page startup and boot latency is the cost that matters. +preloadSchemas(); + /** * Whether `fetch()` may throw `TypeError` due to CORS. CORS is a browser-only concept — * in Cloudflare Workers, a `TypeError` from `fetch` is always a real network/configuration diff --git a/packages/client/test/client/workerdSchemaPreload.test.ts b/packages/client/test/client/workerdSchemaPreload.test.ts new file mode 100644 index 0000000000..ffbc08b98f --- /dev/null +++ b/packages/client/test/client/workerdSchemaPreload.test.ts @@ -0,0 +1,90 @@ +/** + * Platform-conditional schema warm-up pins, asserted against the real build + * outputs. + * + * The wire schemas are built lazily by default — the right trade on + * process-per-invocation runtimes, where module evaluation is boot latency. + * On isolate platforms (workerd), module scope evaluates during isolate + * warm-up outside any request's billed CPU, so the workerd shim calls + * `preloadSchemas()` at module scope to keep construction out of the first + * request. Two regressions would be silent without these pins: + * + * 1. The workerd condition loses its module-scope call (a shim refactor drops + * it) — fresh isolates go back to paying schema construction inside the + * first request's CPU. + * 2. The node or browser condition gains one (an import shuffle re-eagerizes + * it) — every process boot / page load pays construction for validations + * that may never happen. + * + * Identity also matters: the warm-up only helps if the shim forces the SAME + * memo module the package entry validates through. The shim entry must + * import `preloadSchemas` from the shared chunk — a duplicated definition in + * the shim chunk would warm a twin module and leave the real one cold. + */ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { beforeAll, describe, expect, test } from 'vitest'; + +import { ensureBuilt } from '../helpers/ensureBuilt'; + +const pkgDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); +const distDir = join(pkgDir, 'dist'); + +/** + * A module-scope `preloadSchemas();` call: statement at column 0 — entry-level + * statements are unindented in the unminified build output, while statements + * inside function bodies are indented, so a call that merely sits in some + * bundled helper body cannot satisfy (or trip) this pin. The CJS build calls + * through the required chunk's namespace (`require_src.preloadSchemas();`), + * so an optional receiver is allowed. + */ +const MODULE_SCOPE_PRELOAD_CALL = /^(?:[\w$]+\.)?preloadSchemas\(\);/m; + +/** + * An entry-level `import { …, X as preloadSchemas, … } from "./chunk"` (or + * the un-aliased `{ preloadSchemas }` form), capturing the chunk specifier. + */ +const PRELOAD_IMPORT = /import\s*\{[^}]*\bpreloadSchemas\b[^}]*\}\s*from\s*"(\.\/[^"]+)"/; + +function dist(file: string): string { + return readFileSync(join(distDir, file), 'utf8'); +} + +describe('workerd schema warm-up (built dist)', () => { + beforeAll(async () => { + await ensureBuilt(pkgDir); + }, 180_000); + + test('shimsWorkerd calls preloadSchemas() at module scope (ESM and CJS)', () => { + expect(dist('shimsWorkerd.mjs')).toMatch(MODULE_SCOPE_PRELOAD_CALL); + expect(dist('shimsWorkerd.cjs')).toMatch(MODULE_SCOPE_PRELOAD_CALL); + }); + + test('node and browser shims stay lazy — no preloadSchemas reference at all', () => { + for (const shim of ['shimsNode.mjs', 'shimsNode.cjs', 'shimsBrowser.mjs', 'shimsBrowser.cjs']) { + expect(dist(shim), `${shim} must not re-eagerize schema construction`).not.toMatch(/\bpreloadSchemas\b/); + } + }); + + test('the root entry exports preloadSchemas but never calls it at module scope', () => { + const index = dist('index.mjs'); + expect(index).toMatch(/\bpreloadSchemas\b/); + expect(index).not.toMatch(MODULE_SCOPE_PRELOAD_CALL); + }); + + test('the workerd shim warms the same chunk the root entry uses (no duplicated schema graph)', () => { + const entries = ['index.mjs', 'shimsWorkerd.mjs', 'shimsNode.mjs', 'shimsBrowser.mjs', 'stdio.mjs']; + for (const entry of entries) { + expect(dist(entry), `${entry} must not carry its own preloadSchemas definition`).not.toMatch(/function preloadSchemas\b/); + } + + const shimSource = dist('shimsWorkerd.mjs').match(PRELOAD_IMPORT)?.[1]; + const indexSource = dist('index.mjs').match(PRELOAD_IMPORT)?.[1]; + expect(shimSource).toBeDefined(); + expect(indexSource).toBeDefined(); + expect(shimSource).toBe(indexSource); + expect(dist(shimSource!.replace('./', ''))).toMatch(/function preloadSchemas\b/); + }); +}); diff --git a/packages/client/test/helpers/ensureBuilt.ts b/packages/client/test/helpers/ensureBuilt.ts index c0721f615f..8cfa9c0627 100644 --- a/packages/client/test/helpers/ensureBuilt.ts +++ b/packages/client/test/helpers/ensureBuilt.ts @@ -15,7 +15,18 @@ const execFileAsync = promisify(execFile); * prevent. */ const DIST_SENTINELS: Record = { - client: ['index.mjs', 'stdio.mjs'], + client: [ + 'index.mjs', + 'stdio.mjs', + // The workerdSchemaPreload suite reads every shim entry in both + // formats; a partial dist missing any of them must trigger a rebuild. + 'shimsWorkerd.mjs', + 'shimsWorkerd.cjs', + 'shimsNode.mjs', + 'shimsNode.cjs', + 'shimsBrowser.mjs', + 'shimsBrowser.cjs' + ], core: ['index.mjs', 'internal.mjs'] }; diff --git a/packages/core-internal/eslint.config.mjs b/packages/core-internal/eslint.config.mjs index ae8ff4ce39..b42960584f 100644 --- a/packages/core-internal/eslint.config.mjs +++ b/packages/core-internal/eslint.config.mjs @@ -8,7 +8,8 @@ export default [ // Wire-layer isolation, outbound direction: nothing outside src/wire/ may // reach into a wire revision module. The wire layer's only public surface // is src/wire/codec.ts (the WireCodec interface), src/wire/bootstrap.ts, - // and the leaf result-family module src/wire/resultFamilies.ts (the shared + // the revision-neutral warm-up entry src/wire/preload.ts, and the leaf + // result-family module src/wire/resultFamilies.ts (the shared // tools/call-result ruling, re-exported on the barrel). // test/wire/layeringInvariants.test.ts re-derives the same invariant with // zero exceptions. Type-only imports are exempted at the lint layer (a diff --git a/packages/core-internal/src/index.ts b/packages/core-internal/src/index.ts index 3e2f961fbe..0aa5aae21a 100644 --- a/packages/core-internal/src/index.ts +++ b/packages/core-internal/src/index.ts @@ -36,6 +36,12 @@ export * from './util/schema'; export * from './util/standardSchema'; export * from './util/zodCompat'; export { codecForVersion, MODERN_WIRE_REVISION } from './wire/codec'; +// Revision-neutral warm-up entry for the lazy wire-schema layers. Exposes no +// per-revision objects — it only forces the memos every consumer already +// pulls through — so it stays within the no-per-revision-exports rule above. +// Re-exported as public API by the client and server packages for platforms +// that bill request CPU but not module evaluation. +export { preloadSchemas } from './wire/preload'; export { normalizeContentlessToolResult, TOOL_RESULT_FOREIGN_FAMILY_KEYS } from './wire/resultFamilies'; // Validator provider classes stay subpath-only. Re-exporting them here, even as diff --git a/packages/core-internal/src/wire/preload.ts b/packages/core-internal/src/wire/preload.ts new file mode 100644 index 0000000000..1af37f89c4 --- /dev/null +++ b/packages/core-internal/src/wire/preload.ts @@ -0,0 +1,57 @@ +/** + * Explicit warm-up entry for the lazy wire-schema layers. + * + * The per-revision wire schemas are built lazily: each era's schema set sits + * behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the + * registry/codec lookup maps above those factories are memoized the same way. + * That laziness is the right default on process-per-invocation runtimes (CLI + * tools, dev servers), where module evaluation IS startup latency and most + * short-lived processes never validate a message on both eras. + * + * On platforms that bill request CPU but not module evaluation — isolate-based + * edge/serverless runtimes such as Cloudflare Workers — the trade inverts: + * module-scope work runs during isolate warm-up outside any request, while + * lazy construction lands inside the first request's billed (and latency + * budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move + * the one-time construction cost back to module scope by calling it at module + * scope themselves. The packages' own workerd shims already do this, so + * Workers deployments get eager construction automatically. + */ +import { buildSchemas2025 } from './rev2025-11-25/buildSchemas'; +import { warmRegistryMaps2025 } from './rev2025-11-25/registry'; +import { buildSchemas2026 } from './rev2026-07-28/buildSchemas'; +import { warmWireResultSchemas2026 } from './rev2026-07-28/codec'; +import { warmInputSchemaMaps2026 } from './rev2026-07-28/inputRequired'; + +/** + * Eagerly builds every lazily-constructed wire-schema layer, so that no later + * validation pays schema-construction cost. + * + * Synchronous and idempotent: every layer is a memo, so the first call does + * all the work and subsequent calls return immediately. Reference identity is + * unaffected — this forces the same memos every lazy consumer pulls through. + * + * Call it at module scope on platforms that bill per-request CPU but not + * module evaluation (isolate-based edge/serverless runtimes), where deferring + * construction would move it into the first request of every fresh isolate: + * + * ```ts + * // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — + * // each package bundles its own schema copy, so warm the one(s) you import. + * preloadSchemas(); // module scope — runs during isolate warm-up + * ``` + * + * On Node CLIs and other process-per-invocation runtimes, prefer the lazy + * default — there, module-scope construction is pure added boot latency. + */ +export function preloadSchemas(): void { + // The era schema factories — the bulk of the construction cost. + buildSchemas2025(); + buildSchemas2026(); + // The memoized lookup layers above the factories. (The 2026 registry has + // no map memo of its own — it reads the dispatch maps straight off the + // built schema set.) + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} 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 96d04b4db9..40fc858c64 100644 --- a/packages/core-internal/src/wire/rev2025-11-25/registry.ts +++ b/packages/core-internal/src/wire/rev2025-11-25/registry.ts @@ -212,6 +212,14 @@ function registryMaps(): RegistryMaps { return maps; } +/** + * Forces the lazy registry maps (and, through them, the era's schema memo). + * Warm-up hook for `preloadSchemas()` — no-op once the maps exist. + */ +export function warmRegistryMaps2025(): void { + registryMaps(); +} + /** The 2025-era request-method set (registry membership = the deletion story). */ export function hasRequestMethod2025(method: string): method is Rev2025RequestMethod { return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); 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 5af749378f..c1373a8f41 100644 --- a/packages/core-internal/src/wire/rev2026-07-28/codec.ts +++ b/packages/core-internal/src/wire/rev2026-07-28/codec.ts @@ -298,3 +298,11 @@ function getWireResultSchemas(): Record { }; return wireResultSchemasMemo; } + +/** + * Forces the lazy wire-result wrapper map (and, through it, the era's schema + * memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. + */ +export function warmWireResultSchemas2026(): void { + getWireResultSchemas(); +} 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 83c9ab9769..da269863be 100644 --- a/packages/core-internal/src/wire/rev2026-07-28/inputRequired.ts +++ b/packages/core-internal/src/wire/rev2026-07-28/inputRequired.ts @@ -67,6 +67,14 @@ function inputSchemaMaps(): InputSchemaMaps { return maps; } +/** + * Forces the lazy embedded-request maps (and, through them, the era's schema + * memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. + */ +export function warmInputSchemaMaps2026(): void { + inputSchemaMaps(); +} + export function isInputRequestMethod2026(method: string): method is InputRequestMethod2026 { return (INPUT_REQUEST_METHODS_2026 as readonly string[]).includes(method); } diff --git a/packages/core-internal/test/wire/preload.test.ts b/packages/core-internal/test/wire/preload.test.ts new file mode 100644 index 0000000000..c4edb170ce --- /dev/null +++ b/packages/core-internal/test/wire/preload.test.ts @@ -0,0 +1,84 @@ +/** + * preloadSchemas(): the explicit warm-up entry for the lazy wire-schema + * layers (era factories + the memoized registry/codec lookup maps). + * + * The contract under test: + * - synchronous and idempotent — repeated calls keep returning the same + * memoized objects; + * - it warms the SAME memos every lazy consumer pulls through, so lookups + * after a preload serve reference-identical objects (no second + * construction, no parallel schema graph); + * - validation on both eras works normally after a preload. + * + * This file deliberately imports no eager schema shim (the per-era + * `schemas.ts` re-export surfaces): vitest isolates module registries per + * test file, so preloadSchemas() is the only thing that warms the memos here. + */ +import { describe, expect, it } from 'vitest'; + +import { codecForVersion, MODERN_WIRE_REVISION } from '../../src/wire/codec'; +import { preloadSchemas } from '../../src/wire/preload'; +import { buildSchemas2025 } from '../../src/wire/rev2025-11-25/buildSchemas'; +import { getNotificationSchema, getRequestSchema } from '../../src/wire/rev2025-11-25/registry'; +import { buildSchemas2026 } from '../../src/wire/rev2026-07-28/buildSchemas'; +import { getInputRequestSchema2026 } from '../../src/wire/rev2026-07-28/inputRequired'; +import { getRequestSchema2026 } from '../../src/wire/rev2026-07-28/registry'; + +// Module scope, mirroring the intended call site on isolate platforms. +preloadSchemas(); + +describe('preloadSchemas', () => { + it('returns void, synchronously', () => { + expect(preloadSchemas()).toBeUndefined(); + }); + + it('is idempotent: repeated calls keep serving the same memoized objects', () => { + const s2025 = buildSchemas2025(); + const s2026 = buildSchemas2026(); + const pingSchema = getRequestSchema('ping'); + const rootsInput = getInputRequestSchema2026('roots/list'); + + preloadSchemas(); + preloadSchemas(); + + expect(buildSchemas2025()).toBe(s2025); + expect(buildSchemas2026()).toBe(s2026); + expect(getRequestSchema('ping')).toBe(pingSchema); + expect(getInputRequestSchema2026('roots/list')).toBe(rootsInput); + }); + + it('warms the same memos the lazy consumers pull through (reference identity, no parallel graph)', () => { + // 2025 era: registry lookups serve objects out of the preloaded set. + const s2025 = buildSchemas2025(); + expect(getRequestSchema('ping')).toBe(s2025.PingRequestSchema); + expect(getRequestSchema('initialize')).toBe(s2025.InitializeRequestSchema); + expect(getNotificationSchema('notifications/progress')).toBe(s2025.ProgressNotificationSchema); + + // 2026 era: the registry reads the dispatch maps straight off the + // preloaded set, and the in-band response map serves the same objects. + const s2026 = buildSchemas2026(); + expect(getRequestSchema2026('tools/list')).toBe(s2026.dispatchRequestSchemas['tools/list']); + expect(getInputRequestSchema2026('roots/list')).toBeDefined(); + }); + + it('leaves validation working normally on both eras', () => { + const legacy = codecForVersion(undefined); + expect(legacy.era).toBe('2025-11-25'); + expect(legacy.validateRequest('ping', { method: 'ping' })).toEqual({ ok: true, value: { method: 'ping' } }); + expect(legacy.validateNotification('notifications/initialized', { method: 'notifications/initialized' })).toMatchObject({ + ok: true + }); + + const modern = codecForVersion(MODERN_WIRE_REVISION); + expect(modern.era).toBe('2026-07-28'); + expect(modern.validateRequest('tools/list', { method: 'tools/list' })).toMatchObject({ ok: true }); + // Warmed wire-result wrappers: decode step 2 parses against the + // preloaded map (a shape violation still fails cleanly). + expect(modern.decodeResult('tools/list', { resultType: 'complete', ttlMs: 0, cacheScope: 'private', tools: [] })).toMatchObject({ + kind: 'complete' + }); + expect( + modern.decodeResult('tools/list', { resultType: 'complete', ttlMs: 0, cacheScope: 'private', tools: 'not-an-array' }) + ).toMatchObject({ kind: 'invalid' }); + }); +}); diff --git a/packages/server/package.json b/packages/server/package.json index 173eaf7f2b..9b7e290258 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -73,12 +73,12 @@ }, "browser": { "import": { - "types": "./dist/shimsWorkerd.d.mts", - "default": "./dist/shimsWorkerd.mjs" + "types": "./dist/shimsBrowser.d.mts", + "default": "./dist/shimsBrowser.mjs" }, "require": { - "types": "./dist/shimsWorkerd.d.cts", - "default": "./dist/shimsWorkerd.cjs" + "types": "./dist/shimsBrowser.d.cts", + "default": "./dist/shimsBrowser.cjs" } }, "node": { diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 0d4b7c0484..d2263d5829 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -99,5 +99,11 @@ export type { CacheHint, CacheScope } from '@modelcontextprotocol/core-internal' export type { ElicitInputParams, InputRequiredSpec, InputResponseView } from '@modelcontextprotocol/core-internal'; export { acceptedContent, inputRequired, inputResponse } from '@modelcontextprotocol/core-internal'; +// Explicit opt-in to eager wire-schema construction, for platforms that bill +// request CPU but not module evaluation (isolate-based edge/serverless +// runtimes). The package's workerd build calls it automatically at module +// scope; other builds stay lazy unless the application calls it itself. +export { preloadSchemas } from '@modelcontextprotocol/core-internal'; + // re-export curated public API from core export * from '@modelcontextprotocol/core-internal/public'; diff --git a/packages/server/src/shimsBrowser.ts b/packages/server/src/shimsBrowser.ts new file mode 100644 index 0000000000..7a9c7154f5 --- /dev/null +++ b/packages/server/src/shimsBrowser.ts @@ -0,0 +1,27 @@ +/** + * Browser runtime shims for server package + * + * This file is selected via package.json export conditions when bundling for + * browsers. It binds the same platform choices as the workerd shim (the + * cfWorker validator, the process stub) WITHOUT the module-scope + * `preloadSchemas()` call: in a browser, module evaluation is page load — + * boot latency — so schema construction stays lazy, exactly like Node. + */ +export { CfWorkerJsonSchemaValidator as DefaultJsonSchemaValidator } from '@modelcontextprotocol/core-internal/validators/cfWorker'; + +/** + * Stub process object for non-Node.js environments. + * StdioServerTransport is not supported in Cloudflare Workers/browser environments. + */ +function notSupported(): never { + throw new Error('StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.'); +} + +export const process = { + get stdin(): never { + return notSupported(); + }, + get stdout(): never { + return notSupported(); + } +}; diff --git a/packages/server/src/shimsWorkerd.ts b/packages/server/src/shimsWorkerd.ts index 92e3bf0f17..bf0ddfc7d4 100644 --- a/packages/server/src/shimsWorkerd.ts +++ b/packages/server/src/shimsWorkerd.ts @@ -3,8 +3,17 @@ * * This file is selected via package.json export conditions when running in workerd. */ +import { preloadSchemas } from '@modelcontextprotocol/core-internal'; + export { CfWorkerJsonSchemaValidator as DefaultJsonSchemaValidator } from '@modelcontextprotocol/core-internal/validators/cfWorker'; +// Platform asymmetry: isolate platforms like workerd evaluate module scope +// during deployment/isolate warm-up, outside any request's billed CPU, while +// lazy construction would land inside the first request each fresh isolate +// serves. The Node and browser shims stay lazy — there, module evaluation is +// process/page startup and boot latency is the cost that matters. +preloadSchemas(); + /** * Stub process object for non-Node.js environments. * StdioServerTransport is not supported in Cloudflare Workers/browser environments. diff --git a/packages/server/test/helpers/ensureBuilt.ts b/packages/server/test/helpers/ensureBuilt.ts new file mode 100644 index 0000000000..e51ce463f9 --- /dev/null +++ b/packages/server/test/helpers/ensureBuilt.ts @@ -0,0 +1,105 @@ +/** + * Server-package copy of packages/client/test/helpers/ensureBuilt.ts (per-package + * test dirs stay self-contained). Keep the locking logic in sync with that file. + */ +import { execFile } from 'node:child_process'; +import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +/** + * Canonical dist sentinels per package. Every caller waits on the same + * complete set: if callers checked their own subsets, a partial dist (from an + * interrupted build) could satisfy one caller's fast path while another still + * rebuilds — and the rebuild's clean step would wipe files under the first + * caller's running tests, which is exactly the race this helper exists to + * prevent. + */ +const DIST_SENTINELS: Record = { + server: [ + 'index.mjs', + 'stdio.mjs', + 'shimsWorkerd.mjs', + 'shimsWorkerd.cjs', + 'shimsNode.mjs', + 'shimsNode.cjs', + 'shimsBrowser.mjs', + 'shimsBrowser.cjs' + ] +}; + +/** The build is killed after this long; execFile's kill still runs our finally. */ +const BUILD_TIMEOUT_MS = 60_000; +/** How long a waiter polls for another worker's build — outlasts BUILD_TIMEOUT_MS. */ +const WAIT_DEADLINE_MS = 90_000; +/** A lock older than this belongs to a dead worker (finally never ran) — steal it. */ +const STALE_LOCK_MS = 120_000; + +/** + * Build a package's dist on demand, safely across parallel vitest workers. + * + * Vitest runs test files in separate worker processes, so two files that each + * "build if dist is missing" can race on a cold checkout: both see no dist, + * both spawn `pnpm build`, and tsdown's clean step deletes files out from + * under whichever worker is already reading them. This helper makes the build + * single-flight with an atomic mkdir lock: the first worker builds, everyone + * else waits for the sentinel files to appear and the lock to clear, and once + * the dist exists nobody ever rebuilds (so no later clean can wipe it + * mid-read). + */ +export async function ensureBuilt(pkgDir: string): Promise { + const sentinels = DIST_SENTINELS[basename(pkgDir)]; + if (!sentinels) { + throw new Error(`No dist sentinels registered for ${pkgDir} — add the package to DIST_SENTINELS`); + } + const lockDir = join(pkgDir, '.dist-build-lock'); + const haveAll = () => sentinels.every(s => existsSync(join(pkgDir, 'dist', s))); + const deadline = Date.now() + WAIT_DEADLINE_MS; + for (;;) { + if (haveAll() && !existsSync(lockDir)) return; + try { + mkdirSync(lockDir); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err; + // Another worker holds the lock. If the holder died without its + // finally running (SIGKILL/OOM), the lock never clears — steal it + // once it is older than any live build could be. + try { + if (Date.now() - statSync(lockDir).mtimeMs > STALE_LOCK_MS) { + rmSync(lockDir, { recursive: true, force: true }); + continue; + } + } catch { + continue; // lock vanished between mkdir and stat — re-check now + } + if (Date.now() > deadline) { + throw new Error( + `Timed out waiting for ${pkgDir}/dist (${sentinels.join(', ')}) ` + + `while another worker held the build lock at ${lockDir}` + ); + } + await sleep(250); + continue; + } + try { + if (!haveAll()) { + try { + await execFileAsync('pnpm', ['build'], { + cwd: pkgDir, + timeout: BUILD_TIMEOUT_MS, + maxBuffer: 16 * 1024 * 1024 + }); + } catch (err) { + const stderr = (err as { stderr?: string }).stderr ?? ''; + throw new Error(`pnpm build failed in ${pkgDir}: ${(err as Error).message}\n${stderr.slice(-2000)}`); + } + } + return; + } finally { + rmSync(lockDir, { recursive: true, force: true }); + } + } +} diff --git a/packages/server/test/server/barrelClean.test.ts b/packages/server/test/server/barrelClean.test.ts index 7b1e4898c7..e248f24265 100644 --- a/packages/server/test/server/barrelClean.test.ts +++ b/packages/server/test/server/barrelClean.test.ts @@ -1,11 +1,12 @@ -import { execFileSync } from 'node:child_process'; -import { existsSync, readFileSync } from 'node:fs'; +import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { beforeAll, describe, expect, test } from 'vitest'; +import { ensureBuilt } from '../helpers/ensureBuilt'; + const pkgDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); const distDir = join(pkgDir, 'dist'); const requireDist = createRequire(join(pkgDir, 'package.json')); @@ -37,11 +38,12 @@ function rootExportBlockOf(content: string): string { } describe('@modelcontextprotocol/server root entry is browser-safe', () => { - beforeAll(() => { - if (!existsSync(join(distDir, 'index.mjs')) || !existsSync(join(distDir, 'stdio.mjs'))) { - execFileSync('pnpm', ['build'], { cwd: pkgDir, stdio: 'inherit' }); - } - }, 60_000); + beforeAll(async () => { + // Single-flight across parallel vitest workers: this file and + // workerdSchemaPreload.test.ts both read the built dist, and two + // unlocked `pnpm build`s would race tsdown's clean step. + await ensureBuilt(pkgDir); + }, 180_000); test('dist/index.mjs does not export StdioServerTransport and has no process-stdio runtime imports', () => { const entry = readFileSync(join(distDir, 'index.mjs'), 'utf8'); @@ -66,7 +68,7 @@ describe('@modelcontextprotocol/server root entry is browser-safe', () => { }); test('runtime shims vendor default validator backends instead of requiring consumers to install them', () => { - for (const shim of ['shimsNode.mjs', 'shimsWorkerd.mjs']) { + for (const shim of ['shimsNode.mjs', 'shimsWorkerd.mjs', 'shimsBrowser.mjs']) { const entry = join(distDir, shim); expect(readFileSync(entry, 'utf8')).not.toMatch(VALIDATOR_BACKEND_IMPORT); diff --git a/packages/server/test/server/workerdSchemaPreload.test.ts b/packages/server/test/server/workerdSchemaPreload.test.ts new file mode 100644 index 0000000000..ffbc08b98f --- /dev/null +++ b/packages/server/test/server/workerdSchemaPreload.test.ts @@ -0,0 +1,90 @@ +/** + * Platform-conditional schema warm-up pins, asserted against the real build + * outputs. + * + * The wire schemas are built lazily by default — the right trade on + * process-per-invocation runtimes, where module evaluation is boot latency. + * On isolate platforms (workerd), module scope evaluates during isolate + * warm-up outside any request's billed CPU, so the workerd shim calls + * `preloadSchemas()` at module scope to keep construction out of the first + * request. Two regressions would be silent without these pins: + * + * 1. The workerd condition loses its module-scope call (a shim refactor drops + * it) — fresh isolates go back to paying schema construction inside the + * first request's CPU. + * 2. The node or browser condition gains one (an import shuffle re-eagerizes + * it) — every process boot / page load pays construction for validations + * that may never happen. + * + * Identity also matters: the warm-up only helps if the shim forces the SAME + * memo module the package entry validates through. The shim entry must + * import `preloadSchemas` from the shared chunk — a duplicated definition in + * the shim chunk would warm a twin module and leave the real one cold. + */ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { beforeAll, describe, expect, test } from 'vitest'; + +import { ensureBuilt } from '../helpers/ensureBuilt'; + +const pkgDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); +const distDir = join(pkgDir, 'dist'); + +/** + * A module-scope `preloadSchemas();` call: statement at column 0 — entry-level + * statements are unindented in the unminified build output, while statements + * inside function bodies are indented, so a call that merely sits in some + * bundled helper body cannot satisfy (or trip) this pin. The CJS build calls + * through the required chunk's namespace (`require_src.preloadSchemas();`), + * so an optional receiver is allowed. + */ +const MODULE_SCOPE_PRELOAD_CALL = /^(?:[\w$]+\.)?preloadSchemas\(\);/m; + +/** + * An entry-level `import { …, X as preloadSchemas, … } from "./chunk"` (or + * the un-aliased `{ preloadSchemas }` form), capturing the chunk specifier. + */ +const PRELOAD_IMPORT = /import\s*\{[^}]*\bpreloadSchemas\b[^}]*\}\s*from\s*"(\.\/[^"]+)"/; + +function dist(file: string): string { + return readFileSync(join(distDir, file), 'utf8'); +} + +describe('workerd schema warm-up (built dist)', () => { + beforeAll(async () => { + await ensureBuilt(pkgDir); + }, 180_000); + + test('shimsWorkerd calls preloadSchemas() at module scope (ESM and CJS)', () => { + expect(dist('shimsWorkerd.mjs')).toMatch(MODULE_SCOPE_PRELOAD_CALL); + expect(dist('shimsWorkerd.cjs')).toMatch(MODULE_SCOPE_PRELOAD_CALL); + }); + + test('node and browser shims stay lazy — no preloadSchemas reference at all', () => { + for (const shim of ['shimsNode.mjs', 'shimsNode.cjs', 'shimsBrowser.mjs', 'shimsBrowser.cjs']) { + expect(dist(shim), `${shim} must not re-eagerize schema construction`).not.toMatch(/\bpreloadSchemas\b/); + } + }); + + test('the root entry exports preloadSchemas but never calls it at module scope', () => { + const index = dist('index.mjs'); + expect(index).toMatch(/\bpreloadSchemas\b/); + expect(index).not.toMatch(MODULE_SCOPE_PRELOAD_CALL); + }); + + test('the workerd shim warms the same chunk the root entry uses (no duplicated schema graph)', () => { + const entries = ['index.mjs', 'shimsWorkerd.mjs', 'shimsNode.mjs', 'shimsBrowser.mjs', 'stdio.mjs']; + for (const entry of entries) { + expect(dist(entry), `${entry} must not carry its own preloadSchemas definition`).not.toMatch(/function preloadSchemas\b/); + } + + const shimSource = dist('shimsWorkerd.mjs').match(PRELOAD_IMPORT)?.[1]; + const indexSource = dist('index.mjs').match(PRELOAD_IMPORT)?.[1]; + expect(shimSource).toBeDefined(); + expect(indexSource).toBeDefined(); + expect(shimSource).toBe(indexSource); + expect(dist(shimSource!.replace('./', ''))).toMatch(/function preloadSchemas\b/); + }); +}); diff --git a/packages/server/tsdown.config.ts b/packages/server/tsdown.config.ts index d15b5de8d4..88004cfc06 100644 --- a/packages/server/tsdown.config.ts +++ b/packages/server/tsdown.config.ts @@ -7,6 +7,7 @@ export default defineConfig({ 'src/stdio.ts', 'src/shimsNode.ts', 'src/shimsWorkerd.ts', + 'src/shimsBrowser.ts', 'src/validators/ajv.ts', 'src/validators/cfWorker.ts' ],