File tree Expand file tree Collapse file tree 2 files changed +20
-4
lines changed Expand file tree Collapse file tree 2 files changed +20
-4
lines changed Original file line number Diff line number Diff line change 3
3
CancelledNotificationSchema ,
4
4
ClientCapabilities ,
5
5
ErrorCode ,
6
+ isJSONRPCRequest ,
7
+ isJSONRPCResponse ,
8
+ isJSONRPCNotification ,
6
9
JSONRPCError ,
7
10
JSONRPCNotification ,
8
11
JSONRPCRequest ,
@@ -241,12 +244,14 @@ export abstract class Protocol<
241
244
} ;
242
245
243
246
this . _transport . onmessage = ( message ) => {
244
- if ( ! ( "method" in message ) ) {
247
+ if ( isJSONRPCResponse ( message ) ) {
245
248
this . _onresponse ( message ) ;
246
- } else if ( "id" in message ) {
249
+ } else if ( isJSONRPCRequest ( message ) ) {
247
250
this . _onrequest ( message ) ;
248
- } else {
251
+ } else if ( isJSONRPCNotification ( message ) ) {
249
252
this . _onnotification ( message ) ;
253
+ } else {
254
+ this . _onerror ( new Error ( `Unknown message type: ${ JSON . stringify ( message ) } ` ) ) ;
250
255
}
251
256
} ;
252
257
@@ -402,7 +407,7 @@ export abstract class Protocol<
402
407
this . _progressHandlers . delete ( messageId ) ;
403
408
this . _cleanupTimeout ( messageId ) ;
404
409
405
- if ( "result" in response ) {
410
+ if ( isJSONRPCResponse ( response ) ) {
406
411
handler ( response ) ;
407
412
} else {
408
413
const error = new McpError (
Original file line number Diff line number Diff line change @@ -78,6 +78,9 @@ export const JSONRPCRequestSchema = z
78
78
. merge ( RequestSchema )
79
79
. strict ( ) ;
80
80
81
+ export const isJSONRPCRequest = ( value : unknown ) : value is JSONRPCRequest =>
82
+ JSONRPCRequestSchema . safeParse ( value ) . success ;
83
+
81
84
/**
82
85
* A notification which does not expect a response.
83
86
*/
@@ -88,6 +91,11 @@ export const JSONRPCNotificationSchema = z
88
91
. merge ( NotificationSchema )
89
92
. strict ( ) ;
90
93
94
+ export const isJSONRPCNotification = (
95
+ value : unknown
96
+ ) : value is JSONRPCNotification =>
97
+ JSONRPCNotificationSchema . safeParse ( value ) . success ;
98
+
91
99
/**
92
100
* A successful (non-error) response to a request.
93
101
*/
@@ -99,6 +107,9 @@ export const JSONRPCResponseSchema = z
99
107
} )
100
108
. strict ( ) ;
101
109
110
+ export const isJSONRPCResponse = ( value : unknown ) : value is JSONRPCResponse =>
111
+ JSONRPCResponseSchema . safeParse ( value ) . success ;
112
+
102
113
/**
103
114
* Error codes defined by the JSON-RPC specification.
104
115
*/
You can’t perform that action at this time.
0 commit comments