From bf5a7ef4cccca88d4dcc9b0597ecc58640a01a1e Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sun, 7 Dec 2025 14:37:15 +0200 Subject: [PATCH 1/4] passthrough, looseoebject removal part 2 --- src/client/index.ts | 22 +- src/experimental/tasks/interfaces.ts | 6 +- src/experimental/tasks/stores/in-memory.ts | 6 +- src/server/index.ts | 12 +- src/shared/protocol.ts | 16 +- src/types.ts | 415 +++++++++--------- .../tasks/stores/in-memory.test.ts | 10 +- test/server/index.test.ts | 7 +- test/server/streamableHttp.test.ts | 4 +- test/shared/protocol.test.ts | 134 +++--- test/spec.types.test.ts | 162 +++---- tsconfig.cjs.json | 1 + tsconfig.json | 2 +- tsconfig.prod.json | 1 + 14 files changed, 368 insertions(+), 430 deletions(-) diff --git a/src/client/index.ts b/src/client/index.ts index eda412f67..91703e4d6 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 RequestGeneric, + type NotificationGeneric, + type Result } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from '../validation/types.js'; @@ -231,8 +231,8 @@ export type ClientOptions = ProtocolOptions & { * ``` */ export class Client< - RequestT extends Request = Request, - NotificationT extends Notification = Notification, + RequestT extends RequestGeneric = RequestGeneric, + NotificationT extends NotificationGeneric = NotificationGeneric, ResultT extends Result = Result > extends Protocol { private _serverCapabilities?: ServerCapabilities; @@ -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/experimental/tasks/interfaces.ts b/src/experimental/tasks/interfaces.ts index 4800e65dc..a433b7ad8 100644 --- a/src/experimental/tasks/interfaces.ts +++ b/src/experimental/tasks/interfaces.ts @@ -5,7 +5,6 @@ import { Task, - Request, RequestId, Result, JSONRPCRequest, @@ -16,7 +15,8 @@ import { ServerNotification, CallToolResult, GetTaskResult, - ToolExecution + ToolExecution, + RequestGeneric } from '../../types.js'; import { CreateTaskResult } from './types.js'; import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js'; @@ -226,7 +226,7 @@ export interface TaskStore { * @param sessionId - Optional session ID for binding the task to a specific session * @returns The created task object */ - createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, sessionId?: string): Promise; + createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: RequestGeneric, sessionId?: string): Promise; /** * Gets the current status of a task. diff --git a/src/experimental/tasks/stores/in-memory.ts b/src/experimental/tasks/stores/in-memory.ts index 4cc903606..e90510919 100644 --- a/src/experimental/tasks/stores/in-memory.ts +++ b/src/experimental/tasks/stores/in-memory.ts @@ -5,13 +5,13 @@ * @experimental */ -import { Task, Request, RequestId, Result } from '../../../types.js'; +import { Task, RequestId, Result, RequestGeneric } from '../../../types.js'; import { TaskStore, isTerminal, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../interfaces.js'; import { randomBytes } from 'node:crypto'; interface StoredTask { task: Task; - request: Request; + request: RequestGeneric; requestId: RequestId; result?: Result; } @@ -39,7 +39,7 @@ export class InMemoryTaskStore implements TaskStore { return randomBytes(16).toString('hex'); } - async createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, _sessionId?: string): Promise { + async createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: RequestGeneric, _sessionId?: string): Promise { // Generate a unique task ID const taskId = this.generateTaskId(); diff --git a/src/server/index.ts b/src/server/index.ts index aa1a62d00..12020345b 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 RequestGeneric, + type NotificationGeneric, + type Result } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; import type { JsonSchemaType, jsonSchemaValidator } from '../validation/types.js'; @@ -127,8 +127,8 @@ export type ServerOptions = ProtocolOptions & { * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. */ export class Server< - RequestT extends Request = Request, - NotificationT extends Notification = Notification, + RequestT extends RequestGeneric = RequestGeneric, + NotificationT extends NotificationGeneric = NotificationGeneric, ResultT extends Result = Result > extends Protocol { private _clientCapabilities?: ClientCapabilities; diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index e195478f2..f7f67d29f 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -22,13 +22,11 @@ import { JSONRPCRequest, JSONRPCResponse, McpError, - Notification, PingRequestSchema, Progress, ProgressNotification, ProgressNotificationSchema, RELATED_TASK_META_KEY, - Request, RequestId, Result, ServerCapabilities, @@ -41,7 +39,9 @@ import { CancelledNotification, Task, TaskStatusNotification, - TaskStatusNotificationSchema + TaskStatusNotificationSchema, + RequestGeneric, + NotificationGeneric } from '../types.js'; import { Transport, TransportSendOptions } from './transport.js'; import { AuthInfo } from '../server/auth/types.js'; @@ -232,7 +232,7 @@ export interface RequestTaskStore { /** * Extra data given to request handlers. */ -export type RequestHandlerExtra = { +export type RequestHandlerExtra = { /** * An abort signal used to communicate if the request was cancelled from the sender's side. */ @@ -315,7 +315,11 @@ type TimeoutInfo = { * Implements MCP protocol framing on top of a pluggable transport, including * features like request/response linking, notifications, and progress. */ -export abstract class Protocol { +export abstract class Protocol< + SendRequestT extends RequestGeneric, + SendNotificationT extends NotificationGeneric, + SendResultT extends Result +> { private _transport?: Transport; private _requestMessageId = 0; private _requestHandlers: Map< @@ -359,7 +363,7 @@ export abstract class Protocol Promise; + fallbackNotificationHandler?: (notification: NotificationGeneric) => Promise; constructor(private _options?: ProtocolOptions) { this.setNotificationHandler(CancelledNotificationSchema, notification => { diff --git a/src/types.ts b/src/types.ts index 49a1c4b6d..d8cd71789 100644 --- a/src/types.ts +++ b/src/types.ts @@ -49,7 +49,7 @@ export const TaskCreationParamsSchema = z.looseObject({ /** * Task association metadata, used to signal which task a message originated from. */ -export const RelatedTaskMetadataSchema = z.looseObject({ +export const RelatedTaskMetadataSchema = z.object({ taskId: z.string() }); @@ -67,7 +67,7 @@ const RequestMetaSchema = z.looseObject({ /** * Common params for any request. */ -const BaseRequestParamsSchema = z.looseObject({ +const BaseRequestParamsSchema = z.object({ /** * 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. @@ -84,20 +84,23 @@ export const RequestSchema = z.object({ params: BaseRequestParamsSchema.optional() }); -const NotificationsParamsSchema = z.looseObject({ +/** + * Generic request schema that allows any additional fields to be added to the params. + * + * Used in {@link JSONRPCRequestSchema} for generic shape matching. + */ +export const RequestSchemaGeneric = RequestSchema.extend({ + params: z.intersection(RequestSchema.shape.params.optional(), z.record(z.string(), z.unknown()).optional()) +}); + +export type RequestGeneric = z.infer; + +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({ @@ -105,19 +108,23 @@ export const NotificationSchema = z.object({ params: NotificationsParamsSchema.optional() }); +/** + * Generic notification schema that allows any additional fields to be added to the params. + * + * Used in {@link JSONRPCNotificationSchema} for generic shape matching. + */ +export const NotificationSchemaGeneric = NotificationSchema.extend({ + params: z.intersection(NotificationSchema.shape.params, z.record(z.string(), z.unknown()).optional()) +}); + +export type NotificationGeneric = z.infer; + 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() }); /** @@ -132,7 +139,7 @@ export const JSONRPCRequestSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), id: RequestIdSchema, - ...RequestSchema.shape + ...RequestSchemaGeneric.shape }) .strict(); @@ -144,7 +151,7 @@ export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSO export const JSONRPCNotificationSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), - ...NotificationSchema.shape + ...NotificationSchemaGeneric.shape }) .strict(); @@ -201,7 +208,7 @@ 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(); @@ -343,82 +350,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: z.object({}).loose().optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.object({}).loose().optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for sampling requests. + */ + sampling: z + .looseObject({ + createMessage: z.object({}).loose().optional() }) - .passthrough() - ) - }) - .passthrough(); + .optional(), + /** + * Task support for elicitation requests. + */ + elicitation: z + .looseObject({ + create: z.object({}).loose().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: z.object({}).loose().optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.object({}).loose().optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for tool requests. + */ + tools: z + .looseObject({ + call: z.object({}).loose().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 +455,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 +479,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. @@ -633,7 +624,7 @@ 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() }); /* Tasks */ @@ -1138,31 +1129,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 +1205,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) }); @@ -1334,11 +1323,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 +1383,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() }); /** @@ -1417,7 +1406,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() }); /** @@ -1581,19 +1570,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 +1595,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,17 +1637,15 @@ 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. @@ -1699,13 +1684,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. diff --git a/test/experimental/tasks/stores/in-memory.test.ts b/test/experimental/tasks/stores/in-memory.test.ts index ceef6c6d8..532da8251 100644 --- a/test/experimental/tasks/stores/in-memory.test.ts +++ b/test/experimental/tasks/stores/in-memory.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../../../src/experimental/tasks/stores/in-memory.js'; -import { TaskCreationParams, Request } from '../../../../src/types.js'; +import { TaskCreationParams, RequestGeneric } from '../../../../src/types.js'; import { QueuedMessage } from '../../../../src/experimental/tasks/interfaces.js'; describe('InMemoryTaskStore', () => { @@ -19,7 +19,7 @@ describe('InMemoryTaskStore', () => { const taskParams: TaskCreationParams = { ttl: 60000 }; - const request: Request = { + const request: RequestGeneric = { method: 'tools/call', params: { name: 'test-tool' } }; @@ -39,7 +39,7 @@ describe('InMemoryTaskStore', () => { it('should create task without ttl', async () => { const taskParams: TaskCreationParams = {}; - const request: Request = { + const request: RequestGeneric = { method: 'tools/call', params: {} }; @@ -52,7 +52,7 @@ describe('InMemoryTaskStore', () => { it('should generate unique taskIds', async () => { const taskParams: TaskCreationParams = {}; - const request: Request = { + const request: RequestGeneric = { method: 'tools/call', params: {} }; @@ -72,7 +72,7 @@ describe('InMemoryTaskStore', () => { it('should return task state', async () => { const taskParams: TaskCreationParams = {}; - const request: Request = { + const request: RequestGeneric = { method: 'tools/call', params: {} }; 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 8d94b272e..be5908f60 100644 --- a/test/server/streamableHttp.test.ts +++ b/test/server/streamableHttp.test.ts @@ -2280,8 +2280,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Verify we received the notification that was sent while disconnected expect(allText).toContain('Missed while disconnected'); - }); - }, 10000); + }, 10000); + }); // Test onsessionclosed callback describe('StreamableHTTPServerTransport onsessionclosed callback', () => { diff --git a/test/shared/protocol.test.ts b/test/shared/protocol.test.ts index 6681cfd17..eec14ddb8 100644 --- a/test/shared/protocol.test.ts +++ b/test/shared/protocol.test.ts @@ -5,14 +5,14 @@ import { ErrorCode, JSONRPCMessage, McpError, - Notification, RELATED_TASK_META_KEY, - Request, RequestId, - Result, ServerCapabilities, Task, - TaskCreationParams + TaskCreationParams, + type RequestGeneric, + type NotificationGeneric, + type Result } from '../../src/types.js'; import { Protocol, mergeCapabilities } from '../../src/shared/protocol.js'; import { Transport, TransportSendOptions } from '../../src/shared/transport.js'; @@ -29,11 +29,11 @@ interface TestProtocol { _responseHandlers: Map void>; _taskProgressTokens: Map; _clearTaskQueue: (taskId: string, sessionId?: string) => Promise; - requestTaskStore: (request: Request, authInfo: unknown) => TaskStore; + requestTaskStore: (request: RequestGeneric, authInfo: unknown) => TaskStore; // Protected task methods (exposed for testing) listTasks: (params?: { cursor?: string }) => Promise<{ tasks: Task[]; nextCursor?: string }>; cancelTask: (params: { taskId: string }) => Promise; - requestStream: (request: Request, schema: ZodType, options?: unknown) => AsyncGenerator>; + requestStream: (request: RequestGeneric, schema: ZodType, options?: unknown) => AsyncGenerator>; } // Mock Transport class @@ -139,14 +139,14 @@ function assertQueuedRequest(o?: QueuedMessage): asserts o is QueuedRequest { } describe('protocol tests', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let sendSpy: MockInstance; beforeEach(() => { transport = new MockTransport(); sendSpy = vi.spyOn(transport, 'send'); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -620,7 +620,7 @@ describe('protocol tests', () => { it('should NOT debounce a notification that has parameters', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -643,7 +643,7 @@ describe('protocol tests', () => { it('should NOT debounce a notification that has a relatedRequestId', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -664,7 +664,7 @@ describe('protocol tests', () => { it('should clear pending debounced notifications on connection close', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -690,7 +690,7 @@ describe('protocol tests', () => { it('should debounce multiple synchronous calls when params property is omitted', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -719,7 +719,7 @@ describe('protocol tests', () => { it('should debounce calls when params is explicitly undefined', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -746,7 +746,7 @@ describe('protocol tests', () => { it('should send non-debounced notifications immediately and multiple times', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -781,7 +781,7 @@ describe('protocol tests', () => { it('should handle sequential batches of debounced notifications correctly', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -993,14 +993,14 @@ describe('mergeCapabilities', () => { }); describe('Task-based execution', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let sendSpy: MockInstance; beforeEach(() => { transport = new MockTransport(); sendSpy = vi.spyOn(transport, 'send'); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1247,7 +1247,7 @@ describe('Task-based execution', () => { // rather than in _meta, and that task management is handled by tool implementors const mockTaskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1316,7 +1316,7 @@ describe('Task-based execution', () => { } ); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1377,7 +1377,7 @@ describe('Task-based execution', () => { } ); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1423,7 +1423,7 @@ describe('Task-based execution', () => { onList: () => listedTasks.releaseLatch() }); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1456,7 +1456,7 @@ describe('Task-based execution', () => { const mockTaskStore = createMockTaskStore(); mockTaskStore.listTasks.mockRejectedValue(new Error('Invalid cursor: bad-cursor')); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1590,7 +1590,7 @@ describe('Task-based execution', () => { throw new Error('Task not found'); }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1632,7 +1632,7 @@ describe('Task-based execution', () => { mockTaskStore.getTask.mockResolvedValue(null); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1680,7 +1680,7 @@ describe('Task-based execution', () => { mockTaskStore.updateTaskStatus.mockClear(); mockTaskStore.getTask.mockResolvedValue(completedTask); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1762,7 +1762,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1812,7 +1812,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1861,7 +1861,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1898,7 +1898,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1943,7 +1943,7 @@ describe('Task-based execution', () => { await mockTaskStore.storeTaskResult(task.taskId, 'completed', testResult); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1986,7 +1986,7 @@ describe('Task-based execution', () => { it('should propagate related-task metadata to handler sendRequest and sendNotification', async () => { const mockTaskStore = createMockTaskStore(); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2062,14 +2062,14 @@ describe('Task-based execution', () => { }); describe('Request Cancellation vs Task Cancellation', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let taskStore: TaskStore; beforeEach(() => { transport = new MockTransport(); taskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2355,14 +2355,14 @@ describe('Request Cancellation vs Task Cancellation', () => { }); describe('Progress notification support for tasks', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let sendSpy: MockInstance; beforeEach(() => { transport = new MockTransport(); sendSpy = vi.spyOn(transport, 'send'); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2373,7 +2373,7 @@ describe('Progress notification support for tasks', () => { it('should maintain progress token association after CreateTaskResult is returned', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2466,7 +2466,7 @@ describe('Progress notification support for tasks', () => { it('should stop progress notifications when task reaches terminal status (completed)', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2601,7 +2601,7 @@ describe('Progress notification support for tasks', () => { it('should stop progress notifications when task reaches terminal status (failed)', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2699,7 +2699,7 @@ describe('Progress notification support for tasks', () => { it('should stop progress notifications when task is cancelled', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2794,7 +2794,7 @@ describe('Progress notification support for tasks', () => { it('should use the same progressToken throughout task lifetime', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -3063,7 +3063,7 @@ describe('Message interception for task-related notifications', () => { it('should queue notifications with io.modelcontextprotocol/related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3100,7 +3100,7 @@ describe('Message interception for task-related notifications', () => { it('should not queue notifications without related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3127,7 +3127,7 @@ describe('Message interception for task-related notifications', () => { it('should propagate queue overflow errors without failing the task', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3174,7 +3174,7 @@ describe('Message interception for task-related notifications', () => { it('should extract task ID correctly from metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3207,7 +3207,7 @@ describe('Message interception for task-related notifications', () => { it('should preserve message order when queuing multiple notifications', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3249,7 +3249,7 @@ describe('Message interception for task-related requests', () => { it('should queue requests with io.modelcontextprotocol/related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3301,7 +3301,7 @@ describe('Message interception for task-related requests', () => { it('should not queue requests without related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3340,7 +3340,7 @@ describe('Message interception for task-related requests', () => { it('should store request resolver for response routing', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3393,7 +3393,7 @@ describe('Message interception for task-related requests', () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); const queue = new InMemoryTaskMessageQueue(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3458,7 +3458,7 @@ describe('Message interception for task-related requests', () => { it('should log error when resolver is missing for side-channeled request', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3534,7 +3534,7 @@ describe('Message interception for task-related requests', () => { it('should propagate queue overflow errors for requests without failing the task', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3588,14 +3588,14 @@ describe('Message interception for task-related requests', () => { }); describe('Message Interception', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let mockTaskStore: TaskStore & { [K in keyof TaskStore]: MockInstance }; beforeEach(() => { transport = new MockTransport(); mockTaskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4129,14 +4129,14 @@ describe('Message Interception', () => { }); describe('Queue lifecycle management', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let mockTaskStore: TaskStore & { [K in keyof TaskStore]: MockInstance }; beforeEach(() => { transport = new MockTransport(); mockTaskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4450,7 +4450,7 @@ describe('requestStream() method', () => { test('should yield result immediately for non-task requests', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4493,7 +4493,7 @@ describe('requestStream() method', () => { test('should yield error message on request failure', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4539,7 +4539,7 @@ describe('requestStream() method', () => { test('should handle cancellation via AbortSignal', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4577,7 +4577,7 @@ describe('requestStream() method', () => { describe('Error responses', () => { test('should yield error as terminal message for server error response', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4619,7 +4619,7 @@ describe('requestStream() method', () => { vi.useFakeTimers(); try { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4657,7 +4657,7 @@ describe('requestStream() method', () => { test('should yield error as terminal message for cancellation', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4690,7 +4690,7 @@ describe('requestStream() method', () => { test('should not yield any messages after error message', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4742,7 +4742,7 @@ describe('requestStream() method', () => { test('should yield error as terminal message for task failure', async () => { const transport = new MockTransport(); const mockTaskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4802,7 +4802,7 @@ describe('requestStream() method', () => { test('should yield error as terminal message for network error', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4830,7 +4830,7 @@ describe('requestStream() method', () => { test('should ensure error is always the final message', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4875,7 +4875,7 @@ describe('requestStream() method', () => { }); describe('Error handling for missing resolvers', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let taskStore: TaskStore & { [K in keyof TaskStore]: MockInstance }; let taskMessageQueue: TaskMessageQueue; @@ -4886,7 +4886,7 @@ describe('Error handling for missing resolvers', () => { taskMessageQueue = new InMemoryTaskMessageQueue(); errorHandler = vi.fn(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} diff --git a/test/spec.types.test.ts b/test/spec.types.test.ts index 3b65d4d4f..ed8cf3187 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; }, @@ -567,15 +529,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 +552,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 +595,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; }, diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json index ed5f7fe3e..4b712da77 100644 --- a/tsconfig.cjs.json +++ b/tsconfig.cjs.json @@ -5,5 +5,6 @@ "moduleResolution": "node", "outDir": "./dist/cjs" }, + "include": ["src/**/*"], "exclude": ["**/*.test.ts", "src/__mocks__/**/*", "src/__fixtures__/**/*"] } diff --git a/tsconfig.json b/tsconfig.json index a146fb03d..c7346e4fe 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,6 +18,6 @@ }, "types": ["node", "vitest/globals"] }, - "include": ["src/**/*"], + "include": ["src/**/*", "test/**/*"], "exclude": ["node_modules", "dist"] } diff --git a/tsconfig.prod.json b/tsconfig.prod.json index a07311af7..82710bd6a 100644 --- a/tsconfig.prod.json +++ b/tsconfig.prod.json @@ -3,5 +3,6 @@ "compilerOptions": { "outDir": "./dist/esm" }, + "include": ["src/**/*"], "exclude": ["**/*.test.ts", "src/__mocks__/**/*", "src/__fixtures__/**/*"] } From a297f9d69231fea7e6555992e11f77e6d2b09271 Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sun, 7 Dec 2025 14:43:15 +0200 Subject: [PATCH 2/4] flaky test fix --- test/types.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/types.test.ts b/test/types.test.ts index 64bb78a21..78e5bf5a7 100644 --- a/test/types.test.ts +++ b/test/types.test.ts @@ -178,7 +178,7 @@ describe('Types', () => { annotations: { audience: ['user'], priority: 0.5, - lastModified: new Date().toISOString() + lastModified: mockDate } }; From b4278c87bb6fd948ba88316cfdbccd0aa4b3ea0e Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Mon, 8 Dec 2025 19:22:02 +0200 Subject: [PATCH 3/4] remove result generic and notification generic, align types with Task types from 2025-11-25 spec --- src/client/index.ts | 8 +- src/client/streamableHttp.ts | 4 +- src/experimental/tasks/interfaces.ts | 12 +- src/experimental/tasks/stores/in-memory.ts | 6 +- src/server/index.ts | 8 +- src/server/streamableHttp.ts | 12 +- src/shared/protocol.ts | 55 +-- src/spec.types.ts | 443 +++++++++++++++--- src/types.ts | 154 +++--- .../tasks/stores/in-memory.test.ts | 10 +- test/server/streamableHttp.test.ts | 2 +- test/shared/protocol.test.ts | 168 +++---- test/spec.types.test.ts | 77 ++- 13 files changed, 700 insertions(+), 259 deletions(-) diff --git a/src/client/index.ts b/src/client/index.ts index 91703e4d6..28c0e6253 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -46,8 +46,8 @@ import { ListChangedOptions, ListChangedOptionsBaseSchema, type ListChangedHandlers, - type RequestGeneric, - type NotificationGeneric, + type Request, + type Notification, type Result } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; @@ -231,8 +231,8 @@ export type ClientOptions = ProtocolOptions & { * ``` */ export class Client< - RequestT extends RequestGeneric = RequestGeneric, - NotificationT extends NotificationGeneric = NotificationGeneric, + RequestT extends Request = Request, + NotificationT extends Notification = Notification, ResultT extends Result = Result > extends Protocol { private _serverCapabilities?: ServerCapabilities; 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/experimental/tasks/interfaces.ts b/src/experimental/tasks/interfaces.ts index a433b7ad8..88e53028b 100644 --- a/src/experimental/tasks/interfaces.ts +++ b/src/experimental/tasks/interfaces.ts @@ -9,14 +9,14 @@ import { Result, JSONRPCRequest, JSONRPCNotification, - JSONRPCResponse, - JSONRPCError, + JSONRPCResultResponse, + JSONRPCErrorResponse, ServerRequest, ServerNotification, CallToolResult, GetTaskResult, ToolExecution, - RequestGeneric + 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; } /** @@ -226,7 +226,7 @@ export interface TaskStore { * @param sessionId - Optional session ID for binding the task to a specific session * @returns The created task object */ - createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: RequestGeneric, sessionId?: string): Promise; + createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, sessionId?: string): Promise; /** * Gets the current status of a task. diff --git a/src/experimental/tasks/stores/in-memory.ts b/src/experimental/tasks/stores/in-memory.ts index e90510919..aff3ad910 100644 --- a/src/experimental/tasks/stores/in-memory.ts +++ b/src/experimental/tasks/stores/in-memory.ts @@ -5,13 +5,13 @@ * @experimental */ -import { Task, RequestId, Result, RequestGeneric } 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'; interface StoredTask { task: Task; - request: RequestGeneric; + request: Request; requestId: RequestId; result?: Result; } @@ -39,7 +39,7 @@ export class InMemoryTaskStore implements TaskStore { return randomBytes(16).toString('hex'); } - async createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: RequestGeneric, _sessionId?: string): Promise { + async createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, _sessionId?: string): Promise { // Generate a unique task ID const taskId = this.generateTaskId(); diff --git a/src/server/index.ts b/src/server/index.ts index 12020345b..531a559dd 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -38,8 +38,8 @@ import { CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema, - type RequestGeneric, - type NotificationGeneric, + type Request, + type Notification, type Result } from '../types.js'; import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; @@ -127,8 +127,8 @@ export type ServerOptions = ProtocolOptions & { * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. */ export class Server< - RequestT extends RequestGeneric = RequestGeneric, - NotificationT extends NotificationGeneric = NotificationGeneric, + RequestT extends Request = Request, + NotificationT extends Notification = Notification, ResultT extends Result = Result > extends Protocol { private _clientCapabilities?: ClientCapabilities; diff --git a/src/server/streamableHttp.ts b/src/server/streamableHttp.ts index 35e7f64e7..1dd84f4c4 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'; @@ -858,7 +858,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; } @@ -868,7 +868,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'); } @@ -911,7 +911,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 f7f67d29f..aa242a647 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -13,11 +13,11 @@ import { ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, - isJSONRPCError, + isJSONRPCErrorResponse, isJSONRPCRequest, - isJSONRPCResponse, + isJSONRPCResultResponse, isJSONRPCNotification, - JSONRPCError, + JSONRPCErrorResponse, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, @@ -40,8 +40,10 @@ import { Task, TaskStatusNotification, TaskStatusNotificationSchema, - RequestGeneric, - NotificationGeneric + Request, + Notification, + JSONRPCResultResponse, + isTaskAugmentedRequestParams } from '../types.js'; import { Transport, TransportSendOptions } from './transport.js'; import { AuthInfo } from '../server/auth/types.js'; @@ -232,7 +234,7 @@ export interface RequestTaskStore { /** * Extra data given to request handlers. */ -export type RequestHandlerExtra = { +export type RequestHandlerExtra = { /** * An abort signal used to communicate if the request was cancelled from the sender's side. */ @@ -315,11 +317,7 @@ type TimeoutInfo = { * Implements MCP protocol framing on top of a pluggable transport, including * features like request/response linking, notifications, and progress. */ -export abstract class Protocol< - SendRequestT extends RequestGeneric, - SendNotificationT extends NotificationGeneric, - SendResultT extends Result -> { +export abstract class Protocol { private _transport?: Transport; private _requestMessageId = 0; private _requestHandlers: Map< @@ -328,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(); @@ -339,7 +337,7 @@ export abstract class Protocol< private _taskStore?: TaskStore; private _taskMessageQueue?: TaskMessageQueue; - private _requestResolvers: Map void> = new Map(); + private _requestResolvers: Map void> = new Map(); /** * Callback for when the connection is closed for any reason. @@ -363,7 +361,7 @@ export abstract class Protocol< /** * A handler to invoke for any notification types that do not have their own handler installed. */ - fallbackNotificationHandler?: (notification: NotificationGeneric) => Promise; + fallbackNotificationHandler?: (notification: Notification) => Promise; constructor(private _options?: ProtocolOptions) { this.setNotificationHandler(CancelledNotificationSchema, notification => { @@ -412,18 +410,18 @@ export abstract class Protocol< const requestId = message.id; // Lookup resolver in _requestResolvers map - const resolver = this._requestResolvers.get(requestId); + const resolver = this._requestResolvers.get(requestId as RequestId); if (resolver) { // Remove resolver from map after invocation - this._requestResolvers.delete(requestId); + this._requestResolvers.delete(requestId as RequestId); // Invoke resolver with response or error if (queuedMessage.type === 'response') { - resolver(message as JSONRPCResponse); + resolver(message as JSONRPCResultResponse); } else { // Convert JSONRPCError to McpError - const errorMessage = message as JSONRPCError; + const errorMessage = message as JSONRPCErrorResponse; const error = new McpError( errorMessage.error.code, errorMessage.error.message, @@ -550,6 +548,9 @@ export abstract class Protocol< } private async _oncancel(notification: CancelledNotification): Promise { + if (!notification.params.requestId) { + return; + } // Handle request cancellation const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); controller?.abort(notification.params.reason); @@ -620,7 +621,7 @@ export abstract class Protocol< const _onmessage = this._transport?.onmessage; this._transport.onmessage = (message, extra) => { _onmessage?.(message, extra); - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { this._onrequest(message, extra); @@ -679,7 +680,7 @@ export abstract class Protocol< const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; if (handler === undefined) { - const errorResponse: JSONRPCError = { + const errorResponse: JSONRPCErrorResponse = { jsonrpc: '2.0', id: request.id, error: { @@ -710,7 +711,7 @@ export abstract class Protocol< const abortController = new AbortController(); this._requestHandlerAbortControllers.set(request.id, abortController); - const taskCreationParams = request.params?.task; + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined; const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; const fullExtra: RequestHandlerExtra = { @@ -795,7 +796,7 @@ export abstract class Protocol< return; } - const errorResponse: JSONRPCError = { + const errorResponse: JSONRPCErrorResponse = { jsonrpc: '2.0', id: request.id, error: { @@ -856,14 +857,14 @@ export abstract class Protocol< handler(params); } - private _onresponse(response: JSONRPCResponse | JSONRPCError): void { + private _onresponse(response: JSONRPCResponse | JSONRPCErrorResponse): void { const messageId = Number(response.id); // Check if this is a response to a queued request const resolver = this._requestResolvers.get(messageId); if (resolver) { this._requestResolvers.delete(messageId); - if (isJSONRPCResponse(response)) { + if (isJSONRPCResultResponse(response)) { resolver(response); } else { const error = new McpError(response.error.code, response.error.message, response.error.data); @@ -883,7 +884,7 @@ export abstract class Protocol< // Keep progress handler alive for CreateTaskResult responses let isTaskResponse = false; - if (isJSONRPCResponse(response) && response.result && typeof response.result === 'object') { + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') { const result = response.result as Record; if (result.task && typeof result.task === 'object') { const task = result.task as Record; @@ -898,7 +899,7 @@ export abstract class Protocol< this._progressHandlers.delete(messageId); } - if (isJSONRPCResponse(response)) { + if (isJSONRPCResultResponse(response)) { handler(response); } else { const error = McpError.fromError(response.error.code, response.error.message, response.error.data); @@ -1195,7 +1196,7 @@ export abstract class Protocol< const relatedTaskId = relatedTask?.taskId; if (relatedTaskId) { // Store the response resolver for this request so responses can be routed back - const responseResolver = (response: JSONRPCResponse | Error) => { + 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 d8cd71789..dc0c22353 100644 --- a/src/types.ts +++ b/src/types.ts @@ -46,8 +46,13 @@ 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.object({ taskId: z.string() @@ -68,32 +73,40 @@ const RequestMetaSchema = z.looseObject({ * Common params for any request. */ const BaseRequestParamsSchema = z.object({ - /** - * 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(), /** * 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: BaseRequestParamsSchema.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() }); /** - * Generic request schema that allows any additional fields to be added to the params. + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. * - * Used in {@link JSONRPCRequestSchema} for generic shape matching. + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. */ -export const RequestSchemaGeneric = RequestSchema.extend({ - params: z.intersection(RequestSchema.shape.params.optional(), z.record(z.string(), z.unknown()).optional()) -}); +export const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams => + TaskAugmentedRequestParamsSchema.safeParse(value).success; -export type RequestGeneric = z.infer; +export const RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.loose().optional() +}); const NotificationsParamsSchema = z.object({ /** @@ -105,20 +118,9 @@ const NotificationsParamsSchema = z.object({ export const NotificationSchema = z.object({ method: z.string(), - params: NotificationsParamsSchema.optional() + params: NotificationsParamsSchema.loose().optional() }); -/** - * Generic notification schema that allows any additional fields to be added to the params. - * - * Used in {@link JSONRPCNotificationSchema} for generic shape matching. - */ -export const NotificationSchemaGeneric = NotificationSchema.extend({ - params: z.intersection(NotificationSchema.shape.params, z.record(z.string(), z.unknown()).optional()) -}); - -export type NotificationGeneric = z.infer; - export const ResultSchema = z.looseObject({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) @@ -139,7 +141,7 @@ export const JSONRPCRequestSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), id: RequestIdSchema, - ...RequestSchemaGeneric.shape + ...RequestSchema.shape }) .strict(); @@ -151,7 +153,7 @@ export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSO export const JSONRPCNotificationSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), - ...NotificationSchemaGeneric.shape + ...NotificationSchema.shape }) .strict(); @@ -160,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, @@ -168,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. @@ -192,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. @@ -213,9 +216,16 @@ export const JSONRPCErrorSchema = z }) .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 */ /** @@ -229,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. */ @@ -354,11 +364,11 @@ export const ClientTasksCapabilitySchema = z.looseObject({ /** * Present if the client supports listing tasks. */ - list: z.object({}).loose().optional(), + list: AssertObjectSchema.optional(), /** * Present if the client supports cancelling tasks. */ - cancel: z.object({}).loose().optional(), + cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ @@ -369,7 +379,7 @@ export const ClientTasksCapabilitySchema = z.looseObject({ */ sampling: z .looseObject({ - createMessage: z.object({}).loose().optional() + createMessage: AssertObjectSchema.optional() }) .optional(), /** @@ -377,7 +387,7 @@ export const ClientTasksCapabilitySchema = z.looseObject({ */ elicitation: z .looseObject({ - create: z.object({}).loose().optional() + create: AssertObjectSchema.optional() }) .optional() }) @@ -391,11 +401,11 @@ export const ServerTasksCapabilitySchema = z.looseObject({ /** * Present if the server supports listing tasks. */ - list: z.object({}).loose().optional(), + list: AssertObjectSchema.optional(), /** * Present if the server supports cancelling tasks. */ - cancel: z.object({}).loose().optional(), + cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ @@ -406,7 +416,7 @@ export const ServerTasksCapabilitySchema = z.looseObject({ */ tools: z .looseObject({ - call: z.object({}).loose().optional() + call: AssertObjectSchema.optional() }) .optional() }) @@ -558,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 => @@ -569,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 */ @@ -627,13 +639,18 @@ export const PaginatedResultSchema = ResultSchema.extend({ 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. @@ -699,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. */ @@ -937,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; @@ -1213,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 */ @@ -1398,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. */ @@ -1421,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() }); /** @@ -1650,7 +1678,7 @@ export const SamplingMessageSchema = z.object({ /** * 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. @@ -1889,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. * @@ -1914,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. */ @@ -2116,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() }); /** @@ -2130,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 */ @@ -2150,7 +2180,8 @@ export const ClientRequestSchema = z.union([ ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema + ListTasksRequestSchema, + CancelTaskRequestSchema ]); export const ClientNotificationSchema = z.union([ @@ -2180,7 +2211,8 @@ export const ServerRequestSchema = z.union([ ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema + ListTasksRequestSchema, + CancelTaskRequestSchema ]); export const ServerNotificationSchema = z.union([ @@ -2315,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; @@ -2322,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; @@ -2360,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; @@ -2372,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/experimental/tasks/stores/in-memory.test.ts b/test/experimental/tasks/stores/in-memory.test.ts index 532da8251..ceef6c6d8 100644 --- a/test/experimental/tasks/stores/in-memory.test.ts +++ b/test/experimental/tasks/stores/in-memory.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../../../src/experimental/tasks/stores/in-memory.js'; -import { TaskCreationParams, RequestGeneric } from '../../../../src/types.js'; +import { TaskCreationParams, Request } from '../../../../src/types.js'; import { QueuedMessage } from '../../../../src/experimental/tasks/interfaces.js'; describe('InMemoryTaskStore', () => { @@ -19,7 +19,7 @@ describe('InMemoryTaskStore', () => { const taskParams: TaskCreationParams = { ttl: 60000 }; - const request: RequestGeneric = { + const request: Request = { method: 'tools/call', params: { name: 'test-tool' } }; @@ -39,7 +39,7 @@ describe('InMemoryTaskStore', () => { it('should create task without ttl', async () => { const taskParams: TaskCreationParams = {}; - const request: RequestGeneric = { + const request: Request = { method: 'tools/call', params: {} }; @@ -52,7 +52,7 @@ describe('InMemoryTaskStore', () => { it('should generate unique taskIds', async () => { const taskParams: TaskCreationParams = {}; - const request: RequestGeneric = { + const request: Request = { method: 'tools/call', params: {} }; @@ -72,7 +72,7 @@ describe('InMemoryTaskStore', () => { it('should return task state', async () => { const taskParams: TaskCreationParams = {}; - const request: RequestGeneric = { + const request: Request = { method: 'tools/call', params: {} }; diff --git a/test/server/streamableHttp.test.ts b/test/server/streamableHttp.test.ts index be5908f60..9574d1fc0 100644 --- a/test/server/streamableHttp.test.ts +++ b/test/server/streamableHttp.test.ts @@ -2280,7 +2280,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 eec14ddb8..886dcbb21 100644 --- a/test/shared/protocol.test.ts +++ b/test/shared/protocol.test.ts @@ -10,30 +10,30 @@ import { ServerCapabilities, Task, TaskCreationParams, - type RequestGeneric, - type NotificationGeneric, + 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: RequestGeneric, authInfo: unknown) => TaskStore; + requestTaskStore: (request: Request, authInfo: unknown) => TaskStore; // Protected task methods (exposed for testing) listTasks: (params?: { cursor?: string }) => Promise<{ tasks: Task[]; nextCursor?: string }>; cancelTask: (params: { taskId: string }) => Promise; - requestStream: (request: RequestGeneric, schema: ZodType, options?: unknown) => AsyncGenerator>; + requestStream: (request: Request, schema: ZodType, options?: unknown) => AsyncGenerator>; } // Mock Transport class @@ -139,14 +139,14 @@ function assertQueuedRequest(o?: QueuedMessage): asserts o is QueuedRequest { } describe('protocol tests', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let sendSpy: MockInstance; beforeEach(() => { transport = new MockTransport(); sendSpy = vi.spyOn(transport, 'send'); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -620,7 +620,7 @@ describe('protocol tests', () => { it('should NOT debounce a notification that has parameters', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -643,7 +643,7 @@ describe('protocol tests', () => { it('should NOT debounce a notification that has a relatedRequestId', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -664,7 +664,7 @@ describe('protocol tests', () => { it('should clear pending debounced notifications on connection close', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -690,7 +690,7 @@ describe('protocol tests', () => { it('should debounce multiple synchronous calls when params property is omitted', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -719,7 +719,7 @@ describe('protocol tests', () => { it('should debounce calls when params is explicitly undefined', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -746,7 +746,7 @@ describe('protocol tests', () => { it('should send non-debounced notifications immediately and multiple times', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -781,7 +781,7 @@ describe('protocol tests', () => { it('should handle sequential batches of debounced notifications correctly', async () => { // ARRANGE - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -993,14 +993,14 @@ describe('mergeCapabilities', () => { }); describe('Task-based execution', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let sendSpy: MockInstance; beforeEach(() => { transport = new MockTransport(); sendSpy = vi.spyOn(transport, 'send'); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1247,7 +1247,7 @@ describe('Task-based execution', () => { // rather than in _meta, and that task management is handled by tool implementors const mockTaskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1316,7 +1316,7 @@ describe('Task-based execution', () => { } ); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1377,7 +1377,7 @@ describe('Task-based execution', () => { } ); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1423,7 +1423,7 @@ describe('Task-based execution', () => { onList: () => listedTasks.releaseLatch() }); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1456,7 +1456,7 @@ describe('Task-based execution', () => { const mockTaskStore = createMockTaskStore(); mockTaskStore.listTasks.mockRejectedValue(new Error('Invalid cursor: bad-cursor')); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1590,7 +1590,7 @@ describe('Task-based execution', () => { throw new Error('Task not found'); }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -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(); @@ -1632,7 +1632,7 @@ describe('Task-based execution', () => { mockTaskStore.getTask.mockResolvedValue(null); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -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(); @@ -1680,7 +1680,7 @@ describe('Task-based execution', () => { mockTaskStore.updateTaskStatus.mockClear(); mockTaskStore.getTask.mockResolvedValue(completedTask); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -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(); @@ -1762,7 +1762,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1812,7 +1812,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1861,7 +1861,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1898,7 +1898,7 @@ describe('Task-based execution', () => { params: {} }); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1943,7 +1943,7 @@ describe('Task-based execution', () => { await mockTaskStore.storeTaskResult(task.taskId, 'completed', testResult); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -1986,7 +1986,7 @@ describe('Task-based execution', () => { it('should propagate related-task metadata to handler sendRequest and sendNotification', async () => { const mockTaskStore = createMockTaskStore(); - const serverProtocol = new (class extends Protocol { + const serverProtocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2062,14 +2062,14 @@ describe('Task-based execution', () => { }); describe('Request Cancellation vs Task Cancellation', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let taskStore: TaskStore; beforeEach(() => { transport = new MockTransport(); taskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2355,14 +2355,14 @@ describe('Request Cancellation vs Task Cancellation', () => { }); describe('Progress notification support for tasks', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let sendSpy: MockInstance; beforeEach(() => { transport = new MockTransport(); sendSpy = vi.spyOn(transport, 'send'); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2373,7 +2373,7 @@ describe('Progress notification support for tasks', () => { it('should maintain progress token association after CreateTaskResult is returned', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2466,7 +2466,7 @@ describe('Progress notification support for tasks', () => { it('should stop progress notifications when task reaches terminal status (completed)', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2601,7 +2601,7 @@ describe('Progress notification support for tasks', () => { it('should stop progress notifications when task reaches terminal status (failed)', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2699,7 +2699,7 @@ describe('Progress notification support for tasks', () => { it('should stop progress notifications when task is cancelled', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -2794,7 +2794,7 @@ describe('Progress notification support for tasks', () => { it('should use the same progressToken throughout task lifetime', async () => { const taskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -3063,7 +3063,7 @@ describe('Message interception for task-related notifications', () => { it('should queue notifications with io.modelcontextprotocol/related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3100,7 +3100,7 @@ describe('Message interception for task-related notifications', () => { it('should not queue notifications without related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3127,7 +3127,7 @@ describe('Message interception for task-related notifications', () => { it('should propagate queue overflow errors without failing the task', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3174,7 +3174,7 @@ describe('Message interception for task-related notifications', () => { it('should extract task ID correctly from metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3207,7 +3207,7 @@ describe('Message interception for task-related notifications', () => { it('should preserve message order when queuing multiple notifications', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3249,7 +3249,7 @@ describe('Message interception for task-related requests', () => { it('should queue requests with io.modelcontextprotocol/related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3301,7 +3301,7 @@ describe('Message interception for task-related requests', () => { it('should not queue requests without related-task metadata', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3340,7 +3340,7 @@ describe('Message interception for task-related requests', () => { it('should store request resolver for response routing', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3393,7 +3393,7 @@ describe('Message interception for task-related requests', () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); const queue = new InMemoryTaskMessageQueue(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3458,7 +3458,7 @@ describe('Message interception for task-related requests', () => { it('should log error when resolver is missing for side-channeled request', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3534,7 +3534,7 @@ describe('Message interception for task-related requests', () => { it('should propagate queue overflow errors for requests without failing the task', async () => { const taskStore = createMockTaskStore(); const transport = new MockTransport(); - const server = new (class extends Protocol { + const server = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -3588,14 +3588,14 @@ describe('Message interception for task-related requests', () => { }); describe('Message Interception', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let mockTaskStore: TaskStore & { [K in keyof TaskStore]: MockInstance }; beforeEach(() => { transport = new MockTransport(); mockTaskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -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, @@ -4129,14 +4129,14 @@ describe('Message Interception', () => { }); describe('Queue lifecycle management', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let mockTaskStore: TaskStore & { [K in keyof TaskStore]: MockInstance }; beforeEach(() => { transport = new MockTransport(); mockTaskStore = createMockTaskStore(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4450,7 +4450,7 @@ describe('requestStream() method', () => { test('should yield result immediately for non-task requests', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4493,7 +4493,7 @@ describe('requestStream() method', () => { test('should yield error message on request failure', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4539,7 +4539,7 @@ describe('requestStream() method', () => { test('should handle cancellation via AbortSignal', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4577,7 +4577,7 @@ describe('requestStream() method', () => { describe('Error responses', () => { test('should yield error as terminal message for server error response', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4619,7 +4619,7 @@ describe('requestStream() method', () => { vi.useFakeTimers(); try { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4657,7 +4657,7 @@ describe('requestStream() method', () => { test('should yield error as terminal message for cancellation', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4690,7 +4690,7 @@ describe('requestStream() method', () => { test('should not yield any messages after error message', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4742,7 +4742,7 @@ describe('requestStream() method', () => { test('should yield error as terminal message for task failure', async () => { const transport = new MockTransport(); const mockTaskStore = createMockTaskStore(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4802,7 +4802,7 @@ describe('requestStream() method', () => { test('should yield error as terminal message for network error', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4830,7 +4830,7 @@ describe('requestStream() method', () => { test('should ensure error is always the final message', async () => { const transport = new MockTransport(); - const protocol = new (class extends Protocol { + const protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} protected assertRequestHandlerCapability(): void {} @@ -4875,7 +4875,7 @@ describe('requestStream() method', () => { }); describe('Error handling for missing resolvers', () => { - let protocol: Protocol; + let protocol: Protocol; let transport: MockTransport; let taskStore: TaskStore & { [K in keyof TaskStore]: MockInstance }; let taskMessageQueue: TaskMessageQueue; @@ -4886,7 +4886,7 @@ describe('Error handling for missing resolvers', () => { taskMessageQueue = new InMemoryTaskMessageQueue(); errorHandler = vi.fn(); - protocol = new (class extends Protocol { + protocol = new (class extends Protocol { protected assertCapabilityForMethod(_method: string): void {} protected assertNotificationCapability(_method: string): void {} protected assertRequestHandlerCapability(_method: string): void {} @@ -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 ed8cf3187..8d463674b 100644 --- a/test/spec.types.test.ts +++ b/test/spec.types.test.ts @@ -521,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; }, @@ -614,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; } }; @@ -639,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', () => { @@ -657,6 +729,7 @@ describe('Spec Types', () => { } } + console.log(missingTests); expect(missingTests).toHaveLength(0); }); From bbbf2cf04018c548e76584cf3bf1f0b701ff5cdd Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Mon, 8 Dec 2025 20:21:08 +0200 Subject: [PATCH 4/4] GetTaskPayloadResult in examples --- src/examples/server/simpleTaskInteractive.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 ?? '');