Merge pull request #103 from sumitesh9/sumiteshn9/fix-error-codes

Updates SDK error codes to use JSON-RPC server error range
This commit is contained in:
Justin Spahr-Summers 2025-01-03 08:58:02 +00:00 • committed by GitHub
commit 2fd4e3555e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 68 additions and 5 deletions

View file

@ -0,0 +1,63 @@
import { Protocol } from "./protocol.js";
import { Transport } from "./transport.js";
import {
McpError,
ErrorCode,
Request,
Result,
Notification,
} from "../types.js";
import { ZodType, z } from "zod";
// Mock Transport class
class MockTransport implements Transport {
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: unknown) => void;
async start(): Promise<void> {}
async close(): Promise<void> {
this.onclose?.();
}
async send(_message: unknown): Promise<void> {}
}
describe("protocol tests", () => {
let protocol: Protocol<Request, Notification, Result>;
let transport: MockTransport;
beforeEach(() => {
transport = new MockTransport();
protocol = new (class extends Protocol<Request, Notification, Result> {
protected assertCapabilityForMethod(): void {}
protected assertNotificationCapability(): void {}
protected assertRequestHandlerCapability(): void {}
})();
});
test("should throw a timeout error if the request exceeds the timeout", async () => {
await protocol.connect(transport);
const request = { method: "example", params: {} };
try {
const mockSchema: ZodType<{ result: string }> = z.object({
result: z.string(),
});
await protocol.request(request, mockSchema, {
timeout: 0,
});
} catch (error) {
expect(error).toBeInstanceOf(McpError);
if (error instanceof McpError) {
expect(error.code).toBe(ErrorCode.RequestTimeout);
}
}
});
test("should invoke onclose when the connection is closed", async () => {
const oncloseMock = jest.fn();
protocol.onclose = oncloseMock;
await protocol.connect(transport);
await transport.close();
expect(oncloseMock).toHaveBeenCalled();
});
});

View file

@ -100,13 +100,13 @@ export const JSONRPCResponseSchema = z
.strict();
/**
* An incomplete set of error codes that may appear in JSON-RPC responses.
* Error codes defined by the JSON-RPC specification.
*/
export enum ErrorCode {
// SDK error codes
ConnectionClosed = -1,
RequestTimeout = -2,
ConnectionClosed = -32000,
RequestTimeout = -32001,
// Standard JSON-RPC error codes
ParseError = -32700,
InvalidRequest = -32600,
@ -1237,4 +1237,4 @@ export type ClientResult = z.infer<typeof ClientResultSchema>;
/* Server messages */
export type ServerRequest = z.infer<typeof ServerRequestSchema>;
export type ServerNotification = z.infer<typeof ServerNotificationSchema>;
export type ServerResult = z.infer<typeof ServerResultSchema>;
export type ServerResult = z.infer<typeof ServerResultSchema>;