@modelcontextprotocol/sdk 1.24.2 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/dist/cjs/client/auth-extensions.js +5 -9
  2. package/dist/cjs/client/auth-extensions.js.map +1 -1
  3. package/dist/cjs/client/auth.js +30 -37
  4. package/dist/cjs/client/auth.js.map +1 -1
  5. package/dist/cjs/client/index.d.ts +61 -14
  6. package/dist/cjs/client/index.d.ts.map +1 -1
  7. package/dist/cjs/client/index.js +117 -36
  8. package/dist/cjs/client/index.js.map +1 -1
  9. package/dist/cjs/client/middleware.js +3 -3
  10. package/dist/cjs/client/middleware.js.map +1 -1
  11. package/dist/cjs/client/sse.d.ts.map +1 -1
  12. package/dist/cjs/client/sse.js +20 -26
  13. package/dist/cjs/client/sse.js.map +1 -1
  14. package/dist/cjs/client/stdio.js +18 -28
  15. package/dist/cjs/client/stdio.js.map +1 -1
  16. package/dist/cjs/client/streamableHttp.d.ts.map +1 -1
  17. package/dist/cjs/client/streamableHttp.js +42 -47
  18. package/dist/cjs/client/streamableHttp.js.map +1 -1
  19. package/dist/cjs/client/websocket.js +6 -11
  20. package/dist/cjs/client/websocket.js.map +1 -1
  21. package/dist/cjs/examples/client/elicitationUrlExample.js +4 -5
  22. package/dist/cjs/examples/client/elicitationUrlExample.js.map +1 -1
  23. package/dist/cjs/examples/client/simpleOAuthClient.js +3 -3
  24. package/dist/cjs/examples/client/simpleOAuthClient.js.map +1 -1
  25. package/dist/cjs/examples/client/simpleStreamableHttp.js +7 -9
  26. package/dist/cjs/examples/client/simpleStreamableHttp.js.map +1 -1
  27. package/dist/cjs/examples/client/simpleTaskInteractiveClient.js +1 -2
  28. package/dist/cjs/examples/client/simpleTaskInteractiveClient.js.map +1 -1
  29. package/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts +10 -0
  30. package/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts.map +1 -0
  31. package/dist/cjs/examples/server/honoWebStandardStreamableHttp.js +81 -0
  32. package/dist/cjs/examples/server/honoWebStandardStreamableHttp.js.map +1 -0
  33. package/dist/cjs/examples/server/jsonResponseStreamableHttp.js +10 -4
  34. package/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map +1 -1
  35. package/dist/cjs/examples/server/simpleSseServer.js +6 -3
  36. package/dist/cjs/examples/server/simpleSseServer.js.map +1 -1
  37. package/dist/cjs/examples/server/simpleStatelessStreamableHttp.js +12 -6
  38. package/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map +1 -1
  39. package/dist/cjs/examples/server/simpleStreamableHttp.js +21 -11
  40. package/dist/cjs/examples/server/simpleStreamableHttp.js.map +1 -1
  41. package/dist/cjs/examples/server/simpleTaskInteractive.js +7 -11
  42. package/dist/cjs/examples/server/simpleTaskInteractive.js.map +1 -1
  43. package/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js +10 -7
  44. package/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map +1 -1
  45. package/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js +1 -1
  46. package/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map +1 -1
  47. package/dist/cjs/experimental/tasks/client.js +1 -2
  48. package/dist/cjs/experimental/tasks/client.js.map +1 -1
  49. package/dist/cjs/experimental/tasks/helpers.js +3 -5
  50. package/dist/cjs/experimental/tasks/helpers.js.map +1 -1
  51. package/dist/cjs/experimental/tasks/interfaces.d.ts +3 -3
  52. package/dist/cjs/experimental/tasks/interfaces.d.ts.map +1 -1
  53. package/dist/cjs/experimental/tasks/stores/in-memory.d.ts +1 -1
  54. package/dist/cjs/experimental/tasks/stores/in-memory.d.ts.map +1 -1
  55. package/dist/cjs/experimental/tasks/stores/in-memory.js +3 -5
  56. package/dist/cjs/experimental/tasks/stores/in-memory.js.map +1 -1
  57. package/dist/cjs/inMemory.js +5 -7
  58. package/dist/cjs/inMemory.js.map +1 -1
  59. package/dist/cjs/server/auth/handlers/token.js +1 -1
  60. package/dist/cjs/server/auth/handlers/token.js.map +1 -1
  61. package/dist/cjs/server/auth/providers/proxyProvider.js +11 -17
  62. package/dist/cjs/server/auth/providers/proxyProvider.js.map +1 -1
  63. package/dist/cjs/server/auth/router.js +3 -6
  64. package/dist/cjs/server/auth/router.js.map +1 -1
  65. package/dist/cjs/server/completable.js +1 -1
  66. package/dist/cjs/server/completable.js.map +1 -1
  67. package/dist/cjs/server/index.d.ts +3 -3
  68. package/dist/cjs/server/index.d.ts.map +1 -1
  69. package/dist/cjs/server/index.js +20 -30
  70. package/dist/cjs/server/index.js.map +1 -1
  71. package/dist/cjs/server/mcp.d.ts.map +1 -1
  72. package/dist/cjs/server/mcp.js +25 -11
  73. package/dist/cjs/server/mcp.js.map +1 -1
  74. package/dist/cjs/server/middleware/hostHeaderValidation.js +1 -1
  75. package/dist/cjs/server/middleware/hostHeaderValidation.js.map +1 -1
  76. package/dist/cjs/server/sse.js +14 -17
  77. package/dist/cjs/server/sse.js.map +1 -1
  78. package/dist/cjs/server/stdio.js +4 -7
  79. package/dist/cjs/server/stdio.js.map +1 -1
  80. package/dist/cjs/server/streamableHttp.d.ts +52 -153
  81. package/dist/cjs/server/streamableHttp.d.ts.map +1 -1
  82. package/dist/cjs/server/streamableHttp.js +78 -636
  83. package/dist/cjs/server/streamableHttp.js.map +1 -1
  84. package/dist/cjs/server/webStandardStreamableHttp.d.ts +267 -0
  85. package/dist/cjs/server/webStandardStreamableHttp.d.ts.map +1 -0
  86. package/dist/cjs/server/webStandardStreamableHttp.js +729 -0
  87. package/dist/cjs/server/webStandardStreamableHttp.js.map +1 -0
  88. package/dist/cjs/server/zod-compat.d.ts +3 -1
  89. package/dist/cjs/server/zod-compat.d.ts.map +1 -1
  90. package/dist/cjs/server/zod-compat.js +11 -19
  91. package/dist/cjs/server/zod-compat.js.map +1 -1
  92. package/dist/cjs/server/zod-json-schema-compat.js +5 -6
  93. package/dist/cjs/server/zod-json-schema-compat.js.map +1 -1
  94. package/dist/cjs/shared/metadataUtils.js +1 -2
  95. package/dist/cjs/shared/metadataUtils.js.map +1 -1
  96. package/dist/cjs/shared/protocol.d.ts +1 -1
  97. package/dist/cjs/shared/protocol.d.ts.map +1 -1
  98. package/dist/cjs/shared/protocol.js +76 -88
  99. package/dist/cjs/shared/protocol.js.map +1 -1
  100. package/dist/cjs/shared/transport.js +1 -1
  101. package/dist/cjs/shared/transport.js.map +1 -1
  102. package/dist/cjs/spec.types.d.ts +315 -26
  103. package/dist/cjs/spec.types.d.ts.map +1 -1
  104. package/dist/cjs/spec.types.js +2 -2
  105. package/dist/cjs/spec.types.js.map +1 -1
  106. package/dist/cjs/types.d.ts +1392 -1248
  107. package/dist/cjs/types.d.ts.map +1 -1
  108. package/dist/cjs/types.js +201 -136
  109. package/dist/cjs/types.js.map +1 -1
  110. package/dist/cjs/validation/ajv-provider.d.ts +1 -1
  111. package/dist/cjs/validation/ajv-provider.d.ts.map +1 -1
  112. package/dist/cjs/validation/ajv-provider.js +4 -5
  113. package/dist/cjs/validation/ajv-provider.js.map +1 -1
  114. package/dist/cjs/validation/cfworker-provider.js +4 -5
  115. package/dist/cjs/validation/cfworker-provider.js.map +1 -1
  116. package/dist/cjs/validation/types.d.ts +12 -2
  117. package/dist/cjs/validation/types.d.ts.map +1 -1
  118. package/dist/esm/client/auth-extensions.js +5 -9
  119. package/dist/esm/client/auth-extensions.js.map +1 -1
  120. package/dist/esm/client/auth.js +30 -37
  121. package/dist/esm/client/auth.js.map +1 -1
  122. package/dist/esm/client/index.d.ts +61 -14
  123. package/dist/esm/client/index.d.ts.map +1 -1
  124. package/dist/esm/client/index.js +118 -37
  125. package/dist/esm/client/index.js.map +1 -1
  126. package/dist/esm/client/middleware.js +3 -3
  127. package/dist/esm/client/middleware.js.map +1 -1
  128. package/dist/esm/client/sse.d.ts.map +1 -1
  129. package/dist/esm/client/sse.js +20 -26
  130. package/dist/esm/client/sse.js.map +1 -1
  131. package/dist/esm/client/stdio.js +18 -28
  132. package/dist/esm/client/stdio.js.map +1 -1
  133. package/dist/esm/client/streamableHttp.d.ts.map +1 -1
  134. package/dist/esm/client/streamableHttp.js +43 -48
  135. package/dist/esm/client/streamableHttp.js.map +1 -1
  136. package/dist/esm/client/websocket.js +6 -11
  137. package/dist/esm/client/websocket.js.map +1 -1
  138. package/dist/esm/examples/client/elicitationUrlExample.js +4 -5
  139. package/dist/esm/examples/client/elicitationUrlExample.js.map +1 -1
  140. package/dist/esm/examples/client/simpleOAuthClient.js +3 -3
  141. package/dist/esm/examples/client/simpleOAuthClient.js.map +1 -1
  142. package/dist/esm/examples/client/simpleStreamableHttp.js +7 -9
  143. package/dist/esm/examples/client/simpleStreamableHttp.js.map +1 -1
  144. package/dist/esm/examples/client/simpleTaskInteractiveClient.js +1 -2
  145. package/dist/esm/examples/client/simpleTaskInteractiveClient.js.map +1 -1
  146. package/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts +10 -0
  147. package/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts.map +1 -0
  148. package/dist/esm/examples/server/honoWebStandardStreamableHttp.js +56 -0
  149. package/dist/esm/examples/server/honoWebStandardStreamableHttp.js.map +1 -0
  150. package/dist/esm/examples/server/jsonResponseStreamableHttp.js +10 -4
  151. package/dist/esm/examples/server/jsonResponseStreamableHttp.js.map +1 -1
  152. package/dist/esm/examples/server/simpleSseServer.js +6 -3
  153. package/dist/esm/examples/server/simpleSseServer.js.map +1 -1
  154. package/dist/esm/examples/server/simpleStatelessStreamableHttp.js +12 -6
  155. package/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map +1 -1
  156. package/dist/esm/examples/server/simpleStreamableHttp.js +21 -11
  157. package/dist/esm/examples/server/simpleStreamableHttp.js.map +1 -1
  158. package/dist/esm/examples/server/simpleTaskInteractive.js +7 -11
  159. package/dist/esm/examples/server/simpleTaskInteractive.js.map +1 -1
  160. package/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js +10 -7
  161. package/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map +1 -1
  162. package/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js +1 -1
  163. package/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map +1 -1
  164. package/dist/esm/experimental/tasks/client.js +1 -2
  165. package/dist/esm/experimental/tasks/client.js.map +1 -1
  166. package/dist/esm/experimental/tasks/helpers.js +3 -5
  167. package/dist/esm/experimental/tasks/helpers.js.map +1 -1
  168. package/dist/esm/experimental/tasks/interfaces.d.ts +3 -3
  169. package/dist/esm/experimental/tasks/interfaces.d.ts.map +1 -1
  170. package/dist/esm/experimental/tasks/stores/in-memory.d.ts +1 -1
  171. package/dist/esm/experimental/tasks/stores/in-memory.d.ts.map +1 -1
  172. package/dist/esm/experimental/tasks/stores/in-memory.js +3 -5
  173. package/dist/esm/experimental/tasks/stores/in-memory.js.map +1 -1
  174. package/dist/esm/inMemory.js +5 -7
  175. package/dist/esm/inMemory.js.map +1 -1
  176. package/dist/esm/server/auth/handlers/token.js +1 -1
  177. package/dist/esm/server/auth/handlers/token.js.map +1 -1
  178. package/dist/esm/server/auth/providers/proxyProvider.js +11 -17
  179. package/dist/esm/server/auth/providers/proxyProvider.js.map +1 -1
  180. package/dist/esm/server/auth/router.js +3 -6
  181. package/dist/esm/server/auth/router.js.map +1 -1
  182. package/dist/esm/server/completable.js +1 -1
  183. package/dist/esm/server/completable.js.map +1 -1
  184. package/dist/esm/server/index.d.ts +3 -3
  185. package/dist/esm/server/index.d.ts.map +1 -1
  186. package/dist/esm/server/index.js +20 -30
  187. package/dist/esm/server/index.js.map +1 -1
  188. package/dist/esm/server/mcp.d.ts.map +1 -1
  189. package/dist/esm/server/mcp.js +25 -11
  190. package/dist/esm/server/mcp.js.map +1 -1
  191. package/dist/esm/server/middleware/hostHeaderValidation.js +1 -1
  192. package/dist/esm/server/middleware/hostHeaderValidation.js.map +1 -1
  193. package/dist/esm/server/sse.js +14 -17
  194. package/dist/esm/server/sse.js.map +1 -1
  195. package/dist/esm/server/stdio.js +4 -7
  196. package/dist/esm/server/stdio.js.map +1 -1
  197. package/dist/esm/server/streamableHttp.d.ts +52 -153
  198. package/dist/esm/server/streamableHttp.d.ts.map +1 -1
  199. package/dist/esm/server/streamableHttp.js +78 -633
  200. package/dist/esm/server/streamableHttp.js.map +1 -1
  201. package/dist/esm/server/webStandardStreamableHttp.d.ts +267 -0
  202. package/dist/esm/server/webStandardStreamableHttp.d.ts.map +1 -0
  203. package/dist/esm/server/webStandardStreamableHttp.js +725 -0
  204. package/dist/esm/server/webStandardStreamableHttp.js.map +1 -0
  205. package/dist/esm/server/zod-compat.d.ts +3 -1
  206. package/dist/esm/server/zod-compat.d.ts.map +1 -1
  207. package/dist/esm/server/zod-compat.js +11 -19
  208. package/dist/esm/server/zod-compat.js.map +1 -1
  209. package/dist/esm/server/zod-json-schema-compat.js +5 -6
  210. package/dist/esm/server/zod-json-schema-compat.js.map +1 -1
  211. package/dist/esm/shared/metadataUtils.js +1 -2
  212. package/dist/esm/shared/metadataUtils.js.map +1 -1
  213. package/dist/esm/shared/protocol.d.ts +1 -1
  214. package/dist/esm/shared/protocol.d.ts.map +1 -1
  215. package/dist/esm/shared/protocol.js +77 -89
  216. package/dist/esm/shared/protocol.js.map +1 -1
  217. package/dist/esm/shared/transport.js +1 -1
  218. package/dist/esm/shared/transport.js.map +1 -1
  219. package/dist/esm/spec.types.d.ts +315 -26
  220. package/dist/esm/spec.types.d.ts.map +1 -1
  221. package/dist/esm/spec.types.js +2 -2
  222. package/dist/esm/spec.types.js.map +1 -1
  223. package/dist/esm/types.d.ts +1392 -1248
  224. package/dist/esm/types.d.ts.map +1 -1
  225. package/dist/esm/types.js +194 -130
  226. package/dist/esm/types.js.map +1 -1
  227. package/dist/esm/validation/ajv-provider.d.ts +1 -1
  228. package/dist/esm/validation/ajv-provider.d.ts.map +1 -1
  229. package/dist/esm/validation/ajv-provider.js +3 -4
  230. package/dist/esm/validation/ajv-provider.js.map +1 -1
  231. package/dist/esm/validation/cfworker-provider.js +4 -5
  232. package/dist/esm/validation/cfworker-provider.js.map +1 -1
  233. package/dist/esm/validation/types.d.ts +12 -2
  234. package/dist/esm/validation/types.d.ts.map +1 -1
  235. package/package.json +4 -2
@@ -1,18 +1,23 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ /**
3
+ * Node.js HTTP Streamable HTTP Server Transport
4
+ *
5
+ * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides
6
+ * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse).
7
+ *
8
+ * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly.
9
+ */
5
10
  Object.defineProperty(exports, "__esModule", { value: true });
6
11
  exports.StreamableHTTPServerTransport = void 0;
7
- const types_js_1 = require("../types.js");
8
- const raw_body_1 = __importDefault(require("raw-body"));
9
- const content_type_1 = __importDefault(require("content-type"));
10
- const node_crypto_1 = require("node:crypto");
11
- const MAXIMUM_MESSAGE_SIZE = '4mb';
12
+ const node_server_1 = require("@hono/node-server");
13
+ const webStandardStreamableHttp_js_1 = require("./webStandardStreamableHttp.js");
12
14
  /**
13
15
  * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
14
16
  * It supports both SSE streaming and direct HTTP responses.
15
17
  *
18
+ * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility.
19
+ * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs.
20
+ *
16
21
  * Usage example:
17
22
  *
18
23
  * ```typescript
@@ -44,562 +49,97 @@ const MAXIMUM_MESSAGE_SIZE = '4mb';
44
49
  * - No session validation is performed
45
50
  */
46
51
  class StreamableHTTPServerTransport {
47
- constructor(options) {
48
- var _a, _b;
49
- this._started = false;
50
- this._streamMapping = new Map();
51
- this._requestToStreamMapping = new Map();
52
- this._requestResponseMap = new Map();
53
- this._initialized = false;
54
- this._enableJsonResponse = false;
55
- this._standaloneSseStreamId = '_GET_stream';
56
- this.sessionIdGenerator = options.sessionIdGenerator;
57
- this._enableJsonResponse = (_a = options.enableJsonResponse) !== null && _a !== void 0 ? _a : false;
58
- this._eventStore = options.eventStore;
59
- this._onsessioninitialized = options.onsessioninitialized;
60
- this._onsessionclosed = options.onsessionclosed;
61
- this._allowedHosts = options.allowedHosts;
62
- this._allowedOrigins = options.allowedOrigins;
63
- this._enableDnsRebindingProtection = (_b = options.enableDnsRebindingProtection) !== null && _b !== void 0 ? _b : false;
64
- this._retryInterval = options.retryInterval;
52
+ constructor(options = {}) {
53
+ // Store auth and parsedBody per request for passing through to handleRequest
54
+ this._requestContext = new WeakMap();
55
+ this._webStandardTransport = new webStandardStreamableHttp_js_1.WebStandardStreamableHTTPServerTransport(options);
56
+ // Create a request listener that wraps the web standard transport
57
+ // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming
58
+ this._requestListener = (0, node_server_1.getRequestListener)(async (webRequest) => {
59
+ // Get context if available (set during handleRequest)
60
+ const context = this._requestContext.get(webRequest);
61
+ return this._webStandardTransport.handleRequest(webRequest, {
62
+ authInfo: context?.authInfo,
63
+ parsedBody: context?.parsedBody
64
+ });
65
+ });
65
66
  }
66
67
  /**
67
- * Starts the transport. This is required by the Transport interface but is a no-op
68
- * for the Streamable HTTP transport as connections are managed per-request.
68
+ * Gets the session ID for this transport instance.
69
69
  */
70
- async start() {
71
- if (this._started) {
72
- throw new Error('Transport already started');
73
- }
74
- this._started = true;
70
+ get sessionId() {
71
+ return this._webStandardTransport.sessionId;
75
72
  }
76
73
  /**
77
- * Validates request headers for DNS rebinding protection.
78
- * @returns Error message if validation fails, undefined if validation passes.
74
+ * Sets callback for when the transport is closed.
79
75
  */
80
- validateRequestHeaders(req) {
81
- // Skip validation if protection is not enabled
82
- if (!this._enableDnsRebindingProtection) {
83
- return undefined;
84
- }
85
- // Validate Host header if allowedHosts is configured
86
- if (this._allowedHosts && this._allowedHosts.length > 0) {
87
- const hostHeader = req.headers.host;
88
- if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {
89
- return `Invalid Host header: ${hostHeader}`;
90
- }
91
- }
92
- // Validate Origin header if allowedOrigins is configured
93
- if (this._allowedOrigins && this._allowedOrigins.length > 0) {
94
- const originHeader = req.headers.origin;
95
- if (originHeader && !this._allowedOrigins.includes(originHeader)) {
96
- return `Invalid Origin header: ${originHeader}`;
97
- }
98
- }
99
- return undefined;
76
+ set onclose(handler) {
77
+ this._webStandardTransport.onclose = handler;
100
78
  }
101
- /**
102
- * Handles an incoming HTTP request, whether GET or POST
103
- */
104
- async handleRequest(req, res, parsedBody) {
105
- var _a;
106
- // Validate request headers for DNS rebinding protection
107
- const validationError = this.validateRequestHeaders(req);
108
- if (validationError) {
109
- res.writeHead(403).end(JSON.stringify({
110
- jsonrpc: '2.0',
111
- error: {
112
- code: -32000,
113
- message: validationError
114
- },
115
- id: null
116
- }));
117
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError));
118
- return;
119
- }
120
- if (req.method === 'POST') {
121
- await this.handlePostRequest(req, res, parsedBody);
122
- }
123
- else if (req.method === 'GET') {
124
- await this.handleGetRequest(req, res);
125
- }
126
- else if (req.method === 'DELETE') {
127
- await this.handleDeleteRequest(req, res);
128
- }
129
- else {
130
- await this.handleUnsupportedRequest(res);
131
- }
79
+ get onclose() {
80
+ return this._webStandardTransport.onclose;
132
81
  }
133
82
  /**
134
- * Writes a priming event to establish resumption capability.
135
- * Only sends if eventStore is configured (opt-in for resumability).
83
+ * Sets callback for transport errors.
136
84
  */
137
- async _maybeWritePrimingEvent(res, streamId) {
138
- if (!this._eventStore) {
139
- return;
140
- }
141
- const primingEventId = await this._eventStore.storeEvent(streamId, {});
142
- let primingEvent = `id: ${primingEventId}\ndata: \n\n`;
143
- if (this._retryInterval !== undefined) {
144
- primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`;
145
- }
146
- res.write(primingEvent);
85
+ set onerror(handler) {
86
+ this._webStandardTransport.onerror = handler;
147
87
  }
148
- /**
149
- * Handles GET requests for SSE stream
150
- */
151
- async handleGetRequest(req, res) {
152
- // The client MUST include an Accept header, listing text/event-stream as a supported content type.
153
- const acceptHeader = req.headers.accept;
154
- if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('text/event-stream'))) {
155
- res.writeHead(406).end(JSON.stringify({
156
- jsonrpc: '2.0',
157
- error: {
158
- code: -32000,
159
- message: 'Not Acceptable: Client must accept text/event-stream'
160
- },
161
- id: null
162
- }));
163
- return;
164
- }
165
- // If an Mcp-Session-Id is returned by the server during initialization,
166
- // clients using the Streamable HTTP transport MUST include it
167
- // in the Mcp-Session-Id header on all of their subsequent HTTP requests.
168
- if (!this.validateSession(req, res)) {
169
- return;
170
- }
171
- if (!this.validateProtocolVersion(req, res)) {
172
- return;
173
- }
174
- // Handle resumability: check for Last-Event-ID header
175
- if (this._eventStore) {
176
- const lastEventId = req.headers['last-event-id'];
177
- if (lastEventId) {
178
- await this.replayEvents(lastEventId, res);
179
- return;
180
- }
181
- }
182
- // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET,
183
- // or else return HTTP 405 Method Not Allowed
184
- const headers = {
185
- 'Content-Type': 'text/event-stream',
186
- 'Cache-Control': 'no-cache, no-transform',
187
- Connection: 'keep-alive'
188
- };
189
- // After initialization, always include the session ID if we have one
190
- if (this.sessionId !== undefined) {
191
- headers['mcp-session-id'] = this.sessionId;
192
- }
193
- // Check if there's already an active standalone SSE stream for this session
194
- if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) {
195
- // Only one GET SSE stream is allowed per session
196
- res.writeHead(409).end(JSON.stringify({
197
- jsonrpc: '2.0',
198
- error: {
199
- code: -32000,
200
- message: 'Conflict: Only one SSE stream is allowed per session'
201
- },
202
- id: null
203
- }));
204
- return;
205
- }
206
- // We need to send headers immediately as messages will arrive much later,
207
- // otherwise the client will just wait for the first message
208
- res.writeHead(200, headers).flushHeaders();
209
- // Assign the response to the standalone SSE stream
210
- this._streamMapping.set(this._standaloneSseStreamId, res);
211
- // Set up close handler for client disconnects
212
- res.on('close', () => {
213
- this._streamMapping.delete(this._standaloneSseStreamId);
214
- });
215
- // Add error handler for standalone SSE stream
216
- res.on('error', error => {
217
- var _a;
218
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);
219
- });
88
+ get onerror() {
89
+ return this._webStandardTransport.onerror;
220
90
  }
221
91
  /**
222
- * Replays events that would have been sent after the specified event ID
223
- * Only used when resumability is enabled
92
+ * Sets callback for incoming messages.
224
93
  */
225
- async replayEvents(lastEventId, res) {
226
- var _a;
227
- if (!this._eventStore) {
228
- return;
229
- }
230
- try {
231
- // If getStreamIdForEventId is available, use it for conflict checking
232
- let streamId;
233
- if (this._eventStore.getStreamIdForEventId) {
234
- streamId = await this._eventStore.getStreamIdForEventId(lastEventId);
235
- if (!streamId) {
236
- res.writeHead(400).end(JSON.stringify({
237
- jsonrpc: '2.0',
238
- error: {
239
- code: -32000,
240
- message: 'Invalid event ID format'
241
- },
242
- id: null
243
- }));
244
- return;
245
- }
246
- // Check conflict with the SAME streamId we'll use for mapping
247
- if (this._streamMapping.get(streamId) !== undefined) {
248
- res.writeHead(409).end(JSON.stringify({
249
- jsonrpc: '2.0',
250
- error: {
251
- code: -32000,
252
- message: 'Conflict: Stream already has an active connection'
253
- },
254
- id: null
255
- }));
256
- return;
257
- }
258
- }
259
- const headers = {
260
- 'Content-Type': 'text/event-stream',
261
- 'Cache-Control': 'no-cache, no-transform',
262
- Connection: 'keep-alive'
263
- };
264
- if (this.sessionId !== undefined) {
265
- headers['mcp-session-id'] = this.sessionId;
266
- }
267
- res.writeHead(200, headers).flushHeaders();
268
- // Replay events - returns the streamId for backwards compatibility
269
- const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {
270
- send: async (eventId, message) => {
271
- var _a;
272
- if (!this.writeSSEEvent(res, message, eventId)) {
273
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error('Failed replay events'));
274
- res.end();
275
- }
276
- }
277
- });
278
- this._streamMapping.set(replayedStreamId, res);
279
- // Set up close handler for client disconnects
280
- res.on('close', () => {
281
- this._streamMapping.delete(replayedStreamId);
282
- });
283
- // Add error handler for replay stream
284
- res.on('error', error => {
285
- var _a;
286
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);
287
- });
288
- }
289
- catch (error) {
290
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);
291
- }
94
+ set onmessage(handler) {
95
+ this._webStandardTransport.onmessage = handler;
292
96
  }
293
- /**
294
- * Writes an event to the SSE stream with proper formatting
295
- */
296
- writeSSEEvent(res, message, eventId) {
297
- let eventData = `event: message\n`;
298
- // Include event ID if provided - this is important for resumability
299
- if (eventId) {
300
- eventData += `id: ${eventId}\n`;
301
- }
302
- eventData += `data: ${JSON.stringify(message)}\n\n`;
303
- return res.write(eventData);
97
+ get onmessage() {
98
+ return this._webStandardTransport.onmessage;
304
99
  }
305
100
  /**
306
- * Handles unsupported requests (PUT, PATCH, etc.)
101
+ * Starts the transport. This is required by the Transport interface but is a no-op
102
+ * for the Streamable HTTP transport as connections are managed per-request.
307
103
  */
308
- async handleUnsupportedRequest(res) {
309
- res.writeHead(405, {
310
- Allow: 'GET, POST, DELETE'
311
- }).end(JSON.stringify({
312
- jsonrpc: '2.0',
313
- error: {
314
- code: -32000,
315
- message: 'Method not allowed.'
316
- },
317
- id: null
318
- }));
104
+ async start() {
105
+ return this._webStandardTransport.start();
319
106
  }
320
107
  /**
321
- * Handles POST requests containing JSON-RPC messages
108
+ * Closes the transport and all active connections.
322
109
  */
323
- async handlePostRequest(req, res, parsedBody) {
324
- var _a, _b, _c, _d, _e;
325
- try {
326
- // Validate the Accept header
327
- const acceptHeader = req.headers.accept;
328
- // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.
329
- if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('application/json')) || !acceptHeader.includes('text/event-stream')) {
330
- res.writeHead(406).end(JSON.stringify({
331
- jsonrpc: '2.0',
332
- error: {
333
- code: -32000,
334
- message: 'Not Acceptable: Client must accept both application/json and text/event-stream'
335
- },
336
- id: null
337
- }));
338
- return;
339
- }
340
- const ct = req.headers['content-type'];
341
- if (!ct || !ct.includes('application/json')) {
342
- res.writeHead(415).end(JSON.stringify({
343
- jsonrpc: '2.0',
344
- error: {
345
- code: -32000,
346
- message: 'Unsupported Media Type: Content-Type must be application/json'
347
- },
348
- id: null
349
- }));
350
- return;
351
- }
352
- const authInfo = req.auth;
353
- const requestInfo = { headers: req.headers };
354
- let rawMessage;
355
- if (parsedBody !== undefined) {
356
- rawMessage = parsedBody;
357
- }
358
- else {
359
- const parsedCt = content_type_1.default.parse(ct);
360
- const body = await (0, raw_body_1.default)(req, {
361
- limit: MAXIMUM_MESSAGE_SIZE,
362
- encoding: (_a = parsedCt.parameters.charset) !== null && _a !== void 0 ? _a : 'utf-8'
363
- });
364
- rawMessage = JSON.parse(body.toString());
365
- }
366
- let messages;
367
- // handle batch and single messages
368
- if (Array.isArray(rawMessage)) {
369
- messages = rawMessage.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg));
370
- }
371
- else {
372
- messages = [types_js_1.JSONRPCMessageSchema.parse(rawMessage)];
373
- }
374
- // Check if this is an initialization request
375
- // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/
376
- const isInitializationRequest = messages.some(types_js_1.isInitializeRequest);
377
- if (isInitializationRequest) {
378
- // If it's a server with session management and the session ID is already set we should reject the request
379
- // to avoid re-initialization.
380
- if (this._initialized && this.sessionId !== undefined) {
381
- res.writeHead(400).end(JSON.stringify({
382
- jsonrpc: '2.0',
383
- error: {
384
- code: -32600,
385
- message: 'Invalid Request: Server already initialized'
386
- },
387
- id: null
388
- }));
389
- return;
390
- }
391
- if (messages.length > 1) {
392
- res.writeHead(400).end(JSON.stringify({
393
- jsonrpc: '2.0',
394
- error: {
395
- code: -32600,
396
- message: 'Invalid Request: Only one initialization request is allowed'
397
- },
398
- id: null
399
- }));
400
- return;
401
- }
402
- this.sessionId = (_b = this.sessionIdGenerator) === null || _b === void 0 ? void 0 : _b.call(this);
403
- this._initialized = true;
404
- // If we have a session ID and an onsessioninitialized handler, call it immediately
405
- // This is needed in cases where the server needs to keep track of multiple sessions
406
- if (this.sessionId && this._onsessioninitialized) {
407
- await Promise.resolve(this._onsessioninitialized(this.sessionId));
408
- }
409
- }
410
- if (!isInitializationRequest) {
411
- // If an Mcp-Session-Id is returned by the server during initialization,
412
- // clients using the Streamable HTTP transport MUST include it
413
- // in the Mcp-Session-Id header on all of their subsequent HTTP requests.
414
- if (!this.validateSession(req, res)) {
415
- return;
416
- }
417
- // Mcp-Protocol-Version header is required for all requests after initialization.
418
- if (!this.validateProtocolVersion(req, res)) {
419
- return;
420
- }
421
- }
422
- // check if it contains requests
423
- const hasRequests = messages.some(types_js_1.isJSONRPCRequest);
424
- if (!hasRequests) {
425
- // if it only contains notifications or responses, return 202
426
- res.writeHead(202).end();
427
- // handle each message
428
- for (const message of messages) {
429
- (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, message, { authInfo, requestInfo });
430
- }
431
- }
432
- else if (hasRequests) {
433
- // The default behavior is to use SSE streaming
434
- // but in some cases server will return JSON responses
435
- const streamId = (0, node_crypto_1.randomUUID)();
436
- if (!this._enableJsonResponse) {
437
- const headers = {
438
- 'Content-Type': 'text/event-stream',
439
- 'Cache-Control': 'no-cache',
440
- Connection: 'keep-alive'
441
- };
442
- // After initialization, always include the session ID if we have one
443
- if (this.sessionId !== undefined) {
444
- headers['mcp-session-id'] = this.sessionId;
445
- }
446
- res.writeHead(200, headers);
447
- await this._maybeWritePrimingEvent(res, streamId);
448
- }
449
- // Store the response for this request to send messages back through this connection
450
- // We need to track by request ID to maintain the connection
451
- for (const message of messages) {
452
- if ((0, types_js_1.isJSONRPCRequest)(message)) {
453
- this._streamMapping.set(streamId, res);
454
- this._requestToStreamMapping.set(message.id, streamId);
455
- }
456
- }
457
- // Set up close handler for client disconnects
458
- res.on('close', () => {
459
- this._streamMapping.delete(streamId);
460
- });
461
- // Add error handler for stream write errors
462
- res.on('error', error => {
463
- var _a;
464
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);
465
- });
466
- // handle each message
467
- for (const message of messages) {
468
- // Build closeSSEStream callback for requests when eventStore is configured
469
- let closeSSEStream;
470
- let closeStandaloneSSEStream;
471
- if ((0, types_js_1.isJSONRPCRequest)(message) && this._eventStore) {
472
- closeSSEStream = () => {
473
- this.closeSSEStream(message.id);
474
- };
475
- closeStandaloneSSEStream = () => {
476
- this.closeStandaloneSSEStream();
477
- };
478
- }
479
- (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, message, { authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });
480
- }
481
- // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses
482
- // This will be handled by the send() method when responses are ready
483
- }
484
- }
485
- catch (error) {
486
- // return JSON-RPC formatted error
487
- res.writeHead(400).end(JSON.stringify({
488
- jsonrpc: '2.0',
489
- error: {
490
- code: -32700,
491
- message: 'Parse error',
492
- data: String(error)
493
- },
494
- id: null
495
- }));
496
- (_e = this.onerror) === null || _e === void 0 ? void 0 : _e.call(this, error);
497
- }
110
+ async close() {
111
+ return this._webStandardTransport.close();
498
112
  }
499
113
  /**
500
- * Handles DELETE requests to terminate sessions
114
+ * Sends a JSON-RPC message through the transport.
501
115
  */
502
- async handleDeleteRequest(req, res) {
503
- var _a;
504
- if (!this.validateSession(req, res)) {
505
- return;
506
- }
507
- if (!this.validateProtocolVersion(req, res)) {
508
- return;
509
- }
510
- await Promise.resolve((_a = this._onsessionclosed) === null || _a === void 0 ? void 0 : _a.call(this, this.sessionId));
511
- await this.close();
512
- res.writeHead(200).end();
116
+ async send(message, options) {
117
+ return this._webStandardTransport.send(message, options);
513
118
  }
514
119
  /**
515
- * Validates session ID for non-initialization requests
516
- * Returns true if the session is valid, false otherwise
120
+ * Handles an incoming HTTP request, whether GET or POST.
121
+ *
122
+ * This method converts Node.js HTTP objects to Web Standard Request/Response
123
+ * and delegates to the underlying WebStandardStreamableHTTPServerTransport.
124
+ *
125
+ * @param req - Node.js IncomingMessage, optionally with auth property from middleware
126
+ * @param res - Node.js ServerResponse
127
+ * @param parsedBody - Optional pre-parsed body from body-parser middleware
517
128
  */
518
- validateSession(req, res) {
519
- if (this.sessionIdGenerator === undefined) {
520
- // If the sessionIdGenerator ID is not set, the session management is disabled
521
- // and we don't need to validate the session ID
522
- return true;
523
- }
524
- if (!this._initialized) {
525
- // If the server has not been initialized yet, reject all requests
526
- res.writeHead(400).end(JSON.stringify({
527
- jsonrpc: '2.0',
528
- error: {
529
- code: -32000,
530
- message: 'Bad Request: Server not initialized'
531
- },
532
- id: null
533
- }));
534
- return false;
535
- }
536
- const sessionId = req.headers['mcp-session-id'];
537
- if (!sessionId) {
538
- // Non-initialization requests without a session ID should return 400 Bad Request
539
- res.writeHead(400).end(JSON.stringify({
540
- jsonrpc: '2.0',
541
- error: {
542
- code: -32000,
543
- message: 'Bad Request: Mcp-Session-Id header is required'
544
- },
545
- id: null
546
- }));
547
- return false;
548
- }
549
- else if (Array.isArray(sessionId)) {
550
- res.writeHead(400).end(JSON.stringify({
551
- jsonrpc: '2.0',
552
- error: {
553
- code: -32000,
554
- message: 'Bad Request: Mcp-Session-Id header must be a single value'
555
- },
556
- id: null
557
- }));
558
- return false;
559
- }
560
- else if (sessionId !== this.sessionId) {
561
- // Reject requests with invalid session ID with 404 Not Found
562
- res.writeHead(404).end(JSON.stringify({
563
- jsonrpc: '2.0',
564
- error: {
565
- code: -32001,
566
- message: 'Session not found'
567
- },
568
- id: null
569
- }));
570
- return false;
571
- }
572
- return true;
573
- }
574
- validateProtocolVersion(req, res) {
575
- var _a;
576
- let protocolVersion = (_a = req.headers['mcp-protocol-version']) !== null && _a !== void 0 ? _a : types_js_1.DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
577
- if (Array.isArray(protocolVersion)) {
578
- protocolVersion = protocolVersion[protocolVersion.length - 1];
579
- }
580
- if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {
581
- res.writeHead(400).end(JSON.stringify({
582
- jsonrpc: '2.0',
583
- error: {
584
- code: -32000,
585
- message: `Bad Request: Unsupported protocol version (supported versions: ${types_js_1.SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`
586
- },
587
- id: null
588
- }));
589
- return false;
590
- }
591
- return true;
592
- }
593
- async close() {
594
- var _a;
595
- // Close all SSE connections
596
- this._streamMapping.forEach(response => {
597
- response.end();
129
+ async handleRequest(req, res, parsedBody) {
130
+ // Store context for this request to pass through auth and parsedBody
131
+ // We need to intercept the request creation to attach this context
132
+ const authInfo = req.auth;
133
+ // Create a custom handler that includes our context
134
+ const handler = (0, node_server_1.getRequestListener)(async (webRequest) => {
135
+ return this._webStandardTransport.handleRequest(webRequest, {
136
+ authInfo,
137
+ parsedBody
138
+ });
598
139
  });
599
- this._streamMapping.clear();
600
- // Clear any pending responses
601
- this._requestResponseMap.clear();
602
- (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
140
+ // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion
141
+ // including proper SSE streaming support
142
+ await handler(req, res);
603
143
  }
604
144
  /**
605
145
  * Close an SSE stream for a specific request, triggering client reconnection.
@@ -607,112 +147,14 @@ class StreamableHTTPServerTransport {
607
147
  * client will reconnect after the retry interval specified in the priming event.
608
148
  */
609
149
  closeSSEStream(requestId) {
610
- const streamId = this._requestToStreamMapping.get(requestId);
611
- if (!streamId)
612
- return;
613
- const stream = this._streamMapping.get(streamId);
614
- if (stream) {
615
- stream.end();
616
- this._streamMapping.delete(streamId);
617
- }
150
+ this._webStandardTransport.closeSSEStream(requestId);
618
151
  }
619
152
  /**
620
153
  * Close the standalone GET SSE stream, triggering client reconnection.
621
154
  * Use this to implement polling behavior for server-initiated notifications.
622
155
  */
623
156
  closeStandaloneSSEStream() {
624
- const stream = this._streamMapping.get(this._standaloneSseStreamId);
625
- if (stream) {
626
- stream.end();
627
- this._streamMapping.delete(this._standaloneSseStreamId);
628
- }
629
- }
630
- async send(message, options) {
631
- let requestId = options === null || options === void 0 ? void 0 : options.relatedRequestId;
632
- if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) {
633
- // If the message is a response, use the request ID from the message
634
- requestId = message.id;
635
- }
636
- // Check if this message should be sent on the standalone SSE stream (no request ID)
637
- // Ignore notifications from tools (which have relatedRequestId set)
638
- // Those will be sent via dedicated response SSE streams
639
- if (requestId === undefined) {
640
- // For standalone SSE streams, we can only send requests and notifications
641
- if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) {
642
- throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request');
643
- }
644
- // Generate and store event ID if event store is provided
645
- // Store even if stream is disconnected so events can be replayed on reconnect
646
- let eventId;
647
- if (this._eventStore) {
648
- // Stores the event and gets the generated event ID
649
- eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);
650
- }
651
- const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);
652
- if (standaloneSse === undefined) {
653
- // Stream is disconnected - event is stored for replay, nothing more to do
654
- return;
655
- }
656
- // Send the message to the standalone SSE stream
657
- this.writeSSEEvent(standaloneSse, message, eventId);
658
- return;
659
- }
660
- // Get the response for this request
661
- const streamId = this._requestToStreamMapping.get(requestId);
662
- const response = this._streamMapping.get(streamId);
663
- if (!streamId) {
664
- throw new Error(`No connection established for request ID: ${String(requestId)}`);
665
- }
666
- if (!this._enableJsonResponse) {
667
- // For SSE responses, generate event ID if event store is provided
668
- let eventId;
669
- if (this._eventStore) {
670
- eventId = await this._eventStore.storeEvent(streamId, message);
671
- }
672
- if (response) {
673
- // Write the event to the response stream
674
- this.writeSSEEvent(response, message, eventId);
675
- }
676
- }
677
- if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) {
678
- this._requestResponseMap.set(requestId, message);
679
- const relatedIds = Array.from(this._requestToStreamMapping.entries())
680
- .filter(([_, streamId]) => this._streamMapping.get(streamId) === response)
681
- .map(([id]) => id);
682
- // Check if we have responses for all requests using this connection
683
- const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id));
684
- if (allResponsesReady) {
685
- if (!response) {
686
- throw new Error(`No connection established for request ID: ${String(requestId)}`);
687
- }
688
- if (this._enableJsonResponse) {
689
- // All responses ready, send as JSON
690
- const headers = {
691
- 'Content-Type': 'application/json'
692
- };
693
- if (this.sessionId !== undefined) {
694
- headers['mcp-session-id'] = this.sessionId;
695
- }
696
- const responses = relatedIds.map(id => this._requestResponseMap.get(id));
697
- response.writeHead(200, headers);
698
- if (responses.length === 1) {
699
- response.end(JSON.stringify(responses[0]));
700
- }
701
- else {
702
- response.end(JSON.stringify(responses));
703
- }
704
- }
705
- else {
706
- // End the SSE stream
707
- response.end();
708
- }
709
- // Clean up
710
- for (const id of relatedIds) {
711
- this._requestResponseMap.delete(id);
712
- this._requestToStreamMapping.delete(id);
713
- }
714
- }
715
- }
157
+ this._webStandardTransport.closeStandaloneSSEStream();
716
158
  }
717
159
  }
718
160
  exports.StreamableHTTPServerTransport = StreamableHTTPServerTransport;