protocol.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Protocol = exports.DEFAULT_REQUEST_TIMEOUT_MSEC = void 0;
  4. exports.mergeCapabilities = mergeCapabilities;
  5. const zod_compat_js_1 = require("../server/zod-compat.js");
  6. const types_js_1 = require("../types.js");
  7. const interfaces_js_1 = require("../experimental/tasks/interfaces.js");
  8. const zod_json_schema_compat_js_1 = require("../server/zod-json-schema-compat.js");
  9. /**
  10. * The default request timeout, in miliseconds.
  11. */
  12. exports.DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;
  13. /**
  14. * Implements MCP protocol framing on top of a pluggable transport, including
  15. * features like request/response linking, notifications, and progress.
  16. */
  17. class Protocol {
  18. constructor(_options) {
  19. this._options = _options;
  20. this._requestMessageId = 0;
  21. this._requestHandlers = new Map();
  22. this._requestHandlerAbortControllers = new Map();
  23. this._notificationHandlers = new Map();
  24. this._responseHandlers = new Map();
  25. this._progressHandlers = new Map();
  26. this._timeoutInfo = new Map();
  27. this._pendingDebouncedNotifications = new Set();
  28. // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult
  29. this._taskProgressTokens = new Map();
  30. this._requestResolvers = new Map();
  31. this.setNotificationHandler(types_js_1.CancelledNotificationSchema, notification => {
  32. this._oncancel(notification);
  33. });
  34. this.setNotificationHandler(types_js_1.ProgressNotificationSchema, notification => {
  35. this._onprogress(notification);
  36. });
  37. this.setRequestHandler(types_js_1.PingRequestSchema,
  38. // Automatic pong by default.
  39. _request => ({}));
  40. // Install task handlers if TaskStore is provided
  41. this._taskStore = _options?.taskStore;
  42. this._taskMessageQueue = _options?.taskMessageQueue;
  43. if (this._taskStore) {
  44. this.setRequestHandler(types_js_1.GetTaskRequestSchema, async (request, extra) => {
  45. const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
  46. if (!task) {
  47. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');
  48. }
  49. // Per spec: tasks/get responses SHALL NOT include related-task metadata
  50. // as the taskId parameter is the source of truth
  51. // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else
  52. return {
  53. ...task
  54. };
  55. });
  56. this.setRequestHandler(types_js_1.GetTaskPayloadRequestSchema, async (request, extra) => {
  57. const handleTaskResult = async () => {
  58. const taskId = request.params.taskId;
  59. // Deliver queued messages
  60. if (this._taskMessageQueue) {
  61. let queuedMessage;
  62. while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {
  63. // Handle response and error messages by routing them to the appropriate resolver
  64. if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {
  65. const message = queuedMessage.message;
  66. const requestId = message.id;
  67. // Lookup resolver in _requestResolvers map
  68. const resolver = this._requestResolvers.get(requestId);
  69. if (resolver) {
  70. // Remove resolver from map after invocation
  71. this._requestResolvers.delete(requestId);
  72. // Invoke resolver with response or error
  73. if (queuedMessage.type === 'response') {
  74. resolver(message);
  75. }
  76. else {
  77. // Convert JSONRPCError to McpError
  78. const errorMessage = message;
  79. const error = new types_js_1.McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
  80. resolver(error);
  81. }
  82. }
  83. else {
  84. // Handle missing resolver gracefully with error logging
  85. const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';
  86. this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
  87. }
  88. // Continue to next message
  89. continue;
  90. }
  91. // Send the message on the response stream by passing the relatedRequestId
  92. // This tells the transport to write the message to the tasks/result response stream
  93. await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
  94. }
  95. }
  96. // Now check task status
  97. const task = await this._taskStore.getTask(taskId, extra.sessionId);
  98. if (!task) {
  99. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task not found: ${taskId}`);
  100. }
  101. // Block if task is not terminal (we've already delivered all queued messages above)
  102. if (!(0, interfaces_js_1.isTerminal)(task.status)) {
  103. // Wait for status change or new messages
  104. await this._waitForTaskUpdate(taskId, extra.signal);
  105. // After waking up, recursively call to deliver any new messages or result
  106. return await handleTaskResult();
  107. }
  108. // If task is terminal, return the result
  109. if ((0, interfaces_js_1.isTerminal)(task.status)) {
  110. const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
  111. this._clearTaskQueue(taskId);
  112. return {
  113. ...result,
  114. _meta: {
  115. ...result._meta,
  116. [types_js_1.RELATED_TASK_META_KEY]: {
  117. taskId: taskId
  118. }
  119. }
  120. };
  121. }
  122. return await handleTaskResult();
  123. };
  124. return await handleTaskResult();
  125. });
  126. this.setRequestHandler(types_js_1.ListTasksRequestSchema, async (request, extra) => {
  127. try {
  128. const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
  129. // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else
  130. return {
  131. tasks,
  132. nextCursor,
  133. _meta: {}
  134. };
  135. }
  136. catch (error) {
  137. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
  138. }
  139. });
  140. this.setRequestHandler(types_js_1.CancelTaskRequestSchema, async (request, extra) => {
  141. try {
  142. // Get the current task to check if it's in a terminal state, in case the implementation is not atomic
  143. const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
  144. if (!task) {
  145. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
  146. }
  147. // Reject cancellation of terminal tasks
  148. if ((0, interfaces_js_1.isTerminal)(task.status)) {
  149. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
  150. }
  151. await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);
  152. this._clearTaskQueue(request.params.taskId);
  153. const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
  154. if (!cancelledTask) {
  155. // Task was deleted during cancellation (e.g., cleanup happened)
  156. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
  157. }
  158. return {
  159. _meta: {},
  160. ...cancelledTask
  161. };
  162. }
  163. catch (error) {
  164. // Re-throw McpError as-is
  165. if (error instanceof types_js_1.McpError) {
  166. throw error;
  167. }
  168. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
  169. }
  170. });
  171. }
  172. }
  173. async _oncancel(notification) {
  174. if (!notification.params.requestId) {
  175. return;
  176. }
  177. // Handle request cancellation
  178. const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
  179. controller?.abort(notification.params.reason);
  180. }
  181. _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
  182. this._timeoutInfo.set(messageId, {
  183. timeoutId: setTimeout(onTimeout, timeout),
  184. startTime: Date.now(),
  185. timeout,
  186. maxTotalTimeout,
  187. resetTimeoutOnProgress,
  188. onTimeout
  189. });
  190. }
  191. _resetTimeout(messageId) {
  192. const info = this._timeoutInfo.get(messageId);
  193. if (!info)
  194. return false;
  195. const totalElapsed = Date.now() - info.startTime;
  196. if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
  197. this._timeoutInfo.delete(messageId);
  198. throw types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {
  199. maxTotalTimeout: info.maxTotalTimeout,
  200. totalElapsed
  201. });
  202. }
  203. clearTimeout(info.timeoutId);
  204. info.timeoutId = setTimeout(info.onTimeout, info.timeout);
  205. return true;
  206. }
  207. _cleanupTimeout(messageId) {
  208. const info = this._timeoutInfo.get(messageId);
  209. if (info) {
  210. clearTimeout(info.timeoutId);
  211. this._timeoutInfo.delete(messageId);
  212. }
  213. }
  214. /**
  215. * Attaches to the given transport, starts it, and starts listening for messages.
  216. *
  217. * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
  218. */
  219. async connect(transport) {
  220. if (this._transport) {
  221. throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');
  222. }
  223. this._transport = transport;
  224. const _onclose = this.transport?.onclose;
  225. this._transport.onclose = () => {
  226. _onclose?.();
  227. this._onclose();
  228. };
  229. const _onerror = this.transport?.onerror;
  230. this._transport.onerror = (error) => {
  231. _onerror?.(error);
  232. this._onerror(error);
  233. };
  234. const _onmessage = this._transport?.onmessage;
  235. this._transport.onmessage = (message, extra) => {
  236. _onmessage?.(message, extra);
  237. if ((0, types_js_1.isJSONRPCResultResponse)(message) || (0, types_js_1.isJSONRPCErrorResponse)(message)) {
  238. this._onresponse(message);
  239. }
  240. else if ((0, types_js_1.isJSONRPCRequest)(message)) {
  241. this._onrequest(message, extra);
  242. }
  243. else if ((0, types_js_1.isJSONRPCNotification)(message)) {
  244. this._onnotification(message);
  245. }
  246. else {
  247. this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
  248. }
  249. };
  250. await this._transport.start();
  251. }
  252. _onclose() {
  253. const responseHandlers = this._responseHandlers;
  254. this._responseHandlers = new Map();
  255. this._progressHandlers.clear();
  256. this._taskProgressTokens.clear();
  257. this._pendingDebouncedNotifications.clear();
  258. for (const info of this._timeoutInfo.values()) {
  259. clearTimeout(info.timeoutId);
  260. }
  261. this._timeoutInfo.clear();
  262. // Abort all in-flight request handlers so they stop sending messages
  263. for (const controller of this._requestHandlerAbortControllers.values()) {
  264. controller.abort();
  265. }
  266. this._requestHandlerAbortControllers.clear();
  267. const error = types_js_1.McpError.fromError(types_js_1.ErrorCode.ConnectionClosed, 'Connection closed');
  268. this._transport = undefined;
  269. this.onclose?.();
  270. for (const handler of responseHandlers.values()) {
  271. handler(error);
  272. }
  273. }
  274. _onerror(error) {
  275. this.onerror?.(error);
  276. }
  277. _onnotification(notification) {
  278. const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
  279. // Ignore notifications not being subscribed to.
  280. if (handler === undefined) {
  281. return;
  282. }
  283. // Starting with Promise.resolve() puts any synchronous errors into the monad as well.
  284. Promise.resolve()
  285. .then(() => handler(notification))
  286. .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
  287. }
  288. _onrequest(request, extra) {
  289. const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
  290. // Capture the current transport at request time to ensure responses go to the correct client
  291. const capturedTransport = this._transport;
  292. // Extract taskId from request metadata if present (needed early for method not found case)
  293. const relatedTaskId = request.params?._meta?.[types_js_1.RELATED_TASK_META_KEY]?.taskId;
  294. if (handler === undefined) {
  295. const errorResponse = {
  296. jsonrpc: '2.0',
  297. id: request.id,
  298. error: {
  299. code: types_js_1.ErrorCode.MethodNotFound,
  300. message: 'Method not found'
  301. }
  302. };
  303. // Queue or send the error response based on whether this is a task-related request
  304. if (relatedTaskId && this._taskMessageQueue) {
  305. this._enqueueTaskMessage(relatedTaskId, {
  306. type: 'error',
  307. message: errorResponse,
  308. timestamp: Date.now()
  309. }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
  310. }
  311. else {
  312. capturedTransport
  313. ?.send(errorResponse)
  314. .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));
  315. }
  316. return;
  317. }
  318. const abortController = new AbortController();
  319. this._requestHandlerAbortControllers.set(request.id, abortController);
  320. const taskCreationParams = (0, types_js_1.isTaskAugmentedRequestParams)(request.params) ? request.params.task : undefined;
  321. const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;
  322. const fullExtra = {
  323. signal: abortController.signal,
  324. sessionId: capturedTransport?.sessionId,
  325. _meta: request.params?._meta,
  326. sendNotification: async (notification) => {
  327. if (abortController.signal.aborted)
  328. return;
  329. // Include related-task metadata if this request is part of a task
  330. const notificationOptions = { relatedRequestId: request.id };
  331. if (relatedTaskId) {
  332. notificationOptions.relatedTask = { taskId: relatedTaskId };
  333. }
  334. await this.notification(notification, notificationOptions);
  335. },
  336. sendRequest: async (r, resultSchema, options) => {
  337. if (abortController.signal.aborted) {
  338. throw new types_js_1.McpError(types_js_1.ErrorCode.ConnectionClosed, 'Request was cancelled');
  339. }
  340. // Include related-task metadata if this request is part of a task
  341. const requestOptions = { ...options, relatedRequestId: request.id };
  342. if (relatedTaskId && !requestOptions.relatedTask) {
  343. requestOptions.relatedTask = { taskId: relatedTaskId };
  344. }
  345. // Set task status to input_required when sending a request within a task context
  346. // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)
  347. const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
  348. if (effectiveTaskId && taskStore) {
  349. await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');
  350. }
  351. return await this.request(r, resultSchema, requestOptions);
  352. },
  353. authInfo: extra?.authInfo,
  354. requestId: request.id,
  355. requestInfo: extra?.requestInfo,
  356. taskId: relatedTaskId,
  357. taskStore: taskStore,
  358. taskRequestedTtl: taskCreationParams?.ttl,
  359. closeSSEStream: extra?.closeSSEStream,
  360. closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
  361. };
  362. // Starting with Promise.resolve() puts any synchronous errors into the monad as well.
  363. Promise.resolve()
  364. .then(() => {
  365. // If this request asked for task creation, check capability first
  366. if (taskCreationParams) {
  367. // Check if the request method supports task creation
  368. this.assertTaskHandlerCapability(request.method);
  369. }
  370. })
  371. .then(() => handler(request, fullExtra))
  372. .then(async (result) => {
  373. if (abortController.signal.aborted) {
  374. // Request was cancelled
  375. return;
  376. }
  377. const response = {
  378. result,
  379. jsonrpc: '2.0',
  380. id: request.id
  381. };
  382. // Queue or send the response based on whether this is a task-related request
  383. if (relatedTaskId && this._taskMessageQueue) {
  384. await this._enqueueTaskMessage(relatedTaskId, {
  385. type: 'response',
  386. message: response,
  387. timestamp: Date.now()
  388. }, capturedTransport?.sessionId);
  389. }
  390. else {
  391. await capturedTransport?.send(response);
  392. }
  393. }, async (error) => {
  394. if (abortController.signal.aborted) {
  395. // Request was cancelled
  396. return;
  397. }
  398. const errorResponse = {
  399. jsonrpc: '2.0',
  400. id: request.id,
  401. error: {
  402. code: Number.isSafeInteger(error['code']) ? error['code'] : types_js_1.ErrorCode.InternalError,
  403. message: error.message ?? 'Internal error',
  404. ...(error['data'] !== undefined && { data: error['data'] })
  405. }
  406. };
  407. // Queue or send the error response based on whether this is a task-related request
  408. if (relatedTaskId && this._taskMessageQueue) {
  409. await this._enqueueTaskMessage(relatedTaskId, {
  410. type: 'error',
  411. message: errorResponse,
  412. timestamp: Date.now()
  413. }, capturedTransport?.sessionId);
  414. }
  415. else {
  416. await capturedTransport?.send(errorResponse);
  417. }
  418. })
  419. .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))
  420. .finally(() => {
  421. // Only delete if the stored controller is still ours; after close()+connect(),
  422. // a new connection may have reused the same request ID with a different controller.
  423. if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
  424. this._requestHandlerAbortControllers.delete(request.id);
  425. }
  426. });
  427. }
  428. _onprogress(notification) {
  429. const { progressToken, ...params } = notification.params;
  430. const messageId = Number(progressToken);
  431. const handler = this._progressHandlers.get(messageId);
  432. if (!handler) {
  433. this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
  434. return;
  435. }
  436. const responseHandler = this._responseHandlers.get(messageId);
  437. const timeoutInfo = this._timeoutInfo.get(messageId);
  438. if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
  439. try {
  440. this._resetTimeout(messageId);
  441. }
  442. catch (error) {
  443. // Clean up if maxTotalTimeout was exceeded
  444. this._responseHandlers.delete(messageId);
  445. this._progressHandlers.delete(messageId);
  446. this._cleanupTimeout(messageId);
  447. responseHandler(error);
  448. return;
  449. }
  450. }
  451. handler(params);
  452. }
  453. _onresponse(response) {
  454. const messageId = Number(response.id);
  455. // Check if this is a response to a queued request
  456. const resolver = this._requestResolvers.get(messageId);
  457. if (resolver) {
  458. this._requestResolvers.delete(messageId);
  459. if ((0, types_js_1.isJSONRPCResultResponse)(response)) {
  460. resolver(response);
  461. }
  462. else {
  463. const error = new types_js_1.McpError(response.error.code, response.error.message, response.error.data);
  464. resolver(error);
  465. }
  466. return;
  467. }
  468. const handler = this._responseHandlers.get(messageId);
  469. if (handler === undefined) {
  470. this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
  471. return;
  472. }
  473. this._responseHandlers.delete(messageId);
  474. this._cleanupTimeout(messageId);
  475. // Keep progress handler alive for CreateTaskResult responses
  476. let isTaskResponse = false;
  477. if ((0, types_js_1.isJSONRPCResultResponse)(response) && response.result && typeof response.result === 'object') {
  478. const result = response.result;
  479. if (result.task && typeof result.task === 'object') {
  480. const task = result.task;
  481. if (typeof task.taskId === 'string') {
  482. isTaskResponse = true;
  483. this._taskProgressTokens.set(task.taskId, messageId);
  484. }
  485. }
  486. }
  487. if (!isTaskResponse) {
  488. this._progressHandlers.delete(messageId);
  489. }
  490. if ((0, types_js_1.isJSONRPCResultResponse)(response)) {
  491. handler(response);
  492. }
  493. else {
  494. const error = types_js_1.McpError.fromError(response.error.code, response.error.message, response.error.data);
  495. handler(error);
  496. }
  497. }
  498. get transport() {
  499. return this._transport;
  500. }
  501. /**
  502. * Closes the connection.
  503. */
  504. async close() {
  505. await this._transport?.close();
  506. }
  507. /**
  508. * Sends a request and returns an AsyncGenerator that yields response messages.
  509. * The generator is guaranteed to end with either a 'result' or 'error' message.
  510. *
  511. * @example
  512. * ```typescript
  513. * const stream = protocol.requestStream(request, resultSchema, options);
  514. * for await (const message of stream) {
  515. * switch (message.type) {
  516. * case 'taskCreated':
  517. * console.log('Task created:', message.task.taskId);
  518. * break;
  519. * case 'taskStatus':
  520. * console.log('Task status:', message.task.status);
  521. * break;
  522. * case 'result':
  523. * console.log('Final result:', message.result);
  524. * break;
  525. * case 'error':
  526. * console.error('Error:', message.error);
  527. * break;
  528. * }
  529. * }
  530. * ```
  531. *
  532. * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
  533. */
  534. async *requestStream(request, resultSchema, options) {
  535. const { task } = options ?? {};
  536. // For non-task requests, just yield the result
  537. if (!task) {
  538. try {
  539. const result = await this.request(request, resultSchema, options);
  540. yield { type: 'result', result };
  541. }
  542. catch (error) {
  543. yield {
  544. type: 'error',
  545. error: error instanceof types_js_1.McpError ? error : new types_js_1.McpError(types_js_1.ErrorCode.InternalError, String(error))
  546. };
  547. }
  548. return;
  549. }
  550. // For task-augmented requests, we need to poll for status
  551. // First, make the request to create the task
  552. let taskId;
  553. try {
  554. // Send the request and get the CreateTaskResult
  555. const createResult = await this.request(request, types_js_1.CreateTaskResultSchema, options);
  556. // Extract taskId from the result
  557. if (createResult.task) {
  558. taskId = createResult.task.taskId;
  559. yield { type: 'taskCreated', task: createResult.task };
  560. }
  561. else {
  562. throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, 'Task creation did not return a task');
  563. }
  564. // Poll for task completion
  565. while (true) {
  566. // Get current task status
  567. const task = await this.getTask({ taskId }, options);
  568. yield { type: 'taskStatus', task };
  569. // Check if task is terminal
  570. if ((0, interfaces_js_1.isTerminal)(task.status)) {
  571. if (task.status === 'completed') {
  572. // Get the final result
  573. const result = await this.getTaskResult({ taskId }, resultSchema, options);
  574. yield { type: 'result', result };
  575. }
  576. else if (task.status === 'failed') {
  577. yield {
  578. type: 'error',
  579. error: new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Task ${taskId} failed`)
  580. };
  581. }
  582. else if (task.status === 'cancelled') {
  583. yield {
  584. type: 'error',
  585. error: new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Task ${taskId} was cancelled`)
  586. };
  587. }
  588. return;
  589. }
  590. // When input_required, call tasks/result to deliver queued messages
  591. // (elicitation, sampling) via SSE and block until terminal
  592. if (task.status === 'input_required') {
  593. const result = await this.getTaskResult({ taskId }, resultSchema, options);
  594. yield { type: 'result', result };
  595. return;
  596. }
  597. // Wait before polling again
  598. const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;
  599. await new Promise(resolve => setTimeout(resolve, pollInterval));
  600. // Check if cancelled
  601. options?.signal?.throwIfAborted();
  602. }
  603. }
  604. catch (error) {
  605. yield {
  606. type: 'error',
  607. error: error instanceof types_js_1.McpError ? error : new types_js_1.McpError(types_js_1.ErrorCode.InternalError, String(error))
  608. };
  609. }
  610. }
  611. /**
  612. * Sends a request and waits for a response.
  613. *
  614. * Do not use this method to emit notifications! Use notification() instead.
  615. */
  616. request(request, resultSchema, options) {
  617. const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
  618. // Send the request
  619. return new Promise((resolve, reject) => {
  620. const earlyReject = (error) => {
  621. reject(error);
  622. };
  623. if (!this._transport) {
  624. earlyReject(new Error('Not connected'));
  625. return;
  626. }
  627. if (this._options?.enforceStrictCapabilities === true) {
  628. try {
  629. this.assertCapabilityForMethod(request.method);
  630. // If task creation is requested, also check task capabilities
  631. if (task) {
  632. this.assertTaskCapability(request.method);
  633. }
  634. }
  635. catch (e) {
  636. earlyReject(e);
  637. return;
  638. }
  639. }
  640. options?.signal?.throwIfAborted();
  641. const messageId = this._requestMessageId++;
  642. const jsonrpcRequest = {
  643. ...request,
  644. jsonrpc: '2.0',
  645. id: messageId
  646. };
  647. if (options?.onprogress) {
  648. this._progressHandlers.set(messageId, options.onprogress);
  649. jsonrpcRequest.params = {
  650. ...request.params,
  651. _meta: {
  652. ...(request.params?._meta || {}),
  653. progressToken: messageId
  654. }
  655. };
  656. }
  657. // Augment with task creation parameters if provided
  658. if (task) {
  659. jsonrpcRequest.params = {
  660. ...jsonrpcRequest.params,
  661. task: task
  662. };
  663. }
  664. // Augment with related task metadata if relatedTask is provided
  665. if (relatedTask) {
  666. jsonrpcRequest.params = {
  667. ...jsonrpcRequest.params,
  668. _meta: {
  669. ...(jsonrpcRequest.params?._meta || {}),
  670. [types_js_1.RELATED_TASK_META_KEY]: relatedTask
  671. }
  672. };
  673. }
  674. const cancel = (reason) => {
  675. this._responseHandlers.delete(messageId);
  676. this._progressHandlers.delete(messageId);
  677. this._cleanupTimeout(messageId);
  678. this._transport
  679. ?.send({
  680. jsonrpc: '2.0',
  681. method: 'notifications/cancelled',
  682. params: {
  683. requestId: messageId,
  684. reason: String(reason)
  685. }
  686. }, { relatedRequestId, resumptionToken, onresumptiontoken })
  687. .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
  688. // Wrap the reason in an McpError if it isn't already
  689. const error = reason instanceof types_js_1.McpError ? reason : new types_js_1.McpError(types_js_1.ErrorCode.RequestTimeout, String(reason));
  690. reject(error);
  691. };
  692. this._responseHandlers.set(messageId, response => {
  693. if (options?.signal?.aborted) {
  694. return;
  695. }
  696. if (response instanceof Error) {
  697. return reject(response);
  698. }
  699. try {
  700. const parseResult = (0, zod_compat_js_1.safeParse)(resultSchema, response.result);
  701. if (!parseResult.success) {
  702. // Type guard: if success is false, error is guaranteed to exist
  703. reject(parseResult.error);
  704. }
  705. else {
  706. resolve(parseResult.data);
  707. }
  708. }
  709. catch (error) {
  710. reject(error);
  711. }
  712. });
  713. options?.signal?.addEventListener('abort', () => {
  714. cancel(options?.signal?.reason);
  715. });
  716. const timeout = options?.timeout ?? exports.DEFAULT_REQUEST_TIMEOUT_MSEC;
  717. const timeoutHandler = () => cancel(types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Request timed out', { timeout }));
  718. this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
  719. // Queue request if related to a task
  720. const relatedTaskId = relatedTask?.taskId;
  721. if (relatedTaskId) {
  722. // Store the response resolver for this request so responses can be routed back
  723. const responseResolver = (response) => {
  724. const handler = this._responseHandlers.get(messageId);
  725. if (handler) {
  726. handler(response);
  727. }
  728. else {
  729. // Log error when resolver is missing, but don't fail
  730. this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
  731. }
  732. };
  733. this._requestResolvers.set(messageId, responseResolver);
  734. this._enqueueTaskMessage(relatedTaskId, {
  735. type: 'request',
  736. message: jsonrpcRequest,
  737. timestamp: Date.now()
  738. }).catch(error => {
  739. this._cleanupTimeout(messageId);
  740. reject(error);
  741. });
  742. // Don't send through transport - queued messages are delivered via tasks/result only
  743. // This prevents duplicate delivery for bidirectional transports
  744. }
  745. else {
  746. // No related task - send through transport normally
  747. this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {
  748. this._cleanupTimeout(messageId);
  749. reject(error);
  750. });
  751. }
  752. });
  753. }
  754. /**
  755. * Gets the current status of a task.
  756. *
  757. * @experimental Use `client.experimental.tasks.getTask()` to access this method.
  758. */
  759. async getTask(params, options) {
  760. // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways
  761. return this.request({ method: 'tasks/get', params }, types_js_1.GetTaskResultSchema, options);
  762. }
  763. /**
  764. * Retrieves the result of a completed task.
  765. *
  766. * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
  767. */
  768. async getTaskResult(params, resultSchema, options) {
  769. // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways
  770. return this.request({ method: 'tasks/result', params }, resultSchema, options);
  771. }
  772. /**
  773. * Lists tasks, optionally starting from a pagination cursor.
  774. *
  775. * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
  776. */
  777. async listTasks(params, options) {
  778. // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways
  779. return this.request({ method: 'tasks/list', params }, types_js_1.ListTasksResultSchema, options);
  780. }
  781. /**
  782. * Cancels a specific task.
  783. *
  784. * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
  785. */
  786. async cancelTask(params, options) {
  787. // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways
  788. return this.request({ method: 'tasks/cancel', params }, types_js_1.CancelTaskResultSchema, options);
  789. }
  790. /**
  791. * Emits a notification, which is a one-way message that does not expect a response.
  792. */
  793. async notification(notification, options) {
  794. if (!this._transport) {
  795. throw new Error('Not connected');
  796. }
  797. this.assertNotificationCapability(notification.method);
  798. // Queue notification if related to a task
  799. const relatedTaskId = options?.relatedTask?.taskId;
  800. if (relatedTaskId) {
  801. // Build the JSONRPC notification with metadata
  802. const jsonrpcNotification = {
  803. ...notification,
  804. jsonrpc: '2.0',
  805. params: {
  806. ...notification.params,
  807. _meta: {
  808. ...(notification.params?._meta || {}),
  809. [types_js_1.RELATED_TASK_META_KEY]: options.relatedTask
  810. }
  811. }
  812. };
  813. await this._enqueueTaskMessage(relatedTaskId, {
  814. type: 'notification',
  815. message: jsonrpcNotification,
  816. timestamp: Date.now()
  817. });
  818. // Don't send through transport - queued messages are delivered via tasks/result only
  819. // This prevents duplicate delivery for bidirectional transports
  820. return;
  821. }
  822. const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
  823. // A notification can only be debounced if it's in the list AND it's "simple"
  824. // (i.e., has no parameters and no related request ID or related task that could be lost).
  825. const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
  826. if (canDebounce) {
  827. // If a notification of this type is already scheduled, do nothing.
  828. if (this._pendingDebouncedNotifications.has(notification.method)) {
  829. return;
  830. }
  831. // Mark this notification type as pending.
  832. this._pendingDebouncedNotifications.add(notification.method);
  833. // Schedule the actual send to happen in the next microtask.
  834. // This allows all synchronous calls in the current event loop tick to be coalesced.
  835. Promise.resolve().then(() => {
  836. // Un-mark the notification so the next one can be scheduled.
  837. this._pendingDebouncedNotifications.delete(notification.method);
  838. // SAFETY CHECK: If the connection was closed while this was pending, abort.
  839. if (!this._transport) {
  840. return;
  841. }
  842. let jsonrpcNotification = {
  843. ...notification,
  844. jsonrpc: '2.0'
  845. };
  846. // Augment with related task metadata if relatedTask is provided
  847. if (options?.relatedTask) {
  848. jsonrpcNotification = {
  849. ...jsonrpcNotification,
  850. params: {
  851. ...jsonrpcNotification.params,
  852. _meta: {
  853. ...(jsonrpcNotification.params?._meta || {}),
  854. [types_js_1.RELATED_TASK_META_KEY]: options.relatedTask
  855. }
  856. }
  857. };
  858. }
  859. // Send the notification, but don't await it here to avoid blocking.
  860. // Handle potential errors with a .catch().
  861. this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));
  862. });
  863. // Return immediately.
  864. return;
  865. }
  866. let jsonrpcNotification = {
  867. ...notification,
  868. jsonrpc: '2.0'
  869. };
  870. // Augment with related task metadata if relatedTask is provided
  871. if (options?.relatedTask) {
  872. jsonrpcNotification = {
  873. ...jsonrpcNotification,
  874. params: {
  875. ...jsonrpcNotification.params,
  876. _meta: {
  877. ...(jsonrpcNotification.params?._meta || {}),
  878. [types_js_1.RELATED_TASK_META_KEY]: options.relatedTask
  879. }
  880. }
  881. };
  882. }
  883. await this._transport.send(jsonrpcNotification, options);
  884. }
  885. /**
  886. * Registers a handler to invoke when this protocol object receives a request with the given method.
  887. *
  888. * Note that this will replace any previous request handler for the same method.
  889. */
  890. setRequestHandler(requestSchema, handler) {
  891. const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(requestSchema);
  892. this.assertRequestHandlerCapability(method);
  893. this._requestHandlers.set(method, (request, extra) => {
  894. const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(requestSchema, request);
  895. return Promise.resolve(handler(parsed, extra));
  896. });
  897. }
  898. /**
  899. * Removes the request handler for the given method.
  900. */
  901. removeRequestHandler(method) {
  902. this._requestHandlers.delete(method);
  903. }
  904. /**
  905. * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
  906. */
  907. assertCanSetRequestHandler(method) {
  908. if (this._requestHandlers.has(method)) {
  909. throw new Error(`A request handler for ${method} already exists, which would be overridden`);
  910. }
  911. }
  912. /**
  913. * Registers a handler to invoke when this protocol object receives a notification with the given method.
  914. *
  915. * Note that this will replace any previous notification handler for the same method.
  916. */
  917. setNotificationHandler(notificationSchema, handler) {
  918. const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(notificationSchema);
  919. this._notificationHandlers.set(method, notification => {
  920. const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(notificationSchema, notification);
  921. return Promise.resolve(handler(parsed));
  922. });
  923. }
  924. /**
  925. * Removes the notification handler for the given method.
  926. */
  927. removeNotificationHandler(method) {
  928. this._notificationHandlers.delete(method);
  929. }
  930. /**
  931. * Cleans up the progress handler associated with a task.
  932. * This should be called when a task reaches a terminal status.
  933. */
  934. _cleanupTaskProgressHandler(taskId) {
  935. const progressToken = this._taskProgressTokens.get(taskId);
  936. if (progressToken !== undefined) {
  937. this._progressHandlers.delete(progressToken);
  938. this._taskProgressTokens.delete(taskId);
  939. }
  940. }
  941. /**
  942. * Enqueues a task-related message for side-channel delivery via tasks/result.
  943. * @param taskId The task ID to associate the message with
  944. * @param message The message to enqueue
  945. * @param sessionId Optional session ID for binding the operation to a specific session
  946. * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
  947. *
  948. * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
  949. * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
  950. * simply propagates the error.
  951. */
  952. async _enqueueTaskMessage(taskId, message, sessionId) {
  953. // Task message queues are only used when taskStore is configured
  954. if (!this._taskStore || !this._taskMessageQueue) {
  955. throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');
  956. }
  957. const maxQueueSize = this._options?.maxTaskQueueSize;
  958. await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
  959. }
  960. /**
  961. * Clears the message queue for a task and rejects any pending request resolvers.
  962. * @param taskId The task ID whose queue should be cleared
  963. * @param sessionId Optional session ID for binding the operation to a specific session
  964. */
  965. async _clearTaskQueue(taskId, sessionId) {
  966. if (this._taskMessageQueue) {
  967. // Reject any pending request resolvers
  968. const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
  969. for (const message of messages) {
  970. if (message.type === 'request' && (0, types_js_1.isJSONRPCRequest)(message.message)) {
  971. // Extract request ID from the message
  972. const requestId = message.message.id;
  973. const resolver = this._requestResolvers.get(requestId);
  974. if (resolver) {
  975. resolver(new types_js_1.McpError(types_js_1.ErrorCode.InternalError, 'Task cancelled or completed'));
  976. this._requestResolvers.delete(requestId);
  977. }
  978. else {
  979. // Log error when resolver is missing during cleanup for better observability
  980. this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
  981. }
  982. }
  983. }
  984. }
  985. }
  986. /**
  987. * Waits for a task update (new messages or status change) with abort signal support.
  988. * Uses polling to check for updates at the task's configured poll interval.
  989. * @param taskId The task ID to wait for
  990. * @param signal Abort signal to cancel the wait
  991. * @returns Promise that resolves when an update occurs or rejects if aborted
  992. */
  993. async _waitForTaskUpdate(taskId, signal) {
  994. // Get the task's poll interval, falling back to default
  995. let interval = this._options?.defaultTaskPollInterval ?? 1000;
  996. try {
  997. const task = await this._taskStore?.getTask(taskId);
  998. if (task?.pollInterval) {
  999. interval = task.pollInterval;
  1000. }
  1001. }
  1002. catch {
  1003. // Use default interval if task lookup fails
  1004. }
  1005. return new Promise((resolve, reject) => {
  1006. if (signal.aborted) {
  1007. reject(new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, 'Request cancelled'));
  1008. return;
  1009. }
  1010. // Wait for the poll interval, then resolve so caller can check for updates
  1011. const timeoutId = setTimeout(resolve, interval);
  1012. // Clean up timeout and reject if aborted
  1013. signal.addEventListener('abort', () => {
  1014. clearTimeout(timeoutId);
  1015. reject(new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, 'Request cancelled'));
  1016. }, { once: true });
  1017. });
  1018. }
  1019. requestTaskStore(request, sessionId) {
  1020. const taskStore = this._taskStore;
  1021. if (!taskStore) {
  1022. throw new Error('No task store configured');
  1023. }
  1024. return {
  1025. createTask: async (taskParams) => {
  1026. if (!request) {
  1027. throw new Error('No request provided');
  1028. }
  1029. return await taskStore.createTask(taskParams, request.id, {
  1030. method: request.method,
  1031. params: request.params
  1032. }, sessionId);
  1033. },
  1034. getTask: async (taskId) => {
  1035. const task = await taskStore.getTask(taskId, sessionId);
  1036. if (!task) {
  1037. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');
  1038. }
  1039. return task;
  1040. },
  1041. storeTaskResult: async (taskId, status, result) => {
  1042. await taskStore.storeTaskResult(taskId, status, result, sessionId);
  1043. // Get updated task state and send notification
  1044. const task = await taskStore.getTask(taskId, sessionId);
  1045. if (task) {
  1046. const notification = types_js_1.TaskStatusNotificationSchema.parse({
  1047. method: 'notifications/tasks/status',
  1048. params: task
  1049. });
  1050. await this.notification(notification);
  1051. if ((0, interfaces_js_1.isTerminal)(task.status)) {
  1052. this._cleanupTaskProgressHandler(taskId);
  1053. // Don't clear queue here - it will be cleared after delivery via tasks/result
  1054. }
  1055. }
  1056. },
  1057. getTaskResult: taskId => {
  1058. return taskStore.getTaskResult(taskId, sessionId);
  1059. },
  1060. updateTaskStatus: async (taskId, status, statusMessage) => {
  1061. // Check if task exists
  1062. const task = await taskStore.getTask(taskId, sessionId);
  1063. if (!task) {
  1064. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
  1065. }
  1066. // Don't allow transitions from terminal states
  1067. if ((0, interfaces_js_1.isTerminal)(task.status)) {
  1068. throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
  1069. }
  1070. await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
  1071. // Get updated task state and send notification
  1072. const updatedTask = await taskStore.getTask(taskId, sessionId);
  1073. if (updatedTask) {
  1074. const notification = types_js_1.TaskStatusNotificationSchema.parse({
  1075. method: 'notifications/tasks/status',
  1076. params: updatedTask
  1077. });
  1078. await this.notification(notification);
  1079. if ((0, interfaces_js_1.isTerminal)(updatedTask.status)) {
  1080. this._cleanupTaskProgressHandler(taskId);
  1081. // Don't clear queue here - it will be cleared after delivery via tasks/result
  1082. }
  1083. }
  1084. },
  1085. listTasks: cursor => {
  1086. return taskStore.listTasks(cursor, sessionId);
  1087. }
  1088. };
  1089. }
  1090. }
  1091. exports.Protocol = Protocol;
  1092. function isPlainObject(value) {
  1093. return value !== null && typeof value === 'object' && !Array.isArray(value);
  1094. }
  1095. function mergeCapabilities(base, additional) {
  1096. const result = { ...base };
  1097. for (const key in additional) {
  1098. const k = key;
  1099. const addValue = additional[k];
  1100. if (addValue === undefined)
  1101. continue;
  1102. const baseValue = result[k];
  1103. if (isPlainObject(baseValue) && isPlainObject(addValue)) {
  1104. result[k] = { ...baseValue, ...addValue };
  1105. }
  1106. else {
  1107. result[k] = addValue;
  1108. }
  1109. }
  1110. return result;
  1111. }
  1112. //# sourceMappingURL=protocol.js.map