|
1 | 1 | import express from "express"; |
2 | 2 | import http from "http"; |
3 | 3 | import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; |
| 4 | +import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; |
4 | 5 | import { TransportRunnerBase } from "./base.js"; |
5 | 6 | import { config } from "../common/config.js"; |
6 | 7 | import logger, { LogId } from "../common/logger.js"; |
| 8 | +import { randomUUID } from "crypto"; |
| 9 | +import { SessionStore } from "../common/sessionStore.js"; |
7 | 10 |
|
8 | 11 | const JSON_RPC_ERROR_CODE_PROCESSING_REQUEST_FAILED = -32000; |
9 | | -const JSON_RPC_ERROR_CODE_METHOD_NOT_ALLOWED = -32601; |
| 12 | +const JSON_RPC_ERROR_CODE_SESSION_ID_REQUIRED = -32001; |
| 13 | +const JSON_RPC_ERROR_CODE_SESSION_NOT_FOUND = -32002; |
| 14 | +const JSON_RPC_ERROR_CODE_INVALID_REQUEST = -32003; |
10 | 15 |
|
11 | 16 | function promiseHandler( |
12 | 17 | fn: (req: express.Request, res: express.Response, next: express.NextFunction) => Promise<void> |
13 | 18 | ) { |
14 | 19 | return (req: express.Request, res: express.Response, next: express.NextFunction) => { |
15 | | - fn(req, res, next).catch(next); |
| 20 | + fn(req, res, next).catch((error) => { |
| 21 | + logger.error( |
| 22 | + LogId.streamableHttpTransportRequestFailure, |
| 23 | + "streamableHttpTransport", |
| 24 | + `Error handling request: ${error instanceof Error ? error.message : String(error)}` |
| 25 | + ); |
| 26 | + res.status(400).json({ |
| 27 | + jsonrpc: "2.0", |
| 28 | + error: { |
| 29 | + code: JSON_RPC_ERROR_CODE_PROCESSING_REQUEST_FAILED, |
| 30 | + message: `failed to handle request`, |
| 31 | + data: error instanceof Error ? error.message : String(error), |
| 32 | + }, |
| 33 | + }); |
| 34 | + }); |
16 | 35 | }; |
17 | 36 | } |
18 | 37 |
|
19 | 38 | export class StreamableHttpRunner extends TransportRunnerBase { |
20 | 39 | private httpServer: http.Server | undefined; |
| 40 | + private sessionStore: SessionStore = new SessionStore(); |
21 | 41 |
|
22 | 42 | async start() { |
23 | 43 | const app = express(); |
24 | 44 | app.enable("trust proxy"); // needed for reverse proxy support |
25 | | - app.use(express.urlencoded({ extended: true })); |
26 | 45 | app.use(express.json()); |
27 | 46 |
|
| 47 | + const handleRequest = async (req: express.Request, res: express.Response) => { |
| 48 | + const sessionId = req.headers["mcp-session-id"] as string; |
| 49 | + if (!sessionId) { |
| 50 | + res.status(400).json({ |
| 51 | + jsonrpc: "2.0", |
| 52 | + error: { |
| 53 | + code: JSON_RPC_ERROR_CODE_SESSION_ID_REQUIRED, |
| 54 | + message: `session id is required`, |
| 55 | + }, |
| 56 | + }); |
| 57 | + return; |
| 58 | + } |
| 59 | + const transport = this.sessionStore.getSession(sessionId); |
| 60 | + if (!transport) { |
| 61 | + res.status(404).json({ |
| 62 | + jsonrpc: "2.0", |
| 63 | + error: { |
| 64 | + code: JSON_RPC_ERROR_CODE_SESSION_NOT_FOUND, |
| 65 | + message: `session not found`, |
| 66 | + }, |
| 67 | + }); |
| 68 | + return; |
| 69 | + } |
| 70 | + await transport.handleRequest(req, res, req.body); |
| 71 | + }; |
| 72 | + |
28 | 73 | app.post( |
29 | 74 | "/mcp", |
30 | 75 | promiseHandler(async (req: express.Request, res: express.Response) => { |
31 | | - const transport = new StreamableHTTPServerTransport({ |
32 | | - sessionIdGenerator: undefined, |
33 | | - }); |
| 76 | + const sessionId = req.headers["mcp-session-id"] as string; |
| 77 | + if (sessionId) { |
| 78 | + await handleRequest(req, res); |
| 79 | + return; |
| 80 | + } |
34 | 81 |
|
35 | | - const server = this.setupServer(); |
| 82 | + if (!isInitializeRequest(req.body)) { |
| 83 | + res.status(400).json({ |
| 84 | + jsonrpc: "2.0", |
| 85 | + error: { |
| 86 | + code: JSON_RPC_ERROR_CODE_INVALID_REQUEST, |
| 87 | + message: `invalid request`, |
| 88 | + }, |
| 89 | + }); |
| 90 | + return; |
| 91 | + } |
36 | 92 |
|
37 | | - await server.connect(transport); |
| 93 | + const server = this.setupServer(); |
| 94 | + const transport = new StreamableHTTPServerTransport({ |
| 95 | + sessionIdGenerator: () => randomUUID().toString(), |
| 96 | + onsessioninitialized: (sessionId) => { |
| 97 | + this.sessionStore.setSession(sessionId, transport); |
| 98 | + }, |
| 99 | + onsessionclosed: async (sessionId) => { |
| 100 | + try { |
| 101 | + await this.sessionStore.closeSession(sessionId, false); |
| 102 | + } catch (error) { |
| 103 | + logger.error( |
| 104 | + LogId.streamableHttpTransportSessionCloseFailure, |
| 105 | + "streamableHttpTransport", |
| 106 | + `Error closing session: ${error instanceof Error ? error.message : String(error)}` |
| 107 | + ); |
| 108 | + } |
| 109 | + }, |
| 110 | + }); |
38 | 111 |
|
39 | | - res.on("close", () => { |
40 | | - Promise.all([transport.close(), server.close()]).catch((error: unknown) => { |
| 112 | + transport.onclose = () => { |
| 113 | + server.close().catch((error) => { |
41 | 114 | logger.error( |
42 | 115 | LogId.streamableHttpTransportCloseFailure, |
43 | 116 | "streamableHttpTransport", |
44 | 117 | `Error closing server: ${error instanceof Error ? error.message : String(error)}` |
45 | 118 | ); |
46 | 119 | }); |
47 | | - }); |
| 120 | + }; |
48 | 121 |
|
49 | | - try { |
50 | | - await transport.handleRequest(req, res, req.body); |
51 | | - } catch (error) { |
52 | | - logger.error( |
53 | | - LogId.streamableHttpTransportRequestFailure, |
54 | | - "streamableHttpTransport", |
55 | | - `Error handling request: ${error instanceof Error ? error.message : String(error)}` |
56 | | - ); |
57 | | - res.status(400).json({ |
58 | | - jsonrpc: "2.0", |
59 | | - error: { |
60 | | - code: JSON_RPC_ERROR_CODE_PROCESSING_REQUEST_FAILED, |
61 | | - message: `failed to handle request`, |
62 | | - data: error instanceof Error ? error.message : String(error), |
63 | | - }, |
64 | | - }); |
65 | | - } |
| 122 | + await server.connect(transport); |
| 123 | + |
| 124 | + await transport.handleRequest(req, res, req.body); |
66 | 125 | }) |
67 | 126 | ); |
68 | 127 |
|
69 | | - app.get("/mcp", (req: express.Request, res: express.Response) => { |
70 | | - res.status(405).json({ |
71 | | - jsonrpc: "2.0", |
72 | | - error: { |
73 | | - code: JSON_RPC_ERROR_CODE_METHOD_NOT_ALLOWED, |
74 | | - message: `method not allowed`, |
75 | | - }, |
76 | | - }); |
77 | | - }); |
78 | | - |
79 | | - app.delete("/mcp", (req: express.Request, res: express.Response) => { |
80 | | - res.status(405).json({ |
81 | | - jsonrpc: "2.0", |
82 | | - error: { |
83 | | - code: JSON_RPC_ERROR_CODE_METHOD_NOT_ALLOWED, |
84 | | - message: `method not allowed`, |
85 | | - }, |
86 | | - }); |
87 | | - }); |
| 128 | + app.get("/mcp", promiseHandler(handleRequest)); |
| 129 | + app.delete("/mcp", promiseHandler(handleRequest)); |
88 | 130 |
|
89 | 131 | this.httpServer = await new Promise<http.Server>((resolve, reject) => { |
90 | 132 | const result = app.listen(config.httpPort, config.httpHost, (err?: Error) => { |
|
0 commit comments