diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7f4ba87c7..ea619bd01 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -18,19 +18,35 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 18 + node-version: 24 cache: npm - run: npm ci - run: npm run check - run: npm run build + + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [18, 24] + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + + - run: npm ci - run: npm test publish: runs-on: ubuntu-latest if: github.event_name == 'release' environment: release - needs: build + needs: [build, test] permissions: contents: read @@ -40,7 +56,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 18 + node-version: 24 cache: npm registry-url: 'https://registry.npmjs.org/' diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 000000000..00ffd6efe --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,27 @@ +name: Publish Any Commit +permissions: + contents: read +on: + pull_request: + push: + branches: + - '**' + tags: + - '!**' + +jobs: + pkg-publish: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + + - run: npm ci + - name: Build + run: npm run build + - name: Publish + run: npx pkg-pr-new publish diff --git a/eslint.config.mjs b/eslint.config.mjs index 5849013f3..5fd27f3ab 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -15,6 +15,9 @@ export default tseslint.config( '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }] } }, + { + ignores: ['src/spec.types.ts'] + }, { files: ['src/client/**/*.ts', 'src/server/**/*.ts'], ignores: ['**/*.test.ts'], diff --git a/package-lock.json b/package-lock.json index b29ef11fd..8b245aa0c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.21.1", + "version": "1.22.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.21.1", + "version": "1.22.0", "license": "MIT", "dependencies": { "ajv": "^8.17.1", diff --git a/package.json b/package.json index 5c595515d..d8eebaeb9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.21.1", + "version": "1.22.0", "description": "Model Context Protocol implementation for TypeScript", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", diff --git a/spec.types.ts b/spec.types.ts new file mode 100644 index 000000000..9c8a0baf9 --- /dev/null +++ b/spec.types.ts @@ -0,0 +1,1578 @@ +/* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @internal + */ +export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse | JSONRPCError; + +/** @internal */ +export const LATEST_PROTOCOL_VERSION = 'DRAFT-2025-v3'; +/** @internal */ +export const JSONRPC_VERSION = '2.0'; + +/** + * A progress token, used to associate progress notifications with the original request. + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + */ +export type Cursor = string; + +/** @internal */ +export interface Request { + method: string; + params?: { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +} + +/** @internal */ +export interface Notification { + method: string; + params?: { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; + }; +} + +export interface Result { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; +} + +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + */ +export interface JSONRPCResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +// Standard JSON-RPC error codes +/** @internal */ +export const PARSE_ERROR = -32700; +/** @internal */ +export const INVALID_REQUEST = -32600; +/** @internal */ +export const METHOD_NOT_FOUND = -32601; +/** @internal */ +export const INVALID_PARAMS = -32602; +/** @internal */ +export const INTERNAL_ERROR = -32603; + +/** + * A response to a request that indicates an error occurred. + */ +export interface JSONRPCError { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + error: Error; +} + +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +export type EmptyResult = Result; + +/* 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 `initialize` request. + * + * @category notifications/cancelled + */ +export interface CancelledNotification extends JSONRPCNotification { + method: 'notifications/cancelled'; + params: { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; + }; +} + +/* Initialization */ +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category initialize + */ +export interface InitializeRequest extends JSONRPCRequest { + method: 'initialize'; + params: { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; + }; +} + +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category initialize + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} + +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category notifications/initialized + */ +export interface InitializedNotification extends JSONRPCNotification { + method: 'notifications/initialized'; +} + +/** + * 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 interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: object; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: object; +} + +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; +} + +/** + * An optionally-sized icon that can be displayed in a user interface. + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: 'light' | 'dark'; +} + +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} + +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} + +/** + * Describes the MCP implementation + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category ping + */ +export interface PingRequest extends JSONRPCRequest { + method: 'ping'; +} + +/* Progress notifications */ +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export interface ProgressNotification extends JSONRPCNotification { + method: 'notifications/progress'; + params: { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; + }; +} + +/* Pagination */ +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; + }; +} + +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + * + * @category resources/list + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: 'resources/list'; +} + +/** + * The server's response to a resources/list request from the client. + * + * @category resources/list + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} + +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category resources/templates/list + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: 'resources/templates/list'; +} + +/** + * The server's response to a resources/templates/list request from the client. + * + * @category resources/templates/list + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category resources/read + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: 'resources/read'; + params: { + /** + * 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: string; + }; +} + +/** + * The server's response to a resources/read request from the client. + * + * @category resources/read + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @category notifications/resources/list_changed + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: 'notifications/resources/list_changed'; +} + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category resources/subscribe + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: 'resources/subscribe'; + params: { + /** + * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; + }; +} + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category resources/unsubscribe + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: 'resources/unsubscribe'; + params: { + /** + * The URI of the resource to unsubscribe from. + * + * @format uri + */ + uri: string; + }; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category notifications/resources/updated + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: 'notifications/resources/updated'; + params: { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; + }; +} + +/** + * A known resource that the server is capable of reading. + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A template description for resources available on the server. + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The contents of a specific resource or sub-resource. + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category prompts/list + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: 'prompts/list'; +} + +/** + * The server's response to a prompts/list request from the client. + * + * @category prompts/list + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} + +/** + * Used by the client to get a prompt provided by the server. + * + * @category prompts/get + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: 'prompts/get'; + params: { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * The server's response to a prompts/get request from the client. + * + * @category prompts/get + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A prompt or prompt template that the server offers. + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Describes an argument that a prompt can accept. + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + */ +export type Role = 'user' | 'assistant'; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export interface ResourceLink extends Resource { + type: 'resource_link'; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + */ +export interface EmbeddedResource { + type: 'resource'; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category notifications/prompts/list_changed + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: 'notifications/prompts/list_changed'; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + * + * @category tools/list + */ +export interface ListToolsRequest extends PaginatedRequest { + method: 'tools/list'; +} + +/** + * The server's response to a tools/list request from the client. + * + * @category tools/list + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} + +/** + * The server's response to a tool call. + * + * @category tools/call + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} + +/** + * Used by the client to invoke a tool provided by the server. + * + * @category tools/call + */ +export interface CallToolRequest extends JSONRPCRequest { + method: 'tools/call'; + params: { + name: string; + arguments?: { [key: string]: unknown }; + }; +} + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category notifications/tools/list_changed + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: 'notifications/tools/list_changed'; +} + +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Definition for a tool the client can call. + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + type: 'object'; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + */ + outputSchema?: { + type: 'object'; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/* Logging */ +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category logging/setLevel + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: 'logging/setLevel'; + params: { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; + }; +} + +/** + * JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @category notifications/message + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: 'notifications/message'; + params: { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; + }; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + */ +export type LoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency'; + +/* Sampling */ +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @category sampling/createMessage + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: 'sampling/createMessage'; + params: { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. + */ + includeContext?: 'none' | 'thisServer' | 'allServers'; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + }; +} + +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category sampling/createMessage + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + */ + stopReason?: 'endTurn' | 'stopSequence' | 'maxTokens' | string; +} + +/** + * Describes a message issued to or received from an LLM API. + */ +export interface SamplingMessage { + role: Role; + content: TextContent | ImageContent | AudioContent; +} + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + */ +export interface Annotations { + /** + * Describes who the intended customer of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} + +export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; + +/** + * Text provided to or from an LLM. + */ +export interface TextContent { + type: 'text'; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * An image provided to or from an LLM. + */ +export interface ImageContent { + type: 'image'; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Audio provided to or from an LLM. + */ +export interface AudioContent { + type: 'audio'; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * A request from the client to the server, to ask for completion options. + * + * @category completion/complete + */ +export interface CompleteRequest extends JSONRPCRequest { + method: 'completion/complete'; + params: { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; + }; +} + +/** + * The server's response to a completion/complete request + * + * @category completion/complete + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A reference to a resource or resource template definition. + */ +export interface ResourceTemplateReference { + type: 'ref/resource'; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + */ +export interface PromptReference extends BaseMetadata { + type: 'ref/prompt'; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category roots/list + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: 'roots/list'; +} + +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category roots/list + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category notifications/roots/list_changed + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: 'notifications/roots/list_changed'; +} + +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category elicitation/create + */ +export interface ElicitRequest extends JSONRPCRequest { + method: 'elicitation/create'; + params: { + /** + * The message to present to the user. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + type: 'object'; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; + }; +} + +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + */ +export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; + +export interface StringSchema { + type: 'string'; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: 'email' | 'uri' | 'date' | 'date-time'; + default?: string; +} + +export interface NumberSchema { + type: 'number' | 'integer'; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} + +export interface BooleanSchema { + type: 'boolean'; + title?: string; + description?: string; + default?: boolean; +} + +export interface EnumSchema { + type: 'string'; + title?: string; + description?: string; + enum: string[]; + enumNames?: string[]; // Display names for enum values + default?: string; +} + +/** + * The client's response to an elicitation request. + * + * @category elicitation/create + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: 'accept' | 'decline' | 'cancel'; + + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + */ + content?: { [key: string]: string | number | boolean }; +} + +/* Client messages */ +/** @internal */ +export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest; + +/** @internal */ +export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification; + +/** @internal */ +export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult; + +/* Server messages */ +/** @internal */ +export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest; + +/** @internal */ +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification; + +/** @internal */ +export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult; diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index fc71b03d9..8124fe768 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -1585,10 +1585,81 @@ describe('OAuth Authorization', () => { // First call should be to protected resource metadata expect(mockFetch.mock.calls[0][0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - // Second call should be to oauth metadata + // Second call should be to oauth metadata at the root path expect(mockFetch.mock.calls[1][0].toString()).toBe('https://resource.example.com/.well-known/oauth-authorization-server'); }); + it('uses base URL (with root path) as authorization server when protected-resource-metadata discovery fails', async () => { + // Setup: First call to protected resource metadata fails (404) + // When no authorization_servers are found in protected resource metadata, + // the auth server URL should be set to the base URL with "/" path + let callCount = 0; + mockFetch.mockImplementation(url => { + callCount++; + + const urlString = url.toString(); + + if (urlString.includes('/.well-known/oauth-protected-resource')) { + // Protected resource metadata discovery attempts (both path-aware and root) fail with 404 + return Promise.resolve({ + ok: false, + status: 404 + }); + } else if (urlString === 'https://resource.example.com/.well-known/oauth-authorization-server') { + // Should fetch from base URL with root path, not the full serverUrl path + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: 'https://resource.example.com/', + authorization_endpoint: 'https://resource.example.com/authorize', + token_endpoint: 'https://resource.example.com/token', + registration_endpoint: 'https://resource.example.com/register', + response_types_supported: ['code'], + code_challenge_methods_supported: ['S256'] + }) + }); + } else if (urlString.includes('/register')) { + // Client registration succeeds + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + client_id: 'test-client-id', + client_secret: 'test-client-secret', + client_id_issued_at: 1612137600, + client_secret_expires_at: 1612224000, + redirect_uris: ['http://localhost:3000/callback'], + client_name: 'Test Client' + }) + }); + } + + return Promise.reject(new Error(`Unexpected fetch call #${callCount}: ${urlString}`)); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue(undefined); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + mockProvider.saveClientInformation = jest.fn(); + + // Call the auth function with a server URL that has a path + const result = await auth(mockProvider, { + serverUrl: 'https://resource.example.com/path/to/server' + }); + + // Verify the result + expect(result).toBe('REDIRECT'); + + // Verify that the oauth-authorization-server call uses the base URL + // This proves the fix: using new URL("/", serverUrl) instead of serverUrl + const authServerCall = mockFetch.mock.calls.find(call => + call[0].toString().includes('/.well-known/oauth-authorization-server') + ); + expect(authServerCall).toBeDefined(); + expect(authServerCall[0].toString()).toBe('https://resource.example.com/.well-known/oauth-authorization-server'); + }); + it('passes resource parameter through authorization flow', async () => { // Mock successful metadata discovery - need to include protected resource metadata mockFetch.mockImplementation(url => { diff --git a/src/client/auth.ts b/src/client/auth.ts index 6d4ede84b..fba0e7bf7 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -348,6 +348,7 @@ async function authInternal( ): Promise { let resourceMetadata: OAuthProtectedResourceMetadata | undefined; let authorizationServerUrl: string | URL | undefined; + try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { @@ -359,10 +360,10 @@ async function authInternal( /** * If we don't get a valid authorization server metadata from protected resource metadata, - * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server acts as the Authorization server. + * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. */ if (!authorizationServerUrl) { - authorizationServerUrl = serverUrl; + authorizationServerUrl = new URL('/', serverUrl); } const resource: URL | undefined = await selectResourceURL(serverUrl, provider, resourceMetadata); diff --git a/src/client/index.test.ts b/src/client/index.test.ts index de37b2d90..912abaac3 100644 --- a/src/client/index.test.ts +++ b/src/client/index.test.ts @@ -217,8 +217,7 @@ test('should connect new client to old, supported server version', async () => { const client = new Client( { name: 'new client', - version: '1.0', - protocolVersion: LATEST_PROTOCOL_VERSION + version: '1.0' }, { capabilities: { @@ -279,8 +278,7 @@ test('should negotiate version when client is old, and newer server supports its const client = new Client( { name: 'old client', - version: '1.0', - protocolVersion: OLD_VERSION + version: '1.0' }, { capabilities: { @@ -342,8 +340,7 @@ test("should throw when client is old, and server doesn't support its version", const client = new Client( { name: 'old client', - version: '1.0', - protocolVersion: OLD_VERSION + version: '1.0' }, { capabilities: { diff --git a/src/client/index.ts b/src/client/index.ts index cc6819815..5770f9d7f 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -36,10 +36,54 @@ import { SUPPORTED_PROTOCOL_VERSIONS, type SubscribeRequest, type Tool, - type UnsubscribeRequest + type UnsubscribeRequest, + ElicitResultSchema, + ElicitRequestSchema } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from '../validation/types.js'; +import { ZodLiteral, ZodObject, z } from 'zod'; +import type { RequestHandlerExtra } from '../shared/protocol.js'; + +/** + * Elicitation default application helper. Applies defaults to the data based on the schema. + * + * @param schema - The schema to apply defaults to. + * @param data - The data to apply defaults to. + */ +function applyElicitationDefaults(schema: JsonSchemaType | undefined, data: unknown): void { + if (!schema || data === null || typeof data !== 'object') return; + + // Handle object properties + if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { + const obj = data as Record; + const props = schema.properties as Record; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + // If missing or explicitly undefined, apply default if present + if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { + obj[key] = propSchema.default; + } + // Recurse into existing nested objects/arrays + if (obj[key] !== undefined) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + applyElicitationDefaults(sub, data); + } + } + + // Combine schemas + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + applyElicitationDefaults(sub, data); + } + } +} export type ClientOptions = ProtocolOptions & { /** @@ -141,6 +185,64 @@ export class Client< this._capabilities = mergeCapabilities(this._capabilities, capabilities); } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + public override setRequestHandler< + T extends ZodObject<{ + method: ZodLiteral; + }> + >( + requestSchema: T, + handler: ( + request: z.infer, + extra: RequestHandlerExtra + ) => ClientResult | ResultT | Promise + ): void { + const method = requestSchema.shape.method.value; + if (method === 'elicitation/create') { + const wrappedHandler = async ( + request: z.infer, + extra: RequestHandlerExtra + ): Promise => { + const validatedRequest = ElicitRequestSchema.safeParse(request); + if (!validatedRequest.success) { + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${validatedRequest.error.message}`); + } + + const result = await Promise.resolve(handler(request, extra)); + + const validationResult = ElicitResultSchema.safeParse(result); + if (!validationResult.success) { + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${validationResult.error.message}`); + } + + const validatedResult = validationResult.data; + + if ( + this._capabilities.elicitation?.applyDefaults && + validatedResult.action === 'accept' && + validatedResult.content && + validatedRequest.data.params.requestedSchema + ) { + try { + applyElicitationDefaults(validatedRequest.data.params.requestedSchema, validatedResult.content); + } catch { + // gracefully ignore errors in default application + } + } + + return validatedResult; + }; + + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler as unknown as typeof handler); + } + + // Non-elicitation handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + protected assertCapability(capability: keyof ServerCapabilities, method: string): void { if (!this._serverCapabilities?.[capability]) { throw new Error(`Server does not support ${capability} (required for ${method})`); diff --git a/src/examples/client/simpleStreamableHttp.ts b/src/examples/client/simpleStreamableHttp.ts index bf58a7a79..353861397 100644 --- a/src/examples/client/simpleStreamableHttp.ts +++ b/src/examples/client/simpleStreamableHttp.ts @@ -703,7 +703,7 @@ async function getPrompt(name: string, args: Record): Promise { - console.log(` [${index + 1}] ${msg.role}: ${msg.content.text}`); + console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); }); } catch (error) { console.log(`Error getting prompt ${name}: ${error}`); diff --git a/src/examples/server/elicitationExample.ts b/src/examples/server/elicitationExample.ts index 8b1f81d12..6607e8cca 100644 --- a/src/examples/server/elicitationExample.ts +++ b/src/examples/server/elicitationExample.ts @@ -177,8 +177,7 @@ mcpServer.registerTool( startTime: { type: 'string', title: 'Start Time', - description: 'Event start time (HH:MM)', - pattern: '^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$' + description: 'Event start time (HH:MM)' }, duration: { type: 'integer', @@ -268,8 +267,7 @@ mcpServer.registerTool( zipCode: { type: 'string', title: 'ZIP/Postal Code', - description: '5-digit ZIP code', - pattern: '^[0-9]{5}$' + description: '5-digit ZIP code' }, phone: { type: 'string', diff --git a/src/integration-tests/taskResumability.test.ts b/src/integration-tests/taskResumability.test.ts index d397ffab3..224d8e382 100644 --- a/src/integration-tests/taskResumability.test.ts +++ b/src/integration-tests/taskResumability.test.ts @@ -145,13 +145,13 @@ describe('Transport resumability', () => { // across client disconnection/reconnection it('should resume long-running notifications with lastEventId', async () => { // Create unique client ID for this test - const clientId = 'test-client-long-running'; + const clientTitle = 'test-client-long-running'; const notifications = []; let lastEventId: string | undefined; // Create first client const client1 = new Client({ - id: clientId, + title: clientTitle, name: 'test-client', version: '1.0.0' }); @@ -223,7 +223,7 @@ describe('Transport resumability', () => { // Create second client with same client ID const client2 = new Client({ - id: clientId, + title: clientTitle, name: 'test-client', version: '1.0.0' }); diff --git a/src/server/elicitation.test.ts b/src/server/elicitation.test.ts index 845a08cb2..dad56d133 100644 --- a/src/server/elicitation.test.ts +++ b/src/server/elicitation.test.ts @@ -9,7 +9,7 @@ import { Client } from '../client/index.js'; import { InMemoryTransport } from '../inMemory.js'; -import { ElicitRequestSchema } from '../types.js'; +import { ElicitRequestParams, ElicitRequestSchema } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; import { CfWorkerJsonSchemaValidator } from '../validation/cfworker-provider.js'; import { Server } from './index.js'; @@ -17,36 +17,58 @@ import { Server } from './index.js'; const ajvProvider = new AjvJsonSchemaValidator(); const cfWorkerProvider = new CfWorkerJsonSchemaValidator(); +let server: Server; +let client: Client; + describe('Elicitation Flow', () => { describe('with AJV validator', () => { + beforeEach(async () => { + server = new Server( + { name: 'test-server', version: '1.0.0' }, + { + capabilities: {}, + jsonSchemaValidator: ajvProvider + } + ); + + client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); + }); + testElicitationFlow(ajvProvider, 'AJV'); }); describe('with CfWorker validator', () => { + beforeEach(async () => { + server = new Server( + { name: 'test-server', version: '1.0.0' }, + { + capabilities: {}, + jsonSchemaValidator: cfWorkerProvider + } + ); + + client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); + }); + testElicitationFlow(cfWorkerProvider, 'CfWorker'); }); }); function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWorkerProvider, validatorName: string) { test(`${validatorName}: should elicit simple object with string field`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { name: 'John Doe' } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'What is your name?', requestedSchema: { @@ -65,24 +87,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should elicit object with integer field`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { age: 42 } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'What is your age?', requestedSchema: { @@ -101,24 +110,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should elicit object with boolean field`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { agree: true } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Do you agree?', requestedSchema: { @@ -137,16 +133,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should elicit complex object with multiple fields`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - const userData = { name: 'Jane Smith', email: 'jane@example.com', @@ -163,9 +149,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo content: userData })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Please provide your information', requestedSchema: { @@ -176,6 +159,7 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo age: { type: 'integer', minimum: 0, maximum: 150 }, street: { type: 'string' }, city: { type: 'string' }, + // @ts-expect-error - pattern is not a valid property by MCP spec, however it is making use of the Ajv validator zipCode: { type: 'string', pattern: '^[0-9]{5}$' }, newsletter: { type: 'boolean' }, notifications: { type: 'boolean' } @@ -191,16 +175,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should reject invalid object (missing required field)`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { @@ -209,9 +183,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - await expect( server.elicitInput({ message: 'Please provide your information', @@ -228,16 +199,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should reject invalid field type`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { @@ -246,9 +207,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - await expect( server.elicitInput({ message: 'Please provide your information', @@ -265,24 +223,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should reject invalid string (too short)`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { name: '' } // Too short })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - await expect( server.elicitInput({ message: 'What is your name?', @@ -298,24 +243,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should reject invalid integer (out of range)`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { age: 200 } // Too high })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - await expect( server.elicitInput({ message: 'What is your age?', @@ -331,30 +263,18 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should reject invalid pattern`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { zipCode: 'ABC123' } // Doesn't match pattern })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - await expect( server.elicitInput({ message: 'Enter a 5-digit zip code', requestedSchema: { type: 'object', properties: { + // @ts-expect-error - pattern is not a valid property by MCP spec, however it is making use of the Ajv validator zipCode: { type: 'string', pattern: '^[0-9]{5}$' } }, required: ['zipCode'] @@ -364,23 +284,10 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should allow decline action without validation`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'decline' })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Please provide your information', requestedSchema: { @@ -398,23 +305,10 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should allow cancel action without validation`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'cancel' })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Please provide your information', requestedSchema: { @@ -432,16 +326,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should handle multiple sequential elicitation requests`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - let requestCount = 0; client.setRequestHandler(ElicitRequestSchema, request => { requestCount++; @@ -455,9 +339,6 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo return { action: 'decline' }; }); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const nameResult = await server.elicitInput({ message: 'What is your name?', requestedSchema: { @@ -498,24 +379,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should validate with optional fields present`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { name: 'John', nickname: 'Johnny' } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Enter your name', requestedSchema: { @@ -535,24 +403,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should validate with optional fields absent`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { name: 'John' } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Enter your name', requestedSchema: { @@ -572,24 +427,11 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); test(`${validatorName}: should validate email format`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { email: 'user@example.com' } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - const result = await server.elicitInput({ message: 'Enter your email', requestedSchema: { @@ -607,7 +449,7 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }); }); - test(`${validatorName}: should reject invalid email format`, async () => { + test(`${validatorName}: should default missing fields from schema defaults`, async () => { const server = new Server( { name: 'test-server', version: '1.0.0' }, { @@ -616,16 +458,128 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo } ); - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); + const client = new Client( + { name: 'test-client', version: '1.0.0' }, + { + capabilities: { + elicitation: { + applyDefaults: true + } + } + } + ); + + const testSchemaProperties: ElicitRequestParams['requestedSchema'] = { + type: 'object', + properties: { + subscribe: { type: 'boolean', default: true }, + nickname: { type: 'string', default: 'Guest' }, + age: { type: 'integer', minimum: 0, maximum: 150, default: 18 }, + color: { type: 'string', enum: ['red', 'green'], default: 'green' }, + untitledSingleSelectEnum: { + type: 'string', + title: 'Untitled Single Select Enum', + description: 'Choose your favorite color', + enum: ['red', 'green', 'blue'], + default: 'green' + }, + untitledMultipleSelectEnum: { + type: 'array', + title: 'Untitled Multiple Select Enum', + description: 'Choose your favorite colors', + minItems: 1, + maxItems: 3, + items: { type: 'string', enum: ['red', 'green', 'blue'] }, + default: ['green', 'blue'] + }, + titledSingleSelectEnum: { + type: 'string', + title: 'Single Select Enum', + description: 'Choose your favorite color', + oneOf: [ + { const: 'red', title: 'Red' }, + { const: 'green', title: 'Green' }, + { const: 'blue', title: 'Blue' } + ], + default: 'green' + }, + titledMultipleSelectEnum: { + type: 'array', + title: 'Multiple Select Enum', + description: 'Choose your favorite colors', + minItems: 1, + maxItems: 3, + items: { + anyOf: [ + { const: 'red', title: 'Red' }, + { const: 'green', title: 'Green' }, + { const: 'blue', title: 'Blue' } + ] + }, + default: ['green', 'blue'] + }, + legacyTitledEnum: { + type: 'string', + title: 'Legacy Titled Enum', + description: 'Choose your favorite color', + enum: ['red', 'green', 'blue'], + enumNames: ['Red', 'Green', 'Blue'], + default: 'green' + }, + optionalWithADefault: { type: 'string', default: 'default value' } + }, + required: [ + 'subscribe', + 'nickname', + 'age', + 'color', + 'titledSingleSelectEnum', + 'titledMultipleSelectEnum', + 'untitledSingleSelectEnum', + 'untitledMultipleSelectEnum' + ] + }; + + // Client returns no values; SDK should apply defaults automatically (and validate) + client.setRequestHandler(ElicitRequestSchema, request => { + expect(request.params.requestedSchema).toEqual(testSchemaProperties); + return { + action: 'accept', + content: {} + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); + + const result = await server.elicitInput({ + message: 'Provide your preferences', + requestedSchema: testSchemaProperties + }); + + expect(result).toEqual({ + action: 'accept', + content: { + subscribe: true, + nickname: 'Guest', + age: 18, + color: 'green', + untitledSingleSelectEnum: 'green', + untitledMultipleSelectEnum: ['green', 'blue'], + titledSingleSelectEnum: 'green', + titledMultipleSelectEnum: ['green', 'blue'], + legacyTitledEnum: 'green', + optionalWithADefault: 'default value' + } + }); + }); + test(`${validatorName}: should reject invalid email format`, async () => { client.setRequestHandler(ElicitRequestSchema, _request => ({ action: 'accept', content: { email: 'not-an-email' } })); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - await expect( server.elicitInput({ message: 'Enter your email', @@ -639,4 +593,369 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo }) ).rejects.toThrow(/does not match requested schema/); }); + + // Enums - Valid - Single Select - Untitled / Titled + + test(`${validatorName}: should succeed with valid selection in single-select untitled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: 'Red' + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'string', + title: 'Color Selection', + description: 'Choose your favorite color', + enum: ['Red', 'Green', 'Blue'], + default: 'Green' + } + }, + required: ['color'] + } + }) + ).resolves.toEqual({ + action: 'accept', + content: { + color: 'Red' + } + }); + }); + + test(`${validatorName}: should succeed with valid selection in single-select titled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: '#FF0000' + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'string', + title: 'Color Selection', + description: 'Choose your favorite color', + oneOf: [ + { const: '#FF0000', title: 'Red' }, + { const: '#00FF00', title: 'Green' }, + { const: '#0000FF', title: 'Blue' } + ], + default: '#00FF00' + } + }, + required: ['color'] + } + }) + ).resolves.toEqual({ + action: 'accept', + content: { + color: '#FF0000' + } + }); + }); + + test(`${validatorName}: should succeed with valid selection in single-select titled legacy enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: '#FF0000' + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'string', + title: 'Color Selection', + description: 'Choose your favorite color', + enum: ['#FF0000', '#00FF00', '#0000FF'], + enumNames: ['Red', 'Green', 'Blue'], + default: '#00FF00' + } + }, + required: ['color'] + } + }) + ).resolves.toEqual({ + action: 'accept', + content: { + color: '#FF0000' + } + }); + }); + + // Enums - Valid - Multi Select - Untitled / Titled + + test(`${validatorName}: should succeed with valid selection in multi-select untitled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + colors: ['Red', 'Blue'] + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + colors: { + type: 'array', + title: 'Color Selection', + description: 'Choose your favorite colors', + minItems: 1, + maxItems: 3, + items: { + type: 'string', + enum: ['Red', 'Green', 'Blue'] + } + } + }, + required: ['colors'] + } + }) + ).resolves.toEqual({ + action: 'accept', + content: { + colors: ['Red', 'Blue'] + } + }); + }); + + test(`${validatorName}: should succeed with valid selection in multi-select titled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + colors: ['#FF0000', '#0000FF'] + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + colors: { + type: 'array', + title: 'Color Selection', + description: 'Choose your favorite colors', + minItems: 1, + maxItems: 3, + items: { + anyOf: [ + { const: '#FF0000', title: 'Red' }, + { const: '#00FF00', title: 'Green' }, + { const: '#0000FF', title: 'Blue' } + ] + } + } + }, + required: ['colors'] + } + }) + ).resolves.toEqual({ + action: 'accept', + content: { + colors: ['#FF0000', '#0000FF'] + } + }); + }); + + // Enums - Invalid - Single Select - Untitled / Titled + + test(`${validatorName}: should reject invalid selection in single-select untitled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: 'Black' // Color not in enum list + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'string', + title: 'Color Selection', + description: 'Choose your favorite color', + enum: ['Red', 'Green', 'Blue'], + default: 'Green' + } + }, + required: ['color'] + } + }) + ).rejects.toThrow(/^MCP error -32602: Elicitation response content does not match requested schema/); + }); + + test(`${validatorName}: should reject invalid selection in single-select titled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: 'Red' // Should be "#FF0000" (const not title) + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'string', + title: 'Color Selection', + description: 'Choose your favorite color', + oneOf: [ + { const: '#FF0000', title: 'Red' }, + { const: '#00FF00', title: 'Green' }, + { const: '#0000FF', title: 'Blue' } + ], + default: '#00FF00' + } + }, + required: ['color'] + } + }) + ).rejects.toThrow(/^MCP error -32602: Elicitation response content does not match requested schema/); + }); + + test(`${validatorName}: should reject invalid selection in single-select titled legacy enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: 'Red' // Should be "#FF0000" (enum not enumNames) + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'string', + title: 'Color Selection', + description: 'Choose your favorite color', + enum: ['#FF0000', '#00FF00', '#0000FF'], + enumNames: ['Red', 'Green', 'Blue'], + default: '#00FF00' + } + }, + required: ['color'] + } + }) + ).rejects.toThrow(/^MCP error -32602: Elicitation response content does not match requested schema/); + }); + + // Enums - Invalid - Multi Select - Untitled / Titled + + test(`${validatorName}: should reject invalid selection in multi-select untitled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + color: 'Red' // Should be array, not string + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + color: { + type: 'array', + title: 'Color Selection', + description: 'Choose your favorite colors', + minItems: 1, + maxItems: 3, + items: { + type: 'string', + enum: ['Red', 'Green', 'Blue'] + } + } + }, + required: ['color'] + } + }) + ).rejects.toThrow(/^MCP error -32602: Elicitation response content does not match requested schema/); + }); + + test(`${validatorName}: should reject invalid selection in multi-select titled enum`, async () => { + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, _request => ({ + action: 'accept', + content: { + colors: ['Red', 'Blue'] // Should be ["#FF0000", "#0000FF"] (const not title) + } + })); + + // Test with valid response + await expect( + server.elicitInput({ + message: 'Please provide your information', + requestedSchema: { + type: 'object', + properties: { + colors: { + type: 'array', + title: 'Color Selection', + description: 'Choose your favorite colors', + minItems: 1, + maxItems: 3, + items: { + anyOf: [ + { const: '#FF0000', title: 'Red' }, + { const: '#00FF00', title: 'Green' }, + { const: '#0000FF', title: 'Blue' } + ] + } + } + }, + required: ['colors'] + } + }) + ).rejects.toThrow(/^MCP error -32602: Elicitation response content does not match requested schema/); + }); } diff --git a/src/server/index.test.ts b/src/server/index.test.ts index bea9c31d6..d2c453931 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -702,9 +702,7 @@ test('should handle server cancelling a request', async () => { version: '1.0' }, { - capabilities: { - sampling: {} - } + capabilities: {} } ); @@ -763,9 +761,7 @@ test('should handle request timeout', async () => { version: '1.0' }, { - capabilities: { - sampling: {} - } + capabilities: {} } ); diff --git a/src/server/index.ts b/src/server/index.ts index d63b4a207..47b5f538f 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -237,9 +237,9 @@ export class Server< protected assertRequestHandlerCapability(method: string): void { switch (method) { - case 'sampling/createMessage': - if (!this._capabilities.sampling) { - throw new Error(`Server does not support sampling (required for ${method})`); + case 'completion/complete': + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); } break; diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index f3669fa64..9bc40f316 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -227,6 +227,10 @@ describe('ResourceTemplate', () => { }); describe('tool()', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + /*** * Test: Zero-Argument Tool Registration */ @@ -1407,7 +1411,14 @@ describe('tool()', () => { expect(receivedRequestId).toBeDefined(); expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); - expect(result.content?.[0].text).toContain('Received request ID:'); + expect(result.content).toEqual( + expect.arrayContaining([ + { + type: 'text', + text: expect.stringContaining('Received request ID:') + } + ]) + ); }); /*** @@ -1685,6 +1696,56 @@ describe('tool()', () => { expect(result.tools[0].name).toBe('test-without-meta'); expect(result.tools[0]._meta).toBeUndefined(); }); + + test('should validate tool names according to SEP specification', () => { + // Create a new server instance for this test + const testServer = new McpServer({ + name: 'test server', + version: '1.0' + }); + + // Spy on console.warn to verify warnings are logged + const warnSpy = jest.spyOn(console, 'warn').mockImplementation(); + + // Test valid tool names + testServer.registerTool( + 'valid-tool-name', + { + description: 'A valid tool name' + }, + async () => ({ content: [{ type: 'text' as const, text: 'Success' }] }) + ); + + // Test tool name with warnings (starts with dash) + testServer.registerTool( + '-warning-tool', + { + description: 'A tool name that generates warnings' + }, + async () => ({ content: [{ type: 'text' as const, text: 'Success' }] }) + ); + + // Test invalid tool name (contains spaces) + testServer.registerTool( + 'invalid tool name', + { + description: 'An invalid tool name' + }, + async () => ({ content: [{ type: 'text' as const, text: 'Success' }] }) + ); + + // Verify that warnings were issued (both for warnings and validation failures) + expect(warnSpy).toHaveBeenCalled(); + + // Verify specific warning content + const warningCalls = warnSpy.mock.calls.map(call => call.join(' ')); + expect(warningCalls.some(call => call.includes('Tool name starts or ends with a dash'))).toBe(true); + expect(warningCalls.some(call => call.includes('Tool name contains spaces'))).toBe(true); + expect(warningCalls.some(call => call.includes('Tool name contains invalid characters'))).toBe(true); + + // Clean up spies + warnSpy.mockRestore(); + }); }); describe('resource()', () => { @@ -1781,7 +1842,14 @@ describe('resource()', () => { ); expect(result.contents).toHaveLength(1); - expect(result.contents[0].text).toBe('Updated content'); + expect(result.contents).toEqual( + expect.arrayContaining([ + { + text: expect.stringContaining('Updated content'), + uri: 'test://resource' + } + ]) + ); // Update happened before transport was connected, so no notifications should be expected expect(notifications).toHaveLength(0); @@ -1846,7 +1914,14 @@ describe('resource()', () => { ); expect(result.contents).toHaveLength(1); - expect(result.contents[0].text).toBe('Updated content'); + expect(result.contents).toEqual( + expect.arrayContaining([ + { + text: expect.stringContaining('Updated content'), + uri: 'test://resource/123' + } + ]) + ); // Update happened before transport was connected, so no notifications should be expected expect(notifications).toHaveLength(0); @@ -2195,7 +2270,14 @@ describe('resource()', () => { ReadResourceResultSchema ); - expect(result.contents[0].text).toBe('Category: books, ID: 123'); + expect(result.contents).toEqual( + expect.arrayContaining([ + { + text: expect.stringContaining('Category: books, ID: 123'), + uri: 'test://resource/books/123' + } + ]) + ); }); /*** @@ -2556,7 +2638,14 @@ describe('resource()', () => { expect(receivedRequestId).toBeDefined(); expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); - expect(result.contents[0].text).toContain('Received request ID:'); + expect(result.contents).toEqual( + expect.arrayContaining([ + { + text: expect.stringContaining(`Received request ID:`), + uri: 'test://resource' + } + ]) + ); }); }); @@ -2662,7 +2751,17 @@ describe('prompt()', () => { ); expect(result.messages).toHaveLength(1); - expect(result.messages[0].content.text).toBe('Updated response'); + expect(result.messages).toEqual( + expect.arrayContaining([ + { + role: 'assistant', + content: { + type: 'text', + text: 'Updated response' + } + } + ]) + ); // Update happened before transport was connected, so no notifications should be expected expect(notifications).toHaveLength(0); @@ -2754,7 +2853,17 @@ describe('prompt()', () => { ); expect(getResult.messages).toHaveLength(1); - expect(getResult.messages[0].content.text).toBe('Updated: test, value'); + expect(getResult.messages).toEqual( + expect.arrayContaining([ + { + role: 'assistant', + content: { + type: 'text', + text: 'Updated: test, value' + } + } + ]) + ); // Update happened before transport was connected, so no notifications should be expected expect(notifications).toHaveLength(0); @@ -3411,7 +3520,17 @@ describe('prompt()', () => { expect(receivedRequestId).toBeDefined(); expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); - expect(result.messages[0].content.text).toContain('Received request ID:'); + expect(result.messages).toEqual( + expect.arrayContaining([ + { + role: 'assistant', + content: { + type: 'text', + text: expect.stringContaining(`Received request ID:`) + } + } + ]) + ); }); /*** @@ -3513,7 +3632,7 @@ describe('prompt()', () => { }) }), { - name: 'Template Name', + title: 'Template Name', description: 'Template description', mimeType: 'application/json' }, @@ -3583,7 +3702,7 @@ describe('Tool title precedence', () => { description: 'Tool with regular title' }, async () => ({ - content: [{ type: 'text', text: 'Response' }] + content: [{ type: 'text' as const, text: 'Response' }] }) ); @@ -3598,7 +3717,7 @@ describe('Tool title precedence', () => { } }, async () => ({ - content: [{ type: 'text', text: 'Response' }] + content: [{ type: 'text' as const, text: 'Response' }] }) ); @@ -4162,3 +4281,239 @@ describe('elicitInput()', () => { ]); }); }); + +describe('Tools with union and intersection schemas', () => { + test('should support union schemas', async () => { + const server = new McpServer({ + name: 'test', + version: '1.0.0' + }); + + const client = new Client({ + name: 'test-client', + version: '1.0.0' + }); + + const unionSchema = z.union([ + z.object({ type: z.literal('email'), email: z.string().email() }), + z.object({ type: z.literal('phone'), phone: z.string() }) + ]); + + server.registerTool('contact', { inputSchema: unionSchema }, async args => { + if (args.type === 'email') { + return { + content: [{ type: 'text', text: `Email contact: ${args.email}` }] + }; + } else { + return { + content: [{ type: 'text', text: `Phone contact: ${args.phone}` }] + }; + } + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const emailResult = await client.callTool({ + name: 'contact', + arguments: { + type: 'email', + email: 'test@example.com' + } + }); + + expect(emailResult.content).toEqual([ + { + type: 'text', + text: 'Email contact: test@example.com' + } + ]); + + const phoneResult = await client.callTool({ + name: 'contact', + arguments: { + type: 'phone', + phone: '+1234567890' + } + }); + + expect(phoneResult.content).toEqual([ + { + type: 'text', + text: 'Phone contact: +1234567890' + } + ]); + }); + + test('should support intersection schemas', async () => { + const server = new McpServer({ + name: 'test', + version: '1.0.0' + }); + + const client = new Client({ + name: 'test-client', + version: '1.0.0' + }); + + const baseSchema = z.object({ id: z.string() }); + const extendedSchema = z.object({ name: z.string(), age: z.number() }); + const intersectionSchema = z.intersection(baseSchema, extendedSchema); + + server.registerTool('user', { inputSchema: intersectionSchema }, async args => { + return { + content: [ + { + type: 'text', + text: `User: ${args.id}, ${args.name}, ${args.age} years old` + } + ] + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const result = await client.callTool({ + name: 'user', + arguments: { + id: '123', + name: 'John Doe', + age: 30 + } + }); + + expect(result.content).toEqual([ + { + type: 'text', + text: 'User: 123, John Doe, 30 years old' + } + ]); + }); + + test('should support complex nested schemas', async () => { + const server = new McpServer({ + name: 'test', + version: '1.0.0' + }); + + const client = new Client({ + name: 'test-client', + version: '1.0.0' + }); + + const schema = z.object({ + items: z.array( + z.union([ + z.object({ type: z.literal('text'), content: z.string() }), + z.object({ type: z.literal('number'), value: z.number() }) + ]) + ) + }); + + server.registerTool('process', { inputSchema: schema }, async args => { + const processed = args.items.map(item => { + if (item.type === 'text') { + return item.content.toUpperCase(); + } else { + return item.value * 2; + } + }); + return { + content: [ + { + type: 'text', + text: `Processed: ${processed.join(', ')}` + } + ] + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const result = await client.callTool({ + name: 'process', + arguments: { + items: [ + { type: 'text', content: 'hello' }, + { type: 'number', value: 5 }, + { type: 'text', content: 'world' } + ] + } + }); + + expect(result.content).toEqual([ + { + type: 'text', + text: 'Processed: HELLO, 10, WORLD' + } + ]); + }); + + test('should validate union schema inputs correctly', async () => { + const server = new McpServer({ + name: 'test', + version: '1.0.0' + }); + + const client = new Client({ + name: 'test-client', + version: '1.0.0' + }); + + const unionSchema = z.union([ + z.object({ type: z.literal('a'), value: z.string() }), + z.object({ type: z.literal('b'), value: z.number() }) + ]); + + server.registerTool('union-test', { inputSchema: unionSchema }, async () => { + return { + content: [{ type: 'text', text: 'Success' }] + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const invalidTypeResult = await client.callTool({ + name: 'union-test', + arguments: { + type: 'a', + value: 123 + } + }); + + expect(invalidTypeResult.isError).toBe(true); + expect(invalidTypeResult.content).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: 'text', + text: expect.stringContaining('Input validation error') + }) + ]) + ); + + const invalidDiscriminatorResult = await client.callTool({ + name: 'union-test', + arguments: { + type: 'c', + value: 'test' + } + }); + + expect(invalidDiscriminatorResult.isError).toBe(true); + expect(invalidDiscriminatorResult.content).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: 'text', + text: expect.stringContaining('Input validation error') + }) + ]) + ); + }); +}); diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 015f518a1..bee3b76ec 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -1,6 +1,6 @@ import { Server, ServerOptions } from './index.js'; import { zodToJsonSchema } from 'zod-to-json-schema'; -import { z, ZodRawShape, ZodObject, ZodString, AnyZodObject, ZodTypeAny, ZodType, ZodTypeDef, ZodOptional } from 'zod'; +import { z, ZodRawShape, ZodObject, ZodString, ZodTypeAny, ZodType, ZodTypeDef, ZodOptional } from 'zod'; import { Implementation, Tool, @@ -8,7 +8,6 @@ import { CallToolResult, McpError, ErrorCode, - CompleteRequest, CompleteResult, PromptReference, ResourceTemplateReference, @@ -31,12 +30,17 @@ import { ServerRequest, ServerNotification, ToolAnnotations, - LoggingMessageNotification + LoggingMessageNotification, + CompleteRequestPrompt, + CompleteRequestResourceTemplate, + assertCompleteRequestPrompt, + assertCompleteRequestResourceTemplate } from '../types.js'; import { Completable, CompletableDef } from './completable.js'; import { UriTemplate, Variables } from '../shared/uriTemplate.js'; import { RequestHandlerExtra } from '../shared/protocol.js'; import { Transport } from '../shared/transport.js'; +import { validateAndWarnToolName } from '../shared/toolNameValidation.js'; /** * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. @@ -217,9 +221,11 @@ export class McpServer { this.server.setRequestHandler(CompleteRequestSchema, async (request): Promise => { switch (request.params.ref.type) { case 'ref/prompt': + assertCompleteRequestPrompt(request); return this.handlePromptCompletion(request, request.params.ref); case 'ref/resource': + assertCompleteRequestResourceTemplate(request); return this.handleResourceCompletion(request, request.params.ref); default: @@ -230,7 +236,7 @@ export class McpServer { this._completionHandlerInitialized = true; } - private async handlePromptCompletion(request: CompleteRequest, ref: PromptReference): Promise { + private async handlePromptCompletion(request: CompleteRequestPrompt, ref: PromptReference): Promise { const prompt = this._registeredPrompts[ref.name]; if (!prompt) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); @@ -254,7 +260,10 @@ export class McpServer { return createCompletionResult(suggestions); } - private async handleResourceCompletion(request: CompleteRequest, ref: ResourceTemplateReference): Promise { + private async handleResourceCompletion( + request: CompleteRequestResourceTemplate, + ref: ResourceTemplateReference + ): Promise { const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); if (!template) { @@ -650,17 +659,20 @@ export class McpServer { name: string, title: string | undefined, description: string | undefined, - inputSchema: ZodRawShape | undefined, - outputSchema: ZodRawShape | undefined, + inputSchema: ZodRawShape | ZodType | undefined, + outputSchema: ZodRawShape | ZodType | undefined, annotations: ToolAnnotations | undefined, _meta: Record | undefined, callback: ToolCallback ): RegisteredTool { + // Validate tool name according to SEP specification + validateAndWarnToolName(name); + const registeredTool: RegisteredTool = { title, description, - inputSchema: inputSchema === undefined ? undefined : z.object(inputSchema), - outputSchema: outputSchema === undefined ? undefined : z.object(outputSchema), + inputSchema: getZodSchemaObject(inputSchema), + outputSchema: getZodSchemaObject(outputSchema), annotations, _meta, callback, @@ -670,6 +682,9 @@ export class McpServer { remove: () => registeredTool.update({ name: null }), update: updates => { if (typeof updates.name !== 'undefined' && updates.name !== name) { + if (typeof updates.name === 'string') { + validateAndWarnToolName(updates.name); + } delete this._registeredTools[name]; if (updates.name) this._registeredTools[updates.name] = registeredTool; } @@ -798,7 +813,7 @@ export class McpServer { /** * Registers a tool with a config object and callback. */ - registerTool( + registerTool, OutputArgs extends ZodRawShape | ZodType>( name: string, config: { title?: string; @@ -1027,18 +1042,20 @@ export class ResourceTemplate { * - `content` if the tool does not have an outputSchema * - Both fields are optional but typically one should be provided */ -export type ToolCallback = Args extends ZodRawShape +export type ToolCallback = undefined> = Args extends ZodRawShape ? ( args: z.objectOutputType, extra: RequestHandlerExtra ) => CallToolResult | Promise - : (extra: RequestHandlerExtra) => CallToolResult | Promise; + : Args extends ZodType + ? (args: T, extra: RequestHandlerExtra) => CallToolResult | Promise + : (extra: RequestHandlerExtra) => CallToolResult | Promise; export type RegisteredTool = { title?: string; description?: string; - inputSchema?: AnyZodObject; - outputSchema?: AnyZodObject; + inputSchema?: ZodType; + outputSchema?: ZodType; annotations?: ToolAnnotations; _meta?: Record; callback: ToolCallback; @@ -1086,6 +1103,22 @@ function isZodTypeLike(value: unknown): value is ZodType { ); } +/** + * Converts a provided Zod schema to a Zod object if it is a ZodRawShape, + * otherwise returns the schema as is. + */ +function getZodSchemaObject(schema: ZodRawShape | ZodType | undefined): ZodType | undefined { + if (!schema) { + return undefined; + } + + if (isZodRawShape(schema)) { + return z.object(schema); + } + + return schema; +} + /** * Additional, optional information for annotating a resource. */ diff --git a/src/server/title.test.ts b/src/server/title.test.ts index 9606fce44..7f0feedc8 100644 --- a/src/server/title.test.ts +++ b/src/server/title.test.ts @@ -189,7 +189,14 @@ describe('Title field backwards compatibility', () => { // Test reading the resource const readResult = await client.readResource({ uri: 'users://123/profile' }); expect(readResult.contents).toHaveLength(1); - expect(readResult.contents[0].text).toBe('Profile data for user 123'); + expect(readResult.contents).toEqual( + expect.arrayContaining([ + { + text: expect.stringContaining('Profile data for user 123'), + uri: 'users://123/profile' + } + ]) + ); }); it('should support serverInfo with title', async () => { diff --git a/src/shared/metadataUtils.ts b/src/shared/metadataUtils.ts index d58729298..7e9846aa8 100644 --- a/src/shared/metadataUtils.ts +++ b/src/shared/metadataUtils.ts @@ -10,18 +10,15 @@ import { BaseMetadata } from '../types.js'; * For other objects: title → name * This implements the spec requirement: "if no title is provided, name should be used for display purposes" */ -export function getDisplayName(metadata: BaseMetadata): string { +export function getDisplayName(metadata: BaseMetadata & { annotations?: { title?: string } }): string { // First check for title (not undefined and not empty string) if (metadata.title !== undefined && metadata.title !== '') { return metadata.title; } // Then check for annotations.title (only present in Tool objects) - if ('annotations' in metadata) { - const metadataWithAnnotations = metadata as BaseMetadata & { annotations?: { title?: string } }; - if (metadataWithAnnotations.annotations?.title) { - return metadataWithAnnotations.annotations.title; - } + if (metadata.annotations?.title) { + return metadata.annotations.title; } // Finally fall back to name diff --git a/src/shared/protocol.test.ts b/src/shared/protocol.test.ts index 1c098eafa..802c1dd9d 100644 --- a/src/shared/protocol.test.ts +++ b/src/shared/protocol.test.ts @@ -666,11 +666,13 @@ describe('mergeCapabilities', () => { const additional: ClientCapabilities = { experimental: { - feature: true + feature: { + featureFlag: true + } }, elicitation: {}, roots: { - newProp: true + listChanged: true } }; @@ -679,11 +681,12 @@ describe('mergeCapabilities', () => { sampling: {}, elicitation: {}, roots: { - listChanged: true, - newProp: true + listChanged: true }, experimental: { - feature: true + feature: { + featureFlag: true + } } }); }); @@ -701,7 +704,7 @@ describe('mergeCapabilities', () => { subscribe: true }, prompts: { - newProp: true + listChanged: true } }; @@ -709,8 +712,7 @@ describe('mergeCapabilities', () => { expect(merged).toEqual({ logging: {}, prompts: { - listChanged: true, - newProp: true + listChanged: true }, resources: { subscribe: true diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index 5cb969418..48cad896f 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -693,16 +693,24 @@ export abstract class Protocol(base: T, additional: T): T { - return Object.entries(additional).reduce( - (acc, [key, value]) => { - if (value && typeof value === 'object') { - acc[key] = acc[key] ? { ...acc[key], ...value } : value; - } else { - acc[key] = value; - } - return acc; - }, - { ...base } - ); +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +export function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; +export function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; +export function mergeCapabilities(base: T, additional: Partial): T { + const result: T = { ...base }; + for (const key in additional) { + const k = key as keyof T; + const addValue = additional[k]; + if (addValue === undefined) continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) { + result[k] = { ...(baseValue as Record), ...(addValue as Record) } as T[typeof k]; + } else { + result[k] = addValue as T[typeof k]; + } + } + return result; } diff --git a/src/shared/toolNameValidation.test.ts b/src/shared/toolNameValidation.test.ts new file mode 100644 index 000000000..64ba9d3ba --- /dev/null +++ b/src/shared/toolNameValidation.test.ts @@ -0,0 +1,127 @@ +import { validateToolName, validateAndWarnToolName, issueToolNameWarning } from './toolNameValidation.js'; + +// Spy on console.warn to capture output +let warnSpy: jest.SpyInstance; + +beforeEach(() => { + warnSpy = jest.spyOn(console, 'warn').mockImplementation(); +}); + +afterEach(() => { + jest.restoreAllMocks(); +}); + +describe('validateToolName', () => { + describe('valid tool names', () => { + test.each` + description | toolName + ${'simple alphanumeric names'} | ${'getUser'} + ${'names with underscores'} | ${'get_user_profile'} + ${'names with dashes'} | ${'user-profile-update'} + ${'names with dots'} | ${'admin.tools.list'} + ${'mixed character names'} | ${'DATA_EXPORT_v2.1'} + ${'single character names'} | ${'a'} + ${'128 character names'} | ${'a'.repeat(128)} + `('should accept $description', ({ toolName }) => { + const result = validateToolName(toolName); + expect(result.isValid).toBe(true); + expect(result.warnings).toHaveLength(0); + }); + }); + + describe('invalid tool names', () => { + test.each` + description | toolName | expectedWarning + ${'empty names'} | ${''} | ${'Tool name cannot be empty'} + ${'names longer than 128 characters'} | ${'a'.repeat(129)} | ${'Tool name exceeds maximum length of 128 characters (current: 129)'} + ${'names with spaces'} | ${'get user profile'} | ${'Tool name contains invalid characters: " "'} + ${'names with commas'} | ${'get,user,profile'} | ${'Tool name contains invalid characters: ","'} + ${'names with forward slashes'} | ${'user/profile/update'} | ${'Tool name contains invalid characters: "/"'} + ${'names with other special chars'} | ${'user@domain.com'} | ${'Tool name contains invalid characters: "@"'} + ${'names with multiple invalid chars'} | ${'user name@domain,com'} | ${'Tool name contains invalid characters: " ", "@", ","'} + ${'names with unicode characters'} | ${'user-ñame'} | ${'Tool name contains invalid characters: "ñ"'} + `('should reject $description', ({ toolName, expectedWarning }) => { + const result = validateToolName(toolName); + expect(result.isValid).toBe(false); + expect(result.warnings).toContain(expectedWarning); + }); + }); + + describe('warnings for potentially problematic patterns', () => { + test.each` + description | toolName | expectedWarning | shouldBeValid + ${'names with spaces'} | ${'get user profile'} | ${'Tool name contains spaces, which may cause parsing issues'} | ${false} + ${'names with commas'} | ${'get,user,profile'} | ${'Tool name contains commas, which may cause parsing issues'} | ${false} + ${'names starting with dash'} | ${'-get-user'} | ${'Tool name starts or ends with a dash, which may cause parsing issues in some contexts'} | ${true} + ${'names ending with dash'} | ${'get-user-'} | ${'Tool name starts or ends with a dash, which may cause parsing issues in some contexts'} | ${true} + ${'names starting with dot'} | ${'.get.user'} | ${'Tool name starts or ends with a dot, which may cause parsing issues in some contexts'} | ${true} + ${'names ending with dot'} | ${'get.user.'} | ${'Tool name starts or ends with a dot, which may cause parsing issues in some contexts'} | ${true} + ${'names with leading and trailing dots'} | ${'.get.user.'} | ${'Tool name starts or ends with a dot, which may cause parsing issues in some contexts'} | ${true} + `('should warn about $description', ({ toolName, expectedWarning, shouldBeValid }) => { + const result = validateToolName(toolName); + expect(result.isValid).toBe(shouldBeValid); + expect(result.warnings).toContain(expectedWarning); + }); + }); +}); + +describe('issueToolNameWarning', () => { + test('should output warnings to console.warn', () => { + const warnings = ['Warning 1', 'Warning 2']; + issueToolNameWarning('test-tool', warnings); + + expect(warnSpy).toHaveBeenCalledTimes(6); // Header + 2 warnings + 3 guidance lines + const calls = warnSpy.mock.calls.map(call => call.join(' ')); + expect(calls[0]).toContain('Tool name validation warning for "test-tool"'); + expect(calls[1]).toContain('- Warning 1'); + expect(calls[2]).toContain('- Warning 2'); + expect(calls[3]).toContain('Tool registration will proceed, but this may cause compatibility issues.'); + expect(calls[4]).toContain('Consider updating the tool name'); + expect(calls[5]).toContain('See SEP: Specify Format for Tool Names'); + }); + + test('should handle empty warnings array', () => { + issueToolNameWarning('test-tool', []); + expect(warnSpy).toHaveBeenCalledTimes(0); + }); +}); + +describe('validateAndWarnToolName', () => { + test.each` + description | toolName | expectedResult | shouldWarn + ${'valid names with warnings'} | ${'-get-user-'} | ${true} | ${true} + ${'completely valid names'} | ${'get-user-profile'} | ${true} | ${false} + ${'invalid names with spaces'} | ${'get user profile'} | ${false} | ${true} + ${'empty names'} | ${''} | ${false} | ${true} + ${'names exceeding length limit'} | ${'a'.repeat(129)} | ${false} | ${true} + `('should handle $description', ({ toolName, expectedResult, shouldWarn }) => { + const result = validateAndWarnToolName(toolName); + expect(result).toBe(expectedResult); + + if (shouldWarn) { + expect(warnSpy).toHaveBeenCalled(); + } else { + expect(warnSpy).not.toHaveBeenCalled(); + } + }); + + test('should include space warning for invalid names with spaces', () => { + validateAndWarnToolName('get user profile'); + const warningCalls = warnSpy.mock.calls.map(call => call.join(' ')); + expect(warningCalls.some(call => call.includes('Tool name contains spaces'))).toBe(true); + }); +}); + +describe('edge cases and robustness', () => { + test.each` + description | toolName | shouldBeValid | expectedWarning + ${'names with only dots'} | ${'...'} | ${true} | ${'Tool name starts or ends with a dot, which may cause parsing issues in some contexts'} + ${'names with only dashes'} | ${'---'} | ${true} | ${'Tool name starts or ends with a dash, which may cause parsing issues in some contexts'} + ${'names with only forward slashes'} | ${'///'} | ${false} | ${'Tool name contains invalid characters: "/"'} + ${'names with mixed valid/invalid chars'} | ${'user@name123'} | ${false} | ${'Tool name contains invalid characters: "@"'} + `('should handle $description', ({ toolName, shouldBeValid, expectedWarning }) => { + const result = validateToolName(toolName); + expect(result.isValid).toBe(shouldBeValid); + expect(result.warnings).toContain(expectedWarning); + }); +}); diff --git a/src/shared/toolNameValidation.ts b/src/shared/toolNameValidation.ts new file mode 100644 index 000000000..fa96afde0 --- /dev/null +++ b/src/shared/toolNameValidation.ts @@ -0,0 +1,115 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ + +/** + * Regular expression for valid tool names according to SEP-986 specification + */ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; + +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export function validateToolName(name: string): { + isValid: boolean; + warnings: string[]; +} { + const warnings: string[] = []; + + // Check length + if (name.length === 0) { + return { + isValid: false, + warnings: ['Tool name cannot be empty'] + }; + } + + if (name.length > 128) { + return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + } + + // Check for specific problematic patterns (these are warnings, not validation failures) + if (name.includes(' ')) { + warnings.push('Tool name contains spaces, which may cause parsing issues'); + } + + if (name.includes(',')) { + warnings.push('Tool name contains commas, which may cause parsing issues'); + } + + // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) + if (name.startsWith('-') || name.endsWith('-')) { + warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); + } + + if (name.startsWith('.') || name.endsWith('.')) { + warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); + } + + // Check for invalid characters + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = name + .split('') + .filter(char => !/[A-Za-z0-9._-]/.test(char)) + .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates + + warnings.push( + `Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, + 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)' + ); + + return { + isValid: false, + warnings + }; + } + + return { + isValid: true, + warnings + }; +} + +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export function issueToolNameWarning(name: string, warnings: string[]): void { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) { + console.warn(` - ${warning}`); + } + console.warn('Tool registration will proceed, but this may cause compatibility issues.'); + console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); + console.warn( + 'See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.' + ); + } +} + +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export function validateAndWarnToolName(name: string): boolean { + const result = validateToolName(name); + + // Always issue warnings for any validation issues (both invalid names and warnings) + issueToolNameWarning(name, result.warnings); + + return result.isValid; +} diff --git a/src/shared/transport.ts b/src/shared/transport.ts index c64f622b7..8f0c291d2 100644 --- a/src/shared/transport.ts +++ b/src/shared/transport.ts @@ -71,7 +71,7 @@ export interface Transport { * * The requestInfo can be used to get the original request information (headers, etc.) */ - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + onmessage?: (message: T, extra?: MessageExtraInfo) => void; /** * The session ID generated for this connection. diff --git a/src/spec.types.test.ts b/src/spec.types.test.ts index 626eeef35..2417e6b1d 100644 --- a/src/spec.types.test.ts +++ b/src/spec.types.test.ts @@ -62,32 +62,126 @@ type MakeUnknownsNotOptional = } : T; +// Targeted fix: in spec, treat ClientCapabilities.elicitation?: object as Record +type FixSpecClientCapabilities = T extends { elicitation?: object } + ? Omit & { elicitation?: Record } + : T; + +type FixSpecInitializeRequestParams = T extends { capabilities: infer C } + ? Omit & { capabilities: FixSpecClientCapabilities } + : T; + +type FixSpecInitializeRequest = T extends { params: infer P } ? Omit & { params: FixSpecInitializeRequestParams

} : T; + +type FixSpecClientRequest = T extends { params: infer P } ? Omit & { params: FixSpecInitializeRequestParams

} : T; + const sdkTypeChecks = { + RequestParams: (sdk: SDKTypes.RequestParams, spec: SpecTypes.RequestParams) => { + sdk = spec; + spec = sdk; + }, + NotificationParams: (sdk: SDKTypes.NotificationParams, spec: SpecTypes.NotificationParams) => { + sdk = spec; + spec = sdk; + }, + CancelledNotificationParams: (sdk: SDKTypes.CancelledNotificationParams, spec: SpecTypes.CancelledNotificationParams) => { + sdk = spec; + spec = sdk; + }, + InitializeRequestParams: ( + sdk: SDKTypes.InitializeRequestParams, + spec: FixSpecInitializeRequestParams + ) => { + sdk = spec; + spec = sdk; + }, + ProgressNotificationParams: (sdk: SDKTypes.ProgressNotificationParams, spec: SpecTypes.ProgressNotificationParams) => { + sdk = spec; + spec = sdk; + }, + ResourceRequestParams: (sdk: SDKTypes.ResourceRequestParams, spec: SpecTypes.ResourceRequestParams) => { + sdk = spec; + spec = sdk; + }, + ReadResourceRequestParams: (sdk: SDKTypes.ReadResourceRequestParams, spec: SpecTypes.ReadResourceRequestParams) => { + sdk = spec; + spec = sdk; + }, + SubscribeRequestParams: (sdk: SDKTypes.SubscribeRequestParams, spec: SpecTypes.SubscribeRequestParams) => { + sdk = spec; + spec = sdk; + }, + UnsubscribeRequestParams: (sdk: SDKTypes.UnsubscribeRequestParams, spec: SpecTypes.UnsubscribeRequestParams) => { + sdk = spec; + spec = sdk; + }, + ResourceUpdatedNotificationParams: ( + sdk: SDKTypes.ResourceUpdatedNotificationParams, + spec: SpecTypes.ResourceUpdatedNotificationParams + ) => { + sdk = spec; + spec = sdk; + }, + GetPromptRequestParams: (sdk: SDKTypes.GetPromptRequestParams, spec: SpecTypes.GetPromptRequestParams) => { + sdk = spec; + spec = sdk; + }, + CallToolRequestParams: (sdk: SDKTypes.CallToolRequestParams, spec: SpecTypes.CallToolRequestParams) => { + sdk = spec; + spec = sdk; + }, + SetLevelRequestParams: (sdk: SDKTypes.SetLevelRequestParams, spec: SpecTypes.SetLevelRequestParams) => { + sdk = spec; + spec = sdk; + }, + LoggingMessageNotificationParams: ( + sdk: MakeUnknownsNotOptional, + spec: SpecTypes.LoggingMessageNotificationParams + ) => { + sdk = spec; + spec = sdk; + }, + CreateMessageRequestParams: (sdk: SDKTypes.CreateMessageRequestParams, spec: SpecTypes.CreateMessageRequestParams) => { + sdk = spec; + spec = sdk; + }, + CompleteRequestParams: (sdk: SDKTypes.CompleteRequestParams, spec: SpecTypes.CompleteRequestParams) => { + sdk = spec; + spec = sdk; + }, + ElicitRequestParams: (sdk: SDKTypes.ElicitRequestParams, spec: SpecTypes.ElicitRequestParams) => { + sdk = spec; + spec = sdk; + }, + PaginatedRequestParams: (sdk: SDKTypes.PaginatedRequestParams, spec: SpecTypes.PaginatedRequestParams) => { + sdk = spec; + spec = sdk; + }, CancelledNotification: (sdk: WithJSONRPC, spec: SpecTypes.CancelledNotification) => { sdk = spec; spec = sdk; }, - BaseMetadata: (sdk: RemovePassthrough, spec: SpecTypes.BaseMetadata) => { + BaseMetadata: (sdk: SDKTypes.BaseMetadata, spec: SpecTypes.BaseMetadata) => { sdk = spec; spec = sdk; }, - Implementation: (sdk: RemovePassthrough, spec: SpecTypes.Implementation) => { + Implementation: (sdk: SDKTypes.Implementation, spec: SpecTypes.Implementation) => { sdk = spec; spec = sdk; }, - ProgressNotification: (sdk: WithJSONRPC, spec: SpecTypes.ProgressNotification) => { + ProgressNotification: (sdk: RemovePassthrough>, spec: SpecTypes.ProgressNotification) => { sdk = spec; spec = sdk; }, - SubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SubscribeRequest) => { + SubscribeRequest: (sdk: RemovePassthrough>, spec: SpecTypes.SubscribeRequest) => { sdk = spec; spec = sdk; }, - UnsubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.UnsubscribeRequest) => { + UnsubscribeRequest: (sdk: RemovePassthrough>, spec: SpecTypes.UnsubscribeRequest) => { sdk = spec; spec = sdk; }, - PaginatedRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PaginatedRequest) => { + PaginatedRequest: (sdk: RemovePassthrough>, spec: SpecTypes.PaginatedRequest) => { sdk = spec; spec = sdk; }, @@ -95,27 +189,27 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListRootsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListRootsRequest) => { + ListRootsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListRootsRequest) => { sdk = spec; spec = sdk; }, - ListRootsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListRootsResult) => { + ListRootsResult: (sdk: SDKTypes.ListRootsResult, spec: SpecTypes.ListRootsResult) => { sdk = spec; spec = sdk; }, - Root: (sdk: RemovePassthrough, spec: SpecTypes.Root) => { + Root: (sdk: SDKTypes.Root, spec: SpecTypes.Root) => { sdk = spec; spec = sdk; }, - ElicitRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ElicitRequest) => { + ElicitRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ElicitRequest) => { sdk = spec; spec = sdk; }, - ElicitResult: (sdk: RemovePassthrough, spec: SpecTypes.ElicitResult) => { + ElicitResult: (sdk: SDKTypes.ElicitResult, spec: SpecTypes.ElicitResult) => { sdk = spec; spec = sdk; }, - CompleteRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.CompleteRequest) => { + CompleteRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CompleteRequest) => { sdk = spec; spec = sdk; }, @@ -167,7 +261,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ClientNotification: (sdk: WithJSONRPC, spec: SpecTypes.ClientNotification) => { + ClientNotification: (sdk: RemovePassthrough>, spec: SpecTypes.ClientNotification) => { sdk = spec; spec = sdk; }, @@ -175,206 +269,246 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ResourceTemplateReference: (sdk: RemovePassthrough, spec: SpecTypes.ResourceTemplateReference) => { + ResourceTemplateReference: (sdk: SDKTypes.ResourceTemplateReference, spec: SpecTypes.ResourceTemplateReference) => { sdk = spec; spec = sdk; }, - PromptReference: (sdk: RemovePassthrough, spec: SpecTypes.PromptReference) => { + PromptReference: (sdk: SDKTypes.PromptReference, spec: SpecTypes.PromptReference) => { sdk = spec; spec = sdk; }, - ToolAnnotations: (sdk: RemovePassthrough, spec: SpecTypes.ToolAnnotations) => { + ToolAnnotations: (sdk: SDKTypes.ToolAnnotations, spec: SpecTypes.ToolAnnotations) => { sdk = spec; spec = sdk; }, - Tool: (sdk: RemovePassthrough, spec: SpecTypes.Tool) => { + Tool: (sdk: SDKTypes.Tool, spec: SpecTypes.Tool) => { sdk = spec; spec = sdk; }, - ListToolsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListToolsRequest) => { + ListToolsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListToolsRequest) => { sdk = spec; spec = sdk; }, - ListToolsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListToolsResult) => { + ListToolsResult: (sdk: SDKTypes.ListToolsResult, spec: SpecTypes.ListToolsResult) => { sdk = spec; spec = sdk; }, - CallToolResult: (sdk: RemovePassthrough, spec: SpecTypes.CallToolResult) => { + CallToolResult: (sdk: SDKTypes.CallToolResult, spec: SpecTypes.CallToolResult) => { sdk = spec; spec = sdk; }, - CallToolRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CallToolRequest) => { + CallToolRequest: (sdk: RemovePassthrough>, spec: SpecTypes.CallToolRequest) => { sdk = spec; spec = sdk; }, - ToolListChangedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ToolListChangedNotification) => { + ToolListChangedNotification: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ToolListChangedNotification + ) => { sdk = spec; spec = sdk; }, ResourceListChangedNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.ResourceListChangedNotification ) => { sdk = spec; spec = sdk; }, PromptListChangedNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.PromptListChangedNotification ) => { sdk = spec; spec = sdk; }, RootsListChangedNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.RootsListChangedNotification ) => { sdk = spec; spec = sdk; }, - ResourceUpdatedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ResourceUpdatedNotification) => { + ResourceUpdatedNotification: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ResourceUpdatedNotification + ) => { sdk = spec; spec = sdk; }, - SamplingMessage: (sdk: RemovePassthrough, spec: SpecTypes.SamplingMessage) => { + SamplingMessage: (sdk: SDKTypes.SamplingMessage, spec: SpecTypes.SamplingMessage) => { sdk = spec; spec = sdk; }, - CreateMessageResult: (sdk: RemovePassthrough, spec: SpecTypes.CreateMessageResult) => { + CreateMessageResult: (sdk: SDKTypes.CreateMessageResult, spec: SpecTypes.CreateMessageResult) => { sdk = spec; spec = sdk; }, - SetLevelRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SetLevelRequest) => { + SetLevelRequest: (sdk: RemovePassthrough>, spec: SpecTypes.SetLevelRequest) => { sdk = spec; spec = sdk; }, - PingRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PingRequest) => { + PingRequest: (sdk: RemovePassthrough>, spec: SpecTypes.PingRequest) => { sdk = spec; spec = sdk; }, - InitializedNotification: (sdk: WithJSONRPC, spec: SpecTypes.InitializedNotification) => { + InitializedNotification: ( + sdk: RemovePassthrough>, + spec: SpecTypes.InitializedNotification + ) => { sdk = spec; spec = sdk; }, - ListResourcesRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListResourcesRequest) => { + ListResourcesRequest: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ListResourcesRequest + ) => { sdk = spec; spec = sdk; }, - ListResourcesResult: (sdk: RemovePassthrough, spec: SpecTypes.ListResourcesResult) => { + ListResourcesResult: (sdk: SDKTypes.ListResourcesResult, spec: SpecTypes.ListResourcesResult) => { sdk = spec; spec = sdk; }, ListResourceTemplatesRequest: ( - sdk: WithJSONRPCRequest, + sdk: RemovePassthrough>, spec: SpecTypes.ListResourceTemplatesRequest ) => { sdk = spec; spec = sdk; }, - ListResourceTemplatesResult: ( - sdk: RemovePassthrough, - spec: SpecTypes.ListResourceTemplatesResult + ListResourceTemplatesResult: (sdk: SDKTypes.ListResourceTemplatesResult, spec: SpecTypes.ListResourceTemplatesResult) => { + sdk = spec; + spec = sdk; + }, + ReadResourceRequest: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ReadResourceRequest ) => { sdk = spec; spec = sdk; }, - ReadResourceRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ReadResourceRequest) => { + ReadResourceResult: (sdk: SDKTypes.ReadResourceResult, spec: SpecTypes.ReadResourceResult) => { + sdk = spec; + spec = sdk; + }, + ResourceContents: (sdk: SDKTypes.ResourceContents, spec: SpecTypes.ResourceContents) => { + sdk = spec; + spec = sdk; + }, + TextResourceContents: (sdk: SDKTypes.TextResourceContents, spec: SpecTypes.TextResourceContents) => { + sdk = spec; + spec = sdk; + }, + BlobResourceContents: (sdk: SDKTypes.BlobResourceContents, spec: SpecTypes.BlobResourceContents) => { + sdk = spec; + spec = sdk; + }, + Resource: (sdk: SDKTypes.Resource, spec: SpecTypes.Resource) => { + sdk = spec; + spec = sdk; + }, + ResourceTemplate: (sdk: SDKTypes.ResourceTemplate, spec: SpecTypes.ResourceTemplate) => { sdk = spec; spec = sdk; }, - ReadResourceResult: (sdk: RemovePassthrough, spec: SpecTypes.ReadResourceResult) => { + PromptArgument: (sdk: SDKTypes.PromptArgument, spec: SpecTypes.PromptArgument) => { sdk = spec; spec = sdk; }, - ResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.ResourceContents) => { + Prompt: (sdk: SDKTypes.Prompt, spec: SpecTypes.Prompt) => { sdk = spec; spec = sdk; }, - TextResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.TextResourceContents) => { + ListPromptsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListPromptsRequest) => { sdk = spec; spec = sdk; }, - BlobResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.BlobResourceContents) => { + ListPromptsResult: (sdk: SDKTypes.ListPromptsResult, spec: SpecTypes.ListPromptsResult) => { sdk = spec; spec = sdk; }, - Resource: (sdk: RemovePassthrough, spec: SpecTypes.Resource) => { + GetPromptRequest: (sdk: RemovePassthrough>, spec: SpecTypes.GetPromptRequest) => { sdk = spec; spec = sdk; }, - ResourceTemplate: (sdk: RemovePassthrough, spec: SpecTypes.ResourceTemplate) => { + TextContent: (sdk: SDKTypes.TextContent, spec: SpecTypes.TextContent) => { sdk = spec; spec = sdk; }, - PromptArgument: (sdk: RemovePassthrough, spec: SpecTypes.PromptArgument) => { + ImageContent: (sdk: SDKTypes.ImageContent, spec: SpecTypes.ImageContent) => { sdk = spec; spec = sdk; }, - Prompt: (sdk: RemovePassthrough, spec: SpecTypes.Prompt) => { + AudioContent: (sdk: SDKTypes.AudioContent, spec: SpecTypes.AudioContent) => { sdk = spec; spec = sdk; }, - ListPromptsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListPromptsRequest) => { + EmbeddedResource: (sdk: SDKTypes.EmbeddedResource, spec: SpecTypes.EmbeddedResource) => { sdk = spec; spec = sdk; }, - ListPromptsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListPromptsResult) => { + ResourceLink: (sdk: SDKTypes.ResourceLink, spec: SpecTypes.ResourceLink) => { sdk = spec; spec = sdk; }, - GetPromptRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetPromptRequest) => { + ContentBlock: (sdk: SDKTypes.ContentBlock, spec: SpecTypes.ContentBlock) => { sdk = spec; spec = sdk; }, - TextContent: (sdk: RemovePassthrough, spec: SpecTypes.TextContent) => { + PromptMessage: (sdk: SDKTypes.PromptMessage, spec: SpecTypes.PromptMessage) => { sdk = spec; spec = sdk; }, - ImageContent: (sdk: RemovePassthrough, spec: SpecTypes.ImageContent) => { + GetPromptResult: (sdk: SDKTypes.GetPromptResult, spec: SpecTypes.GetPromptResult) => { sdk = spec; spec = sdk; }, - AudioContent: (sdk: RemovePassthrough, spec: SpecTypes.AudioContent) => { + BooleanSchema: (sdk: SDKTypes.BooleanSchema, spec: SpecTypes.BooleanSchema) => { sdk = spec; spec = sdk; }, - EmbeddedResource: (sdk: RemovePassthrough, spec: SpecTypes.EmbeddedResource) => { + StringSchema: (sdk: SDKTypes.StringSchema, spec: SpecTypes.StringSchema) => { sdk = spec; spec = sdk; }, - ResourceLink: (sdk: RemovePassthrough, spec: SpecTypes.ResourceLink) => { + NumberSchema: (sdk: SDKTypes.NumberSchema, spec: SpecTypes.NumberSchema) => { sdk = spec; spec = sdk; }, - ContentBlock: (sdk: RemovePassthrough, spec: SpecTypes.ContentBlock) => { + EnumSchema: (sdk: SDKTypes.EnumSchema, spec: SpecTypes.EnumSchema) => { sdk = spec; spec = sdk; }, - PromptMessage: (sdk: RemovePassthrough, spec: SpecTypes.PromptMessage) => { + UntitledSingleSelectEnumSchema: (sdk: SDKTypes.UntitledSingleSelectEnumSchema, spec: SpecTypes.UntitledSingleSelectEnumSchema) => { sdk = spec; spec = sdk; }, - GetPromptResult: (sdk: RemovePassthrough, spec: SpecTypes.GetPromptResult) => { + TitledSingleSelectEnumSchema: (sdk: SDKTypes.TitledSingleSelectEnumSchema, spec: SpecTypes.TitledSingleSelectEnumSchema) => { sdk = spec; spec = sdk; }, - BooleanSchema: (sdk: RemovePassthrough, spec: SpecTypes.BooleanSchema) => { + SingleSelectEnumSchema: (sdk: SDKTypes.SingleSelectEnumSchema, spec: SpecTypes.SingleSelectEnumSchema) => { sdk = spec; spec = sdk; }, - StringSchema: (sdk: RemovePassthrough, spec: SpecTypes.StringSchema) => { + UntitledMultiSelectEnumSchema: (sdk: SDKTypes.UntitledMultiSelectEnumSchema, spec: SpecTypes.UntitledMultiSelectEnumSchema) => { sdk = spec; spec = sdk; }, - NumberSchema: (sdk: RemovePassthrough, spec: SpecTypes.NumberSchema) => { + TitledMultiSelectEnumSchema: (sdk: SDKTypes.TitledMultiSelectEnumSchema, spec: SpecTypes.TitledMultiSelectEnumSchema) => { sdk = spec; spec = sdk; }, - EnumSchema: (sdk: RemovePassthrough, spec: SpecTypes.EnumSchema) => { + MultiSelectEnumSchema: (sdk: SDKTypes.MultiSelectEnumSchema, spec: SpecTypes.MultiSelectEnumSchema) => { sdk = spec; spec = sdk; }, - PrimitiveSchemaDefinition: (sdk: RemovePassthrough, spec: SpecTypes.PrimitiveSchemaDefinition) => { + LegacyTitledEnumSchema: (sdk: SDKTypes.LegacyTitledEnumSchema, spec: SpecTypes.LegacyTitledEnumSchema) => { + sdk = spec; + spec = sdk; + }, + PrimitiveSchemaDefinition: (sdk: SDKTypes.PrimitiveSchemaDefinition, spec: SpecTypes.PrimitiveSchemaDefinition) => { sdk = spec; spec = sdk; }, @@ -386,45 +520,51 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CreateMessageRequest: ( - sdk: WithJSONRPCRequest>, - spec: SpecTypes.CreateMessageRequest - ) => { + CreateMessageRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CreateMessageRequest) => { sdk = spec; spec = sdk; }, - InitializeRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.InitializeRequest) => { + InitializeRequest: ( + sdk: WithJSONRPCRequest, + spec: FixSpecInitializeRequest + ) => { sdk = spec; spec = sdk; }, - InitializeResult: (sdk: RemovePassthrough, spec: SpecTypes.InitializeResult) => { + InitializeResult: (sdk: SDKTypes.InitializeResult, spec: SpecTypes.InitializeResult) => { sdk = spec; spec = sdk; }, - ClientCapabilities: (sdk: RemovePassthrough, spec: SpecTypes.ClientCapabilities) => { + ClientCapabilities: (sdk: SDKTypes.ClientCapabilities, spec: FixSpecClientCapabilities) => { sdk = spec; spec = sdk; }, - ServerCapabilities: (sdk: RemovePassthrough, spec: SpecTypes.ServerCapabilities) => { + ServerCapabilities: (sdk: SDKTypes.ServerCapabilities, spec: SpecTypes.ServerCapabilities) => { sdk = spec; spec = sdk; }, - ClientRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ClientRequest) => { + ClientRequest: ( + sdk: RemovePassthrough>, + spec: FixSpecClientRequest + ) => { sdk = spec; spec = sdk; }, - ServerRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ServerRequest) => { + ServerRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ServerRequest) => { sdk = spec; spec = sdk; }, LoggingMessageNotification: ( - sdk: MakeUnknownsNotOptional>, + sdk: RemovePassthrough>>, spec: SpecTypes.LoggingMessageNotification ) => { sdk = spec; spec = sdk; }, - ServerNotification: (sdk: MakeUnknownsNotOptional>, spec: SpecTypes.ServerNotification) => { + ServerNotification: ( + sdk: MakeUnknownsNotOptional>>, + spec: SpecTypes.ServerNotification + ) => { sdk = spec; spec = sdk; }, @@ -432,11 +572,19 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - Icon: (sdk: RemovePassthrough, spec: SpecTypes.Icon) => { + Icon: (sdk: SDKTypes.Icon, spec: SpecTypes.Icon) => { + sdk = spec; + spec = sdk; + }, + Icons: (sdk: SDKTypes.Icons, spec: SpecTypes.Icons) => { + sdk = spec; + spec = sdk; + }, + ModelHint: (sdk: SDKTypes.ModelHint, spec: SpecTypes.ModelHint) => { sdk = spec; spec = sdk; }, - Icons: (sdk: RemovePassthrough, spec: SpecTypes.Icons) => { + ModelPreferences: (sdk: SDKTypes.ModelPreferences, spec: SpecTypes.ModelPreferences) => { sdk = spec; spec = sdk; } @@ -450,12 +598,9 @@ const MISSING_SDK_TYPES = [ // These are inlined in the SDK: 'Role', 'Error', // The inner error object of a JSONRPCError - // These aren't supported by the SDK yet: // TODO: Add definitions to the SDK - 'Annotations', - 'ModelHint', - 'ModelPreferences' + 'Annotations' ]; function extractExportedTypes(source: string): string[] { @@ -470,7 +615,7 @@ describe('Spec Types', () => { it('should define some expected types', () => { expect(specTypes).toContain('JSONRPCNotification'); expect(specTypes).toContain('ElicitResult'); - expect(specTypes).toHaveLength(94); + expect(specTypes).toHaveLength(119); }); it('should have up to date list of missing sdk types', () => { @@ -479,10 +624,16 @@ describe('Spec Types', () => { } }); - describe('Compatibility tests', () => { - it.each(typesToCheck)('%s should have a compatibility test', type => { - expect(sdkTypeChecks[type as keyof typeof sdkTypeChecks]).toBeDefined(); - }); + it('should have comprehensive compatibility tests', () => { + const missingTests = []; + + for (const typeName of typesToCheck) { + if (!sdkTypeChecks[typeName as keyof typeof sdkTypeChecks]) { + missingTests.push(typeName); + } + } + + expect(missingTests).toHaveLength(0); }); describe('Missing SDK Types', () => { diff --git a/src/spec.types.ts b/src/spec.types.ts index e485e10e1..c58636350 100644 --- a/src/spec.types.ts +++ b/src/spec.types.ts @@ -3,7 +3,7 @@ * * Source: https://github.com/modelcontextprotocol/modelcontextprotocol * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 50671e92e71da830b101c7d1162b44fbddcbef30 + * Last updated from commit: 11ad2a720d8e2f54881235f734121db0bda39052 * * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. * To update this file, run: npm run fetch:spec-types @@ -35,34 +35,44 @@ export type ProgressToken = string | number; */ export type Cursor = string; -/** @internal */ -export interface Request { - method: string; - params?: { +/** + * Common params for any request. + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * 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. */ - _meta?: { - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken?: ProgressToken; - [key: string]: unknown; - }; + progressToken?: ProgressToken; [key: string]: unknown; }; } +/** @internal */ +export interface Request { + method: string; + // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + /** @internal */ export interface Notification { method: string; - params?: { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; - [key: string]: unknown; - }; + // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; } export interface Result { @@ -86,7 +96,7 @@ export interface Error { * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ data?: unknown; -}; +} /** * A uniquely identifying ID for a request in JSON-RPC. @@ -145,6 +155,25 @@ export interface JSONRPCError { export type EmptyResult = Result; /* Cancellation */ +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category notifications/cancelled + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} + /** * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. * @@ -158,22 +187,24 @@ export type EmptyResult = Result; */ export interface CancelledNotification extends JSONRPCNotification { method: "notifications/cancelled"; - params: { - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestId; - - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason?: string; - }; + params: CancelledNotificationParams; } /* Initialization */ +/** + * Parameters for an `initialize` request. + * + * @category initialize + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} + /** * This request is sent from the client to the server when it first connects, asking it to begin initialization. * @@ -181,14 +212,7 @@ export interface CancelledNotification extends JSONRPCNotification { */ export interface InitializeRequest extends JSONRPCRequest { method: "initialize"; - params: { - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: string; - capabilities: ClientCapabilities; - clientInfo: Implementation; - }; + params: InitializeRequestParams; } /** @@ -219,6 +243,7 @@ export interface InitializeResult extends Result { */ export interface InitializedNotification extends JSONRPCNotification { method: "notifications/initialized"; + params?: NotificationParams; } /** @@ -336,7 +361,7 @@ export interface Icon { * * If not provided, the client should assume the icon can be used with any theme. */ - theme?: 'light' | 'dark'; + theme?: "light" | "dark"; } /** @@ -403,9 +428,39 @@ export interface Implementation extends BaseMetadata, Icons { */ export interface PingRequest extends JSONRPCRequest { method: "ping"; + params?: RequestParams; } /* Progress notifications */ + +/** + * Parameters for a `notifications/progress` notification. + * + * @category notifications/progress + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} + /** * An out-of-band notification used to inform the receiver of a progress update for a long-running request. * @@ -413,40 +468,24 @@ export interface PingRequest extends JSONRPCRequest { */ export interface ProgressNotification extends JSONRPCNotification { method: "notifications/progress"; - params: { - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressToken; - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - * - * @TJS-type number - */ - progress: number; - /** - * Total number of items to process (or total progress required), if known. - * - * @TJS-type number - */ - total?: number; - /** - * An optional message describing the current progress. - */ - message?: string; - }; + params: ProgressNotificationParams; } /* Pagination */ +/** + * Common parameters for paginated requests. + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} + /** @internal */ export interface PaginatedRequest extends JSONRPCRequest { - params?: { - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor?: Cursor; - }; + params?: PaginatedRequestParams; } /** @internal */ @@ -495,6 +534,28 @@ export interface ListResourceTemplatesResult extends PaginatedResult { resourceTemplates: ResourceTemplate[]; } +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} + +/** + * Parameters for a `resources/read` request. + * + * @category resources/read + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface ReadResourceRequestParams extends ResourceRequestParams {} + /** * Sent from the client to the server, to read a specific resource URI. * @@ -502,14 +563,7 @@ export interface ListResourceTemplatesResult extends PaginatedResult { */ export interface ReadResourceRequest extends JSONRPCRequest { method: "resources/read"; - params: { - /** - * 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: string; - }; + params: ReadResourceRequestParams; } /** @@ -528,8 +582,17 @@ export interface ReadResourceResult extends Result { */ export interface ResourceListChangedNotification extends JSONRPCNotification { method: "notifications/resources/list_changed"; + params?: NotificationParams; } +/** + * Parameters for a `resources/subscribe` request. + * + * @category resources/subscribe + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface SubscribeRequestParams extends ResourceRequestParams {} + /** * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. * @@ -537,16 +600,17 @@ export interface ResourceListChangedNotification extends JSONRPCNotification { */ export interface SubscribeRequest extends JSONRPCRequest { method: "resources/subscribe"; - params: { - /** - * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: string; - }; + params: SubscribeRequestParams; } +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category resources/unsubscribe + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface UnsubscribeRequestParams extends ResourceRequestParams {} + /** * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. * @@ -554,14 +618,21 @@ export interface SubscribeRequest extends JSONRPCRequest { */ export interface UnsubscribeRequest extends JSONRPCRequest { method: "resources/unsubscribe"; - params: { - /** - * The URI of the resource to unsubscribe from. - * - * @format uri - */ - uri: string; - }; + params: UnsubscribeRequestParams; +} + +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category notifications/resources/updated + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; } /** @@ -571,14 +642,7 @@ export interface UnsubscribeRequest extends JSONRPCRequest { */ export interface ResourceUpdatedNotification extends JSONRPCNotification { method: "notifications/resources/updated"; - params: { - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - * - * @format uri - */ - uri: string; - }; + params: ResourceUpdatedNotificationParams; } /** @@ -712,6 +776,22 @@ export interface ListPromptsResult extends PaginatedResult { prompts: Prompt[]; } +/** + * Parameters for a `prompts/get` request. + * + * @category prompts/get + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; +} + /** * Used by the client to get a prompt provided by the server. * @@ -719,16 +799,7 @@ export interface ListPromptsResult extends PaginatedResult { */ export interface GetPromptRequest extends JSONRPCRequest { method: "prompts/get"; - params: { - /** - * The name of the prompt or prompt template. - */ - name: string; - /** - * Arguments to use for templating the prompt. - */ - arguments?: { [key: string]: string }; - }; + params: GetPromptRequestParams; } /** @@ -830,6 +901,7 @@ export interface EmbeddedResource { */ export interface PromptListChangedNotification extends JSONRPCNotification { method: "notifications/prompts/list_changed"; + params?: NotificationParams; } /* Tools */ @@ -884,6 +956,22 @@ export interface CallToolResult extends Result { isError?: boolean; } +/** + * Parameters for a `tools/call` request. + * + * @category tools/call + */ +export interface CallToolRequestParams extends RequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { [key: string]: unknown }; +} + /** * Used by the client to invoke a tool provided by the server. * @@ -891,10 +979,7 @@ export interface CallToolResult extends Result { */ export interface CallToolRequest extends JSONRPCRequest { method: "tools/call"; - params: { - name: string; - arguments?: { [key: string]: unknown }; - }; + params: CallToolRequestParams; } /** @@ -904,6 +989,7 @@ export interface CallToolRequest extends JSONRPCRequest { */ export interface ToolListChangedNotification extends JSONRPCNotification { method: "notifications/tools/list_changed"; + params?: NotificationParams; } /** @@ -1004,6 +1090,19 @@ export interface Tool extends BaseMetadata, Icons { } /* Logging */ + +/** + * Parameters for a `logging/setLevel` request. + * + * @category logging/setLevel + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; +} + /** * A request from the client to the server, to enable or adjust logging. * @@ -1011,12 +1110,27 @@ export interface Tool extends BaseMetadata, Icons { */ export interface SetLevelRequest extends JSONRPCRequest { method: "logging/setLevel"; - params: { - /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. - */ - level: LoggingLevel; - }; + params: SetLevelRequestParams; +} + +/** + * Parameters for a `notifications/message` notification. + * + * @category notifications/message + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; } /** @@ -1026,20 +1140,7 @@ export interface SetLevelRequest extends JSONRPCRequest { */ export interface LoggingMessageNotification extends JSONRPCNotification { method: "notifications/message"; - params: { - /** - * The severity of this log message. - */ - level: LoggingLevel; - /** - * An optional name of the logger issuing this message. - */ - logger?: string; - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: unknown; - }; + params: LoggingMessageNotificationParams; } /** @@ -1059,6 +1160,42 @@ export type LoggingLevel = | "emergency"; /* Sampling */ +/** + * Parameters for a `sampling/createMessage` request. + * + * @category sampling/createMessage + */ +export interface CreateMessageRequestParams extends RequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; +} + /** * 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. * @@ -1066,36 +1203,7 @@ export type LoggingLevel = */ export interface CreateMessageRequest extends JSONRPCRequest { method: "sampling/createMessage"; - params: { - messages: SamplingMessage[]; - /** - * The server's preferences for which model to select. The client MAY ignore these preferences. - */ - modelPreferences?: ModelPreferences; - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt?: string; - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. - */ - includeContext?: "none" | "thisServer" | "allServers"; - /** - * @TJS-type number - */ - temperature?: number; - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: number; - stopSequences?: string[]; - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata?: object; - }; + params: CreateMessageRequestParams; } /** @@ -1326,40 +1434,47 @@ export interface ModelHint { /* Autocomplete */ /** - * A request from the client to the server, to ask for completion options. + * Parameters for a `completion/complete` request. * * @category completion/complete */ -export interface CompleteRequest extends JSONRPCRequest { - method: "completion/complete"; - params: { - ref: PromptReference | ResourceTemplateReference; +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { /** - * The argument's information + * The name of the argument */ - argument: { - /** - * The name of the argument - */ - name: string; - /** - * The value of the argument to use for completion matching. - */ - value: string; - }; + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + /** + * Additional, optional context for completions + */ + context?: { /** - * Additional, optional context for completions + * Previously-resolved variables in a URI template or prompt. */ - context?: { - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments?: { [key: string]: string }; - }; + arguments?: { [key: string]: string }; }; } +/** + * A request from the client to the server, to ask for completion options. + * + * @category completion/complete + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} + /** * The server's response to a completion/complete request * @@ -1416,6 +1531,7 @@ export interface PromptReference extends BaseMetadata { */ export interface ListRootsRequest extends JSONRPCRequest { method: "roots/list"; + params?: RequestParams; } /** @@ -1463,6 +1579,30 @@ export interface Root { */ export interface RootsListChangedNotification extends JSONRPCNotification { method: "notifications/roots/list_changed"; + params?: NotificationParams; +} + +/** + * Parameters for an `elicitation/create` request. + * + * @category elicitation/create + */ +export interface ElicitRequestParams extends RequestParams { + /** + * The message to present to the user. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; } /** @@ -1472,23 +1612,7 @@ export interface RootsListChangedNotification extends JSONRPCNotification { */ export interface ElicitRequest extends JSONRPCRequest { method: "elicitation/create"; - params: { - /** - * The message to present to the user. - */ - message: string; - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: { - type: "object"; - properties: { - [key: string]: PrimitiveSchemaDefinition; - }; - required?: string[]; - }; - }; + params: ElicitRequestParams; } /** @@ -1527,15 +1651,176 @@ export interface BooleanSchema { default?: boolean; } -export interface EnumSchema { +/** + * Schema for single-selection enumeration without display titles for options. + */ +export interface UntitledSingleSelectEnumSchema { type: "string"; + /** + * Optional title for the enum field. + */ title?: string; + /** + * Optional description for the enum field. + */ description?: string; + /** + * Array of enum values to choose from. + */ enum: string[]; - enumNames?: string[]; // Display names for enum values + /** + * Optional default value. + */ + default?: string; +} + +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ default?: string; } +// Combined single selection enumeration +export type SingleSelectEnumSchema = + | UntitledSingleSelectEnumSchema + | TitledSingleSelectEnumSchema; + +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +// Combined multiple selection enumeration +export type MultiSelectEnumSchema = + | UntitledMultiSelectEnumSchema + | TitledMultiSelectEnumSchema; + +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} + +// Union type for all enum schemas +export type EnumSchema = + | SingleSelectEnumSchema + | MultiSelectEnumSchema + | LegacyTitledEnumSchema; + /** * The client's response to an elicitation request. * @@ -1554,7 +1839,7 @@ export interface ElicitResult extends Result { * The submitted form data, only present when action is "accept". * Contains values matching the requested schema. */ - content?: { [key: string]: string | number | boolean }; + content?: { [key: string]: string | number | boolean | string[] }; } /* Client messages */ diff --git a/src/types.ts b/src/types.ts index e6d3fe46e..66cc34941 100644 --- a/src/types.ts +++ b/src/types.ts @@ -8,6 +8,16 @@ export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-03-26 /* JSON-RPC types */ export const JSONRPC_VERSION = '2.0'; +/** + * Utility types + */ +type ExpandRecursively = T extends object ? (T extends infer O ? { [K in keyof O]: ExpandRecursively } : never) : T; +/** + * Assert 'object' type schema. + * + * @internal + */ +const AssertObjectSchema = z.custom((v): v is object => v !== null && (typeof v === 'object' || typeof v === 'function')); /** * A progress token, used to associate progress notifications with the original request. */ @@ -23,34 +33,39 @@ const RequestMetaSchema = z /** * 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: z.optional(ProgressTokenSchema) + progressToken: ProgressTokenSchema.optional() }) + /** + * Passthrough required here because we want to allow any additional fields to be added to the request meta. + */ .passthrough(); -const BaseRequestParamsSchema = z - .object({ - _meta: z.optional(RequestMetaSchema) - }) - .passthrough(); +/** + * 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() +}); export const RequestSchema = z.object({ method: z.string(), - params: z.optional(BaseRequestParamsSchema) + params: BaseRequestParamsSchema.passthrough().optional() }); -const BaseNotificationParamsSchema = 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: z.optional(z.object({}).passthrough()) - }) - .passthrough(); +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: z.record(z.string(), z.unknown()).optional() +}); export const NotificationSchema = z.object({ method: z.string(), - params: z.optional(BaseNotificationParamsSchema) + params: NotificationsParamsSchema.passthrough().optional() }); export const ResultSchema = z @@ -59,8 +74,11 @@ export const ResultSchema = z * 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.object({}).passthrough()) + _meta: z.record(z.string(), z.unknown()).optional() }) + /** + * Passthrough required here because we want to allow any additional fields to be added to the result. + */ .passthrough(); /** @@ -156,6 +174,18 @@ export const JSONRPCMessageSchema = z.union([JSONRPCRequestSchema, JSONRPCNotifi */ 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, + /** + * 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. @@ -168,84 +198,66 @@ export const EmptyResultSchema = ResultSchema.strict(); */ export const CancelledNotificationSchema = NotificationSchema.extend({ method: z.literal('notifications/cancelled'), - params: BaseNotificationParamsSchema.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, - - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: z.string().optional() - }) + params: CancelledNotificationParamsSchema }); /* Base Metadata */ /** * Icon schema for use in tools, prompts, resources, and implementations. */ -export const IconSchema = z - .object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), - /** - * Optional MIME type for the icon. - */ - mimeType: z.optional(z.string()), - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes: z.optional(z.array(z.string())) - }) - .passthrough(); +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() +}); /** * 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() - }) - .passthrough(); +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 resources, tools, prompts, and implementations. */ -export const BaseMetadataSchema = z - .object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: z.string(), - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title: z.optional(z.string()) - }) - .passthrough(); +export const BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.string().optional() +}); /* Initialization */ /** @@ -256,55 +268,62 @@ export const ImplementationSchema = BaseMetadataSchema.extend({ /** * An optional URL of the website for this implementation. */ - websiteUrl: z.optional(z.string()) + websiteUrl: z.string().optional() }).merge(IconsSchema); /** * 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.optional(z.object({}).passthrough()), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: z.optional(z.object({}).passthrough()), - /** - * Present if the client supports eliciting user input. - */ - elicitation: z.optional(z.object({}).passthrough()), - /** - * Present if the client supports listing roots. - */ - roots: z.optional( - z - .object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ) - }) - .passthrough(); +export const ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: AssertObjectSchema.optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: z.intersection( + z + .object({ + /** + * Whether the client should apply defaults to the user input. + */ + applyDefaults: z.boolean().optional() + }) + .optional(), + z.record(z.string(), z.unknown()).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() +}); +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: 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 - }) + params: InitializeRequestParamsSchema }); export const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success; @@ -312,66 +331,58 @@ export const isInitializeRequest = (value: unknown): value is InitializeRequest /** * 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.optional(z.object({}).passthrough()), - /** - * Present if the server supports sending log messages to the client. - */ - logging: z.optional(z.object({}).passthrough()), - /** - * Present if the server supports sending completions to the client. - */ - completions: z.optional(z.object({}).passthrough()), - /** - * Present if the server offers any prompt templates. - */ - prompts: z.optional( - z - .object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ), - /** - * Present if the server offers any resources to read. - */ - resources: z.optional( - z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.optional(z.boolean()), - - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ), - /** - * Present if the server offers any tools to call. - */ - tools: z.optional( - z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ) - }) - .passthrough(); +export const ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z.optional( + z.object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.optional(z.boolean()) + }) + ), + /** + * 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() +}); /** * After receiving an initialize request from the client, the server sends this response. @@ -388,7 +399,7 @@ export const InitializeResultSchema = ResultSchema.extend({ * * 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.optional(z.string()) + instructions: z.string().optional() }); /** @@ -410,45 +421,48 @@ export const PingRequestSchema = RequestSchema.extend({ }); /* 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()) - }) - .passthrough(); +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 = NotificationsParamsSchema.merge(ProgressSchema).extend({ + /** + * 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: BaseNotificationParamsSchema.merge(ProgressSchema).extend({ - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema - }) + 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: BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: z.optional(CursorSchema) - }).optional() + params: PaginatedRequestParamsSchema.optional() }); export const PaginatedResultSchema = ResultSchema.extend({ @@ -463,23 +477,21 @@ export const PaginatedResultSchema = ResultSchema.extend({ /** * 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.optional(z.object({}).passthrough()) - }) - .passthrough(); +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({ /** @@ -598,17 +610,26 @@ 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 `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: 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. - */ - uri: z.string() - }) + params: ReadResourceRequestParamsSchema }); /** @@ -625,30 +646,32 @@ export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ method: z.literal('notifications/resources/list_changed') }); +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: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. - */ - uri: z.string() - }) + params: SubscribeRequestParamsSchema }); +export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; /** * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. */ export const UnsubscribeRequestSchema = RequestSchema.extend({ method: z.literal('resources/unsubscribe'), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to unsubscribe from. - */ - uri: z.string() - }) + params: UnsubscribeRequestParamsSchema +}); + +/** + * Parameters for a `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() }); /** @@ -656,34 +679,27 @@ export const UnsubscribeRequestSchema = RequestSchema.extend({ */ export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: z.literal('notifications/resources/updated'), - params: BaseNotificationParamsSchema.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() - }) + 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()) - }) - .passthrough(); +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. @@ -718,102 +734,98 @@ export const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: z.array(PromptSchema) }); +/** + * Parameters for a `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: BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.optional(z.record(z.string())) - }) + 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(), +export const TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: 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.optional(z.object({}).passthrough()) - }) - .passthrough(); + /** + * 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(), +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(), - /** - * 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.object({}).passthrough()) - }) - .passthrough(); + /** + * 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 Audio 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(), +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(), - /** - * 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.object({}).passthrough()) - }) - .passthrough(); + /** + * 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]), - /** - * 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.object({}).passthrough()) - }) - .passthrough(); +export const EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * 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. @@ -838,12 +850,10 @@ export const ContentBlockSchema = z.union([ /** * Describes a message returned as part of a prompt. */ -export const PromptMessageSchema = z - .object({ - role: z.enum(['user', 'assistant']), - content: ContentBlockSchema - }) - .passthrough(); +export const PromptMessageSchema = z.object({ + role: z.enum(['user', 'assistant']), + content: ContentBlockSchema +}); /** * The server's response to a prompts/get request from the client. @@ -874,51 +884,49 @@ export const PromptListChangedNotificationSchema = NotificationSchema.extend({ * Clients should never make tool use decisions based on ToolAnnotations * received from untrusted servers. */ -export const ToolAnnotationsSchema = z - .object({ - /** - * A human-readable title for the tool. - */ - title: z.optional(z.string()), +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.optional(z.boolean()), + /** + * 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.optional(z.boolean()), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.boolean().optional(), - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on the its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint: z.optional(z.boolean()), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the 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.optional(z.boolean()) - }) - .passthrough(); + /** + * 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() +}); /** * Definition for a tool the client can call. @@ -927,30 +935,30 @@ export const ToolSchema = BaseMetadataSchema.extend({ /** * A human-readable description of the tool. */ - description: z.optional(z.string()), + description: z.string().optional(), /** * A JSON Schema object defining the expected parameters for the tool. */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.optional(z.object({}).passthrough()), - required: z.optional(z.array(z.string())) - }) - .passthrough(), + inputSchema: z.object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.optional(z.array(z.string())) + }), /** * An optional JSON Schema object defining the structure of the tool's output returned in * the structuredContent field of a CallToolResult. */ - outputSchema: z.optional( - z - .object({ - type: z.literal('object'), - properties: z.optional(z.object({}).passthrough()), - required: z.optional(z.array(z.string())) - }) - .passthrough() - ), + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.optional(z.array(z.string())), + /** + * Not in the MCP specification, but added to support the Ajv validator while removing .passthrough() which previously allowed additionalProperties to be passed through. + */ + additionalProperties: z.optional(z.boolean()) + }) + .optional(), /** * Optional additional tool information. */ @@ -960,7 +968,7 @@ export const ToolSchema = BaseMetadataSchema.extend({ * 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.object({}).passthrough()) + _meta: z.record(z.string(), z.unknown()).optional() }).merge(IconsSchema); /** @@ -994,7 +1002,7 @@ export const CallToolResultSchema = ResultSchema.extend({ * * 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.object({}).passthrough().optional(), + structuredContent: z.record(z.string(), z.unknown()).optional(), /** * Whether the tool call ended in an error. @@ -1022,15 +1030,26 @@ export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( }) ); +/** + * Parameters for a `tools/call` request. + */ +export const CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.optional(z.record(z.string(), z.unknown())) +}); + /** * Used by the client to invoke a tool provided by the server. */ export const CallToolRequestSchema = RequestSchema.extend({ method: z.literal('tools/call'), - params: BaseRequestParamsSchema.extend({ - name: z.string(), - arguments: z.optional(z.record(z.unknown())) - }) + params: CallToolRequestParamsSchema }); /** @@ -1046,117 +1065,125 @@ export const ToolListChangedNotificationSchema = NotificationSchema.extend({ */ 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: 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 - }) + 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: BaseNotificationParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: z.optional(z.string()), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: z.unknown() - }) + params: LoggingMessageNotificationParamsSchema }); /* Sampling */ /** * Hints to use for model selection. */ -export const ModelHintSchema = z - .object({ - /** - * A hint for a model name. - */ - name: z.string().optional() - }) - .passthrough(); +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.optional(z.array(ModelHintSchema)), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: z.optional(z.number().min(0).max(1)) - }) - .passthrough(); +export const ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.optional(z.array(ModelHintSchema)), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.optional(z.number().min(0).max(1)) +}); /** * Describes a message issued to or received from an LLM API. */ -export const SamplingMessageSchema = z - .object({ - role: z.enum(['user', 'assistant']), - content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema]) - }) - .passthrough(); +export const SamplingMessageSchema = z.object({ + role: z.enum(['user', 'assistant']), + content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema]) +}); +/** + * Parameters for a `sampling/createMessage` request. + */ +export const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.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. + */ + 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: AssertObjectSchema.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: BaseRequestParamsSchema.extend({ - messages: z.array(SamplingMessageSchema), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: z.optional(z.string()), - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. - */ - includeContext: z.optional(z.enum(['none', 'thisServer', 'allServers'])), - temperature: z.optional(z.number()), - /** - * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested. - */ - maxTokens: z.number().int(), - stopSequences: z.optional(z.array(z.string())), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: z.optional(z.object({}).passthrough()), - /** - * The server's preferences for which model to select. - */ - modelPreferences: z.optional(ModelPreferencesSchema) - }) + params: CreateMessageRequestParamsSchema }); /** @@ -1179,59 +1206,150 @@ export const CreateMessageResultSchema = ResultSchema.extend({ /** * Primitive schema definition for boolean fields. */ -export const BooleanSchemaSchema = z - .object({ - type: z.literal('boolean'), - title: z.optional(z.string()), - description: z.optional(z.string()), - default: z.optional(z.boolean()) - }) - .passthrough(); +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.optional(z.string()), - description: z.optional(z.string()), - minLength: z.optional(z.number()), - maxLength: z.optional(z.number()), - format: z.optional(z.enum(['email', 'uri', 'date', 'date-time'])) - }) - .passthrough(); +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.optional(z.string()), - description: z.optional(z.string()), - minimum: z.optional(z.number()), - maximum: z.optional(z.number()) - }) - .passthrough(); +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() +}); /** - * Primitive schema definition for enum fields. + * Schema for single-selection enumeration without display titles for options. */ -export const EnumSchemaSchema = z - .object({ +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 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'), - title: z.optional(z.string()), - description: z.optional(z.string()), - enum: z.array(z.string()), - enumNames: z.optional(z.array(z.string())) - }) - .passthrough(); + 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([BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, EnumSchemaSchema]); +export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); + +/** + * Parameters for an `elicitation/create` request. + */ +export const ElicitRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The message to present to the user. + */ + 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() + }) +}); /** * A request from the server to elicit user input via the client. @@ -1239,22 +1357,7 @@ export const PrimitiveSchemaDefinitionSchema = z.union([BooleanSchemaSchema, Str */ export const ElicitRequestSchema = RequestSchema.extend({ method: z.literal('elicitation/create'), - params: BaseRequestParamsSchema.extend({ - /** - * The message to present to the user. - */ - message: z.string(), - /** - * The schema for the requested user input. - */ - requestedSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), - required: z.optional(z.array(z.string())) - }) - .passthrough() - }) + params: ElicitRequestParamsSchema }); /** @@ -1262,28 +1365,30 @@ export const ElicitRequestSchema = RequestSchema.extend({ */ export const ElicitResultSchema = ResultSchema.extend({ /** - * The user's response action. + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice */ action: z.enum(['accept', 'decline', 'cancel']), /** - * The collected user input content (only present if action is "accept"). + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. */ - content: z.optional(z.record(z.string(), z.unknown())) + content: z.record(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() - }) - .passthrough(); +export const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); /** * @deprecated Use ResourceTemplateReferenceSchema instead @@ -1293,49 +1398,61 @@ export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; /** * Identifies a prompt. */ -export const PromptReferenceSchema = z - .object({ - type: z.literal('ref/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 `completion/complete` request. + */ +export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ /** - * The name of the prompt or prompt template + * The name of the argument */ - name: z.string() - }) - .passthrough(); - + 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: 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() - }) - .passthrough(), - context: z.optional( - z.object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.optional(z.record(z.string(), z.string())) - }) - ) - }) + 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}`); + } +} + +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}`); + } +} + /** * The server's response to a completion/complete request */ @@ -1362,24 +1479,22 @@ export const CompleteResultSchema = ResultSchema.extend({ /** * 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.optional(z.string()), +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.optional(z.object({}).passthrough()) - }) - .passthrough(); + /** + * 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. @@ -1523,11 +1638,14 @@ export type JSONRPCNotification = Infer; export type JSONRPCResponse = Infer; export type JSONRPCError = 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 */ @@ -1538,6 +1656,7 @@ export type BaseMetadata = 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; @@ -1548,9 +1667,11 @@ export type PingRequest = Infer; /* Progress notifications */ export type Progress = Infer; +export type ProgressNotificationParams = Infer; export type ProgressNotification = Infer; /* Pagination */ +export type PaginatedRequestParams = Infer; export type PaginatedRequest = Infer; export type PaginatedResult = Infer; @@ -1564,11 +1685,16 @@ 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 */ @@ -1576,6 +1702,7 @@ 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; @@ -1592,6 +1719,7 @@ export type ToolAnnotations = 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; @@ -1599,11 +1727,16 @@ export type ToolListChangedNotification = Infer; +export type SetLevelRequestParams = Infer; export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; export type LoggingMessageNotification = Infer; /* Sampling */ +export type ModelHint = Infer; +export type ModelPreferences = Infer; export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; export type CreateMessageRequest = Infer; export type CreateMessageResult = Infer; @@ -1611,8 +1744,18 @@ export type CreateMessageResult = Infer; 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 ElicitRequest = Infer; export type ElicitResult = Infer; @@ -1623,7 +1766,14 @@ export type ResourceTemplateReference = Infer; +export type CompleteRequestParams = Infer; export type CompleteRequest = Infer; +export type CompleteRequestResourceTemplate = ExpandRecursively< + Omit & { params: Omit & { ref: ResourceTemplateReference } } +>; +export type CompleteRequestPrompt = ExpandRecursively< + Omit & { params: Omit & { ref: PromptReference } } +>; export type CompleteResult = Infer; /* Roots */