|
| 1 | +import cors from 'cors'; |
| 2 | +import { randomUUID } from 'node:crypto'; |
| 3 | +import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js'; |
| 4 | +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; |
| 5 | +import { createMcpAppServer } from './index.js'; |
| 6 | + |
| 7 | +const PORT = Number(process.env['PORT'] ?? 3000); |
| 8 | +const HOST = process.env['HOST'] ?? '0.0.0.0'; |
| 9 | + |
| 10 | +const app = createMcpExpressApp({ host: HOST }); |
| 11 | + |
| 12 | +// Allow cross-origin requests so Claude web (behind cloudflared) can reach the server |
| 13 | +app.use(cors()); |
| 14 | + |
| 15 | +/** |
| 16 | + * MCP endpoint — stateless mode. |
| 17 | + * |
| 18 | + * Each HTTP request gets its own McpServer + StreamableHTTPServerTransport pair. |
| 19 | + * This is the simplest correct approach for a single-tool hello-world server. |
| 20 | + * Swap to a session store if you need multi-turn stateful interactions. |
| 21 | + */ |
| 22 | +app.all('/mcp', async (req, res) => { |
| 23 | + const mcpServer = createMcpAppServer(); |
| 24 | + const transport = new StreamableHTTPServerTransport({ |
| 25 | + sessionIdGenerator: () => randomUUID(), |
| 26 | + }); |
| 27 | + |
| 28 | + // Clean up when the response finishes |
| 29 | + res.on('close', () => { |
| 30 | + void mcpServer.close(); |
| 31 | + }); |
| 32 | + |
| 33 | + try { |
| 34 | + await mcpServer.connect(transport); |
| 35 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument |
| 36 | + await transport.handleRequest(req, res, req.body); |
| 37 | + } catch (err) { |
| 38 | + console.error('[mcp] request error', err); |
| 39 | + if (!res.headersSent) { |
| 40 | + res.status(500).json({ error: 'Internal server error' }); |
| 41 | + } |
| 42 | + } |
| 43 | +}); |
| 44 | + |
| 45 | +/** Health-check endpoint — useful for cloudflared and load-balancer probes. */ |
| 46 | +app.get('/health', (_req, res) => { |
| 47 | + res.json({ status: 'ok', service: 'patchwork-mcp-app-server' }); |
| 48 | +}); |
| 49 | + |
| 50 | +app.listen(PORT, HOST, () => { |
| 51 | + console.log(`MCP App Server listening on http://${HOST}:${PORT}`); |
| 52 | + console.log(` POST /mcp — MCP Streamable HTTP endpoint`); |
| 53 | + console.log(` GET /health — health check`); |
| 54 | + console.log(); |
| 55 | + console.log('To expose locally via cloudflared:'); |
| 56 | + console.log(` cloudflared tunnel --url http://localhost:${PORT}`); |
| 57 | +}); |
0 commit comments