From bf993effe5b68f67a8b510367aa1134e07608e08 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Fri, 10 Jul 2026 15:19:40 +0000 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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": [