( entry: unknown, methods: Record<string, MethodHandler>, onNotification: ((method: string, params: unknown) => void) | undefined, req: http.IncomingMessage, )
| 31 | } |
| 32 | |
| 33 | async function processOne( |
| 34 | entry: unknown, |
| 35 | methods: Record<string, MethodHandler>, |
| 36 | onNotification: ((method: string, params: unknown) => void) | undefined, |
| 37 | req: http.IncomingMessage, |
| 38 | ): Promise<JsonRpcResponse | null> { |
| 39 | if (!isObject(entry)) { |
| 40 | return errorResponse(-32600, "Invalid request"); |
| 41 | } |
| 42 | |
| 43 | const { jsonrpc, method, params, id } = entry; |
| 44 | |
| 45 | if (jsonrpc !== "2.0" || typeof method !== "string") { |
| 46 | const reqId = typeof id === "string" || typeof id === "number" ? id : null; |
| 47 | return errorResponse(-32600, "Invalid request", reqId); |
| 48 | } |
| 49 | |
| 50 | // Notification: id is absent/undefined |
| 51 | const isNotification = !("id" in entry) || id === undefined; |
| 52 | |
| 53 | if (isNotification) { |
| 54 | if (onNotification) { |
| 55 | onNotification(method, params); |
| 56 | } |
| 57 | // Invoke the method handler for side effects (e.g., MCP notifications/initialized), |
| 58 | // but discard the result — notifications MUST NOT produce responses per JSON-RPC 2.0. |
| 59 | const handler = methods[method]; |
| 60 | if (handler) { |
| 61 | try { |
| 62 | await handler(params, null as unknown as string | number, req); |
| 63 | } catch (err: unknown) { |
| 64 | console.warn("Notification handler error:", err); |
| 65 | } |
| 66 | } |
| 67 | return null; |
| 68 | } |
| 69 | |
| 70 | const reqId = typeof id === "string" || typeof id === "number" ? id : null; |
| 71 | |
| 72 | const handler = methods[method]; |
| 73 | if (!handler) { |
| 74 | return errorResponse(-32601, "Method not found", reqId); |
| 75 | } |
| 76 | |
| 77 | try { |
| 78 | const result = await handler(params, reqId as string | number, req); |
| 79 | if (result) return result; |
| 80 | return { jsonrpc: "2.0", id: reqId, result: null }; |
| 81 | } catch (err: unknown) { |
| 82 | const msg = err instanceof Error ? err.message : String(err); |
| 83 | return errorResponse(-32603, `Internal error: ${msg}`, reqId); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | export function createJsonRpcDispatcher( |
| 88 | options: JsonRpcDispatcherOptions, |
no test coverage detected
searching dependent graphs…