-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathprotocol.ts
More file actions
1712 lines (1509 loc) · 68.5 KB
/
protocol.ts
File metadata and controls
1712 lines (1509 loc) · 68.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AnySchema, AnyObjectSchema, SchemaOutput, safeParse } from '../server/zod-compat.js';
import {
CancelledNotificationSchema,
ClientCapabilities,
CreateTaskResultSchema,
ErrorCode,
GetTaskRequest,
GetTaskRequestSchema,
GetTaskResultSchema,
GetTaskPayloadRequest,
GetTaskPayloadRequestSchema,
ListTasksRequestSchema,
ListTasksResultSchema,
CancelTaskRequestSchema,
CancelTaskResultSchema,
isJSONRPCErrorResponse,
isJSONRPCRequest,
isJSONRPCResultResponse,
isJSONRPCNotification,
JSONRPCErrorResponse,
JSONRPCNotification,
JSONRPCRequest,
JSONRPCResponse,
McpError,
PingRequestSchema,
Progress,
ProgressNotification,
ProgressNotificationSchema,
RELATED_TASK_META_KEY,
RequestId,
Result,
ServerCapabilities,
RequestMeta,
MessageExtraInfo,
RequestInfo,
GetTaskResult,
TaskCreationParams,
RelatedTaskMetadata,
CancelledNotification,
Task,
TaskStatusNotification,
TaskStatusNotificationSchema,
Request,
Notification,
JSONRPCResultResponse,
isTaskAugmentedRequestParams
} from '../types.js';
import { Transport, TransportSendOptions } from './transport.js';
import { AuthInfo } from '../server/auth/types.js';
import { isTerminal, TaskStore, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../experimental/tasks/interfaces.js';
import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';
import { ResponseMessage } from './responseMessage.js';
/**
* Callback for progress notifications.
*/
export type ProgressCallback = (progress: Progress) => void;
/**
* Additional initialization options.
*/
export type ProtocolOptions = {
/**
* Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities.
*
* Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those.
*
* Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true.
*/
enforceStrictCapabilities?: boolean;
/**
* An array of notification method names that should be automatically debounced.
* Any notifications with a method in this list will be coalesced if they
* occur in the same tick of the event loop.
* e.g., ['notifications/tools/list_changed']
*/
debouncedNotificationMethods?: string[];
/**
* Optional task storage implementation. If provided, enables task-related request handlers
* and provides task storage capabilities to request handlers.
*/
taskStore?: TaskStore;
/**
* Optional task message queue implementation for managing server-initiated messages
* that will be delivered through the tasks/result response stream.
*/
taskMessageQueue?: TaskMessageQueue;
/**
* Default polling interval (in milliseconds) for task status checks when no pollInterval
* is provided by the server. Defaults to 5000ms if not specified.
*/
defaultTaskPollInterval?: number;
/**
* Maximum number of messages that can be queued per task for side-channel delivery.
* If undefined, the queue size is unbounded.
* When the limit is exceeded, the TaskMessageQueue implementation's enqueue() method
* will throw an error. It's the implementation's responsibility to handle overflow
* appropriately (e.g., by failing the task, dropping messages, etc.).
*/
maxTaskQueueSize?: number;
/**
* Optional hooks for customizing task request handling.
* If a hook is provided, it fully owns the behavior (no fallback to TaskStore).
*/
taskHandlerHooks?: {
/**
* Called when tasks/get is received. If provided, must return the task.
*/
getTask?: (taskId: string, extra: RequestHandlerExtra<Request, Notification>) => Promise<GetTaskResult>;
/**
* Called when tasks/payload needs to retrieve the final result. If provided, must return the result.
*/
getTaskResult?: (taskId: string, extra: RequestHandlerExtra<Request, Notification>) => Promise<Result>;
};
};
/**
* The default request timeout, in miliseconds.
*/
export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;
/**
* Options that can be given per request.
*/
export type RequestOptions = {
/**
* If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked.
*
* For task-augmented requests: progress notifications continue after CreateTaskResult is returned and stop automatically when the task reaches a terminal status.
*/
onprogress?: ProgressCallback;
/**
* Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request().
*/
signal?: AbortSignal;
/**
* A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request().
*
* If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout.
*/
timeout?: number;
/**
* If true, receiving a progress notification will reset the request timeout.
* This is useful for long-running operations that send periodic progress updates.
* Default: false
*/
resetTimeoutOnProgress?: boolean;
/**
* Maximum total time (in milliseconds) to wait for a response.
* If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications.
* If not specified, there is no maximum total timeout.
*/
maxTotalTimeout?: number;
/**
* If provided, augments the request with task creation parameters to enable call-now, fetch-later execution patterns.
*/
task?: TaskCreationParams;
/**
* If provided, associates this request with a related task.
*/
relatedTask?: RelatedTaskMetadata;
} & TransportSendOptions;
/**
* Options that can be given per notification.
*/
export type NotificationOptions = {
/**
* May be used to indicate to the transport which incoming request to associate this outgoing notification with.
*/
relatedRequestId?: RequestId;
/**
* If provided, associates this notification with a related task.
*/
relatedTask?: RelatedTaskMetadata;
};
/**
* Options that can be given per request.
*/
// relatedTask is excluded as the SDK controls if this is sent according to if the source is a task.
export type TaskRequestOptions = Omit<RequestOptions, 'relatedTask'>;
/**
* Request-scoped TaskStore interface.
*/
export interface RequestTaskStore {
/**
* Creates a new task with the given creation parameters.
* The implementation generates a unique taskId and createdAt timestamp.
*
* @param taskParams - The task creation parameters from the request
* @returns The created task object
*/
createTask(taskParams: CreateTaskOptions): Promise<Task>;
/**
* Gets the current status of a task.
*
* @param taskId - The task identifier
* @returns The task object
* @throws If the task does not exist
*/
getTask(taskId: string): Promise<Task>;
/**
* Stores the result of a task and sets its final status.
*
* @param taskId - The task identifier
* @param status - The final status: 'completed' for success, 'failed' for errors
* @param result - The result to store
*/
storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result): Promise<void>;
/**
* Retrieves the stored result of a task.
*
* @param taskId - The task identifier
* @returns The stored result
*/
getTaskResult(taskId: string): Promise<Result>;
/**
* Updates a task's status (e.g., to 'cancelled', 'failed', 'completed').
*
* @param taskId - The task identifier
* @param status - The new status
* @param statusMessage - Optional diagnostic message for failed tasks or other status information
*/
updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string): Promise<void>;
/**
* Lists tasks, optionally starting from a pagination cursor.
*
* @param cursor - Optional cursor for pagination
* @returns An object containing the tasks array and an optional nextCursor
*/
listTasks(cursor?: string): Promise<{ tasks: Task[]; nextCursor?: string }>;
}
/**
* Extra data given to request handlers.
*/
export type RequestHandlerExtra<SendRequestT extends Request, SendNotificationT extends Notification> = {
/**
* An abort signal used to communicate if the request was cancelled from the sender's side.
*/
signal: AbortSignal;
/**
* Information about a validated access token, provided to request handlers.
*/
authInfo?: AuthInfo;
/**
* The session ID from the transport, if available.
*/
sessionId?: string;
/**
* Metadata from the original request.
*/
_meta?: RequestMeta;
/**
* The JSON-RPC ID of the request being handled.
* This can be useful for tracking or logging purposes.
*/
requestId: RequestId;
taskId?: string;
taskStore?: RequestTaskStore;
taskRequestedTtl?: number;
/**
* The original HTTP request.
*/
requestInfo?: RequestInfo;
/**
* Sends a notification that relates to the current request being handled.
*
* This is used by certain transports to correctly associate related messages.
*/
sendNotification: (notification: SendNotificationT) => Promise<void>;
/**
* Sends a request that relates to the current request being handled.
*
* This is used by certain transports to correctly associate related messages.
*/
sendRequest: <U extends AnySchema>(request: SendRequestT, resultSchema: U, options?: TaskRequestOptions) => Promise<SchemaOutput<U>>;
/**
* Closes the SSE stream for this request, triggering client reconnection.
* Only available when using StreamableHTTPServerTransport with eventStore configured.
* Use this to implement polling behavior during long-running operations.
*/
closeSSEStream?: () => void;
/**
* Closes the standalone GET SSE stream, triggering client reconnection.
* Only available when using StreamableHTTPServerTransport with eventStore configured.
* Use this to implement polling behavior for server-initiated notifications.
*/
closeStandaloneSSEStream?: () => void;
};
/**
* Information about a request's timeout state
*/
type TimeoutInfo = {
timeoutId: ReturnType<typeof setTimeout>;
startTime: number;
timeout: number;
maxTotalTimeout?: number;
resetTimeoutOnProgress: boolean;
onTimeout: () => void;
};
/**
* 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 Request, SendNotificationT extends Notification, SendResultT extends Result> {
private _transport?: Transport;
private _requestMessageId = 0;
private _requestHandlers: Map<
string,
(request: JSONRPCRequest, extra: RequestHandlerExtra<SendRequestT, SendNotificationT>) => Promise<SendResultT>
> = new Map();
private _requestHandlerAbortControllers: Map<RequestId, AbortController> = new Map();
private _notificationHandlers: Map<string, (notification: JSONRPCNotification) => Promise<void>> = new Map();
private _responseHandlers: Map<number, (response: JSONRPCResultResponse | Error) => void> = new Map();
private _progressHandlers: Map<number, ProgressCallback> = new Map();
private _timeoutInfo: Map<number, TimeoutInfo> = new Map();
private _pendingDebouncedNotifications = new Set<string>();
// Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult
private _taskProgressTokens: Map<string, number> = new Map();
private _taskStore?: TaskStore;
private _taskMessageQueue?: TaskMessageQueue;
private _requestResolvers: Map<RequestId, (response: JSONRPCResultResponse | Error) => void> = new Map();
/**
* Callback for when the connection is closed for any reason.
*
* This is invoked when close() is called as well.
*/
onclose?: () => void;
/**
* Callback for when an error occurs.
*
* Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.
*/
onerror?: (error: Error) => void;
/**
* A handler to invoke for any request types that do not have their own handler installed.
*/
fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra<SendRequestT, SendNotificationT>) => Promise<SendResultT>;
/**
* A handler to invoke for any notification types that do not have their own handler installed.
*/
fallbackNotificationHandler?: (notification: Notification) => Promise<void>;
constructor(private _options?: ProtocolOptions) {
this.setNotificationHandler(CancelledNotificationSchema, notification => {
this._oncancel(notification);
});
this.setNotificationHandler(ProgressNotificationSchema, notification => {
this._onprogress(notification as unknown as ProgressNotification);
});
this.setRequestHandler(
PingRequestSchema,
// Automatic pong by default.
_request => ({}) as SendResultT
);
// Install task handlers if TaskStore is provided
this._taskStore = _options?.taskStore;
this._taskMessageQueue = _options?.taskMessageQueue;
if (this._taskStore) {
this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
// Use hook if provided, otherwise fall back to TaskStore
if (_options?.taskHandlerHooks?.getTask) {
const hookResult = await _options.taskHandlerHooks.getTask(
request.params.taskId,
extra as unknown as RequestHandlerExtra<Request, Notification>
);
// @ts-expect-error SendResultT cannot contain GetTaskResult
return hookResult as SendResultT;
}
const task = await this._taskStore!.getTask(request.params.taskId, extra.sessionId);
if (!task) {
throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');
}
// Per spec: tasks/get responses SHALL NOT include related-task metadata
// as the taskId parameter is the source of truth
// @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else
return {
...task
} as SendResultT;
});
this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
const handleTaskResult = async (): Promise<SendResultT> => {
const taskId = request.params.taskId;
// Deliver queued messages
if (this._taskMessageQueue) {
let queuedMessage: QueuedMessage | undefined;
while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {
// Handle response and error messages by routing them to the appropriate resolver
if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {
const message = queuedMessage.message;
const requestId = message.id;
// Lookup resolver in _requestResolvers map
const resolver = this._requestResolvers.get(requestId as RequestId);
if (resolver) {
// Remove resolver from map after invocation
this._requestResolvers.delete(requestId as RequestId);
// Invoke resolver with response or error
if (queuedMessage.type === 'response') {
resolver(message as JSONRPCResultResponse);
} else {
// Convert JSONRPCError to McpError
const errorMessage = message as JSONRPCErrorResponse;
const error = new McpError(
errorMessage.error.code,
errorMessage.error.message,
errorMessage.error.data
);
resolver(error);
}
} else {
// Handle missing resolver gracefully with error logging
const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';
this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
}
// Continue to next message
continue;
}
// Send the message on the response stream by passing the relatedRequestId
// This tells the transport to write the message to the tasks/result response stream
await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
}
}
// Now check task status
const task = await this._taskStore!.getTask(taskId, extra.sessionId);
if (!task) {
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
}
// Block if task is not terminal (we've already delivered all queued messages above)
if (!isTerminal(task.status)) {
// Wait for status change or new messages
await this._waitForTaskUpdate(taskId, extra.signal);
// After waking up, recursively call to deliver any new messages or result
return await handleTaskResult();
}
// If task is terminal, return the result
if (isTerminal(task.status)) {
// Use hook if provided, otherwise fall back to TaskStore
const result = this._options?.taskHandlerHooks?.getTaskResult
? await this._options.taskHandlerHooks.getTaskResult(
taskId,
extra as unknown as RequestHandlerExtra<Request, Notification>
)
: await this._taskStore!.getTaskResult(taskId, extra.sessionId);
this._clearTaskQueue(taskId);
return {
...result,
_meta: {
...result._meta,
[RELATED_TASK_META_KEY]: {
taskId: taskId
}
}
} as SendResultT;
}
return await handleTaskResult();
};
return await handleTaskResult();
});
this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
try {
const { tasks, nextCursor } = await this._taskStore!.listTasks(request.params?.cursor, extra.sessionId);
// @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else
return {
tasks,
nextCursor,
_meta: {}
} as SendResultT;
} catch (error) {
throw new McpError(
ErrorCode.InvalidParams,
`Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`
);
}
});
this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
try {
// Get the current task to check if it's in a terminal state, in case the implementation is not atomic
const task = await this._taskStore!.getTask(request.params.taskId, extra.sessionId);
if (!task) {
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
}
// Reject cancellation of terminal tasks
if (isTerminal(task.status)) {
throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
}
await this._taskStore!.updateTaskStatus(
request.params.taskId,
'cancelled',
'Client cancelled task execution.',
extra.sessionId
);
this._clearTaskQueue(request.params.taskId);
const cancelledTask = await this._taskStore!.getTask(request.params.taskId, extra.sessionId);
if (!cancelledTask) {
// Task was deleted during cancellation (e.g., cleanup happened)
throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
}
return {
_meta: {},
...cancelledTask
} as unknown as SendResultT;
} catch (error) {
// Re-throw McpError as-is
if (error instanceof McpError) {
throw error;
}
throw new McpError(
ErrorCode.InvalidRequest,
`Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`
);
}
});
}
}
private async _oncancel(notification: CancelledNotification): Promise<void> {
if (!notification.params.requestId) {
return;
}
// Handle request cancellation
const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
controller?.abort(notification.params.reason);
}
private _setupTimeout(
messageId: number,
timeout: number,
maxTotalTimeout: number | undefined,
onTimeout: () => void,
resetTimeoutOnProgress: boolean = false
) {
this._timeoutInfo.set(messageId, {
timeoutId: setTimeout(onTimeout, timeout),
startTime: Date.now(),
timeout,
maxTotalTimeout,
resetTimeoutOnProgress,
onTimeout
});
}
private _resetTimeout(messageId: number): boolean {
const info = this._timeoutInfo.get(messageId);
if (!info) return false;
const totalElapsed = Date.now() - info.startTime;
if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
this._timeoutInfo.delete(messageId);
throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {
maxTotalTimeout: info.maxTotalTimeout,
totalElapsed
});
}
clearTimeout(info.timeoutId);
info.timeoutId = setTimeout(info.onTimeout, info.timeout);
return true;
}
private _cleanupTimeout(messageId: number) {
const info = this._timeoutInfo.get(messageId);
if (info) {
clearTimeout(info.timeoutId);
this._timeoutInfo.delete(messageId);
}
}
/**
* Attaches to the given transport, starts it, and starts listening for messages.
*
* 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.
*/
async connect(transport: Transport): Promise<void> {
if (this._transport) {
throw new Error(
'Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.'
);
}
this._transport = transport;
const _onclose = this.transport?.onclose;
this._transport.onclose = () => {
_onclose?.();
this._onclose();
};
const _onerror = this.transport?.onerror;
this._transport.onerror = (error: Error) => {
_onerror?.(error);
this._onerror(error);
};
const _onmessage = this._transport?.onmessage;
this._transport.onmessage = (message, extra) => {
_onmessage?.(message, extra);
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
this._onresponse(message);
} else if (isJSONRPCRequest(message)) {
this._onrequest(message, extra);
} else if (isJSONRPCNotification(message)) {
this._onnotification(message);
} else {
this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
}
};
await this._transport.start();
}
private _onclose(): void {
const responseHandlers = this._responseHandlers;
this._responseHandlers = new Map();
this._progressHandlers.clear();
this._taskProgressTokens.clear();
this._pendingDebouncedNotifications.clear();
for (const info of this._timeoutInfo.values()) {
clearTimeout(info.timeoutId);
}
this._timeoutInfo.clear();
// Abort all in-flight request handlers so they stop sending messages
for (const controller of this._requestHandlerAbortControllers.values()) {
controller.abort();
}
this._requestHandlerAbortControllers.clear();
const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');
this._transport = undefined;
this.onclose?.();
for (const handler of responseHandlers.values()) {
handler(error);
}
}
private _onerror(error: Error): void {
this.onerror?.(error);
}
private _onnotification(notification: JSONRPCNotification): void {
const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
// Ignore notifications not being subscribed to.
if (handler === undefined) {
return;
}
// Starting with Promise.resolve() puts any synchronous errors into the monad as well.
Promise.resolve()
.then(() => handler(notification))
.catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
}
private _onrequest(request: JSONRPCRequest, extra?: MessageExtraInfo): void {
const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
// Capture the current transport at request time to ensure responses go to the correct client
const capturedTransport = this._transport;
// Extract taskId from request metadata if present (needed early for method not found case)
const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
if (handler === undefined) {
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: request.id,
error: {
code: ErrorCode.MethodNotFound,
message: 'Method not found'
}
};
// Queue or send the error response based on whether this is a task-related request
if (relatedTaskId && this._taskMessageQueue) {
this._enqueueTaskMessage(
relatedTaskId,
{
type: 'error',
message: errorResponse,
timestamp: Date.now()
},
capturedTransport?.sessionId
).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
} else {
capturedTransport
?.send(errorResponse)
.catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));
}
return;
}
const abortController = new AbortController();
this._requestHandlerAbortControllers.set(request.id, abortController);
const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;
const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;
const fullExtra: RequestHandlerExtra<SendRequestT, SendNotificationT> = {
signal: abortController.signal,
sessionId: capturedTransport?.sessionId,
_meta: request.params?._meta,
sendNotification: async notification => {
if (abortController.signal.aborted) return;
// Include related-task metadata if this request is part of a task
const notificationOptions: NotificationOptions = { relatedRequestId: request.id };
if (relatedTaskId) {
notificationOptions.relatedTask = { taskId: relatedTaskId };
}
await this.notification(notification, notificationOptions);
},
sendRequest: async (r, resultSchema, options?) => {
if (abortController.signal.aborted) {
throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');
}
// Include related-task metadata if this request is part of a task
const requestOptions: RequestOptions = { ...options, relatedRequestId: request.id };
if (relatedTaskId && !requestOptions.relatedTask) {
requestOptions.relatedTask = { taskId: relatedTaskId };
}
// Set task status to input_required when sending a request within a task context
// Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)
const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
if (effectiveTaskId && taskStore) {
await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');
}
return await this.request(r, resultSchema, requestOptions);
},
authInfo: extra?.authInfo,
requestId: request.id,
requestInfo: extra?.requestInfo,
taskId: relatedTaskId,
taskStore: taskStore,
taskRequestedTtl: taskCreationParams?.ttl,
closeSSEStream: extra?.closeSSEStream,
closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
};
// Starting with Promise.resolve() puts any synchronous errors into the monad as well.
Promise.resolve()
.then(() => {
// If this request asked for task creation, check capability first
if (taskCreationParams) {
// Check if the request method supports task creation
this.assertTaskHandlerCapability(request.method);
}
})
.then(() => handler(request, fullExtra))
.then(
async result => {
if (abortController.signal.aborted) {
// Request was cancelled
return;
}
const response: JSONRPCResponse = {
result,
jsonrpc: '2.0',
id: request.id
};
// Queue or send the response based on whether this is a task-related request
if (relatedTaskId && this._taskMessageQueue) {
await this._enqueueTaskMessage(
relatedTaskId,
{
type: 'response',
message: response,
timestamp: Date.now()
},
capturedTransport?.sessionId
);
} else {
await capturedTransport?.send(response);
}
},
async error => {
if (abortController.signal.aborted) {
// Request was cancelled
return;
}
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: request.id,
error: {
code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,
message: error.message ?? 'Internal error',
...(error['data'] !== undefined && { data: error['data'] })
}
};
// Queue or send the error response based on whether this is a task-related request
if (relatedTaskId && this._taskMessageQueue) {
await this._enqueueTaskMessage(
relatedTaskId,
{
type: 'error',
message: errorResponse,
timestamp: Date.now()
},
capturedTransport?.sessionId
);
} else {
await capturedTransport?.send(errorResponse);
}
}
)
.catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))
.finally(() => {
// Only delete if the stored controller is still ours; after close()+connect(),
// a new connection may have reused the same request ID with a different controller.
if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
this._requestHandlerAbortControllers.delete(request.id);
}
});
}
private _onprogress(notification: ProgressNotification): void {
const { progressToken, ...params } = notification.params;
const messageId = Number(progressToken);
const handler = this._progressHandlers.get(messageId);
if (!handler) {
this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
return;
}
const responseHandler = this._responseHandlers.get(messageId);
const timeoutInfo = this._timeoutInfo.get(messageId);
if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
try {
this._resetTimeout(messageId);
} catch (error) {
// Clean up if maxTotalTimeout was exceeded
this._responseHandlers.delete(messageId);
this._progressHandlers.delete(messageId);
this._cleanupTimeout(messageId);
responseHandler(error as Error);
return;
}
}
handler(params);
}
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 (isJSONRPCResultResponse(response)) {
resolver(response);
} else {
const error = new McpError(response.error.code, response.error.message, response.error.data);
resolver(error);
}
return;
}
const handler = this._responseHandlers.get(messageId);
if (handler === undefined) {
this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
return;
}
this._responseHandlers.delete(messageId);
this._cleanupTimeout(messageId);
// Keep progress handler alive for CreateTaskResult responses
let isTaskResponse = false;
if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {
const result = response.result as Record<string, unknown>;
if (result.task && typeof result.task === 'object') {
const task = result.task as Record<string, unknown>;
if (typeof task.taskId === 'string') {
isTaskResponse = true;
this._taskProgressTokens.set(task.taskId, messageId);
}
}
}
if (!isTaskResponse) {
this._progressHandlers.delete(messageId);
}
if (isJSONRPCResultResponse(response)) {
handler(response);
} else {
const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
handler(error);
}
}
get transport(): Transport | undefined {
return this._transport;
}
/**
* Closes the connection.
*/
async close(): Promise<void> {
await this._transport?.close();
}
/**
* A method to check if a capability is supported by the remote side, for the given method to be called.
*
* This should be implemented by subclasses.
*/
protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void;
/**
* A method to check if a notification is supported by the local side, for the given method to be sent.
*
* This should be implemented by subclasses.
*/
protected abstract assertNotificationCapability(method: SendNotificationT['method']): void;
/**
* A method to check if a request handler is supported by the local side, for the given method to be handled.
*
* This should be implemented by subclasses.
*/
protected abstract assertRequestHandlerCapability(method: string): void;
/**
* A method to check if task creation is supported for the given request method.
*
* This should be implemented by subclasses.