Add helper functions to distinguish between jsonRPC message types
This commit is contained in:
parent
df8701937d
commit
8215651552
2 changed files with 20 additions and 4 deletions
|
|
@ -3,6 +3,9 @@ import {
|
|||
CancelledNotificationSchema,
|
||||
ClientCapabilities,
|
||||
ErrorCode,
|
||||
isJSONRPCRequest,
|
||||
isJSONRPCResponse,
|
||||
isJSONRPCNotification,
|
||||
JSONRPCError,
|
||||
JSONRPCNotification,
|
||||
JSONRPCRequest,
|
||||
|
|
@ -271,12 +274,14 @@ export abstract class Protocol<
|
|||
};
|
||||
|
||||
this._transport.onmessage = (message) => {
|
||||
if (!("method" in message)) {
|
||||
if (isJSONRPCResponse(message)) {
|
||||
this._onresponse(message);
|
||||
} else if ("id" in message) {
|
||||
} else if (isJSONRPCRequest(message)) {
|
||||
this._onrequest(message);
|
||||
} else {
|
||||
} else if (isJSONRPCNotification(message)) {
|
||||
this._onnotification(message);
|
||||
} else {
|
||||
this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -437,7 +442,7 @@ export abstract class Protocol<
|
|||
this._progressHandlers.delete(messageId);
|
||||
this._cleanupTimeout(messageId);
|
||||
|
||||
if ("result" in response) {
|
||||
if (isJSONRPCResponse(response)) {
|
||||
handler(response);
|
||||
} else {
|
||||
const error = new McpError(
|
||||
|
|
|
|||
11
src/types.ts
11
src/types.ts
|
|
@ -78,6 +78,9 @@ export const JSONRPCRequestSchema = z
|
|||
.merge(RequestSchema)
|
||||
.strict();
|
||||
|
||||
export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest =>
|
||||
JSONRPCRequestSchema.safeParse(value).success;
|
||||
|
||||
/**
|
||||
* A notification which does not expect a response.
|
||||
*/
|
||||
|
|
@ -88,6 +91,11 @@ export const JSONRPCNotificationSchema = z
|
|||
.merge(NotificationSchema)
|
||||
.strict();
|
||||
|
||||
export const isJSONRPCNotification = (
|
||||
value: unknown
|
||||
): value is JSONRPCNotification =>
|
||||
JSONRPCNotificationSchema.safeParse(value).success;
|
||||
|
||||
/**
|
||||
* A successful (non-error) response to a request.
|
||||
*/
|
||||
|
|
@ -99,6 +107,9 @@ export const JSONRPCResponseSchema = z
|
|||
})
|
||||
.strict();
|
||||
|
||||
export const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse =>
|
||||
JSONRPCResponseSchema.safeParse(value).success;
|
||||
|
||||
/**
|
||||
* Error codes defined by the JSON-RPC specification.
|
||||
*/
|
||||
|
|
|
|||
Loading…
Reference in a new issue