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/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/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/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..67361fc10 100644 --- a/src/server/elicitation.test.ts +++ b/src/server/elicitation.test.ts @@ -176,6 +176,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' } @@ -355,6 +356,7 @@ function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWo 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'] 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 5739c9b85..c4bc9c5a7 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -1407,7 +1407,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:') + } + ]) + ); }); /*** @@ -1781,7 +1788,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 +1860,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 +2216,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 +2584,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 +2697,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 +2799,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 +3466,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 +3578,7 @@ describe('prompt()', () => { }) }), { - name: 'Template Name', + title: 'Template Name', description: 'Template description', mimeType: 'application/json' }, diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 294ed3675..6593ea854 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -8,7 +8,6 @@ import { CallToolResult, McpError, ErrorCode, - CompleteRequest, CompleteResult, PromptReference, ResourceTemplateReference, @@ -31,7 +30,11 @@ 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'; @@ -217,9 +220,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 +235,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 +259,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) { 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/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 b48082fb7..653e9522c 100644 --- a/src/spec.types.test.ts +++ b/src/spec.types.test.ts @@ -63,15 +63,93 @@ type MakeUnknownsNotOptional = : T; const sdkTypeChecks = { - CancelledNotification: (sdk: RemovePassthrough>, spec: SpecTypes.CancelledNotification) => { + RequestParams: (sdk: SDKTypes.RequestParams, spec: SpecTypes.RequestParams) => { sdk = spec; spec = sdk; }, - BaseMetadata: (sdk: RemovePassthrough, spec: SpecTypes.BaseMetadata) => { + NotificationParams: (sdk: SDKTypes.NotificationParams, spec: SpecTypes.NotificationParams) => { sdk = spec; spec = sdk; }, - Implementation: (sdk: RemovePassthrough, spec: SpecTypes.Implementation) => { + CancelledNotificationParams: (sdk: SDKTypes.CancelledNotificationParams, spec: SpecTypes.CancelledNotificationParams) => { + sdk = spec; + spec = sdk; + }, + InitializeRequestParams: (sdk: SDKTypes.InitializeRequestParams, spec: SpecTypes.InitializeRequestParams) => { + 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: SDKTypes.BaseMetadata, spec: SpecTypes.BaseMetadata) => { + sdk = spec; + spec = sdk; + }, + Implementation: (sdk: SDKTypes.Implementation, spec: SpecTypes.Implementation) => { sdk = spec; spec = sdk; }, @@ -99,23 +177,23 @@ const sdkTypeChecks = { 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; }, @@ -175,19 +253,19 @@ 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; }, @@ -195,11 +273,11 @@ const sdkTypeChecks = { 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; }, @@ -242,11 +320,11 @@ const sdkTypeChecks = { 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; }, @@ -272,7 +350,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListResourcesResult: (sdk: RemovePassthrough, spec: SpecTypes.ListResourcesResult) => { + ListResourcesResult: (sdk: SDKTypes.ListResourcesResult, spec: SpecTypes.ListResourcesResult) => { sdk = spec; spec = sdk; }, @@ -283,10 +361,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListResourceTemplatesResult: ( - sdk: RemovePassthrough, - spec: SpecTypes.ListResourceTemplatesResult - ) => { + ListResourceTemplatesResult: (sdk: SDKTypes.ListResourceTemplatesResult, spec: SpecTypes.ListResourceTemplatesResult) => { sdk = spec; spec = sdk; }, @@ -297,35 +372,35 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ReadResourceResult: (sdk: RemovePassthrough, spec: SpecTypes.ReadResourceResult) => { + ReadResourceResult: (sdk: SDKTypes.ReadResourceResult, spec: SpecTypes.ReadResourceResult) => { sdk = spec; spec = sdk; }, - ResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.ResourceContents) => { + ResourceContents: (sdk: SDKTypes.ResourceContents, spec: SpecTypes.ResourceContents) => { sdk = spec; spec = sdk; }, - TextResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.TextResourceContents) => { + TextResourceContents: (sdk: SDKTypes.TextResourceContents, spec: SpecTypes.TextResourceContents) => { sdk = spec; spec = sdk; }, - BlobResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.BlobResourceContents) => { + BlobResourceContents: (sdk: SDKTypes.BlobResourceContents, spec: SpecTypes.BlobResourceContents) => { sdk = spec; spec = sdk; }, - Resource: (sdk: RemovePassthrough, spec: SpecTypes.Resource) => { + Resource: (sdk: SDKTypes.Resource, spec: SpecTypes.Resource) => { sdk = spec; spec = sdk; }, - ResourceTemplate: (sdk: RemovePassthrough, spec: SpecTypes.ResourceTemplate) => { + ResourceTemplate: (sdk: SDKTypes.ResourceTemplate, spec: SpecTypes.ResourceTemplate) => { sdk = spec; spec = sdk; }, - PromptArgument: (sdk: RemovePassthrough, spec: SpecTypes.PromptArgument) => { + PromptArgument: (sdk: SDKTypes.PromptArgument, spec: SpecTypes.PromptArgument) => { sdk = spec; spec = sdk; }, - Prompt: (sdk: RemovePassthrough, spec: SpecTypes.Prompt) => { + Prompt: (sdk: SDKTypes.Prompt, spec: SpecTypes.Prompt) => { sdk = spec; spec = sdk; }, @@ -333,7 +408,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListPromptsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListPromptsResult) => { + ListPromptsResult: (sdk: SDKTypes.ListPromptsResult, spec: SpecTypes.ListPromptsResult) => { sdk = spec; spec = sdk; }, @@ -341,55 +416,55 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - TextContent: (sdk: RemovePassthrough, spec: SpecTypes.TextContent) => { + TextContent: (sdk: SDKTypes.TextContent, spec: SpecTypes.TextContent) => { sdk = spec; spec = sdk; }, - ImageContent: (sdk: RemovePassthrough, spec: SpecTypes.ImageContent) => { + ImageContent: (sdk: SDKTypes.ImageContent, spec: SpecTypes.ImageContent) => { sdk = spec; spec = sdk; }, - AudioContent: (sdk: RemovePassthrough, spec: SpecTypes.AudioContent) => { + AudioContent: (sdk: SDKTypes.AudioContent, spec: SpecTypes.AudioContent) => { sdk = spec; spec = sdk; }, - EmbeddedResource: (sdk: RemovePassthrough, spec: SpecTypes.EmbeddedResource) => { + EmbeddedResource: (sdk: SDKTypes.EmbeddedResource, spec: SpecTypes.EmbeddedResource) => { sdk = spec; spec = sdk; }, - ResourceLink: (sdk: RemovePassthrough, spec: SpecTypes.ResourceLink) => { + ResourceLink: (sdk: SDKTypes.ResourceLink, spec: SpecTypes.ResourceLink) => { sdk = spec; spec = sdk; }, - ContentBlock: (sdk: RemovePassthrough, spec: SpecTypes.ContentBlock) => { + ContentBlock: (sdk: SDKTypes.ContentBlock, spec: SpecTypes.ContentBlock) => { sdk = spec; spec = sdk; }, - PromptMessage: (sdk: RemovePassthrough, spec: SpecTypes.PromptMessage) => { + PromptMessage: (sdk: SDKTypes.PromptMessage, spec: SpecTypes.PromptMessage) => { sdk = spec; spec = sdk; }, - GetPromptResult: (sdk: RemovePassthrough, spec: SpecTypes.GetPromptResult) => { + GetPromptResult: (sdk: SDKTypes.GetPromptResult, spec: SpecTypes.GetPromptResult) => { sdk = spec; spec = sdk; }, - BooleanSchema: (sdk: RemovePassthrough, spec: SpecTypes.BooleanSchema) => { + BooleanSchema: (sdk: SDKTypes.BooleanSchema, spec: SpecTypes.BooleanSchema) => { sdk = spec; spec = sdk; }, - StringSchema: (sdk: RemovePassthrough, spec: SpecTypes.StringSchema) => { + StringSchema: (sdk: SDKTypes.StringSchema, spec: SpecTypes.StringSchema) => { sdk = spec; spec = sdk; }, - NumberSchema: (sdk: RemovePassthrough, spec: SpecTypes.NumberSchema) => { + NumberSchema: (sdk: SDKTypes.NumberSchema, spec: SpecTypes.NumberSchema) => { sdk = spec; spec = sdk; }, - EnumSchema: (sdk: RemovePassthrough, spec: SpecTypes.EnumSchema) => { + EnumSchema: (sdk: SDKTypes.EnumSchema, spec: SpecTypes.EnumSchema) => { sdk = spec; spec = sdk; }, - PrimitiveSchemaDefinition: (sdk: RemovePassthrough, spec: SpecTypes.PrimitiveSchemaDefinition) => { + PrimitiveSchemaDefinition: (sdk: SDKTypes.PrimitiveSchemaDefinition, spec: SpecTypes.PrimitiveSchemaDefinition) => { sdk = spec; spec = sdk; }, @@ -401,34 +476,31 @@ 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: SpecTypes.InitializeRequest) => { 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: SpecTypes.ClientCapabilities) => { 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: SpecTypes.ClientRequest) => { sdk = spec; spec = sdk; }, - ServerRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ServerRequest) => { + ServerRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ServerRequest) => { sdk = spec; spec = sdk; }, @@ -440,7 +512,7 @@ const sdkTypeChecks = { spec = sdk; }, ServerNotification: ( - sdk: RemovePassthrough>>, + sdk: MakeUnknownsNotOptional>>, spec: SpecTypes.ServerNotification ) => { sdk = spec; @@ -450,11 +522,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: RemovePassthrough, spec: SpecTypes.Icons) => { + Icons: (sdk: SDKTypes.Icons, spec: SpecTypes.Icons) => { + sdk = spec; + spec = sdk; + }, + ModelHint: (sdk: SDKTypes.ModelHint, spec: SpecTypes.ModelHint) => { + sdk = spec; + spec = sdk; + }, + ModelPreferences: (sdk: SDKTypes.ModelPreferences, spec: SpecTypes.ModelPreferences) => { sdk = spec; spec = sdk; } @@ -468,32 +548,9 @@ const MISSING_SDK_TYPES = [ // These are inlined in the SDK: 'Role', 'Error', // The inner error object of a JSONRPCError - - // Params types are not exported as standalone types in the SDK (they're inferred from Zod schemas): - 'RequestParams', - 'NotificationParams', - 'CancelledNotificationParams', - 'InitializeRequestParams', - 'ProgressNotificationParams', - 'PaginatedRequestParams', - 'ResourceRequestParams', - 'ReadResourceRequestParams', - 'SubscribeRequestParams', - 'UnsubscribeRequestParams', - 'SetLevelRequestParams', - 'GetPromptRequestParams', - 'CompleteRequestParams', - 'CallToolRequestParams', - 'CreateMessageRequestParams', - 'LoggingMessageNotificationParams', - 'ResourceUpdatedNotificationParams', - 'ElicitRequestParams', - // These aren't supported by the SDK yet: // TODO: Add definitions to the SDK - 'Annotations', - 'ModelHint', - 'ModelPreferences' + 'Annotations' ]; function extractExportedTypes(source: string): string[] { diff --git a/src/spec.types.ts b/src/spec.types.ts index e485e10e1..4b7a4edde 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: bcdd3363e6472b645f196e7ec6988abe3b9799e2 * * 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,43 @@ 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`. + 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`. + params?: { [key: string]: any }; } export interface Result { @@ -145,6 +154,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 +186,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 +211,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 +242,7 @@ export interface InitializeResult extends Result { */ export interface InitializedNotification extends JSONRPCNotification { method: "notifications/initialized"; + params?: NotificationParams; } /** @@ -403,9 +427,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 +467,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 +533,27 @@ 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 + */ +export interface ReadResourceRequestParams extends ResourceRequestParams {} + /** * Sent from the client to the server, to read a specific resource URI. * @@ -502,14 +561,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 +580,16 @@ 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 + */ +export interface SubscribeRequestParams extends ResourceRequestParams {} + /** * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. * @@ -537,16 +597,16 @@ 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 + */ +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 +614,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 +638,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 +772,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 +795,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 +897,7 @@ export interface EmbeddedResource { */ export interface PromptListChangedNotification extends JSONRPCNotification { method: "notifications/prompts/list_changed"; + params?: NotificationParams; } /* Tools */ @@ -884,6 +952,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 +975,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 +985,7 @@ export interface CallToolRequest extends JSONRPCRequest { */ export interface ToolListChangedNotification extends JSONRPCNotification { method: "notifications/tools/list_changed"; + params?: NotificationParams; } /** @@ -1004,6 +1086,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 +1106,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 +1136,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 +1156,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 +1199,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 +1430,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 +1527,7 @@ export interface PromptReference extends BaseMetadata { */ export interface ListRootsRequest extends JSONRPCRequest { method: "roots/list"; + params?: RequestParams; } /** @@ -1463,6 +1575,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 +1608,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; } /** diff --git a/src/types.ts b/src/types.ts index e6d3fe46e..8b695a73b 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,52 @@ 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: AssertObjectSchema.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 +321,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 +389,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 +411,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 +467,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 +600,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 +636,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 +669,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 +724,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 +840,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 +874,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 +925,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 +958,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 +992,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 +1020,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 +1055,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,82 +1196,78 @@ 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.optional(z.string()), + description: z.optional(z.string()), + default: z.optional(z.boolean()) +}); /** * 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.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'])) +}); /** * 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.optional(z.string()), + description: z.optional(z.string()), + minimum: z.optional(z.number()), + maximum: z.optional(z.number()) +}); /** * Primitive schema definition for enum fields. */ -export const EnumSchemaSchema = 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(); +export const EnumSchemaSchema = 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())) +}); /** * Union of all primitive schema definitions. */ export const PrimitiveSchemaDefinitionSchema = z.union([BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, EnumSchemaSchema]); +/** + * 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. * The client should present the message and form fields to the user. */ 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 +1275,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()])).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 +1308,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 +1389,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 +1548,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 +1566,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 +1577,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 +1595,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 +1612,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 +1629,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 +1637,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; @@ -1613,6 +1656,7 @@ export type StringSchema = Infer; export type NumberSchema = Infer; export type EnumSchema = Infer; export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; export type ElicitRequest = Infer; export type ElicitResult = Infer; @@ -1623,7 +1667,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 */