@modelcontextprotocol/sdk 1.24.3 → 1.25.1

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