|
| 1 | +import { randomUUID } from 'node:crypto' |
| 2 | +import type { Server } from '@modelcontextprotocol/sdk/server/index.js' |
| 3 | +import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js' |
| 4 | +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' |
| 5 | +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js' |
| 6 | +import type { Request, Response, NextFunction } from 'express' |
| 7 | +import type { TldrawMcpConfig } from './config.js' |
| 8 | + |
| 9 | +export type McpServerFactory = () => Server |
| 10 | + |
| 11 | +function isAllowedOrigin(config: TldrawMcpConfig, origin?: string): boolean { |
| 12 | + if (!origin) return true |
| 13 | + return config.allowedOrigins.some((allowed) => origin === allowed || origin.startsWith(`${allowed}:`)) |
| 14 | +} |
| 15 | + |
| 16 | +function isAuthorized(config: TldrawMcpConfig, authorization?: string): boolean { |
| 17 | + if (!config.authToken) return true |
| 18 | + return authorization === `Bearer ${config.authToken}` |
| 19 | +} |
| 20 | + |
| 21 | +function securityMiddleware(config: TldrawMcpConfig) { |
| 22 | + return (req: Request, res: Response, next: NextFunction): void => { |
| 23 | + if (!isAllowedOrigin(config, req.header('origin') ?? undefined)) { |
| 24 | + res.status(403).json({ error: 'Origin not allowed' }) |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + if (!isAuthorized(config, req.header('authorization') ?? undefined)) { |
| 29 | + res.status(401).json({ error: 'Unauthorized' }) |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + next() |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function isInitializeRequest(body: unknown): boolean { |
| 38 | + if (!body || Array.isArray(body) || typeof body !== 'object') return false |
| 39 | + return (body as { method?: unknown }).method === 'initialize' |
| 40 | +} |
| 41 | + |
| 42 | +export async function startMcpServer(createServer: McpServerFactory, config: TldrawMcpConfig): Promise<void> { |
| 43 | + if (config.transport === 'stdio') { |
| 44 | + await createServer().connect(new StdioServerTransport()) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + const app = createMcpExpressApp({ |
| 49 | + host: config.httpHost, |
| 50 | + allowedHosts: config.allowedHosts, |
| 51 | + }) |
| 52 | + |
| 53 | + app.use(securityMiddleware(config)) |
| 54 | + |
| 55 | + const transports = new Map<string, StreamableHTTPServerTransport>() |
| 56 | + |
| 57 | + app.all(config.httpPath, async (req, res) => { |
| 58 | + const requestedSessionId = req.header('mcp-session-id') |
| 59 | + let transport = requestedSessionId ? transports.get(requestedSessionId) : undefined |
| 60 | + |
| 61 | + if (!transport) { |
| 62 | + if (!isInitializeRequest(req.body)) { |
| 63 | + res.status(requestedSessionId ? 404 : 400).json({ |
| 64 | + error: requestedSessionId ? 'Unknown MCP session' : 'Missing MCP session; initialize first', |
| 65 | + }) |
| 66 | + return |
| 67 | + } |
| 68 | + |
| 69 | + transport = new StreamableHTTPServerTransport({ |
| 70 | + sessionIdGenerator: () => randomUUID(), |
| 71 | + enableJsonResponse: true, |
| 72 | + allowedHosts: config.allowedHosts, |
| 73 | + allowedOrigins: config.allowedOrigins, |
| 74 | + enableDnsRebindingProtection: true, |
| 75 | + onsessioninitialized: (sessionId) => { |
| 76 | + transports.set(sessionId, transport!) |
| 77 | + }, |
| 78 | + onsessionclosed: (sessionId) => { |
| 79 | + transports.delete(sessionId) |
| 80 | + }, |
| 81 | + }) |
| 82 | + |
| 83 | + transport.onclose = () => { |
| 84 | + if (transport?.sessionId) transports.delete(transport.sessionId) |
| 85 | + } |
| 86 | + |
| 87 | + await createServer().connect(transport) |
| 88 | + } |
| 89 | + |
| 90 | + await transport.handleRequest(req, res, req.body) |
| 91 | + }) |
| 92 | + |
| 93 | + await new Promise<void>((resolve) => { |
| 94 | + app.listen(config.httpPort, config.httpHost, () => resolve()) |
| 95 | + }) |
| 96 | +} |
0 commit comments