(
options: {
handlePayload?: PayloadHandler;
write?: MessageWriter;
} = {},
)
| 37 | } |
| 38 | |
| 39 | export function createMcpPayloadQueue( |
| 40 | options: { |
| 41 | handlePayload?: PayloadHandler; |
| 42 | write?: MessageWriter; |
| 43 | } = {}, |
| 44 | ): { |
| 45 | push: (payload: unknown) => void; |
| 46 | idle: () => Promise<void>; |
| 47 | } { |
| 48 | const handlePayload = options.handlePayload ?? handleMcpPayload; |
| 49 | const write = options.write ?? writeMessage; |
| 50 | let pending = Promise.resolve(); |
| 51 | return { |
| 52 | push: (payload) => { |
| 53 | const fallbackId = fallbackErrorId(payload); |
| 54 | pending = pending |
| 55 | .then(async () => { |
| 56 | const response = await handlePayload(payload); |
| 57 | if (response) write(response); |
| 58 | }) |
| 59 | .catch((error: unknown) => { |
| 60 | write({ |
| 61 | jsonrpc: '2.0', |
| 62 | id: fallbackId, |
| 63 | error: { |
| 64 | code: -32603, |
| 65 | message: error instanceof Error ? error.message : String(error), |
| 66 | }, |
| 67 | }); |
| 68 | }); |
| 69 | }, |
| 70 | idle: async () => { |
| 71 | await pending; |
| 72 | }, |
| 73 | }; |
| 74 | } |
| 75 | |
| 76 | export function handleMcpPayload(payload: unknown): Promise<unknown | null> { |
| 77 | if (Array.isArray(payload)) { |
no test coverage detected