Skip to content

Commit cc13334

Browse files
authored
Merge branch 'modelcontextprotocol:main' into bump-to-0.9.1
2 parents 6a85e77 + c6668c1 commit cc13334

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/shared/protocol.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import {
33
CancelledNotificationSchema,
44
ClientCapabilities,
55
ErrorCode,
6+
isJSONRPCError,
7+
isJSONRPCRequest,
8+
isJSONRPCResponse,
9+
isJSONRPCNotification,
610
JSONRPCError,
711
JSONRPCNotification,
812
JSONRPCRequest,
@@ -271,12 +275,14 @@ export abstract class Protocol<
271275
};
272276

273277
this._transport.onmessage = (message) => {
274-
if (!("method" in message)) {
278+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
275279
this._onresponse(message);
276-
} else if ("id" in message) {
280+
} else if (isJSONRPCRequest(message)) {
277281
this._onrequest(message);
278-
} else {
282+
} else if (isJSONRPCNotification(message)) {
279283
this._onnotification(message);
284+
} else {
285+
this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
280286
}
281287
};
282288

@@ -437,7 +443,7 @@ export abstract class Protocol<
437443
this._progressHandlers.delete(messageId);
438444
this._cleanupTimeout(messageId);
439445

440-
if ("result" in response) {
446+
if (isJSONRPCResponse(response)) {
441447
handler(response);
442448
} else {
443449
const error = new McpError(

src/types.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff 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
*/
@@ -139,6 +150,9 @@ export const JSONRPCErrorSchema = z
139150
})
140151
.strict();
141152

153+
export const isJSONRPCError = (value: unknown): value is JSONRPCError =>
154+
JSONRPCErrorSchema.safeParse(value).success;
155+
142156
export const JSONRPCMessageSchema = z.union([
143157
JSONRPCRequestSchema,
144158
JSONRPCNotificationSchema,

0 commit comments

Comments
 (0)