From cd6820e810c789de92dcf55a05eaecacb286eee8 Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Wed, 2 Oct 2024 14:48:01 +0100 Subject: [PATCH] Use an enum for error codes --- src/shared/protocol.ts | 10 ++++------ src/types.ts | 22 ++++++++++++++-------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index f4ec07a4..ec1083d3 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -1,12 +1,10 @@ import { - CONNECTION_CLOSED_ERROR, - INTERNAL_ERROR, + ErrorCode, JSONRPCError, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, McpError, - METHOD_NOT_FOUND, Notification, PingRequestSchema, Progress, @@ -124,7 +122,7 @@ export class Protocol< this._transport = undefined; this.onclose?.(); - const error = new McpError(CONNECTION_CLOSED_ERROR, "Connection closed"); + const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed"); for (const handler of responseHandlers.values()) { handler(error); } @@ -161,7 +159,7 @@ export class Protocol< jsonrpc: "2.0", id: request.id, error: { - code: METHOD_NOT_FOUND, + code: ErrorCode.MethodNotFound, message: "Method not found", }, }) @@ -189,7 +187,7 @@ export class Protocol< error: { code: error["code"] ? Math.floor(Number(error["code"])) - : INTERNAL_ERROR, + : ErrorCode.InternalError, message: error.message ?? "Internal error", }, }); diff --git a/src/types.ts b/src/types.ts index 4d09cc32..821e5fcc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -82,12 +82,20 @@ export const JSONRPCResponseSchema = z }) .strict(); -// Standard JSON-RPC error codes -export const PARSE_ERROR = -32700; -export const INVALID_REQUEST = -32600; -export const METHOD_NOT_FOUND = -32601; -export const INVALID_PARAMS = -32602; -export const INTERNAL_ERROR = -32603; +/** + * An incomplete set of error codes that may appear in JSON-RPC responses. + */ +export enum ErrorCode { + // SDK error codes + ConnectionClosed = -1, + + // Standard JSON-RPC error codes + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603, +} /** * A response to a request that indicates an error occurred. @@ -802,8 +810,6 @@ export const ServerResultSchema = z.union([ ListToolsResultSchema, ]); -export const CONNECTION_CLOSED_ERROR = -1; - export class McpError extends Error { constructor( public readonly code: number,