From fa77d2eb44e1d606b699a84ab2a08f55de7da17f Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sat, 14 Mar 2026 09:13:23 +0200 Subject: [PATCH 1/5] initial draft: limit public exports --- examples/client-quickstart/tsconfig.json | 3 + examples/client/tsconfig.json | 3 + examples/server-quickstart/tsconfig.json | 3 + examples/server/tsconfig.json | 3 + examples/shared/tsconfig.json | 3 + packages/client/src/client/sse.ts | 2 +- packages/client/src/client/streamableHttp.ts | 2 +- packages/client/src/index.ts | 65 +- packages/client/tsconfig.json | 1 + .../core/src/experimental/tasks/interfaces.ts | 2 +- .../src/experimental/tasks/stores/inMemory.ts | 2 +- packages/core/src/exports/types/index.ts | 2 +- packages/core/src/index.ts | 2 +- packages/core/src/publicExports.ts | 102 + packages/core/src/shared/metadataUtils.ts | 2 +- packages/core/src/shared/protocol.ts | 6 +- packages/core/src/shared/responseMessage.ts | 2 +- packages/core/src/shared/stdio.ts | 4 +- packages/core/src/shared/transport.ts | 4 +- packages/core/src/types/constants.ts | 15 + packages/core/src/types/enums.ts | 16 + packages/core/src/types/errors.ts | 49 + packages/core/src/types/guards.ts | 70 + packages/core/src/types/index.ts | 8 + packages/core/src/types/schemas.ts | 2454 +++++++++++++++ packages/core/src/types/types.ts | 2709 +---------------- packages/core/src/util/inMemory.ts | 2 +- .../core/test/experimental/inMemory.test.ts | 2 +- packages/core/test/inMemory.test.ts | 2 +- packages/core/test/shared/protocol.test.ts | 4 +- .../shared/protocolTransportHandling.test.ts | 2 +- packages/core/test/shared/stdio.test.ts | 2 +- packages/core/test/spec.types.test.ts | 2 +- packages/core/test/types.capabilities.test.ts | 2 +- packages/core/test/types.test.ts | 2 +- packages/middleware/express/tsconfig.json | 3 + packages/middleware/hono/tsconfig.json | 3 + packages/middleware/node/tsconfig.json | 1 + packages/server/src/index.ts | 42 +- packages/server/tsconfig.json | 1 + test/conformance/tsconfig.json | 1 + test/helpers/tsconfig.json | 1 + test/integration/tsconfig.json | 1 + 43 files changed, 2926 insertions(+), 2681 deletions(-) create mode 100644 packages/core/src/publicExports.ts create mode 100644 packages/core/src/types/constants.ts create mode 100644 packages/core/src/types/enums.ts create mode 100644 packages/core/src/types/errors.ts create mode 100644 packages/core/src/types/guards.ts create mode 100644 packages/core/src/types/index.ts create mode 100644 packages/core/src/types/schemas.ts diff --git a/examples/client-quickstart/tsconfig.json b/examples/client-quickstart/tsconfig.json index 9c229e5fe..c3a26b1fe 100644 --- a/examples/client-quickstart/tsconfig.json +++ b/examples/client-quickstart/tsconfig.json @@ -15,6 +15,9 @@ "@modelcontextprotocol/client/_shims": ["./node_modules/@modelcontextprotocol/client/src/shimsNode.ts"], "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/index.ts" + ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/publicExports.ts" ] } }, diff --git a/examples/client/tsconfig.json b/examples/client/tsconfig.json index 480b491c7..1a1b9fca6 100644 --- a/examples/client/tsconfig.json +++ b/examples/client/tsconfig.json @@ -10,6 +10,9 @@ "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/index.ts" ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + ], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], "@modelcontextprotocol/examples-shared": ["./node_modules/@modelcontextprotocol/examples-shared/src/index.ts"] diff --git a/examples/server-quickstart/tsconfig.json b/examples/server-quickstart/tsconfig.json index 9fdefa15e..672e544e6 100644 --- a/examples/server-quickstart/tsconfig.json +++ b/examples/server-quickstart/tsconfig.json @@ -14,6 +14,9 @@ "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" + ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" ] } }, diff --git a/examples/server/tsconfig.json b/examples/server/tsconfig.json index 026b68312..ef83c1042 100644 --- a/examples/server/tsconfig.json +++ b/examples/server/tsconfig.json @@ -13,6 +13,9 @@ "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + ], "@modelcontextprotocol/examples-shared": ["./node_modules/@modelcontextprotocol/examples-shared/src/index.ts"], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] diff --git a/examples/shared/tsconfig.json b/examples/shared/tsconfig.json index 74c1e1172..6d7f38f86 100644 --- a/examples/shared/tsconfig.json +++ b/examples/shared/tsconfig.json @@ -12,6 +12,9 @@ "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + ], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"], diff --git a/packages/client/src/client/sse.ts b/packages/client/src/client/sse.ts index 133aa0004..1e2ab44a6 100644 --- a/packages/client/src/client/sse.ts +++ b/packages/client/src/client/sse.ts @@ -26,7 +26,7 @@ export type SSEClientTransportOptions = { * When an `authProvider` is specified and the SSE connection is started: * 1. The connection is attempted with any existing access token from the `authProvider`. * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, {@linkcode OAuthClientProvider.redirectToAuthorization} is called, and an {@linkcode UnauthorizedError} will be thrown from {@linkcode index.Protocol.connect | connect}/{@linkcode SSEClientTransport.start | start}. + * 3. If token refresh fails or no access token exists, and auth is required, {@linkcode OAuthClientProvider.redirectToAuthorization} is called, and an {@linkcode UnauthorizedError} will be thrown from {@linkcode client/client.Client.connect | connect}/{@linkcode SSEClientTransport.start | start}. * * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call {@linkcode SSEClientTransport.finishAuth} with the authorization code before retrying the connection. * diff --git a/packages/client/src/client/streamableHttp.ts b/packages/client/src/client/streamableHttp.ts index dab9b37ab..4606dc49f 100644 --- a/packages/client/src/client/streamableHttp.ts +++ b/packages/client/src/client/streamableHttp.ts @@ -88,7 +88,7 @@ export type StreamableHTTPClientTransportOptions = { * When an `authProvider` is specified and the connection is started: * 1. The connection is attempted with any existing access token from the `authProvider`. * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, {@linkcode OAuthClientProvider.redirectToAuthorization} is called, and an {@linkcode UnauthorizedError} will be thrown from {@linkcode index.Protocol.connect | connect}/{@linkcode StreamableHTTPClientTransport.start | start}. + * 3. If token refresh fails or no access token exists, and auth is required, {@linkcode OAuthClientProvider.redirectToAuthorization} is called, and an {@linkcode UnauthorizedError} will be thrown from {@linkcode client/client.Client.connect | connect}/{@linkcode StreamableHTTPClientTransport.start | start}. * * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call {@linkcode StreamableHTTPClientTransport.finishAuth} with the authorization code before retrying the connection. * diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 787cfd2f0..b09a01987 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,14 +1,59 @@ -export * from './client/auth.js'; -export * from './client/authExtensions.js'; -export * from './client/client.js'; -export * from './client/middleware.js'; -export * from './client/sse.js'; -export * from './client/stdio.js'; -export * from './client/streamableHttp.js'; -export * from './client/websocket.js'; +// Client-specific exports +export type { + AddClientAuthentication, + AuthResult, + ClientAuthMethod, + OAuthClientProvider, + OAuthDiscoveryState, + OAuthServerInfo +} from './client/auth.js'; +export { + auth, + buildDiscoveryUrls, + discoverAuthorizationServerMetadata, + discoverOAuthMetadata, + discoverOAuthProtectedResourceMetadata, + discoverOAuthServerInfo, + exchangeAuthorization, + extractResourceMetadataUrl, + extractWWWAuthenticateParams, + fetchToken, + isHttpsUrl, + parseErrorResponse, + prepareAuthorizationCodeRequest, + refreshAuthorization, + registerClient, + selectClientAuthMethod, + selectResourceURL, + startAuthorization, + UnauthorizedError +} from './client/auth.js'; +export type { + ClientCredentialsProviderOptions, + PrivateKeyJwtProviderOptions, + StaticPrivateKeyJwtProviderOptions +} from './client/authExtensions.js'; +export { + ClientCredentialsProvider, + createPrivateKeyJwtAuth, + PrivateKeyJwtProvider, + StaticPrivateKeyJwtProvider +} from './client/authExtensions.js'; +export type { ClientOptions } from './client/client.js'; +export { Client } from './client/client.js'; +export { getSupportedElicitationModes } from './client/client.js'; +export type { LoggingOptions, Middleware, RequestLogger } from './client/middleware.js'; +export { applyMiddlewares, createMiddleware, withLogging, withOAuth } from './client/middleware.js'; +export type { SSEClientTransportOptions } from './client/sse.js'; +export { SSEClientTransport, SseError } from './client/sse.js'; +export type { StdioServerParameters } from './client/stdio.js'; +export { DEFAULT_INHERITED_ENV_VARS, getDefaultEnvironment, StdioClientTransport } from './client/stdio.js'; +export type { StartSSEOptions, StreamableHTTPClientTransportOptions, StreamableHTTPReconnectionOptions } from './client/streamableHttp.js'; +export { StreamableHTTPClientTransport } from './client/streamableHttp.js'; +export { WebSocketClientTransport } from './client/websocket.js'; // experimental exports export * from './experimental/index.js'; -// re-export shared types -export * from '@modelcontextprotocol/core'; +// re-export curated public API from core +export * from '@modelcontextprotocol/core/public'; diff --git a/packages/client/tsconfig.json b/packages/client/tsconfig.json index 5c138f2f8..5e1df302a 100644 --- a/packages/client/tsconfig.json +++ b/packages/client/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"], "@modelcontextprotocol/client/_shims": ["./src/shimsNode.ts"] } diff --git a/packages/core/src/experimental/tasks/interfaces.ts b/packages/core/src/experimental/tasks/interfaces.ts index 8b3459b7c..98792a09e 100644 --- a/packages/core/src/experimental/tasks/interfaces.ts +++ b/packages/core/src/experimental/tasks/interfaces.ts @@ -14,7 +14,7 @@ import type { Result, Task, ToolExecution -} from '../../types/types.js'; +} from '../../types/index.js'; // ============================================================================ // Task Handler Types (for registerToolTask) diff --git a/packages/core/src/experimental/tasks/stores/inMemory.ts b/packages/core/src/experimental/tasks/stores/inMemory.ts index c6c4a3015..fbd7e39f5 100644 --- a/packages/core/src/experimental/tasks/stores/inMemory.ts +++ b/packages/core/src/experimental/tasks/stores/inMemory.ts @@ -3,7 +3,7 @@ * @experimental */ -import type { Request, RequestId, Result, Task } from '../../../types/types.js'; +import type { Request, RequestId, Result, Task } from '../../../types/index.js'; import type { CreateTaskOptions, QueuedMessage, TaskMessageQueue, TaskStore } from '../interfaces.js'; import { isTerminal } from '../interfaces.js'; diff --git a/packages/core/src/exports/types/index.ts b/packages/core/src/exports/types/index.ts index 47806ee8b..b957a8874 100644 --- a/packages/core/src/exports/types/index.ts +++ b/packages/core/src/exports/types/index.ts @@ -1 +1 @@ -export type * from '../../types/types.js'; +export type * from '../../types/index.js'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 56769c575..b22f91495 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -9,7 +9,7 @@ export * from './shared/stdio.js'; export * from './shared/toolNameValidation.js'; export * from './shared/transport.js'; export * from './shared/uriTemplate.js'; -export * from './types/types.js'; +export * from './types/index.js'; export * from './util/inMemory.js'; export * from './util/schema.js'; diff --git a/packages/core/src/publicExports.ts b/packages/core/src/publicExports.ts new file mode 100644 index 000000000..c685266dd --- /dev/null +++ b/packages/core/src/publicExports.ts @@ -0,0 +1,102 @@ +/** + * Curated public API exports for @modelcontextprotocol/core. + * + * This module defines the stable, public-facing API surface. Client and server + * packages re-export from here so that end users only see supported symbols. + * + * Internal utilities (Protocol class, stdio parsing, schema helpers, etc.) + * remain available via the internal barrel (@modelcontextprotocol/core) for + * use by client/server packages. + */ + +// Auth error classes +export * from './auth/errors.js'; + +// SDK error types (local errors that never cross the wire) +export { SdkError, SdkErrorCode } from './errors/sdkErrors.js'; + +// Auth TypeScript types (NOT Zod schemas like OAuthMetadataSchema) +export type { + AuthorizationServerMetadata, + OAuthClientInformation, + OAuthClientInformationFull, + OAuthClientInformationMixed, + OAuthClientMetadata, + OAuthClientRegistrationError, + OAuthErrorResponse, + OAuthMetadata, + OAuthProtectedResourceMetadata, + OAuthTokenRevocationRequest, + OAuthTokens, + OpenIdProviderDiscoveryMetadata, + OpenIdProviderMetadata +} from './shared/auth.js'; + +// Auth utilities +export { checkResourceAllowed, resourceUrlFromServerUrl } from './shared/authUtils.js'; + +// Metadata utilities +export { getDisplayName } from './shared/metadataUtils.js'; + +// Protocol types (NOT the Protocol class itself or mergeCapabilities) +export type { + BaseContext, + ClientContext, + NotificationOptions, + ProgressCallback, + ProtocolOptions, + RequestOptions, + RequestTaskStore, + ServerContext, + TaskContext, + TaskRequestOptions +} from './shared/protocol.js'; +export { DEFAULT_REQUEST_TIMEOUT_MSEC } from './shared/protocol.js'; + +// Response message types +export type { + BaseResponseMessage, + ErrorMessage, + ResponseMessage, + ResultMessage, + TaskCreatedMessage, + TaskStatusMessage +} from './shared/responseMessage.js'; +export { takeResult, toArrayAsync } from './shared/responseMessage.js'; + +// Transport types (NOT normalizeHeaders) +export type { FetchLike, Transport, TransportSendOptions } from './shared/transport.js'; +export { createFetchWithInit } from './shared/transport.js'; + +// URI Template +export type { Variables } from './shared/uriTemplate.js'; +export { UriTemplate } from './shared/uriTemplate.js'; + +// Types — all TypeScript types (standalone interfaces + schema-derived) +export * from './types/types.js'; + +// Constants +export * from './types/constants.js'; + +// Enums +export * from './types/enums.js'; + +// Error classes +export * from './types/errors.js'; + +// Type guards +export * from './types/guards.js'; + +// Schemas — temporarily included. Will be removed after decoupling from Zod schemas. +export * from './types/schemas.js'; + +// InMemoryTransport +export { InMemoryTransport } from './util/inMemory.js'; + +// Experimental task types and classes +export * from './experimental/index.js'; + +// Validator types and classes +export * from './validators/ajvProvider.js'; +export * from './validators/cfWorkerProvider.js'; +export type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from './validators/types.js'; diff --git a/packages/core/src/shared/metadataUtils.ts b/packages/core/src/shared/metadataUtils.ts index 73ea27c2c..1b11660e8 100644 --- a/packages/core/src/shared/metadataUtils.ts +++ b/packages/core/src/shared/metadataUtils.ts @@ -1,4 +1,4 @@ -import type { BaseMetadata } from '../types/types.js'; +import type { BaseMetadata } from '../types/index.js'; /** * Utilities for working with {@linkcode BaseMetadata} objects. diff --git a/packages/core/src/shared/protocol.ts b/packages/core/src/shared/protocol.ts index b82731582..2db92c823 100644 --- a/packages/core/src/shared/protocol.ts +++ b/packages/core/src/shared/protocol.ts @@ -39,7 +39,7 @@ import type { Task, TaskCreationParams, TaskStatusNotification -} from '../types/types.js'; +} from '../types/index.js'; import { CancelTaskResultSchema, CreateTaskResultSchema, @@ -58,7 +58,7 @@ import { RELATED_TASK_META_KEY, SUPPORTED_PROTOCOL_VERSIONS, TaskStatusNotificationSchema -} from '../types/types.js'; +} from '../types/index.js'; import type { AnyObjectSchema, AnySchema, SchemaOutput } from '../util/schema.js'; import { parseSchema } from '../util/schema.js'; import type { ResponseMessage } from './responseMessage.js'; @@ -687,7 +687,7 @@ export abstract class Protocol { /** * Attaches to the given transport, starts it, and starts listening for messages. * - * The {@linkcode Protocol} object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. */ async connect(transport: Transport): Promise { this._transport = transport; diff --git a/packages/core/src/shared/responseMessage.ts b/packages/core/src/shared/responseMessage.ts index b776d853c..25922a355 100644 --- a/packages/core/src/shared/responseMessage.ts +++ b/packages/core/src/shared/responseMessage.ts @@ -1,4 +1,4 @@ -import type { Result, Task } from '../types/types.js'; +import type { Result, Task } from '../types/index.js'; /** * Base message type for the response stream. diff --git a/packages/core/src/shared/stdio.ts b/packages/core/src/shared/stdio.ts index 49c658b96..773860770 100644 --- a/packages/core/src/shared/stdio.ts +++ b/packages/core/src/shared/stdio.ts @@ -1,5 +1,5 @@ -import type { JSONRPCMessage } from '../types/types.js'; -import { JSONRPCMessageSchema } from '../types/types.js'; +import type { JSONRPCMessage } from '../types/index.js'; +import { JSONRPCMessageSchema } from '../types/index.js'; /** * Buffers a continuous stdio stream into discrete JSON-RPC messages. diff --git a/packages/core/src/shared/transport.ts b/packages/core/src/shared/transport.ts index a04e054ba..889b319a9 100644 --- a/packages/core/src/shared/transport.ts +++ b/packages/core/src/shared/transport.ts @@ -1,4 +1,4 @@ -import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/types.js'; +import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/index.js'; export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; @@ -77,7 +77,7 @@ export interface Transport { * * This method should only be called after callbacks are installed, or else messages may be lost. * - * NOTE: This method should not be called explicitly when using {@linkcode @modelcontextprotocol/client!client/client.Client | Client}, {@linkcode @modelcontextprotocol/server!server/server.Server | Server}, or {@linkcode @modelcontextprotocol/server!index.Protocol | Protocol} classes, as they will implicitly call {@linkcode Transport.start | start()}. + * NOTE: This method should not be called explicitly when using {@linkcode @modelcontextprotocol/client!client/client.Client | Client} or {@linkcode @modelcontextprotocol/server!server/server.Server | Server} classes, as they will implicitly call {@linkcode Transport.start | start()}. */ start(): Promise; diff --git a/packages/core/src/types/constants.ts b/packages/core/src/types/constants.ts new file mode 100644 index 000000000..878d5111c --- /dev/null +++ b/packages/core/src/types/constants.ts @@ -0,0 +1,15 @@ +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']; + +export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; + +/* 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/types/enums.ts b/packages/core/src/types/enums.ts new file mode 100644 index 000000000..0d80242a8 --- /dev/null +++ b/packages/core/src/types/enums.ts @@ -0,0 +1,16 @@ +/** + * Error codes for protocol errors that cross the wire as JSON-RPC error responses. + * These follow the JSON-RPC specification and MCP-specific extensions. + */ +export enum ProtocolErrorCode { + // Standard JSON-RPC error codes + ParseError = -32_700, + InvalidRequest = -32_600, + MethodNotFound = -32_601, + InvalidParams = -32_602, + InternalError = -32_603, + + // MCP-specific error codes + ResourceNotFound = -32_002, + UrlElicitationRequired = -32_042 +} diff --git a/packages/core/src/types/errors.ts b/packages/core/src/types/errors.ts new file mode 100644 index 000000000..4314bdff7 --- /dev/null +++ b/packages/core/src/types/errors.ts @@ -0,0 +1,49 @@ +import { ProtocolErrorCode } from './enums.js'; +import type { ElicitRequestURLParams } from './schemas.js'; + +/** + * Protocol errors are JSON-RPC errors that cross the wire as error responses. + * They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. + */ +export class ProtocolError extends Error { + constructor( + public readonly code: number, + message: string, + public readonly data?: unknown + ) { + super(`MCP error ${code}: ${message}`); + this.name = 'ProtocolError'; + } + + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code: number, message: string, data?: unknown): ProtocolError { + // Check for specific error types + if (code === ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data as { elicitations?: unknown[] }; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations as ElicitRequestURLParams[], message); + } + } + + // Default to generic ProtocolError + return new ProtocolError(code, message, data); + } +} + +/** + * Specialized error type when a tool requires a URL mode elicitation. + * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. + */ +export class UrlElicitationRequiredError extends ProtocolError { + constructor(elicitations: ElicitRequestURLParams[], message: string = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { + super(ProtocolErrorCode.UrlElicitationRequired, message, { + elicitations: elicitations + }); + } + + get elicitations(): ElicitRequestURLParams[] { + return (this.data as { elicitations: ElicitRequestURLParams[] })?.elicitations ?? []; + } +} diff --git a/packages/core/src/types/guards.ts b/packages/core/src/types/guards.ts new file mode 100644 index 000000000..355b56c63 --- /dev/null +++ b/packages/core/src/types/guards.ts @@ -0,0 +1,70 @@ +import type { + CompleteRequest, + InitializedNotification, + InitializeRequest, + JSONRPCErrorResponse, + JSONRPCNotification, + JSONRPCRequest, + JSONRPCResultResponse, + TaskAugmentedRequestParams +} from './schemas.js'; +import { + InitializedNotificationSchema, + InitializeRequestSchema, + JSONRPCErrorResponseSchema, + JSONRPCNotificationSchema, + JSONRPCRequestSchema, + JSONRPCResultResponseSchema, + TaskAugmentedRequestParamsSchema +} from './schemas.js'; +import type { CompleteRequestPrompt, CompleteRequestResourceTemplate } from './types.js'; + +export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success; + +export const isJSONRPCNotification = (value: unknown): value is JSONRPCNotification => JSONRPCNotificationSchema.safeParse(value).success; + +/** + * Checks if a value is a valid {@linkcode JSONRPCResultResponse}. + * @param value - The value to check. + * + * @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. + */ +export const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse => + JSONRPCResultResponseSchema.safeParse(value).success; + +/** + * Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. + * @param value - The value to check. + * + * @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. + */ +export const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse => + JSONRPCErrorResponseSchema.safeParse(value).success; + +/** + * Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. + * @param value - The value to check. + * + * @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. + */ +export const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams => + TaskAugmentedRequestParamsSchema.safeParse(value).success; + +export const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success; + +export const isInitializedNotification = (value: unknown): value is InitializedNotification => + InitializedNotificationSchema.safeParse(value).success; + +export function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt { + if (request.params.ref.type !== 'ref/prompt') { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void (request as CompleteRequestPrompt); +} + +export function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate { + if (request.params.ref.type !== 'ref/resource') { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); + } + void (request as CompleteRequestResourceTemplate); +} diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts new file mode 100644 index 000000000..29ed78835 --- /dev/null +++ b/packages/core/src/types/index.ts @@ -0,0 +1,8 @@ +// Internal barrel — re-exports everything for use within the SDK packages. +// External consumers should use publicExports.ts instead for a curated public API. +export * from './constants.js'; +export * from './enums.js'; +export * from './errors.js'; +export * from './guards.js'; +export * from './schemas.js'; +export * from './types.js'; diff --git a/packages/core/src/types/schemas.ts b/packages/core/src/types/schemas.ts new file mode 100644 index 000000000..6b20b7c91 --- /dev/null +++ b/packages/core/src/types/schemas.ts @@ -0,0 +1,2454 @@ +import * as z from 'zod/v4'; + +import { JSONRPC_VERSION, RELATED_TASK_META_KEY } from './constants.js'; + +/* JSON types */ +export type JSONValue = string | number | boolean | null | JSONObject | JSONArray; +export type JSONObject = { [key: string]: JSONValue }; +export type JSONArray = JSONValue[]; + +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); + +/** + * Utility types + */ +export type ExpandRecursively = T extends object ? (T extends infer O ? { [K in keyof O]: ExpandRecursively } : never) : T; +/** + * 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(); + +/** + * Task creation parameters, used to ask that the server create a task to represent a request. + */ +export const TaskCreationParamsSchema = z.looseObject({ + /** + * 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()]).optional(), + + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.number().optional() +}); + +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`. + */ +export const RelatedTaskMetadataSchema = z.object({ + taskId: z.string() +}); + +const RequestMetaSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); + +/** + * Common params for any request. + */ +const BaseRequestParamsSchema = z.object({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); + +/** + * Common params for any task-augmented request. + */ +export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a {@linkcode CreateTaskResult} immediately, and the actual result can be + * retrieved later via {@linkcode GetTaskPayloadRequest | tasks/result}. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() +}); + +export const RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.loose().optional() +}); + +const NotificationsParamsSchema = z.object({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); + +export const NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.loose().optional() +}); + +export const ResultSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); + +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export const RequestIdSchema = z.union([z.string(), z.number().int()]); + +/** + * 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 {@linkcode 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. + */ +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. + */ +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. + */ + 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. + */ + 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. + */ + tasks: ClientTasksCapabilitySchema.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. + */ + 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. + */ + tasks: ServerTasksCapabilitySchema.optional() +}); + +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export const InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); + +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export const InitializedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/initialized'), + params: NotificationsParamsSchema.optional() +}); + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export const PingRequestSchema = RequestSchema.extend({ + method: z.literal('ping'), + params: BaseRequestParamsSchema.optional() +}); + +/* Progress notifications */ +export const ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) +}); + +export const ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: ProgressNotificationParamsSchema +}); + +export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() +}); + +/* Pagination */ +export const PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() +}); + +export const PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() +}); + +/** + * The status of a task. + * */ +export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); + +/* Tasks */ +/** + * A pollable state object associated with a request. + */ +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. + */ +export const CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema +}); + +/** + * Parameters for task status notification. + */ +export const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); + +/** + * A notification sent when a task's status changes. + */ +export const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tasks/status'), + params: TaskStatusNotificationParamsSchema +}); + +/** + * A request to get the state of a specific task. + */ +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. + */ +export const GetTaskResultSchema = ResultSchema.merge(TaskSchema); + +/** + * A request to get the result of a specific task. + */ +export const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/result'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); + +/** + * The response to a {@linkcode GetTaskPayloadRequest | tasks/result} request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the {@linkcode CallToolResult} structure. + * + */ +export const GetTaskPayloadResultSchema = ResultSchema.loose(); + +/** + * A request to list tasks. + */ +export const ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tasks/list') +}); + +/** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + */ +export const ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: z.array(TaskSchema) +}); + +/** + * A request to cancel a specific task. + */ +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. + */ +export const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); + +/* 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()), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.optional(z.looseObject({})) +}); + +/** + * A template description for resources available on the server. + */ +export const ResourceTemplateSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.optional(z.looseObject({})) +}); + +/** + * Sent from the client to request a list of resources the server has. + */ +export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/list') +}); + +/** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ +export const ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: z.array(ResourceSchema) +}); + +/** + * Sent from the client to request a list of resource templates the server has. + */ +export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') +}); + +/** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ +export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: z.array(ResourceTemplateSchema) +}); + +export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() +}); + +/** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ +export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; + +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export const ReadResourceRequestSchema = RequestSchema.extend({ + method: z.literal('resources/read'), + params: ReadResourceRequestParamsSchema +}); + +/** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ +export const ReadResourceResultSchema = ResultSchema.extend({ + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) +}); + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() +}); + +export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ +export const SubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: SubscribeRequestParamsSchema +}); + +export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ +export const UnsubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: UnsubscribeRequestParamsSchema +}); + +/** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ +export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string() +}); + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ +export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: ResourceUpdatedNotificationParamsSchema +}); + +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +export const PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) +}); + +/** + * A prompt or prompt template that the server offers. + */ +export const PromptSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.optional(z.looseObject({})) +}); + +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') +}); + +/** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ +export const ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: z.array(PromptSchema) +}); + +/** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ +export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() +}); +/** + * Used by the client to get a prompt provided by the server. + */ +export const GetPromptRequestSchema = RequestSchema.extend({ + method: z.literal('prompts/get'), + params: GetPromptRequestParamsSchema +}); + +/** + * Text provided to or from an LLM. + */ +export const TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); + +/** + * An image provided to or from an LLM. + */ +export const ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); + +/** + * Audio content provided to or from an LLM. + */ +export const AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); + +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +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 {@linkcode 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 {@linkcode 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 {@linkcode ToolAnnotations} + * received from untrusted servers. + */ +export const ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + + /** + * If `true`, the tool does not modify its environment. + * + * Default: `false` + */ + readOnlyHint: z.boolean().optional(), + + /** + * If `true`, the tool may perform destructive updates to its environment. + * If `false`, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: `true` + */ + destructiveHint: z.boolean().optional(), + + /** + * If `true`, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: `false` + */ + idempotentHint: z.boolean().optional(), + + /** + * If `true`, this tool may interact with an "open world" of external + * entities. If `false`, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: `true` + */ + openWorldHint: z.boolean().optional() +}); + +/** + * Execution-related properties for a tool. + */ +export const ToolExecutionSchema = z.object({ + /** + * Indicates the tool's preference for task-augmented execution. + * - `"required"`: Clients MUST invoke the tool as a task + * - `"optional"`: Clients MAY invoke the tool as a task or normal request + * - `"forbidden"`: Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to `"forbidden"`. + */ + taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() +}); + +/** + * Definition for a tool the client can call. + */ +export const ToolSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have `type: 'object'` at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), JSONValueSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the `structuredContent` field of a {@linkcode CallToolResult}. + * Must have `type: 'object'` at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), JSONValueSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); + +/** + * Sent from the client to request a list of tools the server has. + */ +export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tools/list') +}); + +/** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ +export const ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: z.array(ToolSchema) +}); + +/** + * The server's response to a tool call. + */ +export const CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the {@linkcode Tool} does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(ContentBlockSchema).default([]), + + /** + * An object containing structured tool output. + * + * If the {@linkcode Tool} defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be `false` (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to `true`, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.boolean().optional() +}); + +/** + * {@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. + */ +export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); + +/** + * Parameters for a `logging/setLevel` request. + */ +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. + */ +export const SetLevelRequestSchema = RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: SetLevelRequestParamsSchema +}); + +/** + * Parameters for a `notifications/message` notification. + */ +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. + */ +export const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: LoggingMessageNotificationParamsSchema +}); + +/* Sampling */ +/** + * Hints to use for model selection. + */ +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. + */ +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. + */ +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 {@linkcode ToolUseContent}. + */ +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).default([]), + structuredContent: z.object({}).loose().optional(), + isError: z.boolean().optional(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on `_meta` usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); + +/** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + */ +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. + */ +export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); + +/** + * Describes a message issued to or received from an LLM API. + */ +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. + */ +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"`. Values `"thisServer"` and `"allServers"` are soft-deprecated. Servers SHOULD only use these values if the client + * declares {@linkcode ClientCapabilities}.`sampling.context`. These values may be removed in future spec releases. + */ + 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 {@linkcode 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 {@linkcode 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. + */ +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. + */ +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. + */ +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 {@linkcode 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() + }) +}); + +/** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ +export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.string(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() +}); + +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); + +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: ElicitRequestParamsSchema +}); + +/** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() +}); + +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: ElicitationCompleteNotificationParamsSchema +}); + +/** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ +export const ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - `"accept"`: User submitted the form/confirmed the action + * - `"decline"`: User explicitly declined the action + * - `"cancel"`: User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is `"accept"`. + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize `null` to `undefined` for leniency while maintaining type compatibility. + */ + content: z.preprocess( + val => (val === null ? undefined : val), + z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() + ) +}); + +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +export const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); + +/** + * Identifies a prompt. + */ +export const PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() +}); + +/** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ +export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() +}); +/** + * A request from the client to the server, to ask for completion options. + */ +export const CompleteRequestSchema = RequestSchema.extend({ + method: z.literal('completion/complete'), + params: CompleteRequestParamsSchema +}); + +/** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ +export const CompleteResultSchema = ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) +}); + +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +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. + */ +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. + */ +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. + */ +export const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() +}); + +/* Client messages */ +export const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); + +export const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema +]); + +export const ClientResultSchema = z.union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); + +/* Server messages */ +export const ServerRequestSchema = z.union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); + +export const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema +]); + +export const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); + +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive + ? T + : T extends Array + ? Array> + : T extends Set + ? Set> + : T extends Map + ? Map, Flatten> + : T extends object + ? { [K in keyof T]: Flatten } + : T; + +type Infer = Flatten>; + +/* JSON-RPC types */ +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type TaskAugmentedRequestParams = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCErrorResponse = Infer; +export type JSONRPCResultResponse = Infer; + +export type JSONRPCMessage = Infer; +export type RequestParams = Infer; +export type NotificationParams = Infer; + +/* Empty result */ +export type EmptyResult = Infer; + +/* Cancellation */ +export type CancelledNotificationParams = Infer; +export type CancelledNotification = Infer; + +/* Base Metadata */ +export type Icon = Infer; +export type Icons = Infer; +export type BaseMetadata = Infer; +export type Annotations = Infer; +export type Role = Infer; + +/* Initialization */ +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequestParams = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; + +/* Ping */ +export type PingRequest = Infer; + +/* Progress notifications */ +export type Progress = Infer; +export type ProgressNotificationParams = Infer; +export type ProgressNotification = Infer; + +/* Tasks */ +export type Task = Infer; +export type TaskStatus = Infer; +export type TaskCreationParams = Infer; +export type TaskMetadata = Infer; +export type RelatedTaskMetadata = Infer; +export type CreateTaskResult = Infer; +export type TaskStatusNotificationParams = Infer; +export type TaskStatusNotification = Infer; +export type GetTaskRequest = Infer; +export type GetTaskResult = Infer; +export type GetTaskPayloadRequest = Infer; +export type ListTasksRequest = Infer; +export type ListTasksResult = Infer; +export type CancelTaskRequest = Infer; +export type CancelTaskResult = Infer; +export type GetTaskPayloadResult = Infer; + +/* Pagination */ +export type PaginatedRequestParams = Infer; +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; + +/* Resources */ +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +// TODO: Overlaps with exported `ResourceTemplate` class from `server`. +export type ResourceTemplateType = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ResourceRequestParams = Infer; +export type ReadResourceRequestParams = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequestParams = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequestParams = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotificationParams = Infer; +export type ResourceUpdatedNotification = Infer; + +/* Prompts */ +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequestParams = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type ToolUseContent = Infer; +export type ToolResultContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; + +/* Tools */ +export type ToolAnnotations = Infer; +export type ToolExecution = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolRequestParams = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; + +/* Logging */ +export type LoggingLevel = Infer; +export type SetLevelRequestParams = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; +export type LoggingMessageNotification = Infer; + +/* Sampling */ +export type ToolChoice = Infer; +export type ModelHint = Infer; +export type ModelPreferences = Infer; +export type SamplingContent = Infer; +export type SamplingMessageContentBlock = Infer; +export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; +export type CreateMessageResultWithTools = Infer; + +/* Elicitation */ +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; + +export type EnumSchema = Infer; +export type UntitledSingleSelectEnumSchema = Infer; +export type TitledSingleSelectEnumSchema = Infer; +export type LegacyTitledEnumSchema = Infer; +export type UntitledMultiSelectEnumSchema = Infer; +export type TitledMultiSelectEnumSchema = Infer; +export type SingleSelectEnumSchema = Infer; +export type MultiSelectEnumSchema = Infer; + +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; +export type ElicitRequestFormParams = Infer; +export type ElicitRequestURLParams = Infer; +export type ElicitRequest = Infer; +export type ElicitationCompleteNotificationParams = Infer; +export type ElicitationCompleteNotification = Infer; +export type ElicitResult = Infer; + +/* Autocomplete */ +export type ResourceTemplateReference = Infer; +export type PromptReference = Infer; +export type CompleteRequestParams = Infer; +export type CompleteRequest = Infer; +export type CompleteResult = Infer; + +/* Roots */ +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; + +/* Client messages */ +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; + +/* Server messages */ +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; + +/* Protocol type maps */ +type MethodToTypeMap = { + [T in U as T extends { method: infer M extends string } ? M : never]: T; +}; +export type RequestMethod = ClientRequest['method'] | ServerRequest['method']; +export type NotificationMethod = ClientNotification['method'] | ServerNotification['method']; +export type RequestTypeMap = MethodToTypeMap; +export type NotificationTypeMap = MethodToTypeMap; +export type ResultTypeMap = { + ping: EmptyResult; + initialize: InitializeResult; + 'completion/complete': CompleteResult; + 'logging/setLevel': EmptyResult; + 'prompts/get': GetPromptResult; + 'prompts/list': ListPromptsResult; + 'resources/list': ListResourcesResult; + 'resources/templates/list': ListResourceTemplatesResult; + 'resources/read': ReadResourceResult; + 'resources/subscribe': EmptyResult; + 'resources/unsubscribe': EmptyResult; + 'tools/call': CallToolResult | CreateTaskResult; + 'tools/list': ListToolsResult; + 'sampling/createMessage': CreateMessageResult | CreateMessageResultWithTools | CreateTaskResult; + 'elicitation/create': ElicitResult | CreateTaskResult; + 'roots/list': ListRootsResult; + 'tasks/get': GetTaskResult; + 'tasks/result': Result; + 'tasks/list': ListTasksResult; + 'tasks/cancel': CancelTaskResult; +}; + +/* Runtime schema lookup — result schemas by method */ +const resultSchemas: Record = { + ping: EmptyResultSchema, + initialize: InitializeResultSchema, + 'completion/complete': CompleteResultSchema, + 'logging/setLevel': EmptyResultSchema, + 'prompts/get': GetPromptResultSchema, + 'prompts/list': ListPromptsResultSchema, + 'resources/list': ListResourcesResultSchema, + 'resources/templates/list': ListResourceTemplatesResultSchema, + 'resources/read': ReadResourceResultSchema, + 'resources/subscribe': EmptyResultSchema, + 'resources/unsubscribe': EmptyResultSchema, + 'tools/call': z.union([CallToolResultSchema, CreateTaskResultSchema]), + 'tools/list': ListToolsResultSchema, + 'sampling/createMessage': z.union([CreateMessageResultWithToolsSchema, CreateTaskResultSchema]), + 'elicitation/create': z.union([ElicitResultSchema, CreateTaskResultSchema]), + 'roots/list': ListRootsResultSchema, + 'tasks/get': GetTaskResultSchema, + 'tasks/result': ResultSchema, + 'tasks/list': ListTasksResultSchema, + 'tasks/cancel': CancelTaskResultSchema +}; + +/** + * Gets the Zod schema for validating results of a given request method. + * @see getRequestSchema for explanation of the internal type assertion. + */ +export function getResultSchema(method: M): z.ZodType { + return resultSchemas[method] as unknown as z.ZodType; +} + +/* Runtime schema lookup — request schemas by method */ +type RequestSchemaType = (typeof ClientRequestSchema.options)[number] | (typeof ServerRequestSchema.options)[number]; +type NotificationSchemaType = (typeof ClientNotificationSchema.options)[number] | (typeof ServerNotificationSchema.options)[number]; + +function buildSchemaMap(schemas: readonly T[]): Record { + const map: Record = {}; + for (const schema of schemas) { + const method = schema.shape.method.value; + map[method] = schema; + } + return map; +} + +const requestSchemas = buildSchemaMap([...ClientRequestSchema.options, ...ServerRequestSchema.options] as const) as Record< + RequestMethod, + RequestSchemaType +>; +const notificationSchemas = buildSchemaMap([...ClientNotificationSchema.options, ...ServerNotificationSchema.options] as const) as Record< + NotificationMethod, + NotificationSchemaType +>; + +/** + * Gets the Zod schema for a given request method. + * The return type is a ZodType that parses to RequestTypeMap[M], allowing callers + * to use schema.parse() without needing additional type assertions. + * + * Note: The internal cast is necessary because TypeScript can't correlate the + * Record-based schema lookup with the MethodToTypeMap-based RequestTypeMap + * when M is a generic type parameter. Both compute to the same type at + * instantiation, but TypeScript can't prove this statically. + */ +export function getRequestSchema(method: M): z.ZodType { + return requestSchemas[method] as unknown as z.ZodType; +} + +/** + * Gets the Zod schema for a given notification method. + * @see getRequestSchema for explanation of the internal type assertion. + */ +export function getNotificationSchema(method: M): z.ZodType { + return notificationSchemas[method] as unknown as z.ZodType; +} diff --git a/packages/core/src/types/types.ts b/packages/core/src/types/types.ts index 6ac79777b..462b6100e 100644 --- a/packages/core/src/types/types.ts +++ b/packages/core/src/types/types.ts @@ -1,24 +1,16 @@ -import * as z from 'zod/v4'; - -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']; - -export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; - -/* JSON types */ -export type JSONValue = string | number | boolean | null | JSONObject | JSONArray; -export type JSONObject = { [key: string]: JSONValue }; -export type JSONArray = JSONValue[]; - -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); - -/* JSON-RPC types */ -export const JSONRPC_VERSION = '2.0'; +import type { INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, METHOD_NOT_FOUND, PARSE_ERROR } from './constants.js'; +import type { + CompleteRequest, + CompleteRequestParams, + CreateMessageRequestParams, + ExpandRecursively, + Prompt, + PromptReference, + RequestMeta, + Resource, + ResourceTemplateReference, + Tool +} from './schemas.js'; /** * Information about a validated access token, provided to request handlers. @@ -57,193 +49,6 @@ export interface AuthInfo { extra?: Record; } -/** - * Utility types - */ -type ExpandRecursively = T extends object ? (T extends infer O ? { [K in keyof O]: ExpandRecursively } : never) : T; -/** - * 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(); - -/** - * Task creation parameters, used to ask that the server create a task to represent a request. - */ -export const TaskCreationParamsSchema = z.looseObject({ - /** - * 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()]).optional(), - - /** - * Time in milliseconds to wait between task status requests. - */ - pollInterval: z.number().optional() -}); - -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`. - */ -export const RelatedTaskMetadataSchema = z.object({ - taskId: z.string() -}); - -const RequestMetaSchema = z.looseObject({ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: ProgressTokenSchema.optional(), - /** - * If specified, this request is related to the provided task. - */ - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); - -/** - * Common params for any request. - */ -const BaseRequestParamsSchema = z.object({ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); - -/** - * Common params for any task-augmented request. - */ -export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a {@linkcode CreateTaskResult} immediately, and the actual result can be - * retrieved later via {@linkcode GetTaskPayloadRequest | tasks/result}. - * - * Task augmentation is subject to capability negotiation - receivers MUST declare support - * for task augmentation of specific request types in their capabilities. - */ - task: TaskMetadataSchema.optional() -}); - -/** - * Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. - * @param value - The value to check. - * - * @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. - */ -export const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams => - TaskAugmentedRequestParamsSchema.safeParse(value).success; - -export const RequestSchema = z.object({ - method: z.string(), - params: BaseRequestParamsSchema.loose().optional() -}); - -const NotificationsParamsSchema = z.object({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); - -export const NotificationSchema = z.object({ - method: z.string(), - params: NotificationsParamsSchema.loose().optional() -}); - -export const ResultSchema = z.looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); - -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); - -/** - * A request that expects a response. - */ -export const JSONRPCRequestSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape - }) - .strict(); - -export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success; - -/** - * A notification which does not expect a response. - */ -export const JSONRPCNotificationSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - ...NotificationSchema.shape - }) - .strict(); - -export const isJSONRPCNotification = (value: unknown): value is JSONRPCNotification => JSONRPCNotificationSchema.safeParse(value).success; - -/** - * A successful (non-error) response to a request. - */ -export const JSONRPCResultResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema - }) - .strict(); - -/** - * Checks if a value is a valid {@linkcode JSONRPCResultResponse}. - * @param value - The value to check. - * - * @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. - */ -export const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse => - JSONRPCResultResponseSchema.safeParse(value).success; - -/** - * Error codes for protocol errors that cross the wire as JSON-RPC error responses. - * These follow the JSON-RPC specification and MCP-specific extensions. - */ -export enum ProtocolErrorCode { - // Standard JSON-RPC error codes - ParseError = -32_700, - InvalidRequest = -32_600, - MethodNotFound = -32_601, - InvalidParams = -32_602, - InternalError = -32_603, - - // MCP-specific error codes - ResourceNotFound = -32_002, - UrlElicitationRequired = -32_042 -} - -/* 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; - type JSONRPCErrorObject = { code: number; message: string; data?: unknown }; export interface ParseError extends JSONRPCErrorObject { @@ -263,2486 +68,114 @@ export interface InternalError extends JSONRPCErrorObject { } /** - * 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(); - -/** - * Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. - * @param value - The value to check. - * - * @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. - */ -export const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse => - JSONRPCErrorResponseSchema.safeParse(value).success; - -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. + * Callback type for list changed notifications. */ -export const EmptyResultSchema = ResultSchema.strict(); +export type ListChangedCallback = (error: Error | null, items: T[] | null) => void; -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. + * Options for subscribing to list changed notifications. * - * 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}. + * @typeParam T - The type of items in the list ({@linkcode Tool}, {@linkcode Prompt}, or {@linkcode Resource}) */ -export const IconSchema = z.object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), +export type ListChangedOptions = { /** - * Optional MIME type for the icon. + * If `true`, the list will be refreshed automatically when a list changed notification is received. + * @default true */ - mimeType: z.string().optional(), + autoRefresh?: boolean; /** - * 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. + * Debounce time in milliseconds. Set to `0` to disable. + * @default 300 */ - sizes: z.array(z.string()).optional(), + debounceMs?: number; /** - * 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. + * Callback invoked when the list changes. * - * If not provided, the client should assume the icon can be used with any theme. + * If `autoRefresh` is `true`, `items` contains the updated list. + * If `autoRefresh` is `false`, `items` is `null` (caller should refresh manually). */ - theme: z.enum(['light', 'dark']).optional() -}); + onChanged: ListChangedCallback; +}; /** - * Base schema to add `icons` property. + * Configuration for list changed notification handlers. * + * Use this to configure handlers for tools, prompts, and resources list changes + * when creating a client. + * + * Note: Handlers are only activated if the server advertises the corresponding + * `listChanged` capability (e.g., `tools.listChanged: true`). If the server + * doesn't advertise this capability, the handler will not be set up. */ -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 {@linkcode 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. - */ -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. - */ -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. - */ - 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. - */ - 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. - */ - tasks: ClientTasksCapabilitySchema.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 -}); - -export const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success; - -/** - * 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. - */ - 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(), +export type ListChangedHandlers = { /** - * Present if the server offers any resources to read. + * Handler for tool list changes. */ - 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(), + tools?: ListChangedOptions; /** - * Present if the server offers any tools to call. + * Handler for prompt list changes. */ - tools: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.boolean().optional() - }) - .optional(), + prompts?: ListChangedOptions; /** - * Present if the server supports task creation. + * Handler for resource list changes. */ - tasks: ServerTasksCapabilitySchema.optional() -}); + resources?: ListChangedOptions; +}; /** - * After receiving an initialize request from the client, the server sends this response. + * Information about the incoming request. */ -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, +export interface RequestInfo { /** - * 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. + * The headers of the request. */ - 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() -}); - -export const isInitializedNotification = (value: unknown): value is InitializedNotification => - InitializedNotificationSchema.safeParse(value).success; + headers: Headers; +} -/* 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. + * Extra information about a message. */ -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()), +export interface MessageExtraInfo { /** - * An optional message describing the current progress. + * The request information. */ - message: z.optional(z.string()) -}); + requestInfo?: RequestInfo; -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. + * The authentication information. */ - 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 -}); + authInfo?: AuthInfo; -export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. + * Callback to close the SSE stream for this request, triggering client reconnection. + * Only available when using {@linkcode @modelcontextprotocol/node!streamableHttp.NodeStreamableHTTPServerTransport | NodeStreamableHTTPServerTransport} with eventStore configured. */ - cursor: CursorSchema.optional() -}); - -/* Pagination */ -export const PaginatedRequestSchema = RequestSchema.extend({ - params: PaginatedRequestParamsSchema.optional() -}); + closeSSEStream?: () => void; -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. + * Callback to close the standalone GET SSE stream, triggering client reconnection. + * Only available when using {@linkcode @modelcontextprotocol/node!streamableHttp.NodeStreamableHTTPServerTransport | NodeStreamableHTTPServerTransport} with eventStore configured. */ - nextCursor: CursorSchema.optional() -}); - -/** - * The status of a task. - * */ -export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); + closeStandaloneSSEStream?: () => void; +} -/* Tasks */ -/** - * A pollable state object associated with a request. - */ -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()) -}); +export type MetaObject = Record; +export type RequestMetaObject = RequestMeta; /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. + * {@linkcode CreateMessageRequestParams} without tools - for backwards-compatible overload. + * Excludes tools/toolChoice to indicate they should not be provided. */ -export const CreateTaskResultSchema = ResultSchema.extend({ - task: TaskSchema -}); +export type CreateMessageRequestParamsBase = Omit; /** - * Parameters for task status notification. + * {@linkcode CreateMessageRequestParams} with required tools - for tool-enabled overload. */ -export const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +export interface CreateMessageRequestParamsWithTools extends CreateMessageRequestParams { + tools: Tool[]; +} -/** - * A notification sent when a task's status changes. - */ -export const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tasks/status'), - params: TaskStatusNotificationParamsSchema -}); - -/** - * A request to get the state of a specific task. - */ -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. - */ -export const GetTaskResultSchema = ResultSchema.merge(TaskSchema); - -/** - * A request to get the result of a specific task. - */ -export const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/result'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); - -/** - * The response to a {@linkcode GetTaskPayloadRequest | tasks/result} request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the {@linkcode CallToolResult} structure. - * - */ -export const GetTaskPayloadResultSchema = ResultSchema.loose(); - -/** - * A request to list tasks. - */ -export const ListTasksRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tasks/list') -}); - -/** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - */ -export const ListTasksResultSchema = PaginatedResultSchema.extend({ - tasks: z.array(TaskSchema) -}); - -/** - * A request to cancel a specific task. - */ -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. - */ -export const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); - -/* 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()), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.optional(z.looseObject({})) -}); - -/** - * A template description for resources available on the server. - */ -export const ResourceTemplateSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: z.string(), - - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType: z.optional(z.string()), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.optional(z.looseObject({})) -}); - -/** - * Sent from the client to request a list of resources the server has. - */ -export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/list') -}); - -/** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ -export const ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: z.array(ResourceSchema) -}); - -/** - * Sent from the client to request a list of resource templates the server has. - */ -export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/templates/list') -}); - -/** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ -export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: z.array(ResourceTemplateSchema) -}); - -export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: z.string() -}); - -/** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ -export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; - -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export const ReadResourceRequestSchema = RequestSchema.extend({ - method: z.literal('resources/read'), - params: ReadResourceRequestParamsSchema -}); - -/** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ -export const ReadResourceResultSchema = ResultSchema.extend({ - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); - -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ -export const SubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/subscribe'), - params: SubscribeRequestParamsSchema -}); - -export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ -export const UnsubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/unsubscribe'), - params: UnsubscribeRequestParamsSchema -}); - -/** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ -export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: z.string() -}); - -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ -export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: ResourceUpdatedNotificationParamsSchema -}); - -/* Prompts */ -/** - * Describes an argument that a prompt can accept. - */ -export const PromptArgumentSchema = z.object({ - /** - * The name of the argument. - */ - name: z.string(), - /** - * A human-readable description of the argument. - */ - description: z.optional(z.string()), - /** - * Whether this argument must be provided. - */ - required: z.optional(z.boolean()) -}); - -/** - * A prompt or prompt template that the server offers. - */ -export const PromptSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * An optional description of what this prompt provides - */ - description: z.optional(z.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: z.optional(z.array(PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.optional(z.looseObject({})) -}); - -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('prompts/list') -}); - -/** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ -export const ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: z.array(PromptSchema) -}); - -/** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ -export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.record(z.string(), z.string()).optional() -}); -/** - * Used by the client to get a prompt provided by the server. - */ -export const GetPromptRequestSchema = RequestSchema.extend({ - method: z.literal('prompts/get'), - params: GetPromptRequestParamsSchema -}); - -/** - * Text provided to or from an LLM. - */ -export const TextContentSchema = z.object({ - type: z.literal('text'), - /** - * The text content of the message. - */ - text: z.string(), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * An image provided to or from an LLM. - */ -export const ImageContentSchema = z.object({ - type: z.literal('image'), - /** - * The base64-encoded image data. - */ - data: Base64Schema, - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: z.string(), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * Audio content provided to or from an LLM. - */ -export const AudioContentSchema = z.object({ - type: z.literal('audio'), - /** - * The base64-encoded audio data. - */ - data: Base64Schema, - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: z.string(), - - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - */ -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 {@linkcode 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 {@linkcode 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 {@linkcode ToolAnnotations} - * received from untrusted servers. - */ -export const ToolAnnotationsSchema = z.object({ - /** - * A human-readable title for the tool. - */ - title: z.string().optional(), - - /** - * If `true`, the tool does not modify its environment. - * - * Default: `false` - */ - readOnlyHint: z.boolean().optional(), - - /** - * If `true`, the tool may perform destructive updates to its environment. - * If `false`, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: `true` - */ - destructiveHint: z.boolean().optional(), - - /** - * If `true`, calling the tool repeatedly with the same arguments - * will have no additional effect on its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: `false` - */ - idempotentHint: z.boolean().optional(), - - /** - * If `true`, this tool may interact with an "open world" of external - * entities. If `false`, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: `true` - */ - openWorldHint: z.boolean().optional() -}); - -/** - * Execution-related properties for a tool. - */ -export const ToolExecutionSchema = z.object({ - /** - * Indicates the tool's preference for task-augmented execution. - * - `"required"`: Clients MUST invoke the tool as a task - * - `"optional"`: Clients MAY invoke the tool as a task or normal request - * - `"forbidden"`: Clients MUST NOT attempt to invoke the tool as a task - * - * If not present, defaults to `"forbidden"`. - */ - taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() -}); - -/** - * Definition for a tool the client can call. - */ -export const ToolSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A human-readable description of the tool. - */ - description: z.string().optional(), - /** - * A JSON Schema 2020-12 object defining the expected parameters for the tool. - * Must have `type: 'object'` at the root level per MCP spec. - */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), JSONValueSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()), - /** - * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the `structuredContent` field of a {@linkcode CallToolResult}. - * Must have `type: 'object'` at the root level per MCP spec. - */ - outputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), JSONValueSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) - .optional(), - /** - * Optional additional tool information. - */ - annotations: ToolAnnotationsSchema.optional(), - /** - * Execution-related properties for this tool. - */ - execution: ToolExecutionSchema.optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * Sent from the client to request a list of tools the server has. - */ -export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tools/list') -}); - -/** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ -export const ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: z.array(ToolSchema) -}); - -/** - * The server's response to a tool call. - */ -export const CallToolResultSchema = ResultSchema.extend({ - /** - * A list of content objects that represent the result of the tool call. - * - * If the {@linkcode Tool} does not define an outputSchema, this field MUST be present in the result. - * For backwards compatibility, this field is always present, but it may be empty. - */ - content: z.array(ContentBlockSchema).default([]), - - /** - * An object containing structured tool output. - * - * If the {@linkcode Tool} defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. - */ - structuredContent: z.record(z.string(), z.unknown()).optional(), - - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be `false` (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to `true`, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError: z.boolean().optional() -}); - -/** - * {@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() -}); - -/** - * Callback type for list changed notifications. - */ -export type ListChangedCallback = (error: Error | null, items: T[] | null) => void; - -/** - * 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) -}); - -/** - * Options for subscribing to list changed notifications. - * - * @typeParam T - The type of items in the list ({@linkcode Tool}, {@linkcode Prompt}, or {@linkcode Resource}) - */ -export type ListChangedOptions = { - /** - * If `true`, the list will be refreshed automatically when a list changed notification is received. - * @default true - */ - autoRefresh?: boolean; - /** - * Debounce time in milliseconds. Set to `0` to disable. - * @default 300 - */ - debounceMs?: number; - /** - * Callback invoked when the list changes. - * - * If `autoRefresh` is `true`, `items` contains the updated list. - * If `autoRefresh` is `false`, `items` is `null` (caller should refresh manually). - */ - onChanged: ListChangedCallback; -}; - -/** - * Configuration for list changed notification handlers. - * - * Use this to configure handlers for tools, prompts, and resources list changes - * when creating a client. - * - * Note: Handlers are only activated if the server advertises the corresponding - * `listChanged` capability (e.g., `tools.listChanged: true`). If the server - * doesn't advertise this capability, the handler will not be set up. - */ -export type ListChangedHandlers = { - /** - * Handler for tool list changes. - */ - tools?: ListChangedOptions; - /** - * Handler for prompt list changes. - */ - prompts?: ListChangedOptions; - /** - * Handler for resource list changes. - */ - resources?: ListChangedOptions; -}; - -/* Logging */ -/** - * The severity of a log message. - */ -export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); - -/** - * Parameters for a `logging/setLevel` request. - */ -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. - */ -export const SetLevelRequestSchema = RequestSchema.extend({ - method: z.literal('logging/setLevel'), - params: SetLevelRequestParamsSchema -}); - -/** - * Parameters for a `notifications/message` notification. - */ -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. - */ -export const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: LoggingMessageNotificationParamsSchema -}); - -/* Sampling */ -/** - * Hints to use for model selection. - */ -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. - */ -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. - */ -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 {@linkcode ToolUseContent}. - */ -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).default([]), - structuredContent: z.object({}).loose().optional(), - isError: z.boolean().optional(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on `_meta` usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); - -/** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - */ -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. - */ -export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); - -/** - * Describes a message issued to or received from an LLM API. - */ -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. - */ -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"`. Values `"thisServer"` and `"allServers"` are soft-deprecated. Servers SHOULD only use these values if the client - * declares {@linkcode ClientCapabilities}.`sampling.context`. These values may be removed in future spec releases. - */ - 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 {@linkcode 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 {@linkcode 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. - */ -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. - */ -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. - */ -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 {@linkcode 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() - }) -}); - -/** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ -export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('url'), - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: z.string(), - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: z.string(), - /** - * The URL that the user should navigate to. - */ - url: z.string().url() -}); - -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); - -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -export const ElicitRequestSchema = RequestSchema.extend({ - method: z.literal('elicitation/create'), - params: ElicitRequestParamsSchema -}); - -/** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the elicitation that completed. - */ - elicitationId: z.string() -}); - -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/elicitation/complete'), - params: ElicitationCompleteNotificationParamsSchema -}); - -/** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ -export const ElicitResultSchema = ResultSchema.extend({ - /** - * The user action in response to the elicitation. - * - `"accept"`: User submitted the form/confirmed the action - * - `"decline"`: User explicitly declined the action - * - `"cancel"`: User dismissed without making an explicit choice - */ - action: z.enum(['accept', 'decline', 'cancel']), - /** - * The submitted form data, only present when action is `"accept"`. - * Contains values matching the requested schema. - * Per MCP spec, content is "typically omitted" for decline/cancel actions. - * We normalize `null` to `undefined` for leniency while maintaining type compatibility. - */ - content: z.preprocess( - val => (val === null ? undefined : val), - z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() - ) -}); - -/* Autocomplete */ -/** - * A reference to a resource or resource template definition. - */ -export const ResourceTemplateReferenceSchema = z.object({ - type: z.literal('ref/resource'), - /** - * The URI or URI template of the resource. - */ - uri: z.string() -}); - -/** - * Identifies a prompt. - */ -export const PromptReferenceSchema = z.object({ - type: z.literal('ref/prompt'), - /** - * The name of the prompt or prompt template - */ - name: z.string() -}); - -/** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ -export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: z.object({ - /** - * The name of the argument - */ - name: z.string(), - /** - * The value of the argument to use for completion matching. - */ - value: z.string() - }), - context: z - .object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.record(z.string(), z.string()).optional() - }) - .optional() -}); -/** - * A request from the client to the server, to ask for completion options. - */ -export const CompleteRequestSchema = RequestSchema.extend({ - method: z.literal('completion/complete'), - params: CompleteRequestParamsSchema -}); - -export function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt { - if (request.params.ref.type !== 'ref/prompt') { - throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); - } - void (request as CompleteRequestPrompt); -} - -export function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate { - if (request.params.ref.type !== 'ref/resource') { - throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); - } - void (request as CompleteRequestResourceTemplate); -} - -/** - * 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. - */ -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. - */ -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. - */ -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. - */ -export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed'), - params: NotificationsParamsSchema.optional() -}); - -/* Client messages */ -export const ClientRequestSchema = z.union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); - -export const ClientNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema, - TaskStatusNotificationSchema -]); - -export const ClientResultSchema = z.union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); - -/* Server messages */ -export const ServerRequestSchema = z.union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); - -export const ServerNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - TaskStatusNotificationSchema, - ElicitationCompleteNotificationSchema -]); - -export const ServerResultSchema = z.union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); - -/** - * Protocol errors are JSON-RPC errors that cross the wire as error responses. - * They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. - */ -export class ProtocolError extends Error { - constructor( - public readonly code: number, - message: string, - public readonly data?: unknown - ) { - super(`MCP error ${code}: ${message}`); - this.name = 'ProtocolError'; - } - - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code: number, message: string, data?: unknown): ProtocolError { - // Check for specific error types - if (code === ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data as { elicitations?: unknown[] }; - if (errorData.elicitations) { - return new UrlElicitationRequiredError(errorData.elicitations as ElicitRequestURLParams[], message); - } - } - - // Default to generic ProtocolError - return new ProtocolError(code, message, data); - } -} - -/** - * Specialized error type when a tool requires a URL mode elicitation. - * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. - */ -export class UrlElicitationRequiredError extends ProtocolError { - constructor(elicitations: ElicitRequestURLParams[], message: string = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { - super(ProtocolErrorCode.UrlElicitationRequired, message, { - elicitations: elicitations - }); - } - - get elicitations(): ElicitRequestURLParams[] { - return (this.data as { elicitations: ElicitRequestURLParams[] })?.elicitations ?? []; - } -} - -type Primitive = string | number | boolean | bigint | null | undefined; -type Flatten = T extends Primitive - ? T - : T extends Array - ? Array> - : T extends Set - ? Set> - : T extends Map - ? Map, Flatten> - : T extends object - ? { [K in keyof T]: Flatten } - : T; - -type Infer = Flatten>; - -/** - * Information about the incoming request. - */ -export interface RequestInfo { - /** - * The headers of the request. - */ - headers: Headers; -} - -/** - * Extra information about a message. - */ -export interface MessageExtraInfo { - /** - * The request information. - */ - requestInfo?: RequestInfo; - - /** - * The authentication information. - */ - authInfo?: AuthInfo; - - /** - * Callback to close the SSE stream for this request, triggering client reconnection. - * Only available when using {@linkcode @modelcontextprotocol/node!streamableHttp.NodeStreamableHTTPServerTransport | NodeStreamableHTTPServerTransport} with eventStore configured. - */ - closeSSEStream?: () => void; - - /** - * Callback to close the standalone GET SSE stream, triggering client reconnection. - * Only available when using {@linkcode @modelcontextprotocol/node!streamableHttp.NodeStreamableHTTPServerTransport | NodeStreamableHTTPServerTransport} with eventStore configured. - */ - closeStandaloneSSEStream?: () => void; -} - -/* JSON-RPC types */ -export type ProgressToken = Infer; -export type Cursor = Infer; -export type Request = Infer; -export type TaskAugmentedRequestParams = Infer; -export type RequestMeta = Infer; -export type MetaObject = Record; -export type RequestMetaObject = RequestMeta; -export type Notification = Infer; -export type Result = Infer; -export type RequestId = Infer; -export type JSONRPCRequest = Infer; -export type JSONRPCNotification = Infer; -export type JSONRPCResponse = Infer; -export type JSONRPCErrorResponse = Infer; -export type JSONRPCResultResponse = Infer; - -export type JSONRPCMessage = Infer; -export type RequestParams = Infer; -export type NotificationParams = Infer; - -/* Empty result */ -export type EmptyResult = Infer; - -/* Cancellation */ -export type CancelledNotificationParams = Infer; -export type CancelledNotification = Infer; - -/* Base Metadata */ -export type Icon = Infer; -export type Icons = Infer; -export type BaseMetadata = Infer; -export type Annotations = Infer; -export type Role = Infer; - -/* Initialization */ -export type Implementation = Infer; -export type ClientCapabilities = Infer; -export type InitializeRequestParams = Infer; -export type InitializeRequest = Infer; -export type ServerCapabilities = Infer; -export type InitializeResult = Infer; -export type InitializedNotification = Infer; - -/* Ping */ -export type PingRequest = Infer; - -/* Progress notifications */ -export type Progress = Infer; -export type ProgressNotificationParams = Infer; -export type ProgressNotification = Infer; - -/* Tasks */ -export type Task = Infer; -export type TaskStatus = Infer; -export type TaskCreationParams = Infer; -export type TaskMetadata = Infer; -export type RelatedTaskMetadata = Infer; -export type CreateTaskResult = Infer; -export type TaskStatusNotificationParams = Infer; -export type TaskStatusNotification = Infer; -export type GetTaskRequest = Infer; -export type GetTaskResult = Infer; -export type GetTaskPayloadRequest = Infer; -export type ListTasksRequest = Infer; -export type ListTasksResult = Infer; -export type CancelTaskRequest = Infer; -export type CancelTaskResult = Infer; -export type GetTaskPayloadResult = Infer; - -/* Pagination */ -export type PaginatedRequestParams = Infer; -export type PaginatedRequest = Infer; -export type PaginatedResult = Infer; - -/* Resources */ -export type ResourceContents = Infer; -export type TextResourceContents = Infer; -export type BlobResourceContents = Infer; -export type Resource = Infer; -// TODO: Overlaps with exported `ResourceTemplate` class from `server`. -export type ResourceTemplateType = Infer; -export type ListResourcesRequest = Infer; -export type ListResourcesResult = Infer; -export type ListResourceTemplatesRequest = Infer; -export type ListResourceTemplatesResult = Infer; -export type ResourceRequestParams = Infer; -export type ReadResourceRequestParams = Infer; -export type ReadResourceRequest = Infer; -export type ReadResourceResult = Infer; -export type ResourceListChangedNotification = Infer; -export type SubscribeRequestParams = Infer; -export type SubscribeRequest = Infer; -export type UnsubscribeRequestParams = Infer; -export type UnsubscribeRequest = Infer; -export type ResourceUpdatedNotificationParams = Infer; -export type ResourceUpdatedNotification = Infer; - -/* Prompts */ -export type PromptArgument = Infer; -export type Prompt = Infer; -export type ListPromptsRequest = Infer; -export type ListPromptsResult = Infer; -export type GetPromptRequestParams = Infer; -export type GetPromptRequest = Infer; -export type TextContent = Infer; -export type ImageContent = Infer; -export type AudioContent = Infer; -export type ToolUseContent = Infer; -export type ToolResultContent = Infer; -export type EmbeddedResource = Infer; -export type ResourceLink = Infer; -export type ContentBlock = Infer; -export type PromptMessage = Infer; -export type GetPromptResult = Infer; -export type PromptListChangedNotification = Infer; - -/* Tools */ -export type ToolAnnotations = Infer; -export type ToolExecution = Infer; -export type Tool = Infer; -export type ListToolsRequest = Infer; -export type ListToolsResult = Infer; -export type CallToolRequestParams = Infer; -export type CallToolResult = Infer; -export type CompatibilityCallToolResult = Infer; -export type CallToolRequest = Infer; -export type ToolListChangedNotification = Infer; - -/* Logging */ -export type LoggingLevel = Infer; -export type SetLevelRequestParams = Infer; -export type SetLevelRequest = Infer; -export type LoggingMessageNotificationParams = Infer; -export type LoggingMessageNotification = Infer; - -/* Sampling */ -export type ToolChoice = Infer; -export type ModelHint = Infer; -export type ModelPreferences = Infer; -export type SamplingContent = Infer; -export type SamplingMessageContentBlock = Infer; -export type SamplingMessage = Infer; -export type CreateMessageRequestParams = Infer; -export type CreateMessageRequest = Infer; -export type CreateMessageResult = Infer; -export type CreateMessageResultWithTools = Infer; - -/** - * {@linkcode CreateMessageRequestParams} without tools - for backwards-compatible overload. - * Excludes tools/toolChoice to indicate they should not be provided. - */ -export type CreateMessageRequestParamsBase = Omit; - -/** - * {@linkcode CreateMessageRequestParams} with required tools - for tool-enabled overload. - */ -export interface CreateMessageRequestParamsWithTools extends CreateMessageRequestParams { - tools: Tool[]; -} - -/* Elicitation */ -export type BooleanSchema = Infer; -export type StringSchema = Infer; -export type NumberSchema = Infer; - -export type EnumSchema = Infer; -export type UntitledSingleSelectEnumSchema = Infer; -export type TitledSingleSelectEnumSchema = Infer; -export type LegacyTitledEnumSchema = Infer; -export type UntitledMultiSelectEnumSchema = Infer; -export type TitledMultiSelectEnumSchema = Infer; -export type SingleSelectEnumSchema = Infer; -export type MultiSelectEnumSchema = Infer; - -export type PrimitiveSchemaDefinition = Infer; -export type ElicitRequestParams = Infer; -export type ElicitRequestFormParams = Infer; -export type ElicitRequestURLParams = Infer; -export type ElicitRequest = Infer; -export type ElicitationCompleteNotificationParams = Infer; -export type ElicitationCompleteNotification = Infer; -export type ElicitResult = Infer; - -/* Autocomplete */ -export type ResourceTemplateReference = Infer; -export type PromptReference = Infer; -export type CompleteRequestParams = Infer; -export type CompleteRequest = Infer; export type CompleteRequestResourceTemplate = ExpandRecursively< CompleteRequest & { params: CompleteRequestParams & { ref: ResourceTemplateReference } } >; export type CompleteRequestPrompt = ExpandRecursively; -export type CompleteResult = Infer; - -/* Roots */ -export type Root = Infer; -export type ListRootsRequest = Infer; -export type ListRootsResult = Infer; -export type RootsListChangedNotification = Infer; - -/* Client messages */ -export type ClientRequest = Infer; -export type ClientNotification = Infer; -export type ClientResult = Infer; - -/* Server messages */ -export type ServerRequest = Infer; -export type ServerNotification = Infer; -export type ServerResult = Infer; - -/* Protocol type maps */ -type MethodToTypeMap = { - [T in U as T extends { method: infer M extends string } ? M : never]: T; -}; -export type RequestMethod = ClientRequest['method'] | ServerRequest['method']; -export type NotificationMethod = ClientNotification['method'] | ServerNotification['method']; -export type RequestTypeMap = MethodToTypeMap; -export type NotificationTypeMap = MethodToTypeMap; -export type ResultTypeMap = { - ping: EmptyResult; - initialize: InitializeResult; - 'completion/complete': CompleteResult; - 'logging/setLevel': EmptyResult; - 'prompts/get': GetPromptResult; - 'prompts/list': ListPromptsResult; - 'resources/list': ListResourcesResult; - 'resources/templates/list': ListResourceTemplatesResult; - 'resources/read': ReadResourceResult; - 'resources/subscribe': EmptyResult; - 'resources/unsubscribe': EmptyResult; - 'tools/call': CallToolResult | CreateTaskResult; - 'tools/list': ListToolsResult; - 'sampling/createMessage': CreateMessageResult | CreateMessageResultWithTools | CreateTaskResult; - 'elicitation/create': ElicitResult | CreateTaskResult; - 'roots/list': ListRootsResult; - 'tasks/get': GetTaskResult; - 'tasks/result': Result; - 'tasks/list': ListTasksResult; - 'tasks/cancel': CancelTaskResult; -}; - -/* Runtime schema lookup — result schemas by method */ -const resultSchemas: Record = { - ping: EmptyResultSchema, - initialize: InitializeResultSchema, - 'completion/complete': CompleteResultSchema, - 'logging/setLevel': EmptyResultSchema, - 'prompts/get': GetPromptResultSchema, - 'prompts/list': ListPromptsResultSchema, - 'resources/list': ListResourcesResultSchema, - 'resources/templates/list': ListResourceTemplatesResultSchema, - 'resources/read': ReadResourceResultSchema, - 'resources/subscribe': EmptyResultSchema, - 'resources/unsubscribe': EmptyResultSchema, - 'tools/call': z.union([CallToolResultSchema, CreateTaskResultSchema]), - 'tools/list': ListToolsResultSchema, - 'sampling/createMessage': z.union([CreateMessageResultWithToolsSchema, CreateTaskResultSchema]), - 'elicitation/create': z.union([ElicitResultSchema, CreateTaskResultSchema]), - 'roots/list': ListRootsResultSchema, - 'tasks/get': GetTaskResultSchema, - 'tasks/result': ResultSchema, - 'tasks/list': ListTasksResultSchema, - 'tasks/cancel': CancelTaskResultSchema -}; - -/** - * Gets the Zod schema for validating results of a given request method. - * @see getRequestSchema for explanation of the internal type assertion. - */ -export function getResultSchema(method: M): z.ZodType { - return resultSchemas[method] as unknown as z.ZodType; -} - -/* Runtime schema lookup — request schemas by method */ -type RequestSchemaType = (typeof ClientRequestSchema.options)[number] | (typeof ServerRequestSchema.options)[number]; -type NotificationSchemaType = (typeof ClientNotificationSchema.options)[number] | (typeof ServerNotificationSchema.options)[number]; - -function buildSchemaMap(schemas: readonly T[]): Record { - const map: Record = {}; - for (const schema of schemas) { - const method = schema.shape.method.value; - map[method] = schema; - } - return map; -} - -const requestSchemas = buildSchemaMap([...ClientRequestSchema.options, ...ServerRequestSchema.options] as const) as Record< - RequestMethod, - RequestSchemaType ->; -const notificationSchemas = buildSchemaMap([...ClientNotificationSchema.options, ...ServerNotificationSchema.options] as const) as Record< - NotificationMethod, - NotificationSchemaType ->; - -/** - * Gets the Zod schema for a given request method. - * The return type is a ZodType that parses to RequestTypeMap[M], allowing callers - * to use schema.parse() without needing additional type assertions. - * - * Note: The internal cast is necessary because TypeScript can't correlate the - * Record-based schema lookup with the MethodToTypeMap-based RequestTypeMap - * when M is a generic type parameter. Both compute to the same type at - * instantiation, but TypeScript can't prove this statically. - */ -export function getRequestSchema(method: M): z.ZodType { - return requestSchemas[method] as unknown as z.ZodType; -} - -/** - * Gets the Zod schema for a given notification method. - * @see getRequestSchema for explanation of the internal type assertion. - */ -export function getNotificationSchema(method: M): z.ZodType { - return notificationSchemas[method] as unknown as z.ZodType; -} diff --git a/packages/core/src/util/inMemory.ts b/packages/core/src/util/inMemory.ts index a02bcafc9..1103b5733 100644 --- a/packages/core/src/util/inMemory.ts +++ b/packages/core/src/util/inMemory.ts @@ -1,6 +1,6 @@ import { SdkError, SdkErrorCode } from '../errors/sdkErrors.js'; import type { Transport } from '../shared/transport.js'; -import type { AuthInfo, JSONRPCMessage, RequestId } from '../types/types.js'; +import type { AuthInfo, JSONRPCMessage, RequestId } from '../types/index.js'; interface QueuedMessage { message: JSONRPCMessage; diff --git a/packages/core/test/experimental/inMemory.test.ts b/packages/core/test/experimental/inMemory.test.ts index ea6a3a8dc..edbbca040 100644 --- a/packages/core/test/experimental/inMemory.test.ts +++ b/packages/core/test/experimental/inMemory.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { QueuedMessage } from '../../src/experimental/tasks/interfaces.js'; import { InMemoryTaskMessageQueue, InMemoryTaskStore } from '../../src/experimental/tasks/stores/inMemory.js'; -import type { Request, TaskCreationParams } from '../../src/types/types.js'; +import type { Request, TaskCreationParams } from '../../src/types/index.js'; describe('InMemoryTaskStore', () => { let store: InMemoryTaskStore; diff --git a/packages/core/test/inMemory.test.ts b/packages/core/test/inMemory.test.ts index 72f28240b..280efdf4b 100644 --- a/packages/core/test/inMemory.test.ts +++ b/packages/core/test/inMemory.test.ts @@ -1,4 +1,4 @@ -import type { AuthInfo, JSONRPCMessage } from '../src/types/types.js'; +import type { AuthInfo, JSONRPCMessage } from '../src/types/index.js'; import { InMemoryTransport } from '../src/util/inMemory.js'; describe('InMemoryTransport', () => { diff --git a/packages/core/test/shared/protocol.test.ts b/packages/core/test/shared/protocol.test.ts index 8675c1e03..01a54ee42 100644 --- a/packages/core/test/shared/protocol.test.ts +++ b/packages/core/test/shared/protocol.test.ts @@ -29,8 +29,8 @@ import type { ServerCapabilities, Task, TaskCreationParams -} from '../../src/types/types.js'; -import { ProtocolError, ProtocolErrorCode, RELATED_TASK_META_KEY } from '../../src/types/types.js'; +} from '../../src/types/index.js'; +import { ProtocolError, ProtocolErrorCode, RELATED_TASK_META_KEY } from '../../src/types/index.js'; import { SdkError, SdkErrorCode } from '../../src/errors/sdkErrors.js'; // Type helper for accessing private/protected Protocol properties in tests diff --git a/packages/core/test/shared/protocolTransportHandling.test.ts b/packages/core/test/shared/protocolTransportHandling.test.ts index adc7e2234..c137bacb4 100644 --- a/packages/core/test/shared/protocolTransportHandling.test.ts +++ b/packages/core/test/shared/protocolTransportHandling.test.ts @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, test } from 'vitest'; import type { BaseContext } from '../../src/shared/protocol.js'; import { Protocol } from '../../src/shared/protocol.js'; import type { Transport } from '../../src/shared/transport.js'; -import type { EmptyResult, JSONRPCMessage, Notification, Request, Result } from '../../src/types/types.js'; +import type { EmptyResult, JSONRPCMessage, Notification, Request, Result } from '../../src/types/index.js'; // Mock Transport class class MockTransport implements Transport { diff --git a/packages/core/test/shared/stdio.test.ts b/packages/core/test/shared/stdio.test.ts index 455c8a627..7e880aa57 100644 --- a/packages/core/test/shared/stdio.test.ts +++ b/packages/core/test/shared/stdio.test.ts @@ -1,5 +1,5 @@ import { ReadBuffer } from '../../src/shared/stdio.js'; -import type { JSONRPCMessage } from '../../src/types/types.js'; +import type { JSONRPCMessage } from '../../src/types/index.js'; const testMessage: JSONRPCMessage = { jsonrpc: '2.0', diff --git a/packages/core/test/spec.types.test.ts b/packages/core/test/spec.types.test.ts index da6fab109..d7be7cb2f 100644 --- a/packages/core/test/spec.types.test.ts +++ b/packages/core/test/spec.types.test.ts @@ -9,7 +9,7 @@ import fs from 'node:fs'; import path from 'node:path'; import type * as SpecTypes from '../src/types/spec.types.js'; -import type * as SDKTypes from '../src/types/types.js'; +import type * as SDKTypes from '../src/types/index.js'; /* eslint-disable @typescript-eslint/no-unused-vars */ diff --git a/packages/core/test/types.capabilities.test.ts b/packages/core/test/types.capabilities.test.ts index ed414d2db..1f6618452 100644 --- a/packages/core/test/types.capabilities.test.ts +++ b/packages/core/test/types.capabilities.test.ts @@ -1,4 +1,4 @@ -import { ClientCapabilitiesSchema, InitializeRequestParamsSchema } from '../src/types/types.js'; +import { ClientCapabilitiesSchema, InitializeRequestParamsSchema } from '../src/types/index.js'; describe('ClientCapabilitiesSchema backwards compatibility', () => { describe('ElicitationCapabilitySchema preprocessing', () => { diff --git a/packages/core/test/types.test.ts b/packages/core/test/types.test.ts index 8798c496a..429b3ecdd 100644 --- a/packages/core/test/types.test.ts +++ b/packages/core/test/types.test.ts @@ -15,7 +15,7 @@ import { ToolResultContentSchema, ToolSchema, ToolUseContentSchema -} from '../src/types/types.js'; +} from '../src/types/index.js'; describe('Types', () => { test('should have correct latest protocol version', () => { diff --git a/packages/middleware/express/tsconfig.json b/packages/middleware/express/tsconfig.json index c92435851..96788ff0e 100644 --- a/packages/middleware/express/tsconfig.json +++ b/packages/middleware/express/tsconfig.json @@ -9,6 +9,9 @@ "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" + ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" ] } } diff --git a/packages/middleware/hono/tsconfig.json b/packages/middleware/hono/tsconfig.json index c92435851..96788ff0e 100644 --- a/packages/middleware/hono/tsconfig.json +++ b/packages/middleware/hono/tsconfig.json @@ -9,6 +9,9 @@ "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core": [ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" + ], + "@modelcontextprotocol/core/public": [ + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" ] } } diff --git a/packages/middleware/node/tsconfig.json b/packages/middleware/node/tsconfig.json index 206c91177..059708824 100644 --- a/packages/middleware/node/tsconfig.json +++ b/packages/middleware/node/tsconfig.json @@ -8,6 +8,7 @@ "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"] } } diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 1a8dbf143..01b1ef903 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -1,12 +1,38 @@ -export * from './server/completable.js'; -export * from './server/mcp.js'; -export * from './server/middleware/hostHeaderValidation.js'; -export * from './server/server.js'; -export * from './server/stdio.js'; -export * from './server/streamableHttp.js'; +// Server-specific exports +export type { CompletableSchema, CompleteCallback } from './server/completable.js'; +export { completable, isCompletable } from './server/completable.js'; +export type { + AnyToolHandler, + BaseToolCallback, + CompleteResourceTemplateCallback, + ListResourcesCallback, + PromptCallback, + ReadResourceCallback, + ReadResourceTemplateCallback, + RegisteredPrompt, + RegisteredResource, + RegisteredResourceTemplate, + RegisteredTool, + ResourceMetadata, + ToolCallback +} from './server/mcp.js'; +export { McpServer, ResourceTemplate } from './server/mcp.js'; +export type { HostHeaderValidationResult } from './server/middleware/hostHeaderValidation.js'; +export { hostHeaderValidationResponse, localhostAllowedHostnames, validateHostHeader } from './server/middleware/hostHeaderValidation.js'; +export type { ServerOptions } from './server/server.js'; +export { Server } from './server/server.js'; +export { StdioServerTransport } from './server/stdio.js'; +export type { + EventId, + EventStore, + HandleRequestOptions, + StreamId, + WebStandardStreamableHTTPServerTransportOptions +} from './server/streamableHttp.js'; +export { WebStandardStreamableHTTPServerTransport } from './server/streamableHttp.js'; // experimental exports export * from './experimental/index.js'; -// re-export shared types -export * from '@modelcontextprotocol/core'; +// re-export curated public API from core +export * from '@modelcontextprotocol/core/public'; diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.json index e62ac3df9..2128f7747 100644 --- a/packages/server/tsconfig.json +++ b/packages/server/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"], "@modelcontextprotocol/server/_shims": ["./src/shimsNode.ts"] } diff --git a/test/conformance/tsconfig.json b/test/conformance/tsconfig.json index 5c22ec1be..5b35f9aae 100644 --- a/test/conformance/tsconfig.json +++ b/test/conformance/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], "@modelcontextprotocol/express": ["./node_modules/@modelcontextprotocol/express/src/index.ts"], diff --git a/test/helpers/tsconfig.json b/test/helpers/tsconfig.json index c46b557df..ae4a76e66 100644 --- a/test/helpers/tsconfig.json +++ b/test/helpers/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] } } diff --git a/test/integration/tsconfig.json b/test/integration/tsconfig.json index 5d68aa999..73b14e94b 100644 --- a/test/integration/tsconfig.json +++ b/test/integration/tsconfig.json @@ -6,6 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], "@modelcontextprotocol/client/_shims": ["./node_modules/@modelcontextprotocol/client/src/shimsNode.ts"], "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], From d32bc9fba25649533f5ee49ebd18fa1ff4bb2d40 Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sat, 14 Mar 2026 16:50:14 +0200 Subject: [PATCH 2/5] remove schemas from public exports --- examples/client-quickstart/tsconfig.json | 2 +- examples/client/tsconfig.json | 2 +- examples/server-quickstart/tsconfig.json | 2 +- examples/server/tsconfig.json | 2 +- examples/shared/tsconfig.json | 2 +- packages/client/tsconfig.json | 2 +- packages/core/package.json | 14 + .../public/index.ts} | 50 +-- packages/core/src/types/errors.ts | 2 +- packages/core/src/types/guards.ts | 23 +- packages/core/src/types/schemas.ts | 296 ++----------- packages/core/src/types/types.ts | 412 +++++++++++++++++- packages/middleware/express/tsconfig.json | 2 +- packages/middleware/hono/tsconfig.json | 2 +- packages/middleware/node/tsconfig.json | 2 +- packages/server/tsconfig.json | 2 +- test/conformance/tsconfig.json | 2 +- test/helpers/tsconfig.json | 2 +- test/integration/tsconfig.json | 2 +- 19 files changed, 491 insertions(+), 332 deletions(-) rename packages/core/src/{publicExports.ts => exports/public/index.ts} (61%) diff --git a/examples/client-quickstart/tsconfig.json b/examples/client-quickstart/tsconfig.json index c3a26b1fe..0ff230387 100644 --- a/examples/client-quickstart/tsconfig.json +++ b/examples/client-quickstart/tsconfig.json @@ -17,7 +17,7 @@ "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ] } }, diff --git a/examples/client/tsconfig.json b/examples/client/tsconfig.json index 1a1b9fca6..c2863e4db 100644 --- a/examples/client/tsconfig.json +++ b/examples/client/tsconfig.json @@ -11,7 +11,7 @@ "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], diff --git a/examples/server-quickstart/tsconfig.json b/examples/server-quickstart/tsconfig.json index 672e544e6..7cb513cfe 100644 --- a/examples/server-quickstart/tsconfig.json +++ b/examples/server-quickstart/tsconfig.json @@ -16,7 +16,7 @@ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ] } }, diff --git a/examples/server/tsconfig.json b/examples/server/tsconfig.json index ef83c1042..e3c0e9477 100644 --- a/examples/server/tsconfig.json +++ b/examples/server/tsconfig.json @@ -14,7 +14,7 @@ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ], "@modelcontextprotocol/examples-shared": ["./node_modules/@modelcontextprotocol/examples-shared/src/index.ts"], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], diff --git a/examples/shared/tsconfig.json b/examples/shared/tsconfig.json index 6d7f38f86..61a052691 100644 --- a/examples/shared/tsconfig.json +++ b/examples/shared/tsconfig.json @@ -13,7 +13,7 @@ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ], "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], diff --git a/packages/client/tsconfig.json b/packages/client/tsconfig.json index 5e1df302a..f0772820a 100644 --- a/packages/client/tsconfig.json +++ b/packages/client/tsconfig.json @@ -6,7 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/exports/public/index.ts"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"], "@modelcontextprotocol/client/_shims": ["./src/shimsNode.ts"] } diff --git a/packages/core/package.json b/packages/core/package.json index 3b55a71d6..6f0c703a5 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -20,6 +20,20 @@ "mcp", "core" ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs" + }, + "./types": { + "types": "./src/exports/types/index.ts", + "import": "./src/exports/types/index.ts" + }, + "./public": { + "types": "./src/exports/public/index.ts", + "import": "./src/exports/public/index.ts" + } + }, "scripts": { "typecheck": "tsgo -p tsconfig.json --noEmit", "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", diff --git a/packages/core/src/publicExports.ts b/packages/core/src/exports/public/index.ts similarity index 61% rename from packages/core/src/publicExports.ts rename to packages/core/src/exports/public/index.ts index c685266dd..b47a3aae9 100644 --- a/packages/core/src/publicExports.ts +++ b/packages/core/src/exports/public/index.ts @@ -10,10 +10,10 @@ */ // Auth error classes -export * from './auth/errors.js'; +export * from '../../auth/errors.js'; // SDK error types (local errors that never cross the wire) -export { SdkError, SdkErrorCode } from './errors/sdkErrors.js'; +export { SdkError, SdkErrorCode } from '../../errors/sdkErrors.js'; // Auth TypeScript types (NOT Zod schemas like OAuthMetadataSchema) export type { @@ -30,13 +30,13 @@ export type { OAuthTokens, OpenIdProviderDiscoveryMetadata, OpenIdProviderMetadata -} from './shared/auth.js'; +} from '../../shared/auth.js'; // Auth utilities -export { checkResourceAllowed, resourceUrlFromServerUrl } from './shared/authUtils.js'; +export { checkResourceAllowed, resourceUrlFromServerUrl } from '../../shared/authUtils.js'; // Metadata utilities -export { getDisplayName } from './shared/metadataUtils.js'; +export { getDisplayName } from '../../shared/metadataUtils.js'; // Protocol types (NOT the Protocol class itself or mergeCapabilities) export type { @@ -50,8 +50,8 @@ export type { ServerContext, TaskContext, TaskRequestOptions -} from './shared/protocol.js'; -export { DEFAULT_REQUEST_TIMEOUT_MSEC } from './shared/protocol.js'; +} from '../../shared/protocol.js'; +export { DEFAULT_REQUEST_TIMEOUT_MSEC } from '../../shared/protocol.js'; // Response message types export type { @@ -61,42 +61,36 @@ export type { ResultMessage, TaskCreatedMessage, TaskStatusMessage -} from './shared/responseMessage.js'; -export { takeResult, toArrayAsync } from './shared/responseMessage.js'; +} from '../../shared/responseMessage.js'; +export { takeResult, toArrayAsync } from '../../shared/responseMessage.js'; // Transport types (NOT normalizeHeaders) -export type { FetchLike, Transport, TransportSendOptions } from './shared/transport.js'; -export { createFetchWithInit } from './shared/transport.js'; +export type { FetchLike, Transport, TransportSendOptions } from '../../shared/transport.js'; +export { createFetchWithInit } from '../../shared/transport.js'; // URI Template -export type { Variables } from './shared/uriTemplate.js'; -export { UriTemplate } from './shared/uriTemplate.js'; +export type { Variables } from '../../shared/uriTemplate.js'; +export { UriTemplate } from '../../shared/uriTemplate.js'; // Types — all TypeScript types (standalone interfaces + schema-derived) -export * from './types/types.js'; +export * from '../../types/types.js'; // Constants -export * from './types/constants.js'; +export * from '../../types/constants.js'; // Enums -export * from './types/enums.js'; +export * from '../../types/enums.js'; // Error classes -export * from './types/errors.js'; +export * from '../../types/errors.js'; // Type guards -export * from './types/guards.js'; - -// Schemas — temporarily included. Will be removed after decoupling from Zod schemas. -export * from './types/schemas.js'; - -// InMemoryTransport -export { InMemoryTransport } from './util/inMemory.js'; +export * from '../../types/guards.js'; // Experimental task types and classes -export * from './experimental/index.js'; +export * from '../../experimental/index.js'; // Validator types and classes -export * from './validators/ajvProvider.js'; -export * from './validators/cfWorkerProvider.js'; -export type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from './validators/types.js'; +export * from '../../validators/ajvProvider.js'; +export * from '../../validators/cfWorkerProvider.js'; +export type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from '../../validators/types.js'; diff --git a/packages/core/src/types/errors.ts b/packages/core/src/types/errors.ts index 4314bdff7..64bc10ce7 100644 --- a/packages/core/src/types/errors.ts +++ b/packages/core/src/types/errors.ts @@ -1,5 +1,5 @@ import { ProtocolErrorCode } from './enums.js'; -import type { ElicitRequestURLParams } from './schemas.js'; +import type { ElicitRequestURLParams } from './types.js'; /** * Protocol errors are JSON-RPC errors that cross the wire as error responses. diff --git a/packages/core/src/types/guards.ts b/packages/core/src/types/guards.ts index 355b56c63..e5c0027ec 100644 --- a/packages/core/src/types/guards.ts +++ b/packages/core/src/types/guards.ts @@ -1,13 +1,3 @@ -import type { - CompleteRequest, - InitializedNotification, - InitializeRequest, - JSONRPCErrorResponse, - JSONRPCNotification, - JSONRPCRequest, - JSONRPCResultResponse, - TaskAugmentedRequestParams -} from './schemas.js'; import { InitializedNotificationSchema, InitializeRequestSchema, @@ -17,7 +7,18 @@ import { JSONRPCResultResponseSchema, TaskAugmentedRequestParamsSchema } from './schemas.js'; -import type { CompleteRequestPrompt, CompleteRequestResourceTemplate } from './types.js'; +import type { + CompleteRequest, + CompleteRequestPrompt, + CompleteRequestResourceTemplate, + InitializedNotification, + InitializeRequest, + JSONRPCErrorResponse, + JSONRPCNotification, + JSONRPCRequest, + JSONRPCResultResponse, + TaskAugmentedRequestParams +} from './types.js'; export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success; diff --git a/packages/core/src/types/schemas.ts b/packages/core/src/types/schemas.ts index 6b20b7c91..eb87b8332 100644 --- a/packages/core/src/types/schemas.ts +++ b/packages/core/src/types/schemas.ts @@ -1,22 +1,22 @@ import * as z from 'zod/v4'; import { JSONRPC_VERSION, RELATED_TASK_META_KEY } from './constants.js'; - -/* JSON types */ -export type JSONValue = string | number | boolean | null | JSONObject | JSONArray; -export type JSONObject = { [key: string]: JSONValue }; -export type JSONArray = JSONValue[]; +import type { + JSONArray, + JSONObject, + JSONValue, + NotificationMethod, + NotificationTypeMap, + RequestMethod, + RequestTypeMap, + ResultTypeMap +} from './types.js'; 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); - -/** - * Utility types - */ -export type ExpandRecursively = T extends object ? (T extends infer O ? { [K in keyof O]: ExpandRecursively } : never) : T; /** * A progress token, used to associate progress notifications with the original request. */ @@ -55,7 +55,7 @@ export const RelatedTaskMetadataSchema = z.object({ taskId: z.string() }); -const RequestMetaSchema = z.looseObject({ +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. */ @@ -69,7 +69,7 @@ const RequestMetaSchema = z.looseObject({ /** * Common params for any request. */ -const BaseRequestParamsSchema = z.object({ +export const BaseRequestParamsSchema = z.object({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ @@ -82,8 +82,8 @@ const BaseRequestParamsSchema = z.object({ export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a {@linkcode CreateTaskResult} immediately, and the actual result can be - * retrieved later via {@linkcode GetTaskPayloadRequest | tasks/result}. + * 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. @@ -96,7 +96,7 @@ export const RequestSchema = z.object({ params: BaseRequestParamsSchema.loose().optional() }); -const NotificationsParamsSchema = z.object({ +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. @@ -279,7 +279,7 @@ export const BaseMetadataSchema = z.object({ * 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 {@linkcode Tool}, + * 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). */ @@ -687,9 +687,9 @@ export const GetTaskPayloadRequestSchema = RequestSchema.extend({ }); /** - * The response to a {@linkcode GetTaskPayloadRequest | tasks/result} request. + * 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 {@linkcode CallToolResult} structure. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. * */ export const GetTaskPayloadResultSchema = ResultSchema.loose(); @@ -1134,7 +1134,7 @@ export const ToolUseContentSchema = z.object({ name: z.string(), /** * Unique identifier for this tool call. - * Used to correlate with {@linkcode ToolResultContent} in subsequent messages. + * Used to correlate with `ToolResultContent` in subsequent messages. */ id: z.string(), /** @@ -1215,13 +1215,13 @@ export const PromptListChangedNotificationSchema = NotificationSchema.extend({ /* Tools */ /** - * Additional properties describing a {@linkcode Tool} to clients. + * 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 {@linkcode ToolAnnotations} + * Clients should never make tool use decisions based on `ToolAnnotations` * received from untrusted servers. */ export const ToolAnnotationsSchema = z.object({ @@ -1306,7 +1306,7 @@ export const ToolSchema = z.object({ .catchall(z.unknown()), /** * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the `structuredContent` field of a {@linkcode CallToolResult}. + * returned in the `structuredContent` field of a `CallToolResult`. * Must have `type: 'object'` at the root level per MCP spec. */ outputSchema: z @@ -1354,7 +1354,7 @@ export const CallToolResultSchema = ResultSchema.extend({ /** * A list of content objects that represent the result of the tool call. * - * If the {@linkcode Tool} does not define an outputSchema, this field MUST be present in the result. + * If the `Tool` does not define an outputSchema, this field MUST be present in the result. * For backwards compatibility, this field is always present, but it may be empty. */ content: z.array(ContentBlockSchema).default([]), @@ -1362,7 +1362,7 @@ export const CallToolResultSchema = ResultSchema.extend({ /** * An object containing structured tool output. * - * If the {@linkcode Tool} defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + * If the `Tool` defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ structuredContent: z.record(z.string(), z.unknown()).optional(), @@ -1543,7 +1543,7 @@ export const ToolChoiceSchema = z.object({ /** * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via {@linkcode ToolUseContent}. + * Represents the outcome of invoking a tool requested via `ToolUseContent`. */ export const ToolResultContentSchema = z.object({ type: z.literal('tool_result'), @@ -1608,7 +1608,7 @@ export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema * The client MAY ignore this request. * * Default is `"none"`. Values `"thisServer"` and `"allServers"` are soft-deprecated. Servers SHOULD only use these values if the client - * declares {@linkcode ClientCapabilities}.`sampling.context`. These values may be removed in future spec releases. + * declares `ClientCapabilities`.`sampling.context`. These values may be removed in future spec releases. */ includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), temperature: z.number().optional(), @@ -1625,12 +1625,12 @@ export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema metadata: JSONObjectSchema.optional(), /** * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but {@linkcode ClientCapabilities}.`sampling.tools` is not declared. + * 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 {@linkcode ClientCapabilities}.`sampling.tools` is not declared. + * 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() @@ -1694,7 +1694,7 @@ export const CreateMessageResultWithToolsSchema = ResultSchema.extend({ 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 {@linkcode ToolUseContent} if `stopReason` is `"toolUse"`. + * Response content. May be a single block or array. May include `ToolUseContent` if `stopReason` is `"toolUse"`. */ content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) }); @@ -2139,244 +2139,6 @@ export const ServerResultSchema = z.union([ CreateTaskResultSchema ]); -type Primitive = string | number | boolean | bigint | null | undefined; -type Flatten = T extends Primitive - ? T - : T extends Array - ? Array> - : T extends Set - ? Set> - : T extends Map - ? Map, Flatten> - : T extends object - ? { [K in keyof T]: Flatten } - : T; - -type Infer = Flatten>; - -/* JSON-RPC types */ -export type ProgressToken = Infer; -export type Cursor = Infer; -export type Request = Infer; -export type TaskAugmentedRequestParams = Infer; -export type RequestMeta = Infer; -export type Notification = Infer; -export type Result = Infer; -export type RequestId = Infer; -export type JSONRPCRequest = Infer; -export type JSONRPCNotification = Infer; -export type JSONRPCResponse = Infer; -export type JSONRPCErrorResponse = Infer; -export type JSONRPCResultResponse = Infer; - -export type JSONRPCMessage = Infer; -export type RequestParams = Infer; -export type NotificationParams = Infer; - -/* Empty result */ -export type EmptyResult = Infer; - -/* Cancellation */ -export type CancelledNotificationParams = Infer; -export type CancelledNotification = Infer; - -/* Base Metadata */ -export type Icon = Infer; -export type Icons = Infer; -export type BaseMetadata = Infer; -export type Annotations = Infer; -export type Role = Infer; - -/* Initialization */ -export type Implementation = Infer; -export type ClientCapabilities = Infer; -export type InitializeRequestParams = Infer; -export type InitializeRequest = Infer; -export type ServerCapabilities = Infer; -export type InitializeResult = Infer; -export type InitializedNotification = Infer; - -/* Ping */ -export type PingRequest = Infer; - -/* Progress notifications */ -export type Progress = Infer; -export type ProgressNotificationParams = Infer; -export type ProgressNotification = Infer; - -/* Tasks */ -export type Task = Infer; -export type TaskStatus = Infer; -export type TaskCreationParams = Infer; -export type TaskMetadata = Infer; -export type RelatedTaskMetadata = Infer; -export type CreateTaskResult = Infer; -export type TaskStatusNotificationParams = Infer; -export type TaskStatusNotification = Infer; -export type GetTaskRequest = Infer; -export type GetTaskResult = Infer; -export type GetTaskPayloadRequest = Infer; -export type ListTasksRequest = Infer; -export type ListTasksResult = Infer; -export type CancelTaskRequest = Infer; -export type CancelTaskResult = Infer; -export type GetTaskPayloadResult = Infer; - -/* Pagination */ -export type PaginatedRequestParams = Infer; -export type PaginatedRequest = Infer; -export type PaginatedResult = Infer; - -/* Resources */ -export type ResourceContents = Infer; -export type TextResourceContents = Infer; -export type BlobResourceContents = Infer; -export type Resource = Infer; -// TODO: Overlaps with exported `ResourceTemplate` class from `server`. -export type ResourceTemplateType = Infer; -export type ListResourcesRequest = Infer; -export type ListResourcesResult = Infer; -export type ListResourceTemplatesRequest = Infer; -export type ListResourceTemplatesResult = Infer; -export type ResourceRequestParams = Infer; -export type ReadResourceRequestParams = Infer; -export type ReadResourceRequest = Infer; -export type ReadResourceResult = Infer; -export type ResourceListChangedNotification = Infer; -export type SubscribeRequestParams = Infer; -export type SubscribeRequest = Infer; -export type UnsubscribeRequestParams = Infer; -export type UnsubscribeRequest = Infer; -export type ResourceUpdatedNotificationParams = Infer; -export type ResourceUpdatedNotification = Infer; - -/* Prompts */ -export type PromptArgument = Infer; -export type Prompt = Infer; -export type ListPromptsRequest = Infer; -export type ListPromptsResult = Infer; -export type GetPromptRequestParams = Infer; -export type GetPromptRequest = Infer; -export type TextContent = Infer; -export type ImageContent = Infer; -export type AudioContent = Infer; -export type ToolUseContent = Infer; -export type ToolResultContent = Infer; -export type EmbeddedResource = Infer; -export type ResourceLink = Infer; -export type ContentBlock = Infer; -export type PromptMessage = Infer; -export type GetPromptResult = Infer; -export type PromptListChangedNotification = Infer; - -/* Tools */ -export type ToolAnnotations = Infer; -export type ToolExecution = Infer; -export type Tool = Infer; -export type ListToolsRequest = Infer; -export type ListToolsResult = Infer; -export type CallToolRequestParams = Infer; -export type CallToolResult = Infer; -export type CompatibilityCallToolResult = Infer; -export type CallToolRequest = Infer; -export type ToolListChangedNotification = Infer; - -/* Logging */ -export type LoggingLevel = Infer; -export type SetLevelRequestParams = Infer; -export type SetLevelRequest = Infer; -export type LoggingMessageNotificationParams = Infer; -export type LoggingMessageNotification = Infer; - -/* Sampling */ -export type ToolChoice = Infer; -export type ModelHint = Infer; -export type ModelPreferences = Infer; -export type SamplingContent = Infer; -export type SamplingMessageContentBlock = Infer; -export type SamplingMessage = Infer; -export type CreateMessageRequestParams = Infer; -export type CreateMessageRequest = Infer; -export type CreateMessageResult = Infer; -export type CreateMessageResultWithTools = Infer; - -/* Elicitation */ -export type BooleanSchema = Infer; -export type StringSchema = Infer; -export type NumberSchema = Infer; - -export type EnumSchema = Infer; -export type UntitledSingleSelectEnumSchema = Infer; -export type TitledSingleSelectEnumSchema = Infer; -export type LegacyTitledEnumSchema = Infer; -export type UntitledMultiSelectEnumSchema = Infer; -export type TitledMultiSelectEnumSchema = Infer; -export type SingleSelectEnumSchema = Infer; -export type MultiSelectEnumSchema = Infer; - -export type PrimitiveSchemaDefinition = Infer; -export type ElicitRequestParams = Infer; -export type ElicitRequestFormParams = Infer; -export type ElicitRequestURLParams = Infer; -export type ElicitRequest = Infer; -export type ElicitationCompleteNotificationParams = Infer; -export type ElicitationCompleteNotification = Infer; -export type ElicitResult = Infer; - -/* Autocomplete */ -export type ResourceTemplateReference = Infer; -export type PromptReference = Infer; -export type CompleteRequestParams = Infer; -export type CompleteRequest = Infer; -export type CompleteResult = Infer; - -/* Roots */ -export type Root = Infer; -export type ListRootsRequest = Infer; -export type ListRootsResult = Infer; -export type RootsListChangedNotification = Infer; - -/* Client messages */ -export type ClientRequest = Infer; -export type ClientNotification = Infer; -export type ClientResult = Infer; - -/* Server messages */ -export type ServerRequest = Infer; -export type ServerNotification = Infer; -export type ServerResult = Infer; - -/* Protocol type maps */ -type MethodToTypeMap = { - [T in U as T extends { method: infer M extends string } ? M : never]: T; -}; -export type RequestMethod = ClientRequest['method'] | ServerRequest['method']; -export type NotificationMethod = ClientNotification['method'] | ServerNotification['method']; -export type RequestTypeMap = MethodToTypeMap; -export type NotificationTypeMap = MethodToTypeMap; -export type ResultTypeMap = { - ping: EmptyResult; - initialize: InitializeResult; - 'completion/complete': CompleteResult; - 'logging/setLevel': EmptyResult; - 'prompts/get': GetPromptResult; - 'prompts/list': ListPromptsResult; - 'resources/list': ListResourcesResult; - 'resources/templates/list': ListResourceTemplatesResult; - 'resources/read': ReadResourceResult; - 'resources/subscribe': EmptyResult; - 'resources/unsubscribe': EmptyResult; - 'tools/call': CallToolResult | CreateTaskResult; - 'tools/list': ListToolsResult; - 'sampling/createMessage': CreateMessageResult | CreateMessageResultWithTools | CreateTaskResult; - 'elicitation/create': ElicitResult | CreateTaskResult; - 'roots/list': ListRootsResult; - 'tasks/get': GetTaskResult; - 'tasks/result': Result; - 'tasks/list': ListTasksResult; - 'tasks/cancel': CancelTaskResult; -}; - /* Runtime schema lookup — result schemas by method */ const resultSchemas: Record = { ping: EmptyResultSchema, diff --git a/packages/core/src/types/types.ts b/packages/core/src/types/types.ts index 462b6100e..2ac5b08fc 100644 --- a/packages/core/src/types/types.ts +++ b/packages/core/src/types/types.ts @@ -1,17 +1,405 @@ +import type * as z from 'zod/v4'; + import type { INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, METHOD_NOT_FOUND, PARSE_ERROR } from './constants.js'; -import type { - CompleteRequest, - CompleteRequestParams, - CreateMessageRequestParams, - ExpandRecursively, - Prompt, - PromptReference, - RequestMeta, - Resource, - ResourceTemplateReference, - Tool +// eslint-disable-next-line @typescript-eslint/consistent-type-imports -- value import needed for typeof in Infer<> +import { + AnnotationsSchema, + AudioContentSchema, + BaseMetadataSchema, + BaseRequestParamsSchema, + BlobResourceContentsSchema, + BooleanSchemaSchema, + CallToolRequestParamsSchema, + CallToolRequestSchema, + CallToolResultSchema, + CancelledNotificationParamsSchema, + CancelledNotificationSchema, + CancelTaskRequestSchema, + CancelTaskResultSchema, + ClientCapabilitiesSchema, + ClientNotificationSchema, + ClientRequestSchema, + ClientResultSchema, + CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema, + CompleteRequestSchema, + CompleteResultSchema, + ContentBlockSchema, + CreateMessageRequestParamsSchema, + CreateMessageRequestSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + CreateTaskResultSchema, + CursorSchema, + ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema, + ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema, + ElicitRequestSchema, + ElicitRequestURLParamsSchema, + ElicitResultSchema, + EmbeddedResourceSchema, + EmptyResultSchema, + EnumSchemaSchema, + GetPromptRequestParamsSchema, + GetPromptRequestSchema, + GetPromptResultSchema, + GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema, + GetTaskRequestSchema, + GetTaskResultSchema, + IconSchema, + IconsSchema, + ImageContentSchema, + ImplementationSchema, + InitializedNotificationSchema, + InitializeRequestParamsSchema, + InitializeRequestSchema, + InitializeResultSchema, + JSONRPCErrorResponseSchema, + JSONRPCMessageSchema, + JSONRPCNotificationSchema, + JSONRPCRequestSchema, + JSONRPCResponseSchema, + JSONRPCResultResponseSchema, + LegacyTitledEnumSchemaSchema, + ListPromptsRequestSchema, + ListPromptsResultSchema, + ListResourcesRequestSchema, + ListResourcesResultSchema, + ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema, + ListRootsRequestSchema, + ListRootsResultSchema, + ListTasksRequestSchema, + ListTasksResultSchema, + ListToolsRequestSchema, + ListToolsResultSchema, + 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, + SetLevelRequestParamsSchema, + SetLevelRequestSchema, + SingleSelectEnumSchemaSchema, + StringSchemaSchema, + SubscribeRequestParamsSchema, + SubscribeRequestSchema, + TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema, + TaskMetadataSchema, + TaskSchema, + TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema, + TaskStatusSchema, + TextContentSchema, + TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema, + ToolChoiceSchema, + ToolExecutionSchema, + ToolListChangedNotificationSchema, + ToolResultContentSchema, + ToolSchema, + ToolUseContentSchema, + UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema } from './schemas.js'; +/* JSON types */ +export type JSONValue = string | number | boolean | null | JSONObject | JSONArray; +export type JSONObject = { [key: string]: JSONValue }; +export type JSONArray = JSONValue[]; + +/** + * Utility types + */ +export type ExpandRecursively = T extends object ? (T extends infer O ? { [K in keyof O]: ExpandRecursively } : never) : T; + +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive + ? T + : T extends Array + ? Array> + : T extends Set + ? Set> + : T extends Map + ? Map, Flatten> + : T extends object + ? { [K in keyof T]: Flatten } + : T; + +type Infer = Flatten>; + +/* JSON-RPC types */ +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type TaskAugmentedRequestParams = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCErrorResponse = Infer; +export type JSONRPCResultResponse = Infer; +export type JSONRPCMessage = Infer; +export type RequestParams = Infer; +export type NotificationParams = Infer; + +/* Empty result */ +export type EmptyResult = Infer; + +/* Cancellation */ +export type CancelledNotificationParams = Infer; +export type CancelledNotification = Infer; + +/* Base Metadata */ +export type Icon = Infer; +export type Icons = Infer; +export type BaseMetadata = Infer; +export type Annotations = Infer; +export type Role = Infer; + +/* Initialization */ +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequestParams = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; + +/* Ping */ +export type PingRequest = Infer; + +/* Progress notifications */ +export type Progress = Infer; +export type ProgressNotificationParams = Infer; +export type ProgressNotification = Infer; + +/* Tasks */ +export type Task = Infer; +export type TaskStatus = Infer; +export type TaskCreationParams = Infer; +export type TaskMetadata = Infer; +export type RelatedTaskMetadata = Infer; +export type CreateTaskResult = Infer; +export type TaskStatusNotificationParams = Infer; +export type TaskStatusNotification = Infer; +export type GetTaskRequest = Infer; +export type GetTaskResult = Infer; +export type GetTaskPayloadRequest = Infer; +export type ListTasksRequest = Infer; +export type ListTasksResult = Infer; +export type CancelTaskRequest = Infer; +export type CancelTaskResult = Infer; +export type GetTaskPayloadResult = Infer; + +/* Pagination */ +export type PaginatedRequestParams = Infer; +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; + +/* Resources */ +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +// TODO: Overlaps with exported `ResourceTemplate` class from `server`. +export type ResourceTemplateType = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ResourceRequestParams = Infer; +export type ReadResourceRequestParams = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequestParams = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequestParams = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotificationParams = Infer; +export type ResourceUpdatedNotification = Infer; + +/* Prompts */ +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequestParams = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type ToolUseContent = Infer; +export type ToolResultContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; + +/* Tools */ +export type ToolAnnotations = Infer; +export type ToolExecution = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolRequestParams = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; + +/* Logging */ +export type LoggingLevel = Infer; +export type SetLevelRequestParams = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; +export type LoggingMessageNotification = Infer; + +/* Sampling */ +export type ToolChoice = Infer; +export type ModelHint = Infer; +export type ModelPreferences = Infer; +export type SamplingContent = Infer; +export type SamplingMessageContentBlock = Infer; +export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; +export type CreateMessageResultWithTools = Infer; + +/* Elicitation */ +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type UntitledSingleSelectEnumSchema = Infer; +export type TitledSingleSelectEnumSchema = Infer; +export type LegacyTitledEnumSchema = Infer; +export type UntitledMultiSelectEnumSchema = Infer; +export type TitledMultiSelectEnumSchema = Infer; +export type SingleSelectEnumSchema = Infer; +export type MultiSelectEnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; +export type ElicitRequestFormParams = Infer; +export type ElicitRequestURLParams = Infer; +export type ElicitRequest = Infer; +export type ElicitationCompleteNotificationParams = Infer; +export type ElicitationCompleteNotification = Infer; +export type ElicitResult = Infer; + +/* Autocomplete */ +export type ResourceTemplateReference = Infer; +export type PromptReference = Infer; +export type CompleteRequestParams = Infer; +export type CompleteRequest = Infer; +export type CompleteResult = Infer; + +/* Roots */ +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; + +/* Client messages */ +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; + +/* Server messages */ +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; + +/* Protocol type maps */ +type MethodToTypeMap = { + [T in U as T extends { method: infer M extends string } ? M : never]: T; +}; +export type RequestMethod = ClientRequest['method'] | ServerRequest['method']; +export type NotificationMethod = ClientNotification['method'] | ServerNotification['method']; +export type RequestTypeMap = MethodToTypeMap; +export type NotificationTypeMap = MethodToTypeMap; +export type ResultTypeMap = { + ping: EmptyResult; + initialize: InitializeResult; + 'completion/complete': CompleteResult; + 'logging/setLevel': EmptyResult; + 'prompts/get': GetPromptResult; + 'prompts/list': ListPromptsResult; + 'resources/list': ListResourcesResult; + 'resources/templates/list': ListResourceTemplatesResult; + 'resources/read': ReadResourceResult; + 'resources/subscribe': EmptyResult; + 'resources/unsubscribe': EmptyResult; + 'tools/call': CallToolResult | CreateTaskResult; + 'tools/list': ListToolsResult; + 'sampling/createMessage': CreateMessageResult | CreateMessageResultWithTools | CreateTaskResult; + 'elicitation/create': ElicitResult | CreateTaskResult; + 'roots/list': ListRootsResult; + 'tasks/get': GetTaskResult; + 'tasks/result': Result; + 'tasks/list': ListTasksResult; + 'tasks/cancel': CancelTaskResult; +}; + /** * Information about a validated access token, provided to request handlers. */ @@ -75,7 +463,7 @@ export type ListChangedCallback = (error: Error | null, items: T[] | null) => /** * Options for subscribing to list changed notifications. * - * @typeParam T - The type of items in the list ({@linkcode Tool}, {@linkcode Prompt}, or {@linkcode Resource}) + * @typeParam T - The type of items in the list (`Tool`, `Prompt`, or `Resource`) */ export type ListChangedOptions = { /** diff --git a/packages/middleware/express/tsconfig.json b/packages/middleware/express/tsconfig.json index 96788ff0e..0292cb0c2 100644 --- a/packages/middleware/express/tsconfig.json +++ b/packages/middleware/express/tsconfig.json @@ -11,7 +11,7 @@ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ] } } diff --git a/packages/middleware/hono/tsconfig.json b/packages/middleware/hono/tsconfig.json index 96788ff0e..0292cb0c2 100644 --- a/packages/middleware/hono/tsconfig.json +++ b/packages/middleware/hono/tsconfig.json @@ -11,7 +11,7 @@ "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" ], "@modelcontextprotocol/core/public": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/publicExports.ts" + "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/exports/public/index.ts" ] } } diff --git a/packages/middleware/node/tsconfig.json b/packages/middleware/node/tsconfig.json index 059708824..098589535 100644 --- a/packages/middleware/node/tsconfig.json +++ b/packages/middleware/node/tsconfig.json @@ -8,7 +8,7 @@ "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], "@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/exports/public/index.ts"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"] } } diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.json index 2128f7747..0b3ab7600 100644 --- a/packages/server/tsconfig.json +++ b/packages/server/tsconfig.json @@ -6,7 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/exports/public/index.ts"], "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"], "@modelcontextprotocol/server/_shims": ["./src/shimsNode.ts"] } diff --git a/test/conformance/tsconfig.json b/test/conformance/tsconfig.json index 5b35f9aae..f52971974 100644 --- a/test/conformance/tsconfig.json +++ b/test/conformance/tsconfig.json @@ -6,7 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/exports/public/index.ts"], "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], "@modelcontextprotocol/express": ["./node_modules/@modelcontextprotocol/express/src/index.ts"], diff --git a/test/helpers/tsconfig.json b/test/helpers/tsconfig.json index ae4a76e66..ce4477394 100644 --- a/test/helpers/tsconfig.json +++ b/test/helpers/tsconfig.json @@ -6,7 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/exports/public/index.ts"], "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] } } diff --git a/test/integration/tsconfig.json b/test/integration/tsconfig.json index 73b14e94b..2f927336a 100644 --- a/test/integration/tsconfig.json +++ b/test/integration/tsconfig.json @@ -6,7 +6,7 @@ "paths": { "*": ["./*"], "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/publicExports.ts"], + "@modelcontextprotocol/core/public": ["./node_modules/@modelcontextprotocol/core/src/exports/public/index.ts"], "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], "@modelcontextprotocol/client/_shims": ["./node_modules/@modelcontextprotocol/client/src/shimsNode.ts"], "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], From b2b1e72790c14fdfa9d4fa9fb8ac69a7bf9b3a17 Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sat, 14 Mar 2026 17:14:02 +0200 Subject: [PATCH 3/5] comments fix --- packages/core/src/types/index.ts | 2 +- packages/core/src/types/types.ts | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 29ed78835..4bbdd0a99 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -1,5 +1,5 @@ // Internal barrel — re-exports everything for use within the SDK packages. -// External consumers should use publicExports.ts instead for a curated public API. +// External consumers should use exports/public/index.ts instead for a curated public API. export * from './constants.js'; export * from './enums.js'; export * from './errors.js'; diff --git a/packages/core/src/types/types.ts b/packages/core/src/types/types.ts index 2ac5b08fc..dc4761c8e 100644 --- a/packages/core/src/types/types.ts +++ b/packages/core/src/types/types.ts @@ -1,8 +1,7 @@ import type * as z from 'zod/v4'; import type { INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, METHOD_NOT_FOUND, PARSE_ERROR } from './constants.js'; -// eslint-disable-next-line @typescript-eslint/consistent-type-imports -- value import needed for typeof in Infer<> -import { +import type { AnnotationsSchema, AudioContentSchema, BaseMetadataSchema, From 7f8082b90744b47e08877b3c6c5f46cf484be1dc Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sat, 14 Mar 2026 17:21:41 +0200 Subject: [PATCH 4/5] public exports - no wildcard exports; header instructions; update CLAUDE.md --- CLAUDE.md | 13 +++++++++++++ packages/client/src/index.ts | 11 +++++++++-- packages/core/src/types/index.ts | 2 +- packages/server/src/index.ts | 13 +++++++++++-- 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fd087b23c..472ee06ec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,6 +62,19 @@ The SDK is organized into three main layers: - `Server` (`packages/server/src/server/server.ts`) - Server implementation extending Protocol with request handler registration - `McpServer` (`packages/server/src/server/mcp.ts`) - High-level server API with simplified resource/tool/prompt registration +### Public API Exports + +The SDK has a two-layer export structure to separate internal code from the public API: + +- **`@modelcontextprotocol/core`** (main entry, `packages/core/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/public`** (`packages/core/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/public`. + +When modifying exports: +- Use explicit named exports, not `export *`, in package `index.ts` files and `core/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/public` or package index files. + ### Transport System Transports (`packages/core/src/shared/transport.ts`) provide the communication layer: diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index b09a01987..9a1a7214e 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,4 +1,11 @@ -// Client-specific exports +// Public API for @modelcontextprotocol/client. +// +// This file defines the complete public surface. It consists of: +// - Package-specific exports: listed explicitly below (named imports) +// - Protocol-level types: re-exported from @modelcontextprotocol/core/public +// +// Any new export added here becomes public API. Use named exports, not wildcards. + export type { AddClientAuthentication, AuthResult, @@ -53,7 +60,7 @@ export { StreamableHTTPClientTransport } from './client/streamableHttp.js'; export { WebSocketClientTransport } from './client/websocket.js'; // experimental exports -export * from './experimental/index.js'; +export { ExperimentalClientTasks } from './experimental/tasks/client.js'; // re-export curated public API from core export * from '@modelcontextprotocol/core/public'; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 4bbdd0a99..8349a7496 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -1,5 +1,5 @@ // Internal barrel — re-exports everything for use within the SDK packages. -// External consumers should use exports/public/index.ts instead for a curated public API. +// The public API is defined in @modelcontextprotocol/core/public (see exports/public/index.ts). export * from './constants.js'; export * from './enums.js'; export * from './errors.js'; diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 01b1ef903..c680dffe7 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -1,4 +1,11 @@ -// Server-specific exports +// Public API for @modelcontextprotocol/server. +// +// This file defines the complete public surface. It consists of: +// - Package-specific exports: listed explicitly below (named imports) +// - Protocol-level types: re-exported from @modelcontextprotocol/core/public +// +// Any new export added here becomes public API. Use named exports, not wildcards. + export type { CompletableSchema, CompleteCallback } from './server/completable.js'; export { completable, isCompletable } from './server/completable.js'; export type { @@ -32,7 +39,9 @@ export type { export { WebStandardStreamableHTTPServerTransport } from './server/streamableHttp.js'; // experimental exports -export * from './experimental/index.js'; +export type { CreateTaskRequestHandler, TaskRequestHandler, ToolTaskHandler } from './experimental/tasks/interfaces.js'; +export { ExperimentalMcpServerTasks } from './experimental/tasks/mcpServer.js'; +export { ExperimentalServerTasks } from './experimental/tasks/server.js'; // re-export curated public API from core export * from '@modelcontextprotocol/core/public'; From 7c3542edd69f97adf976db5481297ef334c229fe Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sat, 14 Mar 2026 17:26:13 +0200 Subject: [PATCH 5/5] public export on core package - named exports, types.ts - add header comment --- packages/core/src/exports/public/index.ts | 56 +++++++++++++++++++---- packages/core/src/types/types.ts | 4 ++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/packages/core/src/exports/public/index.ts b/packages/core/src/exports/public/index.ts index b47a3aae9..48e150a79 100644 --- a/packages/core/src/exports/public/index.ts +++ b/packages/core/src/exports/public/index.ts @@ -72,25 +72,65 @@ export { createFetchWithInit } from '../../shared/transport.js'; export type { Variables } from '../../shared/uriTemplate.js'; export { UriTemplate } from '../../shared/uriTemplate.js'; -// Types — all TypeScript types (standalone interfaces + schema-derived) +// Types — all TypeScript types (standalone interfaces + schema-derived). +// This is the one intentional `export *`: types.ts contains only spec-derived TS +// types, and every type there should be public. See comment in types.ts. export * from '../../types/types.js'; // Constants -export * from '../../types/constants.js'; +export { + DEFAULT_NEGOTIATED_PROTOCOL_VERSION, + INTERNAL_ERROR, + INVALID_PARAMS, + INVALID_REQUEST, + JSONRPC_VERSION, + LATEST_PROTOCOL_VERSION, + METHOD_NOT_FOUND, + PARSE_ERROR, + RELATED_TASK_META_KEY, + SUPPORTED_PROTOCOL_VERSIONS +} from '../../types/constants.js'; // Enums -export * from '../../types/enums.js'; +export { ProtocolErrorCode } from '../../types/enums.js'; // Error classes -export * from '../../types/errors.js'; +export { ProtocolError, UrlElicitationRequiredError } from '../../types/errors.js'; // Type guards -export * from '../../types/guards.js'; +export { + assertCompleteRequestPrompt, + assertCompleteRequestResourceTemplate, + isInitializedNotification, + isInitializeRequest, + isJSONRPCErrorResponse, + isJSONRPCNotification, + isJSONRPCRequest, + isJSONRPCResultResponse, + isTaskAugmentedRequestParams +} from '../../types/guards.js'; // Experimental task types and classes -export * from '../../experimental/index.js'; +export { assertClientRequestTaskCapability, assertToolsCallTaskCapability } from '../../experimental/tasks/helpers.js'; +export type { + BaseQueuedMessage, + CreateTaskOptions, + CreateTaskServerContext, + QueuedError, + QueuedMessage, + QueuedNotification, + QueuedRequest, + QueuedResponse, + TaskMessageQueue, + TaskServerContext, + TaskStore, + TaskToolExecution +} from '../../experimental/tasks/interfaces.js'; +export { isTerminal } from '../../experimental/tasks/interfaces.js'; +export { InMemoryTaskMessageQueue, InMemoryTaskStore } from '../../experimental/tasks/stores/inMemory.js'; // Validator types and classes -export * from '../../validators/ajvProvider.js'; -export * from '../../validators/cfWorkerProvider.js'; +export { AjvJsonSchemaValidator } from '../../validators/ajvProvider.js'; +export type { CfWorkerSchemaDraft } from '../../validators/cfWorkerProvider.js'; +export { CfWorkerJsonSchemaValidator } from '../../validators/cfWorkerProvider.js'; export type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from '../../validators/types.js'; diff --git a/packages/core/src/types/types.ts b/packages/core/src/types/types.ts index dc4761c8e..cfc7d340f 100644 --- a/packages/core/src/types/types.ts +++ b/packages/core/src/types/types.ts @@ -1,3 +1,7 @@ +// ⚠️ PUBLIC API — every export from this file is re-exported via `export *` +// in exports/public/index.ts and becomes part of the SDK's public surface. +// Only add MCP-spec-derived types here. Internal helpers belong elsewhere. + import type * as z from 'zod/v4'; import type { INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, METHOD_NOT_FOUND, PARSE_ERROR } from './constants.js';