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 33 CancelledNotificationSchema ,
44 ClientCapabilities ,
55 ErrorCode ,
6+ isJSONRPCRequest ,
7+ isJSONRPCResponse ,
8+ isJSONRPCNotification ,
69 JSONRPCError ,
710 JSONRPCNotification ,
811 JSONRPCRequest ,
@@ -241,12 +244,14 @@ export abstract class Protocol<
241244 } ;
242245
243246 this . _transport . onmessage = ( message ) => {
244- if ( ! ( "method" in message ) ) {
247+ if ( isJSONRPCResponse ( message ) ) {
245248 this . _onresponse ( message ) ;
246- } else if ( "id" in message ) {
249+ } else if ( isJSONRPCRequest ( message ) ) {
247250 this . _onrequest ( message ) ;
248- } else {
251+ } else if ( isJSONRPCNotification ( message ) ) {
249252 this . _onnotification ( message ) ;
253+ } else {
254+ this . _onerror ( new Error ( `Unknown message type: ${ JSON . stringify ( message ) } ` ) ) ;
250255 }
251256 } ;
252257
@@ -402,7 +407,7 @@ export abstract class Protocol<
402407 this . _progressHandlers . delete ( messageId ) ;
403408 this . _cleanupTimeout ( messageId ) ;
404409
405- if ( "result" in response ) {
410+ if ( isJSONRPCResponse ( response ) ) {
406411 handler ( response ) ;
407412 } else {
408413 const error = new McpError (
Original file line number Diff line number Diff line change @@ -78,6 +78,9 @@ export const JSONRPCRequestSchema = z
7878 . merge ( RequestSchema )
7979 . strict ( ) ;
8080
81+ export const isJSONRPCRequest = ( value : unknown ) : value is JSONRPCRequest =>
82+ JSONRPCRequestSchema . safeParse ( value ) . success ;
83+
8184/**
8285 * A notification which does not expect a response.
8386 */
@@ -88,6 +91,11 @@ export const JSONRPCNotificationSchema = z
8891 . merge ( NotificationSchema )
8992 . strict ( ) ;
9093
94+ export const isJSONRPCNotification = (
95+ value : unknown
96+ ) : value is JSONRPCNotification =>
97+ JSONRPCNotificationSchema . safeParse ( value ) . success ;
98+
9199/**
92100 * A successful (non-error) response to a request.
93101 */
@@ -99,6 +107,9 @@ export const JSONRPCResponseSchema = z
99107 } )
100108 . strict ( ) ;
101109
110+ export const isJSONRPCResponse = ( value : unknown ) : value is JSONRPCResponse =>
111+ JSONRPCResponseSchema . safeParse ( value ) . success ;
112+
102113/**
103114 * Error codes defined by the JSON-RPC specification.
104115 */
You can’t perform that action at this time.
0 commit comments