* Handle a JSON-RPC request by forwarding to the stdio MCP client. * * This bypasses the MCP SDK's Server class which only accepts one `initialize` * per lifetime. By handling JSON-RPC directly, we support unlimited HTTP clients * (e.g. worker for discovery, then gateway for tool calls) sharing
(req, res, stdioClient, name)
| 67 | * (e.g. worker for discovery, then gateway for tool calls) sharing one stdio server. |
| 68 | */ |
| 69 | async function handleJsonRpc(req, res, stdioClient, name) { |
| 70 | const body = req.body; |
| 71 | |
| 72 | // Notifications have no `id` — return 202 Accepted (expected by MCP SDK client) |
| 73 | if (body && body.method && body.id === undefined) { |
| 74 | return res.status(202).end(); |
| 75 | } |
| 76 | |
| 77 | if (!body || !body.method) { |
| 78 | return res.status(400).json({ |
| 79 | jsonrpc: '2.0', |
| 80 | id: body?.id ?? null, |
| 81 | error: { code: -32600, message: 'Invalid request: missing method' }, |
| 82 | }); |
| 83 | } |
| 84 | |
| 85 | try { |
| 86 | switch (body.method) { |
| 87 | case 'initialize': { |
| 88 | const result = { |
| 89 | protocolVersion: LATEST_PROTOCOL_VERSION, |
| 90 | capabilities: stdioClient.getServerCapabilities() ?? { tools: { listChanged: false } }, |
| 91 | serverInfo: stdioClient.getServerVersion() ?? { |
| 92 | name: `mcp-proxy-${name}`, |
| 93 | version: '1.0.0', |
| 94 | }, |
| 95 | instructions: stdioClient.getInstructions?.(), |
| 96 | }; |
| 97 | return res.json({ jsonrpc: '2.0', id: body.id, result }); |
| 98 | } |
| 99 | |
| 100 | case 'tools/list': { |
| 101 | const result = await stdioClient.listTools(); |
| 102 | return res.json({ jsonrpc: '2.0', id: body.id, result }); |
| 103 | } |
| 104 | |
| 105 | case 'tools/call': { |
| 106 | const result = await stdioClient.callTool({ |
| 107 | name: body.params.name, |
| 108 | arguments: body.params.arguments ?? {}, |
| 109 | }); |
| 110 | return res.json({ jsonrpc: '2.0', id: body.id, result }); |
| 111 | } |
| 112 | |
| 113 | case 'resources/list': { |
| 114 | const result = await stdioClient.listResources(); |
| 115 | return res.json({ jsonrpc: '2.0', id: body.id, result }); |
| 116 | } |
| 117 | |
| 118 | case 'resources/read': { |
| 119 | const result = await stdioClient.readResource({ uri: body.params.uri }); |
| 120 | return res.json({ jsonrpc: '2.0', id: body.id, result }); |
| 121 | } |
| 122 | |
| 123 | case 'prompts/list': { |
| 124 | const result = await stdioClient.listPrompts(); |
| 125 | return res.json({ jsonrpc: '2.0', id: body.id, result }); |
| 126 | } |
no test coverage detected