@@ -211,7 +211,7 @@ await server.connect(transport);
211
211
For remote servers, start a web server with a Server-Sent Events (SSE) endpoint, and a separate endpoint for the client to send its messages to:
212
212
213
213
``` typescript
214
- import express from " express" ;
214
+ import express , { Request , Response } from " express" ;
215
215
import { McpServer } from " @modelcontextprotocol/sdk/server/mcp.js" ;
216
216
import { SSEServerTransport } from " @modelcontextprotocol/sdk/server/sse.js" ;
217
217
@@ -224,16 +224,27 @@ const server = new McpServer({
224
224
225
225
const app = express ();
226
226
227
- app .get (" /sse" , async (req , res ) => {
228
- const transport = new SSEServerTransport (" /messages" , res );
227
+ // to support multiple simultaneous connections we have a lookup object from
228
+ // sessionId to transport
229
+ const transports: {[sessionId : string ]: SSEServerTransport } = {};
230
+
231
+ app .get (" /sse" , async (_ : Request , res : Response ) => {
232
+ const transport = new SSEServerTransport (' /messages' , res );
233
+ transports [transport .sessionId ] = transport ;
234
+ res .on (" close" , () => {
235
+ delete transports [transport .sessionId ];
236
+ });
229
237
await server .connect (transport );
230
238
});
231
239
232
- app .post (" /messages" , async (req , res ) => {
233
- // Note: to support multiple simultaneous connections, these messages will
234
- // need to be routed to a specific matching transport. (This logic isn't
235
- // implemented here, for simplicity.)
236
- await transport .handlePostMessage (req , res );
240
+ app .post (" /messages" , async (req : Request , res : Response ) => {
241
+ const sessionId = req .query .sessionId as string ;
242
+ const transport = transports [sessionId ];
243
+ if (transport ) {
244
+ await transport .handlePostMessage (req , res );
245
+ } else {
246
+ res .status (400 ).send (' No transport found for sessionId' );
247
+ }
237
248
});
238
249
239
250
app .listen (3001 );
0 commit comments