|
| 1 | +/** |
| 2 | + * Copyright (c) Microsoft Corporation. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import http from 'node:http'; |
| 18 | +import assert from 'node:assert'; |
| 19 | +import crypto from 'node:crypto'; |
| 20 | + |
| 21 | +import { ServerList } from './server'; |
| 22 | +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; |
| 23 | +import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'; |
| 24 | +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; |
| 25 | + |
| 26 | +export async function startStdioTransport(serverList: ServerList) { |
| 27 | + const server = await serverList.create(); |
| 28 | + await server.connect(new StdioServerTransport()); |
| 29 | +} |
| 30 | + |
| 31 | +async function handleSSE(req: http.IncomingMessage, res: http.ServerResponse, url: URL, serverList: ServerList, sessions: Map<string, SSEServerTransport>) { |
| 32 | + if (req.method === 'POST') { |
| 33 | + const sessionId = url.searchParams.get('sessionId'); |
| 34 | + if (!sessionId) { |
| 35 | + res.statusCode = 400; |
| 36 | + return res.end('Missing sessionId'); |
| 37 | + } |
| 38 | + |
| 39 | + const transport = sessions.get(sessionId); |
| 40 | + if (!transport) { |
| 41 | + res.statusCode = 404; |
| 42 | + return res.end('Session not found'); |
| 43 | + } |
| 44 | + |
| 45 | + return await transport.handlePostMessage(req, res); |
| 46 | + } else if (req.method === 'GET') { |
| 47 | + const transport = new SSEServerTransport('/sse', res); |
| 48 | + sessions.set(transport.sessionId, transport); |
| 49 | + const server = await serverList.create(); |
| 50 | + res.on('close', () => { |
| 51 | + sessions.delete(transport.sessionId); |
| 52 | + serverList.close(server).catch(e => console.error(e)); |
| 53 | + }); |
| 54 | + return await server.connect(transport); |
| 55 | + } |
| 56 | + |
| 57 | + res.statusCode = 405; |
| 58 | + res.end('Method not allowed'); |
| 59 | +} |
| 60 | + |
| 61 | +async function handleStreamable(req: http.IncomingMessage, res: http.ServerResponse, serverList: ServerList, sessions: Map<string, StreamableHTTPServerTransport>) { |
| 62 | + const sessionId = req.headers['mcp-session-id'] as string | undefined; |
| 63 | + if (sessionId) { |
| 64 | + const transport = sessions.get(sessionId); |
| 65 | + if (!transport) { |
| 66 | + res.statusCode = 404; |
| 67 | + res.end('Session not found'); |
| 68 | + return; |
| 69 | + } |
| 70 | + return await transport.handleRequest(req, res); |
| 71 | + } |
| 72 | + |
| 73 | + if (req.method === 'POST') { |
| 74 | + const transport = new StreamableHTTPServerTransport({ |
| 75 | + sessionIdGenerator: () => crypto.randomUUID(), |
| 76 | + onsessioninitialized: sessionId => { |
| 77 | + sessions.set(sessionId, transport); |
| 78 | + } |
| 79 | + }); |
| 80 | + transport.onclose = () => { |
| 81 | + if (transport.sessionId) |
| 82 | + sessions.delete(transport.sessionId); |
| 83 | + }; |
| 84 | + const server = await serverList.create(); |
| 85 | + await server.connect(transport); |
| 86 | + return await transport.handleRequest(req, res); |
| 87 | + } |
| 88 | + |
| 89 | + res.statusCode = 400; |
| 90 | + res.end('Invalid request'); |
| 91 | +} |
| 92 | + |
| 93 | +export function startHttpTransport(port: number, hostname: string | undefined, serverList: ServerList) { |
| 94 | + const sseSessions = new Map<string, SSEServerTransport>(); |
| 95 | + const streamableSessions = new Map<string, StreamableHTTPServerTransport>(); |
| 96 | + const httpServer = http.createServer(async (req, res) => { |
| 97 | + const url = new URL(`http://localhost${req.url}`); |
| 98 | + if (url.pathname.startsWith('/mcp')) |
| 99 | + await handleStreamable(req, res, serverList, streamableSessions); |
| 100 | + else |
| 101 | + await handleSSE(req, res, url, serverList, sseSessions); |
| 102 | + }); |
| 103 | + httpServer.listen(port, hostname, () => { |
| 104 | + const address = httpServer.address(); |
| 105 | + assert(address, 'Could not bind server socket'); |
| 106 | + let url: string; |
| 107 | + if (typeof address === 'string') { |
| 108 | + url = address; |
| 109 | + } else { |
| 110 | + const resolvedPort = address.port; |
| 111 | + let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`; |
| 112 | + if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]') |
| 113 | + resolvedHost = 'localhost'; |
| 114 | + url = `http://${resolvedHost}:${resolvedPort}`; |
| 115 | + } |
| 116 | + console.log(`Listening on ${url}`); |
| 117 | + console.log('Put this in your client config:'); |
| 118 | + console.log(JSON.stringify({ |
| 119 | + 'mcpServers': { |
| 120 | + 'playwright': { |
| 121 | + 'url': `${url}/sse` |
| 122 | + } |
| 123 | + } |
| 124 | + }, undefined, 2)); |
| 125 | + console.log('If your client supports streamable HTTP, you can use the /mcp endpoint instead.'); |
| 126 | + }); |
| 127 | +} |
0 commit comments