diff --git a/src/client/index.ts b/src/client/index.ts index eda412f67..28c0e6253 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -28,11 +28,8 @@ import { ListToolsResultSchema, type LoggingLevel, McpError, - type Notification, type ReadResourceRequest, ReadResourceResultSchema, - type Request, - type Result, type ServerCapabilities, SUPPORTED_PROTOCOL_VERSIONS, type SubscribeRequest, @@ -48,7 +45,10 @@ import { ResourceListChangedNotificationSchema, ListChangedOptions, ListChangedOptionsBaseSchema, - type ListChangedHandlers + type ListChangedHandlers, + type Request, + type Notification, + type Result } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from '../validation/types.js'; @@ -368,14 +368,14 @@ export class Client< } const { params } = validatedRequest.data; - const mode = params.mode ?? 'form'; + params.mode = params.mode ?? 'form'; const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); - if (mode === 'form' && !supportsFormMode) { + if (params.mode === 'form' && !supportsFormMode) { throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); } - if (mode === 'url' && !supportsUrlMode) { + if (params.mode === 'url' && !supportsUrlMode) { throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); } @@ -404,9 +404,9 @@ export class Client< } const validatedResult = validationResult.data; - const requestedSchema = mode === 'form' ? (params.requestedSchema as JsonSchemaType) : undefined; + const requestedSchema = params.mode === 'form' ? (params.requestedSchema as JsonSchemaType) : undefined; - if (mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { if (this._capabilities.elicitation?.form?.applyDefaults) { try { applyElicitationDefaults(requestedSchema, validatedResult.content); diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index 6473ca48f..736587973 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -1,5 +1,5 @@ import { Transport, FetchLike, createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; -import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; +import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; import { auth, AuthResult, extractWWWAuthenticateParams, OAuthClientProvider, UnauthorizedError } from './auth.js'; import { EventSourceParserStream } from 'eventsource-parser/stream'; @@ -350,7 +350,7 @@ export class StreamableHTTPClientTransport implements Transport { if (!event.event || event.event === 'message') { try { const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - if (isJSONRPCResponse(message)) { + if (isJSONRPCResultResponse(message)) { // Mark that we received a response - no need to reconnect for this request receivedResponse = true; if (replayMessageId !== undefined) { diff --git a/src/examples/server/simpleTaskInteractive.ts b/src/examples/server/simpleTaskInteractive.ts index c35126dc0..db0a4b579 100644 --- a/src/examples/server/simpleTaskInteractive.ts +++ b/src/examples/server/simpleTaskInteractive.ts @@ -34,7 +34,8 @@ import { ListToolsRequestSchema, CallToolRequestSchema, GetTaskRequestSchema, - GetTaskPayloadRequestSchema + GetTaskPayloadRequestSchema, + GetTaskPayloadResult } from '../../types.js'; import { TaskMessageQueue, QueuedMessage, QueuedRequest, isTerminal, CreateTaskOptions } from '../../experimental/tasks/interfaces.js'; import { InMemoryTaskStore } from '../../experimental/tasks/stores/in-memory.js'; @@ -618,7 +619,7 @@ const createServer = (): Server => { }); // Handle tasks/result - server.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra): Promise => { + server.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra): Promise => { const { taskId } = request.params; console.log(`[Server] tasks/result called for task ${taskId}`); return taskResultHandler.handle(taskId, server, extra.sessionId ?? ''); diff --git a/src/experimental/tasks/interfaces.ts b/src/experimental/tasks/interfaces.ts index 4800e65dc..88e53028b 100644 --- a/src/experimental/tasks/interfaces.ts +++ b/src/experimental/tasks/interfaces.ts @@ -5,18 +5,18 @@ import { Task, - Request, RequestId, Result, JSONRPCRequest, JSONRPCNotification, - JSONRPCResponse, - JSONRPCError, + JSONRPCResultResponse, + JSONRPCErrorResponse, ServerRequest, ServerNotification, CallToolResult, GetTaskResult, - ToolExecution + ToolExecution, + Request } from '../../types.js'; import { CreateTaskResult } from './types.js'; import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js'; @@ -124,13 +124,13 @@ export interface QueuedNotification extends BaseQueuedMessage { export interface QueuedResponse extends BaseQueuedMessage { type: 'response'; /** The actual JSONRPC response */ - message: JSONRPCResponse; + message: JSONRPCResultResponse; } export interface QueuedError extends BaseQueuedMessage { type: 'error'; /** The actual JSONRPC error */ - message: JSONRPCError; + message: JSONRPCErrorResponse; } /** diff --git a/src/experimental/tasks/stores/in-memory.ts b/src/experimental/tasks/stores/in-memory.ts index 4cc903606..aff3ad910 100644 --- a/src/experimental/tasks/stores/in-memory.ts +++ b/src/experimental/tasks/stores/in-memory.ts @@ -5,7 +5,7 @@ * @experimental */ -import { Task, Request, RequestId, Result } from '../../../types.js'; +import { Task, RequestId, Result, Request } from '../../../types.js'; import { TaskStore, isTerminal, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../interfaces.js'; import { randomBytes } from 'node:crypto'; diff --git a/src/server/index.ts b/src/server/index.ts index aa1a62d00..531a559dd 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -26,10 +26,7 @@ import { LoggingLevelSchema, type LoggingMessageNotification, McpError, - type Notification, - type Request, type ResourceUpdatedNotification, - type Result, type ServerCapabilities, type ServerNotification, type ServerRequest, @@ -40,7 +37,10 @@ import { type ToolUseContent, CallToolRequestSchema, CallToolResultSchema, - CreateTaskResultSchema + CreateTaskResultSchema, + type Request, + type Notification, + type Result } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; import type { JsonSchemaType, jsonSchemaValidator } from '../validation/types.js'; diff --git a/src/server/streamableHttp.ts b/src/server/streamableHttp.ts index b9ae5eeb7..ab1131f63 100644 --- a/src/server/streamableHttp.ts +++ b/src/server/streamableHttp.ts @@ -4,14 +4,14 @@ import { MessageExtraInfo, RequestInfo, isInitializeRequest, - isJSONRPCError, isJSONRPCRequest, - isJSONRPCResponse, + isJSONRPCResultResponse, JSONRPCMessage, JSONRPCMessageSchema, RequestId, SUPPORTED_PROTOCOL_VERSIONS, - DEFAULT_NEGOTIATED_PROTOCOL_VERSION + DEFAULT_NEGOTIATED_PROTOCOL_VERSION, + isJSONRPCErrorResponse } from '../types.js'; import getRawBody from 'raw-body'; import contentType from 'content-type'; @@ -871,7 +871,7 @@ export class StreamableHTTPServerTransport implements Transport { async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId }): Promise { let requestId = options?.relatedRequestId; - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { // If the message is a response, use the request ID from the message requestId = message.id; } @@ -881,7 +881,7 @@ export class StreamableHTTPServerTransport implements Transport { // Those will be sent via dedicated response SSE streams if (requestId === undefined) { // For standalone SSE streams, we can only send requests and notifications - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); } @@ -924,7 +924,7 @@ export class StreamableHTTPServerTransport implements Transport { } } - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._requestResponseMap.set(requestId, message); const relatedIds = Array.from(this._requestToStreamMapping.entries()) .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index e195478f2..aa242a647 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -13,22 +13,20 @@ import { ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, - isJSONRPCError, + isJSONRPCErrorResponse, isJSONRPCRequest, - isJSONRPCResponse, + isJSONRPCResultResponse, isJSONRPCNotification, - JSONRPCError, + JSONRPCErrorResponse, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, McpError, - Notification, PingRequestSchema, Progress, ProgressNotification, ProgressNotificationSchema, RELATED_TASK_META_KEY, - Request, RequestId, Result, ServerCapabilities, @@ -41,7 +39,11 @@ import { CancelledNotification, Task, TaskStatusNotification, - TaskStatusNotificationSchema + TaskStatusNotificationSchema, + Request, + Notification, + JSONRPCResultResponse, + isTaskAugmentedRequestParams } from '../types.js'; import { Transport, TransportSendOptions } from './transport.js'; import { AuthInfo } from '../server/auth/types.js'; @@ -324,7 +326,7 @@ export abstract class Protocol = new Map(); private _requestHandlerAbortControllers: Map = new Map(); private _notificationHandlers: Map Promise> = new Map(); - private _responseHandlers: Map void> = new Map(); + private _responseHandlers: Map void> = new Map(); private _progressHandlers: Map = new Map(); private _timeoutInfo: Map = new Map(); private _pendingDebouncedNotifications = new Set(); @@ -335,7 +337,7 @@ export abstract class Protocol void> = new Map(); + private _requestResolvers: Map void> = new Map(); /** * Callback for when the connection is closed for any reason. @@ -408,18 +410,18 @@ export abstract class Protocol { + if (!notification.params.requestId) { + return; + } // Handle request cancellation const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); controller?.abort(notification.params.reason); @@ -616,7 +621,7 @@ export abstract class Protocol { _onmessage?.(message, extra); - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { this._onrequest(message, extra); @@ -675,7 +680,7 @@ export abstract class Protocol = { @@ -791,7 +796,7 @@ export abstract class Protocol; if (result.task && typeof result.task === 'object') { const task = result.task as Record; @@ -894,7 +899,7 @@ export abstract class Protocol { + const responseResolver = (response: JSONRPCResultResponse | Error) => { const handler = this._responseHandlers.get(messageId); if (handler) { handler(response); diff --git a/src/spec.types.ts b/src/spec.types.ts index 49f2457ce..3544679cf 100644 --- a/src/spec.types.ts +++ b/src/spec.types.ts @@ -1,13 +1,4 @@ -/** - * This file is automatically generated from the Model Context Protocol specification. - * - * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 7dcdd69262bd488ddec071bf4eefedabf1742023 - * - * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: npm run fetch:spec-types - *//* JSON-RPC types */ +/* JSON-RPC types */ /** * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. @@ -17,11 +8,10 @@ export type JSONRPCMessage = | JSONRPCRequest | JSONRPCNotification - | JSONRPCResponse - | JSONRPCError; + | JSONRPCResponse; /** @internal */ -export const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; +export const LATEST_PROTOCOL_VERSION = "2025-11-25"; /** @internal */ export const JSONRPC_VERSION = "2.0"; @@ -39,6 +29,22 @@ export type ProgressToken = string | number; */ export type Cursor = string; +/** + * Common params for any task-augmented request. + * + * @internal + */ +export interface TaskAugmentedRequestParams extends RequestParams { + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task?: TaskMetadata; +} /** * Common params for any request. * @@ -46,7 +52,7 @@ export type Cursor = string; */ export interface RequestParams { /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { /** @@ -68,7 +74,7 @@ export interface Request { /** @internal */ export interface NotificationParams { /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -86,7 +92,7 @@ export interface Notification { */ export interface Result { /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; [key: string]: unknown; @@ -141,12 +147,28 @@ export interface JSONRPCNotification extends Notification { * * @category JSON-RPC */ -export interface JSONRPCResponse { +export interface JSONRPCResultResponse { jsonrpc: typeof JSONRPC_VERSION; id: RequestId; result: Result; } +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; +} + +/** + * A response to a request, containing either the result or error. + */ +export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; + // Standard JSON-RPC error codes export const PARSE_ERROR = -32700; export const INVALID_REQUEST = -32600; @@ -158,24 +180,13 @@ export const INTERNAL_ERROR = -32603; /** @internal */ export const URL_ELICITATION_REQUIRED = -32042; -/** - * A response to a request that indicates an error occurred. - * - * @category JSON-RPC - */ -export interface JSONRPCError { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - error: Error; -} - /** * An error response that indicates that the server requires the client to provide additional information via an elicitation request. * * @internal */ export interface URLElicitationRequiredError - extends Omit { + extends Omit { error: Error & { code: typeof URL_ELICITATION_REQUIRED; data: { @@ -204,8 +215,10 @@ 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. + * This MUST be provided for cancelling non-task requests. + * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). */ - requestId: RequestId; + requestId?: RequestId; /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. @@ -222,6 +235,8 @@ export interface CancelledNotificationParams extends NotificationParams { * * A client MUST NOT attempt to cancel its `initialize` request. * + * For task cancellation, use the `tasks/cancel` request instead of this notification. + * * @category `notifications/cancelled` */ export interface CancelledNotification extends JSONRPCNotification { @@ -322,6 +337,43 @@ export interface ClientCapabilities { * Present if the client supports elicitation from the server. */ elicitation?: { form?: object; url?: object }; + + /** + * Present if the client supports task-augmented requests. + */ + tasks?: { + /** + * Whether this client supports tasks/list. + */ + list?: object; + /** + * Whether this client supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for sampling-related requests. + */ + sampling?: { + /** + * Whether the client supports task-augmented sampling/createMessage requests. + */ + createMessage?: object; + }; + /** + * Task support for elicitation-related requests. + */ + elicitation?: { + /** + * Whether the client supports task-augmented elicitation/create requests. + */ + create?: object; + }; + }; + }; } /** @@ -373,6 +425,33 @@ export interface ServerCapabilities { */ listChanged?: boolean; }; + /** + * Present if the server supports task-augmented requests. + */ + tasks?: { + /** + * Whether this server supports tasks/list. + */ + list?: object; + /** + * Whether this server supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for tool-related requests. + */ + tools?: { + /** + * Whether the server supports task-augmented tools/call requests. + */ + call?: object; + }; + }; + }; } /** @@ -622,7 +701,7 @@ export interface ResourceRequestParams extends RequestParams { * @category `resources/read` */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface ReadResourceRequestParams extends ResourceRequestParams { } +export interface ReadResourceRequestParams extends ResourceRequestParams {} /** * Sent from the client to the server, to read a specific resource URI. @@ -659,7 +738,7 @@ export interface ResourceListChangedNotification extends JSONRPCNotification { * @category `resources/subscribe` */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface SubscribeRequestParams extends ResourceRequestParams { } +export interface SubscribeRequestParams extends ResourceRequestParams {} /** * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. @@ -677,7 +756,7 @@ export interface SubscribeRequest extends JSONRPCRequest { * @category `resources/unsubscribe` */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface UnsubscribeRequestParams extends ResourceRequestParams { } +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. @@ -751,7 +830,7 @@ export interface Resource extends BaseMetadata, Icons { size?: number; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -787,7 +866,7 @@ export interface ResourceTemplate extends BaseMetadata, Icons { annotations?: Annotations; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -810,7 +889,7 @@ export interface ResourceContents { mimeType?: string; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -912,7 +991,7 @@ export interface Prompt extends BaseMetadata, Icons { arguments?: PromptArgument[]; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -982,7 +1061,7 @@ export interface EmbeddedResource { annotations?: Annotations; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1053,7 +1132,7 @@ export interface CallToolResult extends Result { * * @category `tools/call` */ -export interface CallToolRequestParams extends RequestParams { +export interface CallToolRequestParams extends TaskAugmentedRequestParams { /** * The name of the tool. */ @@ -1140,6 +1219,26 @@ export interface ToolAnnotations { openWorldHint?: boolean; } +/** + * Execution-related properties for a tool. + * + * @category `tools/list` + */ +export interface ToolExecution { + /** + * Indicates whether this tool supports task-augmented execution. + * This allows clients to handle long-running operations through polling + * the task system. + * + * - "forbidden": Tool does not support task-augmented execution (default when absent) + * - "optional": Tool may support task-augmented execution + * - "required": Tool requires task-augmented execution + * + * Default: "forbidden" + */ + taskSupport?: "forbidden" | "optional" | "required"; +} + /** * Definition for a tool the client can call. * @@ -1157,16 +1256,26 @@ export interface Tool extends BaseMetadata, Icons { * A JSON Schema object defining the expected parameters for the tool. */ inputSchema: { + $schema?: string; type: "object"; properties?: { [key: string]: object }; required?: string[]; }; + /** + * Execution-related properties for this tool. + */ + execution?: ToolExecution; + /** * An optional JSON Schema object defining the structure of the tool's output returned in * the structuredContent field of a CallToolResult. + * + * Defaults to JSON Schema 2020-12 when no explicit $schema is provided. + * Currently restricted to type: "object" at the root level. */ outputSchema?: { + $schema?: string; type: "object"; properties?: { [key: string]: object }; required?: string[]; @@ -1180,11 +1289,211 @@ export interface Tool extends BaseMetadata, Icons { annotations?: ToolAnnotations; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } +/* Tasks */ + +/** + * The status of a task. + * + * @category `tasks` + */ +export type TaskStatus = + | "working" // The request is currently being processed + | "input_required" // The task is waiting for input (e.g., elicitation or sampling) + | "completed" // The request completed successfully and results are available + | "failed" // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true. + | "cancelled"; // The request was cancelled before completion + +/** + * Metadata for augmenting a request with task execution. + * Include this in the `task` field of the request parameters. + * + * @category `tasks` + */ +export interface TaskMetadata { + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl?: number; +} + +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @category `tasks` + */ +export interface RelatedTaskMetadata { + /** + * The task identifier this message is associated with. + */ + taskId: string; +} + +/** + * Data associated with a task. + * + * @category `tasks` + */ +export interface Task { + /** + * The task identifier. + */ + taskId: string; + + /** + * Current task state. + */ + status: TaskStatus; + + /** + * Optional human-readable message describing the current task state. + * This can provide context for any status, including: + * - Reasons for "cancelled" status + * - Summaries for "completed" status + * - Diagnostic information for "failed" status (e.g., error details, what went wrong) + */ + statusMessage?: string; + + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string; + + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + + /** + * Actual retention duration from creation in milliseconds, null for unlimited. + */ + ttl: number | null; + + /** + * Suggested polling interval in milliseconds. + */ + pollInterval?: number; +} + +/** + * A response to a task-augmented request. + * + * @category `tasks` + */ +export interface CreateTaskResult extends Result { + task: Task; +} + +/** + * A request to retrieve the state of a task. + * + * @category `tasks/get` + */ +export interface GetTaskRequest extends JSONRPCRequest { + method: "tasks/get"; + params: { + /** + * The task identifier to query. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/get request. + * + * @category `tasks/get` + */ +export type GetTaskResult = Result & Task; + +/** + * A request to retrieve the result of a completed task. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadRequest extends JSONRPCRequest { + method: "tasks/result"; + params: { + /** + * The task identifier to retrieve results for. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadResult extends Result { + [key: string]: unknown; +} + +/** + * A request to cancel a task. + * + * @category `tasks/cancel` + */ +export interface CancelTaskRequest extends JSONRPCRequest { + method: "tasks/cancel"; + params: { + /** + * The task identifier to cancel. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/cancel request. + * + * @category `tasks/cancel` + */ +export type CancelTaskResult = Result & Task; + +/** + * A request to retrieve a list of tasks. + * + * @category `tasks/list` + */ +export interface ListTasksRequest extends PaginatedRequest { + method: "tasks/list"; +} + +/** + * The response to a tasks/list request. + * + * @category `tasks/list` + */ +export interface ListTasksResult extends PaginatedResult { + tasks: Task[]; +} + +/** + * Parameters for a `notifications/tasks/status` notification. + * + * @category `notifications/tasks/status` + */ +export type TaskStatusNotificationParams = NotificationParams & Task; + +/** + * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. + * + * @category `notifications/tasks/status` + */ +export interface TaskStatusNotification extends JSONRPCNotification { + method: "notifications/tasks/status"; + params: TaskStatusNotificationParams; +} + /* Logging */ /** @@ -1263,7 +1572,7 @@ export type LoggingLevel = * * @category `sampling/createMessage` */ -export interface CreateMessageRequestParams extends RequestParams { +export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { messages: SamplingMessage[]; /** * The server's preferences for which model to select. The client MAY ignore these preferences. @@ -1335,7 +1644,9 @@ export interface CreateMessageRequest extends JSONRPCRequest { } /** - * 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. + * The client's response to a sampling/createMessage 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` */ @@ -1368,7 +1679,7 @@ export interface SamplingMessage { role: Role; content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1445,7 +1756,7 @@ export interface TextContent { annotations?: Annotations; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1476,7 +1787,7 @@ export interface ImageContent { annotations?: Annotations; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1507,7 +1818,7 @@ export interface AudioContent { annotations?: Annotations; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1541,7 +1852,7 @@ export interface ToolUseContent { * Optional metadata about the tool use. Clients SHOULD preserve this field when * including tool uses in subsequent sampling requests to enable caching optimizations. * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1588,7 +1899,7 @@ export interface ToolResultContent { * Optional metadata about the tool result. Clients SHOULD preserve this field when * including tool results in subsequent sampling requests to enable caching optimizations. * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1816,7 +2127,7 @@ export interface Root { name?: string; /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. */ _meta?: { [key: string]: unknown }; } @@ -1838,7 +2149,7 @@ export interface RootsListChangedNotification extends JSONRPCNotification { * * @category `elicitation/create` */ -export interface ElicitRequestFormParams extends RequestParams { +export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { /** * The elicitation mode. */ @@ -1868,7 +2179,7 @@ export interface ElicitRequestFormParams extends RequestParams { * * @category `elicitation/create` */ -export interface ElicitRequestURLParams extends RequestParams { +export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { /** * The elicitation mode. */ @@ -2200,21 +2511,30 @@ export type ClientRequest = | SubscribeRequest | UnsubscribeRequest | CallToolRequest - | ListToolsRequest; + | ListToolsRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; /** @internal */ export type ClientNotification = | CancelledNotification | ProgressNotification | InitializedNotification - | RootsListChangedNotification; + | RootsListChangedNotification + | TaskStatusNotification; /** @internal */ export type ClientResult = | EmptyResult | CreateMessageResult | ListRootsResult - | ElicitResult; + | ElicitResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; /* Server messages */ /** @internal */ @@ -2222,7 +2542,11 @@ export type ServerRequest = | PingRequest | CreateMessageRequest | ListRootsRequest - | ElicitRequest; + | ElicitRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; /** @internal */ export type ServerNotification = @@ -2233,7 +2557,8 @@ export type ServerNotification = | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification - | ElicitationCompleteNotification; + | ElicitationCompleteNotification + | TaskStatusNotification; /** @internal */ export type ServerResult = @@ -2246,4 +2571,8 @@ export type ServerResult = | ListResourcesResult | ReadResourceResult | CallToolResult - | ListToolsResult; + | ListToolsResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; \ No newline at end of file diff --git a/src/types.ts b/src/types.ts index 49a1c4b6d..dc0c22353 100644 --- a/src/types.ts +++ b/src/types.ts @@ -46,10 +46,15 @@ export const TaskCreationParamsSchema = z.looseObject({ pollInterval: z.number().optional() }); +export const TaskMetadataSchema = z.object({ + ttl: z.number().optional() +}); + /** - * Task association metadata, used to signal which task a message originated from. + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. */ -export const RelatedTaskMetadataSchema = z.looseObject({ +export const RelatedTaskMetadataSchema = z.object({ taskId: z.string() }); @@ -67,42 +72,53 @@ const RequestMetaSchema = z.looseObject({ /** * Common params for any request. */ -const BaseRequestParamsSchema = z.looseObject({ - /** - * If specified, the caller is requesting that the receiver create a task to represent the request. - * Task creation parameters are now at the top level instead of in _meta. - */ - task: TaskCreationParamsSchema.optional(), +const BaseRequestParamsSchema = z.object({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ _meta: RequestMetaSchema.optional() }); +/** + * Common params for any task-augmented request. + */ +export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() +}); + +/** + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. + * + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. + */ +export const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams => + TaskAugmentedRequestParamsSchema.safeParse(value).success; + export const RequestSchema = z.object({ method: z.string(), - params: BaseRequestParamsSchema.optional() + params: BaseRequestParamsSchema.loose().optional() }); -const NotificationsParamsSchema = z.looseObject({ +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 - .object({ - /** - * If specified, this notification is related to the provided task. - */ - [RELATED_TASK_META_KEY]: z.optional(RelatedTaskMetadataSchema) - }) - .passthrough() - .optional() + _meta: RequestMetaSchema.optional() }); export const NotificationSchema = z.object({ method: z.string(), - params: NotificationsParamsSchema.optional() + params: NotificationsParamsSchema.loose().optional() }); export const ResultSchema = z.looseObject({ @@ -110,14 +126,7 @@ export const ResultSchema = z.looseObject({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: z - .looseObject({ - /** - * If specified, this result is related to the provided task. - */ - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() - }) - .optional() + _meta: RequestMetaSchema.optional() }); /** @@ -153,7 +162,7 @@ export const isJSONRPCNotification = (value: unknown): value is JSONRPCNotificat /** * A successful (non-error) response to a request. */ -export const JSONRPCResponseSchema = z +export const JSONRPCResultResponseSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), id: RequestIdSchema, @@ -161,7 +170,8 @@ export const JSONRPCResponseSchema = z }) .strict(); -export const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => JSONRPCResponseSchema.safeParse(value).success; +export const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse => + JSONRPCResultResponseSchema.safeParse(value).success; /** * Error codes defined by the JSON-RPC specification. @@ -185,10 +195,10 @@ export enum ErrorCode { /** * A response to a request that indicates an error occurred. */ -export const JSONRPCErrorSchema = z +export const JSONRPCErrorResponseSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, + id: RequestIdSchema.optional(), error: z.object({ /** * The error type that occurred. @@ -201,14 +211,21 @@ export const JSONRPCErrorSchema = z /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ - data: z.optional(z.unknown()) + data: z.unknown().optional() }) }) .strict(); -export const isJSONRPCError = (value: unknown): value is JSONRPCError => JSONRPCErrorSchema.safeParse(value).success; +export const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse => + JSONRPCErrorResponseSchema.safeParse(value).success; -export const JSONRPCMessageSchema = z.union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]); +export const JSONRPCMessageSchema = z.union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); /* Empty result */ /** @@ -222,7 +239,7 @@ export const CancelledNotificationParamsSchema = NotificationsParamsSchema.exten * * This MUST correspond to the ID of a request previously issued in the same direction. */ - requestId: RequestIdSchema, + requestId: RequestIdSchema.optional(), /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ @@ -343,82 +360,68 @@ const ElicitationCapabilitySchema = z.preprocess( /** * Task capabilities for clients, indicating which request types support task creation. */ -export const ClientTasksCapabilitySchema = z - .object({ - /** - * Present if the client supports listing tasks. - */ - list: z.optional(z.object({}).passthrough()), - /** - * Present if the client supports cancelling tasks. - */ - cancel: z.optional(z.object({}).passthrough()), - /** - * Capabilities for task creation on specific request types. - */ - requests: z.optional( - z - .object({ - /** - * Task support for sampling requests. - */ - sampling: z.optional( - z - .object({ - createMessage: z.optional(z.object({}).passthrough()) - }) - .passthrough() - ), - /** - * Task support for elicitation requests. - */ - elicitation: z.optional( - z - .object({ - create: z.optional(z.object({}).passthrough()) - }) - .passthrough() - ) +export const ClientTasksCapabilitySchema = z.looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for sampling requests. + */ + sampling: z + .looseObject({ + createMessage: AssertObjectSchema.optional() }) - .passthrough() - ) - }) - .passthrough(); + .optional(), + /** + * Task support for elicitation requests. + */ + elicitation: z + .looseObject({ + create: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); /** * Task capabilities for servers, indicating which request types support task creation. */ -export const ServerTasksCapabilitySchema = z - .object({ - /** - * Present if the server supports listing tasks. - */ - list: z.optional(z.object({}).passthrough()), - /** - * Present if the server supports cancelling tasks. - */ - cancel: z.optional(z.object({}).passthrough()), - /** - * Capabilities for task creation on specific request types. - */ - requests: z.optional( - z - .object({ - /** - * Task support for tool requests. - */ - tools: z.optional( - z - .object({ - call: z.optional(z.object({}).passthrough()) - }) - .passthrough() - ) +export const ServerTasksCapabilitySchema = z.looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for tool requests. + */ + tools: z + .looseObject({ + call: AssertObjectSchema.optional() }) - .passthrough() - ) - }) - .passthrough(); + .optional() + }) + .optional() +}); /** * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. @@ -462,7 +465,7 @@ export const ClientCapabilitiesSchema = z.object({ /** * Present if the client supports task creation. */ - tasks: z.optional(ClientTasksCapabilitySchema) + tasks: ClientTasksCapabilitySchema.optional() }); export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ @@ -486,64 +489,62 @@ 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.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(), - /** - * Present if the server supports task creation. - */ - tasks: z.optional(ServerTasksCapabilitySchema) - }) - .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 + .object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional() +}); /** * After receiving an initialize request from the client, the server sends this response. @@ -567,7 +568,8 @@ export const InitializeResultSchema = ResultSchema.extend({ * This notification is sent from the client to the server after initialization has finished. */ export const InitializedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/initialized') + method: z.literal('notifications/initialized'), + params: NotificationsParamsSchema.optional() }); export const isInitializedNotification = (value: unknown): value is InitializedNotification => @@ -578,7 +580,8 @@ export const isInitializedNotification = (value: unknown): value is InitializedN * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. */ export const PingRequestSchema = RequestSchema.extend({ - method: z.literal('ping') + method: z.literal('ping'), + params: BaseRequestParamsSchema.optional() }); /* Progress notifications */ @@ -633,16 +636,21 @@ export const PaginatedResultSchema = ResultSchema.extend({ * An opaque token representing the pagination position after the last returned result. * If present, there may be more results available. */ - nextCursor: z.optional(CursorSchema) + nextCursor: CursorSchema.optional() }); +/** + * The status of a task. + * */ +export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); + /* Tasks */ /** * A pollable state object associated with a request. */ export const TaskSchema = z.object({ taskId: z.string(), - status: z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']), + status: TaskStatusSchema, /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. @@ -708,6 +716,14 @@ export const GetTaskPayloadRequestSchema = RequestSchema.extend({ }) }); +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + */ +export const GetTaskPayloadResultSchema = ResultSchema.loose(); + /** * A request to list tasks. */ @@ -946,7 +962,8 @@ export const ReadResourceResultSchema = ResultSchema.extend({ * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. */ export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed') + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() }); export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; @@ -1138,31 +1155,29 @@ export const AudioContentSchema = z.object({ * A tool call request from an assistant (LLM). * Represents the assistant's request to use a tool. */ -export const ToolUseContentSchema = z - .object({ - type: z.literal('tool_use'), - /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. - */ - name: z.string(), - /** - * Unique identifier for this tool call. - * Used to correlate with ToolResultContent in subsequent messages. - */ - id: z.string(), - /** - * Arguments to pass to the tool. - * Must conform to the tool's inputSchema. - */ - input: z.object({}).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.optional(z.object({}).passthrough()) - }) - .passthrough(); +export const ToolUseContentSchema = z.object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.record(z.string(), z.unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); /** * The contents of a resource, embedded into a prompt or tool call result. @@ -1216,7 +1231,7 @@ export const GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ - description: z.optional(z.string()), + description: z.string().optional(), messages: z.array(PromptMessageSchema) }); @@ -1224,7 +1239,8 @@ export const GetPromptResultSchema = ResultSchema.extend({ * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. */ export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed') + method: z.literal('notifications/prompts/list_changed'), + params: NotificationsParamsSchema.optional() }); /* Tools */ @@ -1334,11 +1350,11 @@ export const ToolSchema = z.object({ /** * Optional additional tool information. */ - annotations: z.optional(ToolAnnotationsSchema), + annotations: ToolAnnotationsSchema.optional(), /** * Execution-related properties for this tool. */ - execution: z.optional(ToolExecutionSchema), + execution: ToolExecutionSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) @@ -1394,7 +1410,7 @@ export const CallToolResultSchema = ResultSchema.extend({ * server does not support tool calls, or any other exceptional conditions, * should be reported as an MCP error response. */ - isError: z.optional(z.boolean()) + isError: z.boolean().optional() }); /** @@ -1409,7 +1425,7 @@ export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( /** * Parameters for a `tools/call` request. */ -export const CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ +export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The name of the tool to call. */ @@ -1417,7 +1433,7 @@ export const CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * Arguments to pass to the tool. */ - arguments: z.optional(z.record(z.string(), z.unknown())) + arguments: z.record(z.string(), z.unknown()).optional() }); /** @@ -1432,7 +1448,8 @@ export const CallToolRequestSchema = RequestSchema.extend({ * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. */ export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed') + method: z.literal('notifications/tools/list_changed'), + params: NotificationsParamsSchema.optional() }); /** @@ -1581,19 +1598,19 @@ export const ModelPreferencesSchema = z.object({ /** * Optional hints to use for model selection. */ - hints: z.optional(z.array(ModelHintSchema)), + hints: z.array(ModelHintSchema).optional(), /** * How much to prioritize cost when selecting a model. */ - costPriority: z.optional(z.number().min(0).max(1)), + costPriority: z.number().min(0).max(1).optional(), /** * How much to prioritize sampling speed (latency) when selecting a model. */ - speedPriority: z.optional(z.number().min(0).max(1)), + speedPriority: z.number().min(0).max(1).optional(), /** * How much to prioritize intelligence and capabilities when selecting a model. */ - intelligencePriority: z.optional(z.number().min(0).max(1)) + intelligencePriority: z.number().min(0).max(1).optional() }); /** @@ -1606,28 +1623,26 @@ export const ToolChoiceSchema = z.object({ * - "required": Model MUST use at least one tool before completing * - "none": Model MUST NOT use any tools */ - mode: z.optional(z.enum(['auto', 'required', 'none'])) + mode: z.enum(['auto', 'required', 'none']).optional() }); /** * The result of a tool execution, provided by the user (server). * Represents the outcome of invoking a tool requested via ToolUseContent. */ -export const ToolResultContentSchema = z - .object({ - type: z.literal('tool_result'), - toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), - content: z.array(ContentBlockSchema).default([]), - structuredContent: z.object({}).passthrough().optional(), - isError: z.optional(z.boolean()), +export const ToolResultContentSchema = z.object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(ContentBlockSchema).default([]), + structuredContent: z.object({}).loose().optional(), + isError: z.boolean().optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.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() +}); /** * Basic content types for sampling responses (without tool use). @@ -1650,22 +1665,20 @@ export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ /** * Describes a message issued to or received from an LLM API. */ -export const SamplingMessageSchema = z - .object({ - role: RoleSchema, - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); +export const SamplingMessageSchema = z.object({ + role: RoleSchema, + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); /** * Parameters for a `sampling/createMessage` request. */ -export const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ +export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: z.array(SamplingMessageSchema), /** * The server's preferences for which model to select. The client MAY modify or omit this request. @@ -1699,13 +1712,13 @@ export const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ * Tools that the model may use during generation. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. */ - tools: z.optional(z.array(ToolSchema)), + tools: z.array(ToolSchema).optional(), /** * Controls how the model uses tools. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * Default is `{ mode: "auto" }`. */ - toolChoice: z.optional(ToolChoiceSchema) + toolChoice: ToolChoiceSchema.optional() }); /** * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. @@ -1904,7 +1917,7 @@ export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, Boolea /** * Parameters for an `elicitation/create` request for form-based elicitation. */ -export const ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ +export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. * @@ -1929,7 +1942,7 @@ export const ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ /** * Parameters for an `elicitation/create` request for URL-based elicitation. */ -export const ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ +export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. */ @@ -2131,7 +2144,8 @@ export const RootSchema = z.object({ * Sent from the server to request a list of root URIs from the client. */ export const ListRootsRequestSchema = RequestSchema.extend({ - method: z.literal('roots/list') + method: z.literal('roots/list'), + params: BaseRequestParamsSchema.optional() }); /** @@ -2145,7 +2159,8 @@ export const ListRootsResultSchema = ResultSchema.extend({ * A notification from the client to the server, informing it that the list of roots has changed. */ export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed') + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() }); /* Client messages */ @@ -2165,7 +2180,8 @@ export const ClientRequestSchema = z.union([ ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema + ListTasksRequestSchema, + CancelTaskRequestSchema ]); export const ClientNotificationSchema = z.union([ @@ -2195,7 +2211,8 @@ export const ServerRequestSchema = z.union([ ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema + ListTasksRequestSchema, + CancelTaskRequestSchema ]); export const ServerNotificationSchema = z.union([ @@ -2330,6 +2347,7 @@ export interface MessageExtraInfo { export type ProgressToken = Infer; export type Cursor = Infer; export type Request = Infer; +export type TaskAugmentedRequestParams = Infer; export type RequestMeta = Infer; export type Notification = Infer; export type Result = Infer; @@ -2337,7 +2355,9 @@ export type RequestId = Infer; export type JSONRPCRequest = Infer; export type JSONRPCNotification = Infer; export type JSONRPCResponse = Infer; -export type JSONRPCError = Infer; +export type JSONRPCErrorResponse = Infer; +export type JSONRPCResultResponse = Infer; + export type JSONRPCMessage = Infer; export type RequestParams = Infer; export type NotificationParams = Infer; @@ -2375,7 +2395,9 @@ export type ProgressNotification = Infer; /* Tasks */ export type Task = Infer; +export type TaskStatus = Infer; export type TaskCreationParams = Infer; +export type TaskMetadata = Infer; export type RelatedTaskMetadata = Infer; export type CreateTaskResult = Infer; export type TaskStatusNotificationParams = Infer; @@ -2387,6 +2409,7 @@ export type ListTasksRequest = Infer; export type ListTasksResult = Infer; export type CancelTaskRequest = Infer; export type CancelTaskResult = Infer; +export type GetTaskPayloadResult = Infer; /* Pagination */ export type PaginatedRequestParams = Infer; diff --git a/test/server/index.test.ts b/test/server/index.test.ts index a32aa0332..e434e57fc 100644 --- a/test/server/index.test.ts +++ b/test/server/index.test.ts @@ -1982,11 +1982,8 @@ describe('createMessage backwards compatibility', () => { // Verify result is returned correctly expect(result.model).toBe('test-model'); - expect(result.content.type).toBe('text'); - // With tools param, result.content can be array (CreateMessageResultWithTools type) - // This would fail type-check if we used CreateMessageResult which doesn't allow arrays - const contentArray = Array.isArray(result.content) ? result.content : [result.content]; - expect(contentArray.length).toBe(1); + expect(result.content).toMatchObject({ type: 'text', text: 'I will use the weather tool' }); + expect(result.content).not.toBeInstanceOf(Array); }); }); diff --git a/test/server/streamableHttp.test.ts b/test/server/streamableHttp.test.ts index 0161d82fb..a20e6e129 100644 --- a/test/server/streamableHttp.test.ts +++ b/test/server/streamableHttp.test.ts @@ -2285,7 +2285,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Verify we received the notification that was sent while disconnected expect(allText).toContain('Missed while disconnected'); - }, 10000); + }, 15000); }); // Test onsessionclosed callback diff --git a/test/shared/protocol.test.ts b/test/shared/protocol.test.ts index 6681cfd17..886dcbb21 100644 --- a/test/shared/protocol.test.ts +++ b/test/shared/protocol.test.ts @@ -5,28 +5,28 @@ import { ErrorCode, JSONRPCMessage, McpError, - Notification, RELATED_TASK_META_KEY, - Request, RequestId, - Result, ServerCapabilities, Task, - TaskCreationParams + TaskCreationParams, + type Request, + type Notification, + type Result } from '../../src/types.js'; import { Protocol, mergeCapabilities } from '../../src/shared/protocol.js'; import { Transport, TransportSendOptions } from '../../src/shared/transport.js'; import { TaskStore, TaskMessageQueue, QueuedMessage, QueuedNotification, QueuedRequest } from '../../src/experimental/tasks/interfaces.js'; import { MockInstance, vi } from 'vitest'; -import { JSONRPCResponse, JSONRPCRequest, JSONRPCError } from '../../src/types.js'; +import { JSONRPCResultResponse, JSONRPCRequest, JSONRPCErrorResponse } from '../../src/types.js'; import { ErrorMessage, ResponseMessage, toArrayAsync } from '../../src/shared/responseMessage.js'; import { InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js'; // Type helper for accessing private/protected Protocol properties in tests interface TestProtocol { _taskMessageQueue?: TaskMessageQueue; - _requestResolvers: Map void>; - _responseHandlers: Map void>; + _requestResolvers: Map void>; + _responseHandlers: Map void>; _taskProgressTokens: Map; _clearTaskQueue: (taskId: string, sessionId?: string) => Promise; requestTaskStore: (request: Request, authInfo: unknown) => TaskStore; @@ -1620,7 +1620,7 @@ describe('Task-based execution', () => { 'Client cancelled task execution.', undefined ); - const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCResponse; + const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCResultResponse; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(5); expect(sentMessage.result._meta).toBeDefined(); @@ -1658,7 +1658,7 @@ describe('Task-based execution', () => { taskDeleted.releaseLatch(); expect(mockTaskStore.getTask).toHaveBeenCalledWith('non-existent', undefined); - const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCError; + const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCErrorResponse; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(6); expect(sentMessage.error).toBeDefined(); @@ -1706,7 +1706,7 @@ describe('Task-based execution', () => { expect(mockTaskStore.getTask).toHaveBeenCalledWith(completedTask.taskId, undefined); expect(mockTaskStore.updateTaskStatus).not.toHaveBeenCalled(); - const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCError; + const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCErrorResponse; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(7); expect(sentMessage.error).toBeDefined(); @@ -3877,7 +3877,7 @@ describe('Message Interception', () => { expect(queue).toBeDefined(); // Clean up the pending request - const requestId = (sendSpy.mock.calls[0][0] as JSONRPCResponse).id; + const requestId = (sendSpy.mock.calls[0][0] as JSONRPCResultResponse).id; transport.onmessage?.({ jsonrpc: '2.0', id: requestId, @@ -4931,7 +4931,7 @@ describe('Error handling for missing resolvers', () => { // Manually trigger the response handling logic if (queuedMessage && queuedMessage.type === 'response') { - const responseMessage = queuedMessage.message as JSONRPCResponse; + const responseMessage = queuedMessage.message as JSONRPCResultResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); @@ -5137,7 +5137,7 @@ describe('Error handling for missing resolvers', () => { const messageId = 123; // Create a response resolver without a corresponding response handler - const responseResolver = (response: JSONRPCResponse | Error) => { + const responseResolver = (response: JSONRPCResultResponse | Error) => { const handler = testProtocol._responseHandlers.get(messageId); if (handler) { handler(response); @@ -5147,7 +5147,7 @@ describe('Error handling for missing resolvers', () => { }; // Simulate the resolver being called without a handler - const mockResponse: JSONRPCResponse = { + const mockResponse: JSONRPCResultResponse = { jsonrpc: '2.0', id: messageId, result: { content: [] } @@ -5185,7 +5185,7 @@ describe('Error handling for missing resolvers', () => { const msg = await taskMessageQueue.dequeue(task.taskId); if (msg && msg.type === 'response') { const testProtocol = protocol as unknown as TestProtocol; - const responseMessage = msg.message as JSONRPCResponse; + const responseMessage = msg.message as JSONRPCResultResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (!resolver) { @@ -5253,7 +5253,7 @@ describe('Error handling for missing resolvers', () => { // Manually trigger the error handling logic if (queuedMessage && queuedMessage.type === 'error') { - const errorMessage = queuedMessage.message as JSONRPCError; + const errorMessage = queuedMessage.message as JSONRPCErrorResponse; const reqId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(reqId); @@ -5301,7 +5301,7 @@ describe('Error handling for missing resolvers', () => { // Manually trigger the error handling logic if (queuedMessage && queuedMessage.type === 'error') { const testProtocol = protocol as unknown as TestProtocol; - const errorMessage = queuedMessage.message as JSONRPCError; + const errorMessage = queuedMessage.message as JSONRPCErrorResponse; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); @@ -5348,7 +5348,7 @@ describe('Error handling for missing resolvers', () => { const queuedMessage = await taskMessageQueue.dequeue(task.taskId); if (queuedMessage && queuedMessage.type === 'error') { - const errorMessage = queuedMessage.message as JSONRPCError; + const errorMessage = queuedMessage.message as JSONRPCErrorResponse; const reqId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(reqId); @@ -5390,7 +5390,7 @@ describe('Error handling for missing resolvers', () => { const msg = await taskMessageQueue.dequeue(task.taskId); if (msg && msg.type === 'error') { const testProtocol = protocol as unknown as TestProtocol; - const errorMessage = msg.message as JSONRPCError; + const errorMessage = msg.message as JSONRPCErrorResponse; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (!resolver) { @@ -5457,7 +5457,7 @@ describe('Error handling for missing resolvers', () => { let msg; while ((msg = await taskMessageQueue.dequeue(task.taskId))) { if (msg.type === 'response') { - const responseMessage = msg.message as JSONRPCResponse; + const responseMessage = msg.message as JSONRPCResultResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { @@ -5465,7 +5465,7 @@ describe('Error handling for missing resolvers', () => { resolver(responseMessage); } } else if (msg.type === 'error') { - const errorMessage = msg.message as JSONRPCError; + const errorMessage = msg.message as JSONRPCErrorResponse; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { @@ -5532,7 +5532,7 @@ describe('Error handling for missing resolvers', () => { let msg; while ((msg = await taskMessageQueue.dequeue(task.taskId))) { if (msg.type === 'response') { - const responseMessage = msg.message as JSONRPCResponse; + const responseMessage = msg.message as JSONRPCResultResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { @@ -5540,7 +5540,7 @@ describe('Error handling for missing resolvers', () => { resolver(responseMessage); } } else if (msg.type === 'error') { - const errorMessage = msg.message as JSONRPCError; + const errorMessage = msg.message as JSONRPCErrorResponse; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { diff --git a/test/spec.types.test.ts b/test/spec.types.test.ts index 3b65d4d4f..8d463674b 100644 --- a/test/spec.types.test.ts +++ b/test/spec.types.test.ts @@ -12,17 +12,6 @@ import fs from 'node:fs'; /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unsafe-function-type */ -// Removes index signatures added by ZodObject.passthrough(). -type RemovePassthrough = T extends object - ? T extends Array - ? Array> - : T extends Function - ? T - : { - [K in keyof T as string extends K ? never : K]: RemovePassthrough; - } - : T; - // Adds the `jsonrpc` property to a type, to match the on-wire format of notifications. type WithJSONRPC = T & { jsonrpc: '2.0' }; @@ -96,112 +85,103 @@ type FixSpecCreateMessageResult = T extends { content: infer C; role: infer R : T; const sdkTypeChecks = { - RequestParams: (sdk: RemovePassthrough, spec: SpecTypes.RequestParams) => { + RequestParams: (sdk: SDKTypes.RequestParams, spec: SpecTypes.RequestParams) => { sdk = spec; spec = sdk; }, - NotificationParams: (sdk: RemovePassthrough, spec: SpecTypes.NotificationParams) => { + NotificationParams: (sdk: SDKTypes.NotificationParams, spec: SpecTypes.NotificationParams) => { sdk = spec; spec = sdk; }, - CancelledNotificationParams: ( - sdk: RemovePassthrough, - spec: SpecTypes.CancelledNotificationParams - ) => { + CancelledNotificationParams: (sdk: SDKTypes.CancelledNotificationParams, spec: SpecTypes.CancelledNotificationParams) => { sdk = spec; spec = sdk; }, InitializeRequestParams: ( - sdk: RemovePassthrough, + sdk: SDKTypes.InitializeRequestParams, spec: FixSpecInitializeRequestParams ) => { sdk = spec; spec = sdk; }, - ProgressNotificationParams: ( - sdk: RemovePassthrough, - spec: SpecTypes.ProgressNotificationParams - ) => { + ProgressNotificationParams: (sdk: SDKTypes.ProgressNotificationParams, spec: SpecTypes.ProgressNotificationParams) => { sdk = spec; spec = sdk; }, - ResourceRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.ResourceRequestParams) => { + ResourceRequestParams: (sdk: SDKTypes.ResourceRequestParams, spec: SpecTypes.ResourceRequestParams) => { sdk = spec; spec = sdk; }, - ReadResourceRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.ReadResourceRequestParams) => { + ReadResourceRequestParams: (sdk: SDKTypes.ReadResourceRequestParams, spec: SpecTypes.ReadResourceRequestParams) => { sdk = spec; spec = sdk; }, - SubscribeRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.SubscribeRequestParams) => { + SubscribeRequestParams: (sdk: SDKTypes.SubscribeRequestParams, spec: SpecTypes.SubscribeRequestParams) => { sdk = spec; spec = sdk; }, - UnsubscribeRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.UnsubscribeRequestParams) => { + UnsubscribeRequestParams: (sdk: SDKTypes.UnsubscribeRequestParams, spec: SpecTypes.UnsubscribeRequestParams) => { sdk = spec; spec = sdk; }, ResourceUpdatedNotificationParams: ( - sdk: RemovePassthrough, + sdk: SDKTypes.ResourceUpdatedNotificationParams, spec: SpecTypes.ResourceUpdatedNotificationParams ) => { sdk = spec; spec = sdk; }, - GetPromptRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.GetPromptRequestParams) => { + GetPromptRequestParams: (sdk: SDKTypes.GetPromptRequestParams, spec: SpecTypes.GetPromptRequestParams) => { sdk = spec; spec = sdk; }, - CallToolRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.CallToolRequestParams) => { + CallToolRequestParams: (sdk: SDKTypes.CallToolRequestParams, spec: SpecTypes.CallToolRequestParams) => { sdk = spec; spec = sdk; }, - SetLevelRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.SetLevelRequestParams) => { + SetLevelRequestParams: (sdk: SDKTypes.SetLevelRequestParams, spec: SpecTypes.SetLevelRequestParams) => { sdk = spec; spec = sdk; }, LoggingMessageNotificationParams: ( - sdk: MakeUnknownsNotOptional>, + sdk: MakeUnknownsNotOptional, spec: SpecTypes.LoggingMessageNotificationParams ) => { sdk = spec; spec = sdk; }, - CreateMessageRequestParams: ( - sdk: RemovePassthrough, - spec: SpecTypes.CreateMessageRequestParams - ) => { + CreateMessageRequestParams: (sdk: SDKTypes.CreateMessageRequestParams, spec: SpecTypes.CreateMessageRequestParams) => { sdk = spec; spec = sdk; }, - CompleteRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.CompleteRequestParams) => { + CompleteRequestParams: (sdk: SDKTypes.CompleteRequestParams, spec: SpecTypes.CompleteRequestParams) => { sdk = spec; spec = sdk; }, - ElicitRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.ElicitRequestParams) => { + ElicitRequestParams: (sdk: SDKTypes.ElicitRequestParams, spec: SpecTypes.ElicitRequestParams) => { sdk = spec; spec = sdk; }, - ElicitRequestFormParams: (sdk: RemovePassthrough, spec: SpecTypes.ElicitRequestFormParams) => { + ElicitRequestFormParams: (sdk: SDKTypes.ElicitRequestFormParams, spec: SpecTypes.ElicitRequestFormParams) => { sdk = spec; spec = sdk; }, - ElicitRequestURLParams: (sdk: RemovePassthrough, spec: SpecTypes.ElicitRequestURLParams) => { + ElicitRequestURLParams: (sdk: SDKTypes.ElicitRequestURLParams, spec: SpecTypes.ElicitRequestURLParams) => { sdk = spec; spec = sdk; }, ElicitationCompleteNotification: ( - sdk: RemovePassthrough>, + sdk: WithJSONRPC, spec: SpecTypes.ElicitationCompleteNotification ) => { sdk = spec; spec = sdk; }, - PaginatedRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.PaginatedRequestParams) => { + PaginatedRequestParams: (sdk: SDKTypes.PaginatedRequestParams, spec: SpecTypes.PaginatedRequestParams) => { sdk = spec; spec = sdk; }, - CancelledNotification: (sdk: RemovePassthrough>, spec: SpecTypes.CancelledNotification) => { + CancelledNotification: (sdk: WithJSONRPC, spec: SpecTypes.CancelledNotification) => { sdk = spec; spec = sdk; }, @@ -213,19 +193,19 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ProgressNotification: (sdk: RemovePassthrough>, spec: SpecTypes.ProgressNotification) => { + ProgressNotification: (sdk: WithJSONRPC, spec: SpecTypes.ProgressNotification) => { sdk = spec; spec = sdk; }, - SubscribeRequest: (sdk: RemovePassthrough>, spec: SpecTypes.SubscribeRequest) => { + SubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SubscribeRequest) => { sdk = spec; spec = sdk; }, - UnsubscribeRequest: (sdk: RemovePassthrough>, spec: SpecTypes.UnsubscribeRequest) => { + UnsubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.UnsubscribeRequest) => { sdk = spec; spec = sdk; }, - PaginatedRequest: (sdk: RemovePassthrough>, spec: SpecTypes.PaginatedRequest) => { + PaginatedRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PaginatedRequest) => { sdk = spec; spec = sdk; }, @@ -233,7 +213,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListRootsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListRootsRequest) => { + ListRootsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListRootsRequest) => { sdk = spec; spec = sdk; }, @@ -245,7 +225,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ElicitRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ElicitRequest) => { + ElicitRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ElicitRequest) => { sdk = spec; spec = sdk; }, @@ -253,7 +233,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CompleteRequest: (sdk: RemovePassthrough>, spec: SpecTypes.CompleteRequest) => { + CompleteRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CompleteRequest) => { sdk = spec; spec = sdk; }, @@ -305,7 +285,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ClientNotification: (sdk: RemovePassthrough>, spec: SpecTypes.ClientNotification) => { + ClientNotification: (sdk: WithJSONRPC, spec: SpecTypes.ClientNotification) => { sdk = spec; spec = sdk; }, @@ -329,7 +309,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListToolsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListToolsRequest) => { + ListToolsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListToolsRequest) => { sdk = spec; spec = sdk; }, @@ -341,75 +321,60 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CallToolRequest: (sdk: RemovePassthrough>, spec: SpecTypes.CallToolRequest) => { + CallToolRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CallToolRequest) => { sdk = spec; spec = sdk; }, - ToolListChangedNotification: ( - sdk: RemovePassthrough>, - spec: SpecTypes.ToolListChangedNotification - ) => { + ToolListChangedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ToolListChangedNotification) => { sdk = spec; spec = sdk; }, ResourceListChangedNotification: ( - sdk: RemovePassthrough>, + sdk: WithJSONRPC, spec: SpecTypes.ResourceListChangedNotification ) => { sdk = spec; spec = sdk; }, PromptListChangedNotification: ( - sdk: RemovePassthrough>, + sdk: WithJSONRPC, spec: SpecTypes.PromptListChangedNotification ) => { sdk = spec; spec = sdk; }, RootsListChangedNotification: ( - sdk: RemovePassthrough>, + sdk: WithJSONRPC, spec: SpecTypes.RootsListChangedNotification ) => { sdk = spec; spec = sdk; }, - ResourceUpdatedNotification: ( - sdk: RemovePassthrough>, - spec: SpecTypes.ResourceUpdatedNotification - ) => { + ResourceUpdatedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ResourceUpdatedNotification) => { sdk = spec; spec = sdk; }, - SamplingMessage: (sdk: RemovePassthrough, spec: SpecTypes.SamplingMessage) => { + SamplingMessage: (sdk: SDKTypes.SamplingMessage, spec: SpecTypes.SamplingMessage) => { sdk = spec; spec = sdk; }, - CreateMessageResult: ( - sdk: RemovePassthrough, - spec: FixSpecCreateMessageResult - ) => { + CreateMessageResult: (sdk: SDKTypes.CreateMessageResult, spec: FixSpecCreateMessageResult) => { sdk = spec; spec = sdk; }, - SetLevelRequest: (sdk: RemovePassthrough>, spec: SpecTypes.SetLevelRequest) => { + SetLevelRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SetLevelRequest) => { sdk = spec; spec = sdk; }, - PingRequest: (sdk: RemovePassthrough>, spec: SpecTypes.PingRequest) => { + PingRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PingRequest) => { sdk = spec; spec = sdk; }, - InitializedNotification: ( - sdk: RemovePassthrough>, - spec: SpecTypes.InitializedNotification - ) => { + InitializedNotification: (sdk: WithJSONRPC, spec: SpecTypes.InitializedNotification) => { sdk = spec; spec = sdk; }, - ListResourcesRequest: ( - sdk: RemovePassthrough>, - spec: SpecTypes.ListResourcesRequest - ) => { + ListResourcesRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListResourcesRequest) => { sdk = spec; spec = sdk; }, @@ -418,7 +383,7 @@ const sdkTypeChecks = { spec = sdk; }, ListResourceTemplatesRequest: ( - sdk: RemovePassthrough>, + sdk: WithJSONRPCRequest, spec: SpecTypes.ListResourceTemplatesRequest ) => { sdk = spec; @@ -428,10 +393,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ReadResourceRequest: ( - sdk: RemovePassthrough>, - spec: SpecTypes.ReadResourceRequest - ) => { + ReadResourceRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ReadResourceRequest) => { sdk = spec; spec = sdk; }, @@ -467,7 +429,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListPromptsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListPromptsRequest) => { + ListPromptsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListPromptsRequest) => { sdk = spec; spec = sdk; }, @@ -475,7 +437,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - GetPromptRequest: (sdk: RemovePassthrough>, spec: SpecTypes.GetPromptRequest) => { + GetPromptRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetPromptRequest) => { sdk = spec; spec = sdk; }, @@ -559,7 +521,11 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - JSONRPCError: (sdk: SDKTypes.JSONRPCError, spec: SpecTypes.JSONRPCError) => { + JSONRPCErrorResponse: (sdk: SDKTypes.JSONRPCErrorResponse, spec: SpecTypes.JSONRPCErrorResponse) => { + sdk = spec; + spec = sdk; + }, + JSONRPCResultResponse: (sdk: SDKTypes.JSONRPCResultResponse, spec: SpecTypes.JSONRPCResultResponse) => { sdk = spec; spec = sdk; }, @@ -567,15 +533,12 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CreateMessageRequest: ( - sdk: RemovePassthrough>, - spec: SpecTypes.CreateMessageRequest - ) => { + CreateMessageRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CreateMessageRequest) => { sdk = spec; spec = sdk; }, InitializeRequest: ( - sdk: RemovePassthrough>, + sdk: WithJSONRPCRequest, spec: FixSpecInitializeRequest ) => { sdk = spec; @@ -593,28 +556,22 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ClientRequest: ( - sdk: RemovePassthrough>, - spec: FixSpecClientRequest - ) => { + ClientRequest: (sdk: WithJSONRPCRequest, spec: FixSpecClientRequest) => { sdk = spec; spec = sdk; }, - ServerRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ServerRequest) => { + ServerRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ServerRequest) => { sdk = spec; spec = sdk; }, LoggingMessageNotification: ( - sdk: RemovePassthrough>>, + sdk: MakeUnknownsNotOptional>, spec: SpecTypes.LoggingMessageNotification ) => { sdk = spec; spec = sdk; }, - ServerNotification: ( - sdk: MakeUnknownsNotOptional>>, - spec: SpecTypes.ServerNotification - ) => { + ServerNotification: (sdk: MakeUnknownsNotOptional>, spec: SpecTypes.ServerNotification) => { sdk = spec; spec = sdk; }, @@ -642,18 +599,15 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ToolUseContent: (sdk: RemovePassthrough, spec: SpecTypes.ToolUseContent) => { + ToolUseContent: (sdk: SDKTypes.ToolUseContent, spec: SpecTypes.ToolUseContent) => { sdk = spec; spec = sdk; }, - ToolResultContent: (sdk: RemovePassthrough, spec: SpecTypes.ToolResultContent) => { + ToolResultContent: (sdk: SDKTypes.ToolResultContent, spec: SpecTypes.ToolResultContent) => { sdk = spec; spec = sdk; }, - SamplingMessageContentBlock: ( - sdk: RemovePassthrough, - spec: SpecTypes.SamplingMessageContentBlock - ) => { + SamplingMessageContentBlock: (sdk: SDKTypes.SamplingMessageContentBlock, spec: SpecTypes.SamplingMessageContentBlock) => { sdk = spec; spec = sdk; }, @@ -664,6 +618,74 @@ const sdkTypeChecks = { Role: (sdk: SDKTypes.Role, spec: SpecTypes.Role) => { sdk = spec; spec = sdk; + }, + TaskAugmentedRequestParams: (sdk: SDKTypes.TaskAugmentedRequestParams, spec: SpecTypes.TaskAugmentedRequestParams) => { + sdk = spec; + spec = sdk; + }, + ToolExecution: (sdk: SDKTypes.ToolExecution, spec: SpecTypes.ToolExecution) => { + sdk = spec; + spec = sdk; + }, + TaskStatus: (sdk: SDKTypes.TaskStatus, spec: SpecTypes.TaskStatus) => { + sdk = spec; + spec = sdk; + }, + TaskMetadata: (sdk: SDKTypes.TaskMetadata, spec: SpecTypes.TaskMetadata) => { + sdk = spec; + spec = sdk; + }, + RelatedTaskMetadata: (sdk: SDKTypes.RelatedTaskMetadata, spec: SpecTypes.RelatedTaskMetadata) => { + sdk = spec; + spec = sdk; + }, + Task: (sdk: SDKTypes.Task, spec: SpecTypes.Task) => { + sdk = spec; + spec = sdk; + }, + CreateTaskResult: (sdk: SDKTypes.CreateTaskResult, spec: SpecTypes.CreateTaskResult) => { + sdk = spec; + spec = sdk; + }, + GetTaskResult: (sdk: SDKTypes.GetTaskResult, spec: SpecTypes.GetTaskResult) => { + sdk = spec; + spec = sdk; + }, + GetTaskPayloadRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetTaskPayloadRequest) => { + sdk = spec; + spec = sdk; + }, + ListTasksRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListTasksRequest) => { + sdk = spec; + spec = sdk; + }, + ListTasksResult: (sdk: SDKTypes.ListTasksResult, spec: SpecTypes.ListTasksResult) => { + sdk = spec; + spec = sdk; + }, + CancelTaskRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CancelTaskRequest) => { + sdk = spec; + spec = sdk; + }, + CancelTaskResult: (sdk: SDKTypes.CancelTaskResult, spec: SpecTypes.CancelTaskResult) => { + sdk = spec; + spec = sdk; + }, + GetTaskRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetTaskRequest) => { + sdk = spec; + spec = sdk; + }, + GetTaskPayloadResult: (sdk: SDKTypes.GetTaskPayloadResult, spec: SpecTypes.GetTaskPayloadResult) => { + sdk = spec; + spec = sdk; + }, + TaskStatusNotificationParams: (sdk: SDKTypes.TaskStatusNotificationParams, spec: SpecTypes.TaskStatusNotificationParams) => { + sdk = spec; + spec = sdk; + }, + TaskStatusNotification: (sdk: WithJSONRPC, spec: SpecTypes.TaskStatusNotification) => { + sdk = spec; + spec = sdk; } }; @@ -689,7 +711,7 @@ describe('Spec Types', () => { it('should define some expected types', () => { expect(specTypes).toContain('JSONRPCNotification'); expect(specTypes).toContain('ElicitResult'); - expect(specTypes).toHaveLength(127); + expect(specTypes).toHaveLength(145); }); it('should have up to date list of missing sdk types', () => { @@ -707,6 +729,7 @@ describe('Spec Types', () => { } } + console.log(missingTests); expect(missingTests).toHaveLength(0); });