@iworkforces/tracelattice 2.0.6 → 2.0.8
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.
- package/README.md +28 -1
- package/dist/cli.js +296 -196
- package/dist/contracts/summary.d.ts +0 -1
- package/dist/contracts/summary.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.d.ts +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtFormatter.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/compression/CompressionService.d.ts +6 -4
- package/dist/core/compression/CompressionService.d.ts.map +1 -1
- package/dist/core/compression/CompressionService.js +19 -10
- package/dist/core/compression/CompressionService.js.map +1 -1
- package/dist/core/compression/DehydrationPolicy.d.ts +4 -4
- package/dist/core/compression/DehydrationPolicy.d.ts.map +1 -1
- package/dist/core/compression/DehydrationPolicy.js +3 -6
- package/dist/core/compression/DehydrationPolicy.js.map +1 -1
- package/dist/core/compression/InMemorySummaryStore.d.ts +2 -1
- package/dist/core/compression/InMemorySummaryStore.d.ts.map +1 -1
- package/dist/core/compression/InMemorySummaryStore.js.map +1 -1
- package/dist/core/evaluator/Calibrator.d.ts +1 -1
- package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
- package/dist/core/evaluator/Calibrator.js.map +1 -1
- package/dist/core/evaluator/SignalComputer.d.ts +2 -1
- package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
- package/dist/core/evaluator/SignalComputer.js.map +1 -1
- package/dist/core/evaluator/internals.d.ts +1 -1
- package/dist/core/evaluator/internals.d.ts.map +1 -1
- package/dist/core/evaluator/internals.js.map +1 -1
- package/dist/core/graph/GraphView.d.ts +13 -1
- package/dist/core/graph/GraphView.d.ts.map +1 -1
- package/dist/core/graph/GraphView.js +34 -0
- package/dist/core/graph/GraphView.js.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +6 -6
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +16 -2
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
- package/dist/core/reasoning/strategies/totScoring.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/totScoring.js.map +1 -1
- package/dist/core/reasoning.d.ts +1 -3
- package/dist/core/reasoning.d.ts.map +1 -1
- package/dist/core/thought.d.ts +1 -1
- package/dist/core/thought.d.ts.map +1 -1
- package/dist/lib.d.ts +20 -6
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +52 -3
- package/dist/lib.js.map +1 -1
- package/dist/transport/HttpHelpers.d.ts +4 -1
- package/dist/transport/HttpHelpers.d.ts.map +1 -1
- package/dist/transport/HttpHelpers.js +61 -11
- package/dist/transport/HttpHelpers.js.map +1 -1
- package/dist/transport/HttpRequestLifecycle.d.ts +15 -1
- package/dist/transport/HttpRequestLifecycle.d.ts.map +1 -1
- package/dist/transport/HttpRequestLifecycle.js +66 -4
- package/dist/transport/HttpRequestLifecycle.js.map +1 -1
- package/dist/transport/HttpTransport.d.ts +2 -0
- package/dist/transport/HttpTransport.d.ts.map +1 -1
- package/dist/transport/HttpTransport.js +75 -38
- package/dist/transport/HttpTransport.js.map +1 -1
- package/dist/transport/StreamableHttpTransport.d.ts +17 -29
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
- package/dist/transport/StreamableHttpTransport.js +153 -124
- package/dist/transport/StreamableHttpTransport.js.map +1 -1
- package/package.json +4 -4
|
@@ -7,7 +7,17 @@ import { BaseTransport } from "./BaseTransport.js";
|
|
|
7
7
|
import { asSessionId } from "../contracts/ids.js";
|
|
8
8
|
import { readRequestBody } from "./HttpHelpers.js";
|
|
9
9
|
import { runWithContext } from "../context/RequestContext.js";
|
|
10
|
-
import { AcceptedWorkTracker, LifecycleFailureReporter, ResponseFinalizer } from "./HttpRequestLifecycle.js";
|
|
10
|
+
import { AcceptedWorkTracker, LifecycleFailureReporter, PreDispatchTracker, ResponseFinalizer } from "./HttpRequestLifecycle.js";
|
|
11
|
+
function parseSessionRetentionOptions(options) {
|
|
12
|
+
const { maxSessions, sessionIdleTimeoutMs, sessionSweepIntervalMs } = options;
|
|
13
|
+
if (void 0 === maxSessions && void 0 === sessionIdleTimeoutMs && void 0 === sessionSweepIntervalMs) return null;
|
|
14
|
+
if (void 0 === maxSessions || !Number.isFinite(maxSessions) || !Number.isInteger(maxSessions) || maxSessions <= 0 || void 0 === sessionIdleTimeoutMs || !Number.isFinite(sessionIdleTimeoutMs) || !Number.isInteger(sessionIdleTimeoutMs) || sessionIdleTimeoutMs <= 0 || void 0 === sessionSweepIntervalMs || !Number.isFinite(sessionSweepIntervalMs) || !Number.isInteger(sessionSweepIntervalMs) || sessionSweepIntervalMs <= 0) throw new TypeError('maxSessions, sessionIdleTimeoutMs, and sessionSweepIntervalMs must be provided together as positive integers');
|
|
15
|
+
return {
|
|
16
|
+
maxSessions,
|
|
17
|
+
sessionIdleTimeoutMs,
|
|
18
|
+
sessionSweepIntervalMs
|
|
19
|
+
};
|
|
20
|
+
}
|
|
11
21
|
class StreamableHttpTransport extends BaseTransport {
|
|
12
22
|
get kind() {
|
|
13
23
|
return 'streamable-http';
|
|
@@ -27,8 +37,12 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
27
37
|
_metricsProvider;
|
|
28
38
|
_lifecycleFailureReporter;
|
|
29
39
|
_acceptedWork;
|
|
40
|
+
_preDispatch = new PreDispatchTracker();
|
|
41
|
+
_sessionRetention;
|
|
42
|
+
_sessionSweepIntervalId = null;
|
|
30
43
|
_stopPromise = null;
|
|
31
44
|
constructor(options = {}){
|
|
45
|
+
const sessionRetention = parseSessionRetentionOptions(options);
|
|
32
46
|
super(options);
|
|
33
47
|
this._path = options.path ?? '/mcp';
|
|
34
48
|
this._stateful = options.stateful ?? true;
|
|
@@ -38,12 +52,17 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
38
52
|
this._requestTimeout = options.requestTimeout ?? 30000;
|
|
39
53
|
this._metrics = options.metrics;
|
|
40
54
|
this._metricsProvider = options.metricsProvider ?? null;
|
|
55
|
+
this._sessionRetention = sessionRetention;
|
|
41
56
|
this._lifecycleFailureReporter = new LifecycleFailureReporter((error)=>{
|
|
42
57
|
this.log('error', 'Streamable HTTP request lifecycle failed', {
|
|
43
58
|
error: getErrorMessage(error)
|
|
44
59
|
});
|
|
45
60
|
});
|
|
46
61
|
this._acceptedWork = new AcceptedWorkTracker(this._lifecycleFailureReporter);
|
|
62
|
+
if (this._stateful && sessionRetention) {
|
|
63
|
+
this._sessionSweepIntervalId = setInterval(()=>this._sweepExpiredSessions(), sessionRetention.sessionSweepIntervalMs);
|
|
64
|
+
this._sessionSweepIntervalId.unref();
|
|
65
|
+
}
|
|
47
66
|
}
|
|
48
67
|
_requireMcpServer() {
|
|
49
68
|
if (!this._mcpServer) throw new Error('MCP server not initialized. Did you call connect()?');
|
|
@@ -93,13 +112,16 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
93
112
|
}
|
|
94
113
|
});
|
|
95
114
|
}
|
|
96
|
-
|
|
115
|
+
_recordRequestMetrics(res) {
|
|
97
116
|
const startTime = Date.now();
|
|
98
117
|
this._metrics?.counter('streamable_http_requests_total', 1, {}, 'Total Streamable HTTP transport requests');
|
|
99
118
|
res.once('finish', ()=>{
|
|
100
119
|
const durationSeconds = (Date.now() - startTime) / 1000;
|
|
101
120
|
this._metrics?.histogram('streamable_http_request_duration_seconds', durationSeconds, {});
|
|
102
121
|
});
|
|
122
|
+
}
|
|
123
|
+
async _handleRequest(req, res) {
|
|
124
|
+
this._recordRequestMetrics(res);
|
|
103
125
|
if (!this.validateHostHeader(req)) return void this._sendJsonRpcError(res, 403, -32000, 'Forbidden - invalid host header');
|
|
104
126
|
if (this.isShuttingDown) return void this._sendJsonRpcError(res, 503, -32603, 'Server is shutting down');
|
|
105
127
|
const clientIp = this.getClientIp(req);
|
|
@@ -121,11 +143,21 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
121
143
|
if ('GET' === req.method && '/health' === urlPath) return void this._handleHealthCheck(res);
|
|
122
144
|
if ('GET' === req.method && '/ready' === urlPath) return void await this._handleReadinessCheck(res);
|
|
123
145
|
if (urlPath === this._path) {
|
|
124
|
-
if ('POST' === req.method)
|
|
125
|
-
|
|
146
|
+
if ('POST' === req.method) {
|
|
147
|
+
const lease = this._preDispatch.acquire();
|
|
148
|
+
if (!lease) {
|
|
149
|
+
const responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);
|
|
150
|
+
responseFinalizer.finalize((response)=>{
|
|
151
|
+
this._sendJsonRpcError(response, 503, -32603, 'Server is shutting down');
|
|
152
|
+
});
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
await this._handleMcpPost(req, res, lease);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
126
158
|
res.writeHead(405, {
|
|
127
159
|
'Content-Type': 'application/json',
|
|
128
|
-
Allow: '
|
|
160
|
+
Allow: 'POST'
|
|
129
161
|
});
|
|
130
162
|
res.end(JSON.stringify({
|
|
131
163
|
jsonrpc: '2.0',
|
|
@@ -154,60 +186,111 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
154
186
|
error
|
|
155
187
|
}));
|
|
156
188
|
}
|
|
157
|
-
|
|
189
|
+
_parseJsonRpcRequest(body, responseFinalizer) {
|
|
190
|
+
let rawBody;
|
|
191
|
+
try {
|
|
192
|
+
rawBody = JSON.parse(body);
|
|
193
|
+
} catch {
|
|
194
|
+
responseFinalizer.finalize((response)=>{
|
|
195
|
+
this._sendJsonRpcError(response, 200, -32700, 'Parse error');
|
|
196
|
+
});
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
const parseResult = safeParse(JsonRpcRequestSchema, rawBody);
|
|
200
|
+
const rawId = rawBody && 'object' == typeof rawBody && 'id' in rawBody ? rawBody.id ?? null : null;
|
|
201
|
+
if (!parseResult.success) {
|
|
202
|
+
responseFinalizer.finalize((response)=>{
|
|
203
|
+
this._sendJsonRpcError(response, 200, -32600, 'Invalid Request', rawId, {
|
|
204
|
+
data: parseResult.issues
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
return parseResult.output;
|
|
210
|
+
}
|
|
211
|
+
async _handleMcpPost(req, res, lease) {
|
|
158
212
|
this._requestCount++;
|
|
159
213
|
this._activeRequests++;
|
|
160
214
|
const responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);
|
|
215
|
+
let acceptedSession = null;
|
|
216
|
+
const onAborted = ()=>lease.cancel('peer');
|
|
217
|
+
req.once('aborted', onAborted);
|
|
161
218
|
const timeout = setTimeout(()=>{
|
|
162
219
|
responseFinalizer.finalize((response)=>{
|
|
163
220
|
this._sendJsonRpcError(response, 500, -32603, 'Request timeout');
|
|
164
221
|
});
|
|
222
|
+
lease.cancel('timeout');
|
|
165
223
|
}, this._requestTimeout);
|
|
166
224
|
try {
|
|
167
|
-
const body = await readRequestBody(req, this._bodySizeLimitEnabled ? this._maxBodySize : 0);
|
|
225
|
+
const body = await readRequestBody(req, this._bodySizeLimitEnabled ? this._maxBodySize : 0, lease.signal);
|
|
168
226
|
if (null === body) return void responseFinalizer.finalize((response)=>{
|
|
169
227
|
this._sendJsonRpcError(response, 413, -32000, 'Request body too large');
|
|
170
228
|
});
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
229
|
+
const jsonRpcRequest = this._parseJsonRpcRequest(body, responseFinalizer);
|
|
230
|
+
if (null === jsonRpcRequest) return;
|
|
231
|
+
const session = this._acceptPostSession(req, responseFinalizer);
|
|
232
|
+
if (!session) return;
|
|
233
|
+
acceptedSession = session.state;
|
|
234
|
+
if (!this._mcpServer) {
|
|
235
|
+
const requestId = 'id' in jsonRpcRequest ? jsonRpcRequest.id ?? null : null;
|
|
175
236
|
responseFinalizer.finalize((response)=>{
|
|
176
|
-
this._sendJsonRpcError(response,
|
|
237
|
+
this._sendJsonRpcError(response, 503, -32603, 'Server not ready', requestId);
|
|
177
238
|
});
|
|
178
239
|
return;
|
|
179
240
|
}
|
|
180
|
-
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
if ('
|
|
192
|
-
this._sendJsonRpcError(response,
|
|
241
|
+
req.off('aborted', onAborted);
|
|
242
|
+
const acceptedWork = this._acceptedWork.transfer(lease, ()=>this._receiveAndFinalize(jsonRpcRequest, session.id, responseFinalizer).catch((error)=>{
|
|
243
|
+
responseFinalizer.finalize((response)=>{
|
|
244
|
+
this._sendJsonRpcError(response, 200, -32603, 'Internal error', null, {
|
|
245
|
+
data: getErrorMessage(error)
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
}));
|
|
249
|
+
await acceptedWork;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (lease.signal.aborted) {
|
|
252
|
+
if ('shutdown' === lease.cancellationReason) responseFinalizer.finalize((response)=>{
|
|
253
|
+
this._sendJsonRpcError(response, 503, -32603, 'Server is shutting down');
|
|
193
254
|
});
|
|
194
|
-
|
|
255
|
+
return;
|
|
195
256
|
}
|
|
196
|
-
if (!this._mcpServer) return void responseFinalizer.finalize((response)=>{
|
|
197
|
-
this._sendJsonRpcError(response, 503, -32603, 'Server not ready', jsonRpcRequest?.id ?? null);
|
|
198
|
-
});
|
|
199
|
-
await this._receiveAndFinalize(jsonRpcRequest, sessionId, responseFinalizer);
|
|
200
|
-
} catch (error) {
|
|
201
257
|
responseFinalizer.finalize((response)=>{
|
|
202
258
|
this._sendJsonRpcError(response, 200, -32603, 'Internal error', null, {
|
|
203
259
|
data: getErrorMessage(error)
|
|
204
260
|
});
|
|
205
261
|
});
|
|
206
262
|
} finally{
|
|
263
|
+
req.off('aborted', onAborted);
|
|
264
|
+
lease.release();
|
|
265
|
+
if (acceptedSession) acceptedSession.acceptedPostCount--;
|
|
207
266
|
clearTimeout(timeout);
|
|
208
267
|
this._activeRequests--;
|
|
209
268
|
}
|
|
210
269
|
}
|
|
270
|
+
_acceptPostSession(req, responseFinalizer) {
|
|
271
|
+
if (!this._stateful) return {
|
|
272
|
+
id: void 0,
|
|
273
|
+
state: null
|
|
274
|
+
};
|
|
275
|
+
if (this.isShuttingDown) {
|
|
276
|
+
responseFinalizer.finalize((response)=>{
|
|
277
|
+
this._sendJsonRpcError(response, 503, -32603, 'Server is shutting down');
|
|
278
|
+
});
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
const session = this._resolveSession(req);
|
|
282
|
+
if (!('state' in session)) {
|
|
283
|
+
responseFinalizer.finalize((response)=>{
|
|
284
|
+
this._sendJsonRpcError(response, session.statusCode, session.code, session.message);
|
|
285
|
+
});
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
session.state.acceptedPostCount++;
|
|
289
|
+
return {
|
|
290
|
+
id: session.id,
|
|
291
|
+
state: session.state
|
|
292
|
+
};
|
|
293
|
+
}
|
|
211
294
|
async _receiveAndFinalize(jsonRpcRequest, sessionId, responseFinalizer) {
|
|
212
295
|
const owner = this._stateful ? sessionId ?? randomUUID() : randomUUID();
|
|
213
296
|
const response = await runWithContext({
|
|
@@ -231,70 +314,6 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
231
314
|
httpResponse.end();
|
|
232
315
|
});
|
|
233
316
|
}
|
|
234
|
-
_handleMcpGet(req, res) {
|
|
235
|
-
if (!this._stateful) {
|
|
236
|
-
res.writeHead(405, {
|
|
237
|
-
'Content-Type': 'application/json',
|
|
238
|
-
Allow: 'POST'
|
|
239
|
-
});
|
|
240
|
-
res.end(JSON.stringify({
|
|
241
|
-
jsonrpc: '2.0',
|
|
242
|
-
id: null,
|
|
243
|
-
error: {
|
|
244
|
-
code: -32601,
|
|
245
|
-
message: 'GET not supported in stateless mode'
|
|
246
|
-
}
|
|
247
|
-
}));
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
const sessionId = this._getSessionIdFromHeader(req);
|
|
251
|
-
if (!sessionId) {
|
|
252
|
-
res.writeHead(400, {
|
|
253
|
-
'Content-Type': 'application/json'
|
|
254
|
-
});
|
|
255
|
-
res.end(JSON.stringify({
|
|
256
|
-
jsonrpc: '2.0',
|
|
257
|
-
id: null,
|
|
258
|
-
error: {
|
|
259
|
-
code: -32600,
|
|
260
|
-
message: 'Missing Mcp-Session-Id header'
|
|
261
|
-
}
|
|
262
|
-
}));
|
|
263
|
-
return;
|
|
264
|
-
}
|
|
265
|
-
const session = this._sessions.get(asSessionId(sessionId));
|
|
266
|
-
if (!session) {
|
|
267
|
-
res.writeHead(404, {
|
|
268
|
-
'Content-Type': 'application/json'
|
|
269
|
-
});
|
|
270
|
-
res.end(JSON.stringify({
|
|
271
|
-
jsonrpc: '2.0',
|
|
272
|
-
id: null,
|
|
273
|
-
error: {
|
|
274
|
-
code: -32001,
|
|
275
|
-
message: 'Session not found'
|
|
276
|
-
}
|
|
277
|
-
}));
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
res.writeHead(200, {
|
|
281
|
-
'Content-Type': 'text/event-stream',
|
|
282
|
-
'Cache-Control': 'no-cache',
|
|
283
|
-
Connection: 'keep-alive',
|
|
284
|
-
'Mcp-Session-Id': sessionId
|
|
285
|
-
});
|
|
286
|
-
this._sendSseEvent(res, 'connected', {
|
|
287
|
-
sessionId,
|
|
288
|
-
timestamp: Date.now()
|
|
289
|
-
});
|
|
290
|
-
session.notificationStreams.add(res);
|
|
291
|
-
session.lastActivityAt = Date.now();
|
|
292
|
-
this._updateSessionMetrics();
|
|
293
|
-
req.on('close', ()=>{
|
|
294
|
-
session.notificationStreams.delete(res);
|
|
295
|
-
this._updateSessionMetrics();
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
317
|
_resolveSession(req) {
|
|
299
318
|
const headerSessionId = this._getSessionIdFromHeader(req);
|
|
300
319
|
if (headerSessionId) {
|
|
@@ -306,7 +325,10 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
306
325
|
const session = this._sessions.get(asSessionId(headerSessionId));
|
|
307
326
|
if (session) {
|
|
308
327
|
session.lastActivityAt = Date.now();
|
|
309
|
-
return
|
|
328
|
+
return {
|
|
329
|
+
id: session.id,
|
|
330
|
+
state: session
|
|
331
|
+
};
|
|
310
332
|
}
|
|
311
333
|
return {
|
|
312
334
|
statusCode: 404,
|
|
@@ -314,33 +336,47 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
314
336
|
message: 'Session not found'
|
|
315
337
|
};
|
|
316
338
|
}
|
|
317
|
-
|
|
339
|
+
if (this._sessionRetention && this._sessions.size >= this._sessionRetention.maxSessions) return {
|
|
340
|
+
statusCode: 503,
|
|
341
|
+
code: -32000,
|
|
342
|
+
message: 'Session capacity reached'
|
|
343
|
+
};
|
|
344
|
+
const newSessionId = asSessionId(this._sessionIdGenerator());
|
|
345
|
+
const now = Date.now();
|
|
318
346
|
const sessionState = {
|
|
319
347
|
id: newSessionId,
|
|
320
|
-
createdAt:
|
|
321
|
-
lastActivityAt:
|
|
322
|
-
|
|
348
|
+
createdAt: now,
|
|
349
|
+
lastActivityAt: now,
|
|
350
|
+
acceptedPostCount: 0
|
|
323
351
|
};
|
|
324
|
-
this._sessions.set(
|
|
352
|
+
this._sessions.set(newSessionId, sessionState);
|
|
325
353
|
this.log('info', `New session created: ${newSessionId}`);
|
|
326
354
|
this._updateSessionMetrics();
|
|
327
|
-
return
|
|
355
|
+
return {
|
|
356
|
+
id: newSessionId,
|
|
357
|
+
state: sessionState
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
_sweepExpiredSessions() {
|
|
361
|
+
if (!this._sessionRetention) return;
|
|
362
|
+
const now = Date.now();
|
|
363
|
+
for (const [sessionId, session] of this._sessions)if (0 === session.acceptedPostCount && now - session.lastActivityAt >= this._sessionRetention.sessionIdleTimeoutMs) this._disposeSession(sessionId);
|
|
364
|
+
}
|
|
365
|
+
_disposeSession(sessionId) {
|
|
366
|
+
if (!this._sessions.delete(sessionId)) return;
|
|
367
|
+
this._updateSessionMetrics();
|
|
368
|
+
}
|
|
369
|
+
_stopSessionSweep() {
|
|
370
|
+
const interval = this._sessionSweepIntervalId;
|
|
371
|
+
if (!interval) return;
|
|
372
|
+
interval.unref();
|
|
373
|
+
clearInterval(interval);
|
|
374
|
+
this._sessionSweepIntervalId = null;
|
|
328
375
|
}
|
|
329
376
|
_getSessionIdFromHeader(req) {
|
|
330
377
|
const value = req.headers['mcp-session-id'];
|
|
331
378
|
if ('string' == typeof value && value.length > 0) return value;
|
|
332
379
|
}
|
|
333
|
-
_sendSseEvent(res, event, data) {
|
|
334
|
-
try {
|
|
335
|
-
res.write(`event: ${event}\n`);
|
|
336
|
-
res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
337
|
-
} catch {}
|
|
338
|
-
}
|
|
339
|
-
broadcastToSession(sessionId, event, data) {
|
|
340
|
-
const session = this._sessions.get(asSessionId(sessionId));
|
|
341
|
-
if (!session) return;
|
|
342
|
-
for (const stream of session.notificationStreams)this._sendSseEvent(stream, event, data);
|
|
343
|
-
}
|
|
344
380
|
_handleMetrics(res) {
|
|
345
381
|
if (!this._metricsProvider) {
|
|
346
382
|
res.writeHead(404, {
|
|
@@ -391,22 +427,15 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
391
427
|
}
|
|
392
428
|
_updateSessionMetrics() {
|
|
393
429
|
this._metrics?.gauge('streamable_http_active_sessions', this._sessions.size, {}, 'Active Streamable HTTP sessions');
|
|
394
|
-
let totalStreams = 0;
|
|
395
|
-
for (const session of this._sessions.values())totalStreams += session.notificationStreams.size;
|
|
396
|
-
this._metrics?.gauge('streamable_http_notification_streams', totalStreams, {}, 'Active SSE notification streams');
|
|
397
430
|
}
|
|
398
431
|
stop(timeout) {
|
|
399
432
|
if (this._stopPromise) return this._stopPromise;
|
|
400
433
|
this._isShuttingDown = true;
|
|
434
|
+
this._preDispatch.closeAdmission('shutdown');
|
|
401
435
|
this._stopRateLimitCleanup();
|
|
436
|
+
this._stopSessionSweep();
|
|
402
437
|
const shutdownTimeout = timeout ?? 30000;
|
|
403
|
-
for (const
|
|
404
|
-
for (const stream of session.notificationStreams)try {
|
|
405
|
-
stream.end();
|
|
406
|
-
} catch {}
|
|
407
|
-
session.notificationStreams.clear();
|
|
408
|
-
}
|
|
409
|
-
this._sessions.clear();
|
|
438
|
+
for (const sessionId of this._sessions.keys())this._disposeSession(sessionId);
|
|
410
439
|
const server = this._server;
|
|
411
440
|
const serverClosed = new Promise((resolve, reject)=>{
|
|
412
441
|
if (!server?.listening) return void resolve();
|
|
@@ -430,7 +459,7 @@ class StreamableHttpTransport extends BaseTransport {
|
|
|
430
459
|
});
|
|
431
460
|
const stopPromise = Promise.all([
|
|
432
461
|
serverClosed,
|
|
433
|
-
this._acceptedWork.join()
|
|
462
|
+
this._preDispatch.join().then(()=>this._acceptedWork.join())
|
|
434
463
|
]).then(()=>{
|
|
435
464
|
this.log('info', 'Streamable HTTP transport stopped');
|
|
436
465
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport/StreamableHttpTransport.js","sources":["../../src/transport/StreamableHttpTransport.ts"],"sourcesContent":["/**\n * Streamable HTTP Transport implementation (MCP spec recommended transport).\n *\n * This transport implements the MCP Streamable HTTP specification, which replaces\n * the deprecated SSE transport as the recommended HTTP-based transport since March 2025.\n *\n * Key features:\n * - POST /mcp for JSON-RPC requests (main MCP endpoint)\n * - GET /mcp for optional SSE server-to-client notifications\n * - Session management via Mcp-Session-Id header\n * - Supports both stateful (session-based) and stateless (per-request) modes\n * - Health endpoints (/health, /ready)\n *\n * @example\n * ```typescript\n * const transport = new StreamableHttpTransport({\n * port: 3000,\n * host: 'localhost',\n * stateful: true,\n * });\n * await transport.connect(server);\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport type { McpServer } from 'tmcp';\nimport { safeParse } from 'valibot';\nimport type { IMetrics } from '../contracts/interfaces.js';\nimport { getErrorMessage } from '../errors.js';\nimport { JsonRpcRequestSchema } from '../schema.js';\nimport { BaseTransport, type TransportOptions } from './BaseTransport.js';\nimport type { ITransport, TransportKind } from '../contracts/transport.js';\nimport { asSessionId, type SessionId } from '../contracts/ids.js';\nimport { readRequestBody } from './HttpHelpers.js';\nimport { runWithContext } from '../context/RequestContext.js';\nimport {\n\tAcceptedWorkTracker,\n\tLifecycleFailureReporter,\n\tResponseFinalizer,\n} from './HttpRequestLifecycle.js';\n\n/**\n * MCP Streamable HTTP transport options extending base TransportOptions.\n */\nexport interface StreamableHttpTransportOptions extends TransportOptions {\n\t/**\n\t * Path for the MCP endpoint\n\t * @default '/mcp'\n\t */\n\tpath?: string;\n\n\t/**\n\t * Metrics collector for transport telemetry\n\t */\n\tmetrics?: IMetrics;\n\n\t/**\n\t * Prometheus metrics provider function\n\t */\n\tmetricsProvider?: () => string;\n\n\t/**\n\t * Enable stateful session-based mode.\n\t * When true, sessions are tracked via Mcp-Session-Id header.\n\t * When false, each request is processed independently (stateless).\n\t * @default true\n\t */\n\tstateful?: boolean;\n\n\t/**\n\t * Custom session ID generator function.\n\t * @default () => randomUUID()\n\t */\n\tsessionIdGenerator?: () => string;\n\n\t/**\n\t * Enable request body size limit\n\t * @default true\n\t */\n\tenableBodySizeLimit?: boolean;\n\n\t/**\n\t * Maximum request body size in bytes\n\t * @default 10485760 (10MB)\n\t */\n\tmaxBodySize?: number;\n\n\t/**\n\t * Request timeout in milliseconds\n\t * @default 30000 (30 seconds)\n\t */\n\trequestTimeout?: number;\n}\n\n/**\n * Internal session state for stateful mode.\n */\ninterface SessionState {\n\t/** Unique session identifier */\n\tid: string;\n\t/** Timestamp when the session was created */\n\tcreatedAt: number;\n\t/** Timestamp of the last activity */\n\tlastActivityAt: number;\n\t/** Active SSE notification streams for this session */\n\tnotificationStreams: Set<ServerResponse>;\n}\n\ntype SessionError = {\n\treadonly statusCode: number;\n\treadonly code: number;\n\treadonly message: string;\n};\n\n/**\n * Streamable HTTP Transport for MCP server.\n *\n * This transport implements the MCP Streamable HTTP specification,\n * providing JSON-RPC over HTTP with optional session management\n * and server-to-client SSE notification streams.\n *\n * @remarks\n * **Security Features (inherited from BaseTransport):**\n * - Session ID validation (alphanumeric, max 64 chars)\n * - Query parameter sanitization (whitelist allowed keys)\n * - Rate limiting per IP (configurable, default 100 req/min)\n * - CORS origin validation\n * - Host header validation\n *\n * **MCP Streamable HTTP Spec Compliance:**\n * - POST /mcp — JSON-RPC method calls\n * - GET /mcp — SSE notification stream (server-to-client)\n * - Mcp-Session-Id header for session management\n * - Content-Type: application/json for JSON-RPC responses\n * - Content-Type: text/event-stream for SSE notification streams\n *\n * **HTTP Status Code Mapping:**\n * - 200: Success (JSON-RPC response or SSE stream)\n * - 202: Accepted (JSON-RPC notification, no response body)\n * - 204: CORS Preflight (empty body)\n * - 400: Bad Request (invalid JSON, invalid session ID)\n * - 403: Forbidden (invalid CORS, invalid host)\n * - 404: Not Found\n * - 405: Method Not Allowed\n * - 413: Payload Too Large\n * - 429: Too Many Requests\n * - 500: Internal Server Error\n * - 503: Server Not Ready / Shutting Down\n */\nexport class StreamableHttpTransport extends BaseTransport implements ITransport {\n\tget kind(): TransportKind {\n\t\treturn 'streamable-http';\n\t}\n\tprivate _server: Server | null = null;\n\tprivate _mcpServer: McpServer | null = null;\n\tprivate _path: string;\n\tprivate _stateful: boolean;\n\tprivate _sessionIdGenerator: () => string;\n\tprivate _sessions: Map<SessionId, SessionState> = new Map();\n\tprivate _requestCount: number = 0;\n\tprivate _activeRequests: number = 0;\n\tprivate _bodySizeLimitEnabled: boolean;\n\tprivate _maxBodySize: number;\n\tprivate _requestTimeout: number;\n\tprivate _metrics?: IMetrics;\n\tprivate _metricsProvider: (() => string) | null;\n\tprivate readonly _lifecycleFailureReporter: LifecycleFailureReporter;\n\tprivate readonly _acceptedWork: AcceptedWorkTracker;\n\tprivate _stopPromise: Promise<void> | null = null;\n\n\tconstructor(options: StreamableHttpTransportOptions = {}) {\n\t\tsuper(options);\n\n\t\tthis._path = options.path ?? '/mcp';\n\t\tthis._stateful = options.stateful ?? true;\n\t\tthis._sessionIdGenerator = options.sessionIdGenerator ?? (() => randomUUID());\n\t\tthis._bodySizeLimitEnabled = options.enableBodySizeLimit ?? true;\n\t\tthis._maxBodySize = options.maxBodySize ?? 10 * 1024 * 1024;\n\t\tthis._requestTimeout = options.requestTimeout ?? 30000;\n\t\tthis._metrics = options.metrics;\n\t\tthis._metricsProvider = options.metricsProvider ?? null;\n\t\tthis._lifecycleFailureReporter = new LifecycleFailureReporter((error) => {\n\t\t\tthis.log('error', 'Streamable HTTP request lifecycle failed', {\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t});\n\t\tthis._acceptedWork = new AcceptedWorkTracker(this._lifecycleFailureReporter);\n\t}\n\n\tprivate _requireMcpServer(): McpServer {\n\t\tif (!this._mcpServer) {\n\t\t\tthrow new Error('MCP server not initialized. Did you call connect()?');\n\t\t}\n\t\treturn this._mcpServer;\n\t}\n\n\t/**\n\t * Get number of active sessions (stateful) or active requests (stateless).\n\t */\n\tget clientCount(): number {\n\t\treturn this._stateful ? this._sessions.size : this._activeRequests;\n\t}\n\n\t/**\n\t * Get the total number of requests handled.\n\t */\n\tget requestCount(): number {\n\t\treturn this._requestCount;\n\t}\n\n\t/**\n\t * Connects MCP server to this transport and starts listening.\n\t */\n\tasync connect(mcpServer: McpServer): Promise<void> {\n\t\tthis._mcpServer = mcpServer;\n\t\tconst server = createServer((req, res) => {\n\t\t\tconst responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);\n\t\t\tvoid this._handleRequest(req, res).catch((error: unknown) => {\n\t\t\t\tthis._lifecycleFailureReporter.report(error);\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(response, 500, -32603, 'Internal error', null, {\n\t\t\t\t\t\tdata: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tthis._server = server;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = (): void => {\n\t\t\t\tserver.off('error', onError);\n\t\t\t\tserver.off('listening', onListening);\n\t\t\t};\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t};\n\t\t\tconst onListening = (): void => {\n\t\t\t\tcleanup();\n\t\t\t\tthis.log(\n\t\t\t\t\t'info',\n\t\t\t\t\t`Streamable HTTP transport listening on http://${this._host}:${this._port}`\n\t\t\t\t);\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tserver.once('error', onError);\n\t\t\tserver.once('listening', onListening);\n\t\t\ttry {\n\t\t\t\tserver.listen(this._port, this._host);\n\t\t\t} catch (error) {\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Route and handle incoming HTTP requests.\n\t */\n\tprivate async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {\n\t\tconst startTime = Date.now();\n\t\tthis._metrics?.counter(\n\t\t\t'streamable_http_requests_total',\n\t\t\t1,\n\t\t\t{},\n\t\t\t'Total Streamable HTTP transport requests'\n\t\t);\n\t\tres.once('finish', () => {\n\t\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\t\tthis._metrics?.histogram('streamable_http_request_duration_seconds', durationSeconds, {});\n\t\t});\n\n\t\t// Host validation\n\t\tif (!this.validateHostHeader(req)) {\n\t\t\tthis._sendJsonRpcError(res, 403, -32000, 'Forbidden - invalid host header');\n\t\t\treturn;\n\t\t}\n\n\t\t// Shutdown check\n\t\tif (this.isShuttingDown) {\n\t\t\tthis._sendJsonRpcError(res, 503, -32603, 'Server is shutting down');\n\t\t\treturn;\n\t\t}\n\n\t\t// Rate limiting\n\t\tconst clientIp = this.getClientIp(req);\n\t\tif (this.checkRateLimit(clientIp)) {\n\t\t\tres.setHeader('Retry-After', '60');\n\t\t\tthis._sendJsonRpcError(res, 429, -32000, 'Too many requests');\n\t\t\treturn;\n\t\t}\n\n\t\t// CORS validation\n\t\tif (!this.validateCorsOrigin(req)) {\n\t\t\tthis._sendJsonRpcError(res, 403, -32000, 'Forbidden - invalid origin');\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setCorsHeaders(res);\n\n\t\t// CORS preflight\n\t\tif (req.method === 'OPTIONS') {\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'Content-Type, Mcp-Session-Id');\n\t\t\tres.writeHead(204);\n\t\t\tres.end();\n\t\t\treturn;\n\t\t}\n\n\t\t// Parse URL path\n\t\tconst urlPath = req.url?.split('?')[0] ?? '/';\n\n\t\t// Metrics endpoint\n\t\tif (req.method === 'GET' && urlPath === '/metrics') {\n\t\t\tthis._handleMetrics(res);\n\t\t\treturn;\n\t\t}\n\n\t\t// Health check (liveness)\n\t\tif (req.method === 'GET' && urlPath === '/health') {\n\t\t\tthis._handleHealthCheck(res);\n\t\t\treturn;\n\t\t}\n\n\t\t// Readiness check\n\t\tif (req.method === 'GET' && urlPath === '/ready') {\n\t\t\tawait this._handleReadinessCheck(res);\n\t\t\treturn;\n\t\t}\n\n\t\t// MCP endpoint routing\n\t\tif (urlPath === this._path) {\n\t\t\tif (req.method === 'POST') {\n\t\t\t\tthis._acceptedWork.track(this._handleMcpPost(req, res));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (req.method === 'GET') {\n\t\t\t\tthis._handleMcpGet(req, res);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.writeHead(405, { 'Content-Type': 'application/json', Allow: 'GET, POST' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\tid: null,\n\t\t\t\t\terror: { code: -32601, message: 'Method not allowed' },\n\t\t\t\t})\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// 404 for unknown paths\n\t\tthis._sendJsonRpcError(res, 404, -32601, 'Not Found');\n\t}\n\n\t/**\n\t * Send a JSON-RPC error response.\n\t */\n\tprivate _sendJsonRpcError(\n\t\tres: ServerResponse,\n\t\tstatusCode: number,\n\t\tcode: number,\n\t\tmessage: string,\n\t\tid: unknown = null,\n\t\textra?: Record<string, unknown>\n\t): void {\n\t\tconst error: Record<string, unknown> = { code, message };\n\t\tif (extra) {\n\t\t\tObject.assign(error, extra);\n\t\t}\n\t\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\t\tres.end(JSON.stringify({ jsonrpc: '2.0', id, error }));\n\t}\n\n\t/**\n\t * Handle POST /mcp — JSON-RPC method calls.\n\t *\n\t * Per the MCP Streamable HTTP spec:\n\t * - Accepts JSON-RPC request bodies\n\t * - Returns Mcp-Session-Id header for new sessions (stateful mode)\n\t * - Validates Mcp-Session-Id for existing sessions (stateful mode)\n\t * - Content-Type: application/json for responses\n\t */\n\tprivate async _handleMcpPost(req: IncomingMessage, res: ServerResponse): Promise<void> {\n\t\tthis._requestCount++;\n\t\tthis._activeRequests++;\n\t\tconst responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);\n\n\t\tconst timeout = setTimeout(() => {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, 500, -32603, 'Request timeout');\n\t\t\t});\n\t\t}, this._requestTimeout);\n\t\ttry {\n\t\t\t// Read request body with size limit\n\t\t\tconst body = await readRequestBody(req, this._bodySizeLimitEnabled ? this._maxBodySize : 0);\n\t\t\tif (body === null) {\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(response, 413, -32000, 'Request body too large');\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Parse JSON\n\t\t\tlet rawBody: unknown;\n\t\t\ttry {\n\t\t\t\trawBody = JSON.parse(body) as unknown;\n\t\t\t} catch {\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(response, 200, -32700, 'Parse error');\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Validate JSON-RPC schema\n\t\t\tconst parseResult = safeParse(JsonRpcRequestSchema, rawBody);\n\t\t\tconst rawId =\n\t\t\t\trawBody && typeof rawBody === 'object' && 'id' in rawBody\n\t\t\t\t\t? ((rawBody as { id?: unknown }).id ?? null)\n\t\t\t\t\t: null;\n\t\t\tif (!parseResult.success) {\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t200,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t'Invalid Request',\n\t\t\t\t\t\trawId as string | number | null,\n\t\t\t\t\t\t{ data: parseResult.issues }\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst jsonRpcRequest = parseResult.output;\n\n\t\t\t// Session management (stateful mode)\n\t\t\tlet sessionId: string | undefined;\n\t\t\tif (this._stateful) {\n\t\t\t\tconst sessionResult = this._resolveSession(req);\n\t\t\t\tif (typeof sessionResult !== 'string') {\n\t\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\t\tthis._sendJsonRpcError(\n\t\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t\tsessionResult.statusCode,\n\t\t\t\t\t\t\tsessionResult.code,\n\t\t\t\t\t\t\tsessionResult.message\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsessionId = sessionResult;\n\t\t\t}\n\n\t\t\t// Check if MCP server is ready\n\t\t\tif (!this._mcpServer) {\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t503,\n\t\t\t\t\t\t-32603,\n\t\t\t\t\t\t'Server not ready',\n\t\t\t\t\t\tjsonRpcRequest?.id ?? null\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait this._receiveAndFinalize(\n\t\t\t\tjsonRpcRequest as Parameters<McpServer['receive']>[0],\n\t\t\t\tsessionId,\n\t\t\t\tresponseFinalizer\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, 200, -32603, 'Internal error', null, {\n\t\t\t\t\tdata: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t});\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tthis._activeRequests--;\n\t\t}\n\t}\n\n\tprivate async _receiveAndFinalize(\n\t\tjsonRpcRequest: Parameters<McpServer['receive']>[0],\n\t\tsessionId: string | undefined,\n\t\tresponseFinalizer: ResponseFinalizer\n\t): Promise<void> {\n\t\tconst owner = this._stateful ? (sessionId ?? randomUUID()) : randomUUID();\n\t\tconst response = await runWithContext({ requestId: randomUUID(), owner }, () =>\n\t\t\tthis._requireMcpServer().receive(jsonRpcRequest, { sessionInfo: {} })\n\t\t);\n\t\tconst responseHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (sessionId) responseHeaders['Mcp-Session-Id'] = sessionId;\n\n\t\tresponseFinalizer.finalize((httpResponse) => {\n\t\t\tif (response) {\n\t\t\t\thttpResponse.writeHead(200, responseHeaders);\n\t\t\t\thttpResponse.end(JSON.stringify(response));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (sessionId) httpResponse.setHeader('Mcp-Session-Id', sessionId);\n\t\t\thttpResponse.writeHead(202);\n\t\t\thttpResponse.end();\n\t\t});\n\t}\n\n\t/**\n\t * Handle GET /mcp — Optional SSE notification stream.\n\t *\n\t * Per the MCP Streamable HTTP spec, clients may open a GET request\n\t * to receive server-initiated notifications as SSE events.\n\t * Requires a valid Mcp-Session-Id in stateful mode.\n\t */\n\tprivate _handleMcpGet(req: IncomingMessage, res: ServerResponse): void {\n\t\tif (!this._stateful) {\n\t\t\t// SSE notification streams require stateful mode\n\t\t\tres.writeHead(405, {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\tAllow: 'POST',\n\t\t\t});\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\tid: null,\n\t\t\t\t\terror: { code: -32601, message: 'GET not supported in stateless mode' },\n\t\t\t\t})\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Require Mcp-Session-Id for GET requests\n\t\tconst sessionId = this._getSessionIdFromHeader(req);\n\t\tif (!sessionId) {\n\t\t\tres.writeHead(400, { 'Content-Type': 'application/json' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\tid: null,\n\t\t\t\t\terror: { code: -32600, message: 'Missing Mcp-Session-Id header' },\n\t\t\t\t})\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this._sessions.get(asSessionId(sessionId));\n\t\tif (!session) {\n\t\t\tres.writeHead(404, { 'Content-Type': 'application/json' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\tid: null,\n\t\t\t\t\terror: { code: -32001, message: 'Session not found' },\n\t\t\t\t})\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Set SSE headers\n\t\tres.writeHead(200, {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive',\n\t\t\t'Mcp-Session-Id': sessionId,\n\t\t});\n\n\t\t// Send initial connected event\n\t\tthis._sendSseEvent(res, 'connected', {\n\t\t\tsessionId,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Track this notification stream\n\t\tsession.notificationStreams.add(res);\n\t\tsession.lastActivityAt = Date.now();\n\t\tthis._updateSessionMetrics();\n\n\t\t// Handle client disconnect\n\t\treq.on('close', () => {\n\t\t\tsession.notificationStreams.delete(res);\n\t\t\tthis._updateSessionMetrics();\n\t\t});\n\t}\n\n\t/**\n\t * Resolve or create a session for a stateful request.\n\t *\n\t * @returns Session ID string on success, or the response error to finalize.\n\t */\n\tprivate _resolveSession(req: IncomingMessage): string | SessionError {\n\t\tconst headerSessionId = this._getSessionIdFromHeader(req);\n\n\t\tif (headerSessionId) {\n\t\t\t// Validate format\n\t\t\tif (!this.validateSessionId(headerSessionId)) {\n\t\t\t\treturn {\n\t\t\t\t\tstatusCode: 400,\n\t\t\t\t\tcode: -32600,\n\t\t\t\t\tmessage: 'Invalid Mcp-Session-Id format',\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Check if session exists\n\t\t\tconst session = this._sessions.get(asSessionId(headerSessionId));\n\t\t\tif (session) {\n\t\t\t\tsession.lastActivityAt = Date.now();\n\t\t\t\treturn headerSessionId;\n\t\t\t}\n\n\t\t\t// Unknown session ID — per spec, return 404\n\t\t\treturn { statusCode: 404, code: -32001, message: 'Session not found' };\n\t\t}\n\n\t\t// No session header — create new session\n\t\tconst newSessionId = this._sessionIdGenerator();\n\t\tconst sessionState: SessionState = {\n\t\t\tid: newSessionId,\n\t\t\tcreatedAt: Date.now(),\n\t\t\tlastActivityAt: Date.now(),\n\t\t\tnotificationStreams: new Set(),\n\t\t};\n\t\tthis._sessions.set(asSessionId(newSessionId), sessionState);\n\t\tthis.log('info', `New session created: ${newSessionId}`);\n\t\tthis._updateSessionMetrics();\n\n\t\treturn newSessionId;\n\t}\n\n\t/**\n\t * Extract Mcp-Session-Id from request headers.\n\t */\n\tprivate _getSessionIdFromHeader(req: IncomingMessage): string | undefined {\n\t\tconst value = req.headers['mcp-session-id'];\n\t\tif (typeof value === 'string' && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Send an SSE event to a specific client response stream.\n\t */\n\tprivate _sendSseEvent(res: ServerResponse, event: string, data: unknown): void {\n\t\ttry {\n\t\t\tres.write(`event: ${event}\\n`);\n\t\t\tres.write(`data: ${JSON.stringify(data)}\\n\\n`);\n\t\t} catch {\n\t\t\t// Client disconnected — ignore\n\t\t}\n\t}\n\n\t/**\n\t * Broadcast a notification to all SSE streams in a given session.\n\t *\n\t * @param sessionId - Target session ID\n\t * @param event - SSE event name\n\t * @param data - Event payload\n\t */\n\tbroadcastToSession(sessionId: string, event: string, data: unknown): void {\n\t\tconst session = this._sessions.get(asSessionId(sessionId));\n\t\tif (!session) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const stream of session.notificationStreams) {\n\t\t\tthis._sendSseEvent(stream, event, data);\n\t\t}\n\t}\n\n\t/**\n\t * Handle GET /metrics endpoint.\n\t */\n\tprivate _handleMetrics(res: ServerResponse): void {\n\t\tif (!this._metricsProvider) {\n\t\t\tres.writeHead(404, { 'Content-Type': 'text/plain' });\n\t\t\tres.end('Not Found');\n\t\t\treturn;\n\t\t}\n\n\t\tres.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8' });\n\t\tres.end(this._metricsProvider());\n\t}\n\n\t/**\n\t * Handle GET /health — Liveness check.\n\t */\n\tprivate _handleHealthCheck(res: ServerResponse): void {\n\t\tconst healthData: Record<string, unknown> = {\n\t\t\tstatus: 'healthy',\n\t\t\trequests: this._requestCount,\n\t\t\tsessions: this._sessions.size,\n\t\t\ttransport: 'streamable-http',\n\t\t};\n\t\tif (this._healthChecker) {\n\t\t\tconst liveness = this._healthChecker.checkLiveness();\n\t\t\thealthData.liveness = liveness;\n\t\t}\n\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\tres.end(JSON.stringify(healthData));\n\t}\n\n\t/**\n\t * Handle GET /ready — Readiness check.\n\t */\n\tprivate async _handleReadinessCheck(res: ServerResponse): Promise<void> {\n\t\tif (this._healthChecker) {\n\t\t\tconst readiness = await this._healthChecker.checkReadiness();\n\t\t\tconst statusCode = readiness.status === 'ok' ? 200 : 503;\n\t\t\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\t\t\tres.end(JSON.stringify(readiness));\n\t\t} else {\n\t\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tstatus: 'ok',\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tcomponents: {},\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Update session-related metrics.\n\t */\n\tprivate _updateSessionMetrics(): void {\n\t\tthis._metrics?.gauge(\n\t\t\t'streamable_http_active_sessions',\n\t\t\tthis._sessions.size,\n\t\t\t{},\n\t\t\t'Active Streamable HTTP sessions'\n\t\t);\n\n\t\tlet totalStreams = 0;\n\t\tfor (const session of this._sessions.values()) {\n\t\t\ttotalStreams += session.notificationStreams.size;\n\t\t}\n\t\tthis._metrics?.gauge(\n\t\t\t'streamable_http_notification_streams',\n\t\t\ttotalStreams,\n\t\t\t{},\n\t\t\t'Active SSE notification streams'\n\t\t);\n\t}\n\n\t/**\n\t * Stop transport server with graceful shutdown.\n\t *\n\t * @param timeout - Maximum time before force-closing HTTP connections (default: 30s)\n\t */\n\tstop(timeout?: number): Promise<void> {\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tthis._isShuttingDown = true;\n\t\tthis._stopRateLimitCleanup();\n\n\t\tconst shutdownTimeout = timeout ?? 30000;\n\n\t\t// Close all SSE notification streams\n\t\tfor (const session of this._sessions.values()) {\n\t\t\tfor (const stream of session.notificationStreams) {\n\t\t\t\ttry {\n\t\t\t\t\tstream.end();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore errors\n\t\t\t\t}\n\t\t\t}\n\t\t\tsession.notificationStreams.clear();\n\t\t}\n\t\tthis._sessions.clear();\n\n\t\tconst server = this._server;\n\t\tconst serverClosed = new Promise<void>((resolve, reject) => {\n\t\t\tif (!server?.listening) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet settled = false;\n\t\t\tlet forceClose: NodeJS.Timeout | null = null;\n\t\t\tserver.close((error) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (forceClose) clearTimeout(forceClose);\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tif (settled) return;\n\t\t\tforceClose = setTimeout(() => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tthis.log('warn', 'Streamable HTTP transport force-closing after timeout');\n\t\t\t\tserver.closeAllConnections();\n\t\t\t\tresolve();\n\t\t\t}, shutdownTimeout);\n\t\t});\n\t\tconst stopPromise = Promise.all([serverClosed, this._acceptedWork.join()]).then(() => {\n\t\t\tthis.log('info', 'Streamable HTTP transport stopped');\n\t\t});\n\t\tthis._stopPromise = stopPromise;\n\t\tvoid stopPromise.catch(() => {\n\t\t\tif (this._stopPromise === stopPromise) this._stopPromise = null;\n\t\t});\n\t\treturn stopPromise;\n\t}\n}\n\n/**\n * Create a Streamable HTTP transport with given options.\n *\n * @param options - Transport configuration\n * @returns A configured Streamable HTTP transport\n *\n * @example\n * ```typescript\n * const transport = createStreamableHttpTransport({ port: 3000, stateful: true });\n * await transport.connect(server);\n * ```\n */\nexport function createStreamableHttpTransport(\n\toptions: StreamableHttpTransportOptions = {}\n): StreamableHttpTransport {\n\treturn new StreamableHttpTransport(options);\n}\n"],"names":["StreamableHttpTransport","BaseTransport","Map","options","randomUUID","LifecycleFailureReporter","error","getErrorMessage","AcceptedWorkTracker","Error","mcpServer","server","createServer","req","res","responseFinalizer","ResponseFinalizer","response","Promise","resolve","reject","cleanup","onError","onListening","startTime","Date","durationSeconds","clientIp","urlPath","JSON","statusCode","code","message","id","extra","Object","timeout","setTimeout","body","readRequestBody","rawBody","parseResult","safeParse","JsonRpcRequestSchema","rawId","jsonRpcRequest","sessionId","sessionResult","clearTimeout","owner","runWithContext","responseHeaders","httpResponse","session","asSessionId","headerSessionId","newSessionId","sessionState","Set","value","event","data","stream","healthData","liveness","readiness","totalStreams","shutdownTimeout","serverClosed","settled","forceClose","stopPromise","createStreamableHttpTransport"],"mappings":";;;;;;;;;;AAsJO,MAAMA,gCAAgCC;IAC5C,IAAI,OAAsB;QACzB,OAAO;IACR;IACQ,UAAyB,KAAK;IAC9B,aAA+B,KAAK;IACpC,MAAc;IACd,UAAmB;IACnB,oBAAkC;IAClC,YAA0C,IAAIC,MAAM;IACpD,gBAAwB,EAAE;IAC1B,kBAA0B,EAAE;IAC5B,sBAA+B;IAC/B,aAAqB;IACrB,gBAAwB;IACxB,SAAoB;IACpB,iBAAwC;IAC/B,0BAAoD;IACpD,cAAmC;IAC5C,eAAqC,KAAK;IAElD,YAAYC,UAA0C,CAAC,CAAC,CAAE;QACzD,KAAK,CAACA;QAEN,IAAI,CAAC,KAAK,GAAGA,QAAQ,IAAI,IAAI;QAC7B,IAAI,CAAC,SAAS,GAAGA,QAAQ,QAAQ,IAAI;QACrC,IAAI,CAAC,mBAAmB,GAAGA,QAAQ,kBAAkB,IAAM,KAAKC,YAAW;QAC3E,IAAI,CAAC,qBAAqB,GAAGD,QAAQ,mBAAmB,IAAI;QAC5D,IAAI,CAAC,YAAY,GAAGA,QAAQ,WAAW,IAAI;QAC3C,IAAI,CAAC,eAAe,GAAGA,QAAQ,cAAc,IAAI;QACjD,IAAI,CAAC,QAAQ,GAAGA,QAAQ,OAAO;QAC/B,IAAI,CAAC,gBAAgB,GAAGA,QAAQ,eAAe,IAAI;QACnD,IAAI,CAAC,yBAAyB,GAAG,IAAIE,yBAAyB,CAACC;YAC9D,IAAI,CAAC,GA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,CAAC,GAAG,CAAC,QAAQ;QAClB;QACA,IAAI,CAAC,YAAY,GAAGG;QACfA,YAAY,KAAK,CAAC;YACtB,IAAI,IAAI,CAAC,YAAY,KAAKA,aAAa,IAAI,CAAC,YAAY,GAAG;QAC5D;QACA,OAAOA;IACR;AACD;AAcO,SAASC,8BACfrE,UAA0C,CAAC,CAAC;IAE5C,OAAO,IAAIH,wBAAwBG;AACpC"}
|
|
1
|
+
{"version":3,"file":"transport/StreamableHttpTransport.js","sources":["../../src/transport/StreamableHttpTransport.ts"],"sourcesContent":["/**\n * Streamable HTTP Transport implementation (MCP spec recommended transport).\n *\n * Key features:\n * - POST /mcp for JSON-RPC requests (main MCP endpoint)\n * - Session management via Mcp-Session-Id header\n * - Supports both stateful (session-based) and stateless (per-request) modes\n * - Health endpoints (/health, /ready)\n *\n * @example\n * ```typescript\n * const transport = new StreamableHttpTransport({\n * port: 3000,\n * host: 'localhost',\n * stateful: true,\n * });\n * await transport.connect(server);\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport type { McpServer } from 'tmcp';\nimport { safeParse } from 'valibot';\nimport type { IMetrics } from '../contracts/interfaces.js';\nimport { getErrorMessage } from '../errors.js';\nimport { JsonRpcRequestSchema } from '../schema.js';\nimport { BaseTransport, type TransportOptions } from './BaseTransport.js';\nimport type { ITransport, TransportKind } from '../contracts/transport.js';\nimport { asSessionId, type SessionId } from '../contracts/ids.js';\nimport { readRequestBody } from './HttpHelpers.js';\nimport { runWithContext } from '../context/RequestContext.js';\nimport {\n\tAcceptedWorkTracker,\n\tLifecycleFailureReporter,\n\tPreDispatchTracker,\n\tResponseFinalizer,\n\ttype PreDispatchLease,\n} from './HttpRequestLifecycle.js';\n\n/**\n * MCP Streamable HTTP transport options extending base TransportOptions.\n */\nexport interface StreamableHttpTransportOptions extends TransportOptions {\n\t/**\n\t * Path for the MCP endpoint\n\t * @default '/mcp'\n\t */\n\tpath?: string;\n\n\t/**\n\t * Metrics collector for transport telemetry\n\t */\n\tmetrics?: IMetrics;\n\n\t/**\n\t * Prometheus metrics provider function\n\t */\n\tmetricsProvider?: () => string;\n\n\t/**\n\t * Enable stateful session-based mode.\n\t * When true, sessions are tracked via Mcp-Session-Id header.\n\t * When false, each request is processed independently (stateless).\n\t * @default true\n\t */\n\tstateful?: boolean;\n\n\t/**\n\t * Custom session ID generator function.\n\t * @default () => randomUUID()\n\t */\n\tsessionIdGenerator?: () => string;\n\n\t/**\n\t * Enable request body size limit\n\t * @default true\n\t */\n\tenableBodySizeLimit?: boolean;\n\n\t/**\n\t * Maximum request body size in bytes\n\t * @default 10485760 (10MB)\n\t */\n\tmaxBodySize?: number;\n\n\t/**\n\t * Request timeout in milliseconds\n\t * @default 30000 (30 seconds)\n\t */\n\trequestTimeout?: number;\n\n\t/** Maximum retained sessions when idle expiry is enabled. */\n\tmaxSessions?: number;\n\n\t/** Idle duration before an unpinned session expires. */\n\tsessionIdleTimeoutMs?: number;\n\n\t/** Interval between idle-session sweeps. */\n\tsessionSweepIntervalMs?: number;\n}\n\ntype SessionRetentionOptions = {\n\treadonly maxSessions: number;\n\treadonly sessionIdleTimeoutMs: number;\n\treadonly sessionSweepIntervalMs: number;\n};\n\nfunction parseSessionRetentionOptions(\n\toptions: StreamableHttpTransportOptions\n): SessionRetentionOptions | null {\n\tconst { maxSessions, sessionIdleTimeoutMs, sessionSweepIntervalMs } = options;\n\tif (\n\t\tmaxSessions === undefined &&\n\t\tsessionIdleTimeoutMs === undefined &&\n\t\tsessionSweepIntervalMs === undefined\n\t) {\n\t\treturn null;\n\t}\n\tif (\n\t\tmaxSessions === undefined ||\n\t\t!Number.isFinite(maxSessions) ||\n\t\t!Number.isInteger(maxSessions) ||\n\t\tmaxSessions <= 0 ||\n\t\tsessionIdleTimeoutMs === undefined ||\n\t\t!Number.isFinite(sessionIdleTimeoutMs) ||\n\t\t!Number.isInteger(sessionIdleTimeoutMs) ||\n\t\tsessionIdleTimeoutMs <= 0 ||\n\t\tsessionSweepIntervalMs === undefined ||\n\t\t!Number.isFinite(sessionSweepIntervalMs) ||\n\t\t!Number.isInteger(sessionSweepIntervalMs) ||\n\t\tsessionSweepIntervalMs <= 0\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'maxSessions, sessionIdleTimeoutMs, and sessionSweepIntervalMs must be provided together as positive integers'\n\t\t);\n\t}\n\treturn {\n\t\tmaxSessions,\n\t\tsessionIdleTimeoutMs,\n\t\tsessionSweepIntervalMs,\n\t};\n}\n\n/**\n * Internal session state for stateful mode.\n */\ninterface SessionState {\n\t/** Unique session identifier */\n\tid: SessionId;\n\t/** Timestamp when the session was created */\n\tcreatedAt: number;\n\t/** Timestamp of the last activity */\n\tlastActivityAt: number;\n\tacceptedPostCount: number;\n}\n\ntype SessionError = {\n\treadonly statusCode: number;\n\treadonly code: number;\n\treadonly message: string;\n};\n\ntype AcceptedPostSession = {\n\treadonly id: string | undefined;\n\treadonly state: SessionState | null;\n};\n\n/**\n * Streamable HTTP Transport for MCP server.\n *\n * This transport implements the MCP Streamable HTTP specification,\n * providing JSON-RPC over HTTP with optional session management.\n *\n * @remarks\n * **Security Features (inherited from BaseTransport):**\n * - Session ID validation (alphanumeric, max 64 chars)\n * - Query parameter sanitization (whitelist allowed keys)\n * - Rate limiting per IP (configurable, default 100 req/min)\n * - CORS origin validation\n * - Host header validation\n *\n * **MCP Streamable HTTP Spec Compliance:**\n * - POST /mcp — JSON-RPC method calls\n * - Mcp-Session-Id header for session management\n * - Content-Type: application/json for JSON-RPC responses\n *\n * **HTTP Status Code Mapping:**\n * - 200: Success (JSON-RPC response)\n * - 202: Accepted (JSON-RPC notification, no response body)\n * - 204: CORS Preflight (empty body)\n * - 400: Bad Request (invalid JSON, invalid session ID)\n * - 403: Forbidden (invalid CORS, invalid host)\n * - 404: Not Found\n * - 405: Method Not Allowed\n * - 413: Payload Too Large\n * - 429: Too Many Requests\n * - 500: Internal Server Error\n * - 503: Server Not Ready / Shutting Down\n */\nexport class StreamableHttpTransport extends BaseTransport implements ITransport {\n\tget kind(): TransportKind {\n\t\treturn 'streamable-http';\n\t}\n\tprivate _server: Server | null = null;\n\tprivate _mcpServer: McpServer | null = null;\n\tprivate _path: string;\n\tprivate _stateful: boolean;\n\tprivate _sessionIdGenerator: () => string;\n\tprivate _sessions: Map<SessionId, SessionState> = new Map();\n\tprivate _requestCount: number = 0;\n\tprivate _activeRequests: number = 0;\n\tprivate _bodySizeLimitEnabled: boolean;\n\tprivate _maxBodySize: number;\n\tprivate _requestTimeout: number;\n\tprivate _metrics?: IMetrics;\n\tprivate _metricsProvider: (() => string) | null;\n\tprivate readonly _lifecycleFailureReporter: LifecycleFailureReporter;\n\tprivate readonly _acceptedWork: AcceptedWorkTracker;\n\tprivate readonly _preDispatch = new PreDispatchTracker();\n\tprivate readonly _sessionRetention: SessionRetentionOptions | null;\n\tprivate _sessionSweepIntervalId: NodeJS.Timeout | null = null;\n\tprivate _stopPromise: Promise<void> | null = null;\n\n\tconstructor(options: StreamableHttpTransportOptions = {}) {\n\t\tconst sessionRetention = parseSessionRetentionOptions(options);\n\t\tsuper(options);\n\n\t\tthis._path = options.path ?? '/mcp';\n\t\tthis._stateful = options.stateful ?? true;\n\t\tthis._sessionIdGenerator = options.sessionIdGenerator ?? (() => randomUUID());\n\t\tthis._bodySizeLimitEnabled = options.enableBodySizeLimit ?? true;\n\t\tthis._maxBodySize = options.maxBodySize ?? 10 * 1024 * 1024;\n\t\tthis._requestTimeout = options.requestTimeout ?? 30000;\n\t\tthis._metrics = options.metrics;\n\t\tthis._metricsProvider = options.metricsProvider ?? null;\n\t\tthis._sessionRetention = sessionRetention;\n\t\tthis._lifecycleFailureReporter = new LifecycleFailureReporter((error) => {\n\t\t\tthis.log('error', 'Streamable HTTP request lifecycle failed', {\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t});\n\t\tthis._acceptedWork = new AcceptedWorkTracker(this._lifecycleFailureReporter);\n\t\tif (this._stateful && sessionRetention) {\n\t\t\tthis._sessionSweepIntervalId = setInterval(\n\t\t\t\t() => this._sweepExpiredSessions(),\n\t\t\t\tsessionRetention.sessionSweepIntervalMs\n\t\t\t);\n\t\t\tthis._sessionSweepIntervalId.unref();\n\t\t}\n\t}\n\n\tprivate _requireMcpServer(): McpServer {\n\t\tif (!this._mcpServer) {\n\t\t\tthrow new Error('MCP server not initialized. Did you call connect()?');\n\t\t}\n\t\treturn this._mcpServer;\n\t}\n\n\t/**\n\t * Get number of active sessions (stateful) or active requests (stateless).\n\t */\n\tget clientCount(): number {\n\t\treturn this._stateful ? this._sessions.size : this._activeRequests;\n\t}\n\n\t/**\n\t * Get the total number of requests handled.\n\t */\n\tget requestCount(): number {\n\t\treturn this._requestCount;\n\t}\n\n\t/**\n\t * Connects MCP server to this transport and starts listening.\n\t */\n\tasync connect(mcpServer: McpServer): Promise<void> {\n\t\tthis._mcpServer = mcpServer;\n\t\tconst server = createServer((req, res) => {\n\t\t\tconst responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);\n\t\t\tvoid this._handleRequest(req, res).catch((error: unknown) => {\n\t\t\t\tthis._lifecycleFailureReporter.report(error);\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(response, 500, -32603, 'Internal error', null, {\n\t\t\t\t\t\tdata: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tthis._server = server;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = (): void => {\n\t\t\t\tserver.off('error', onError);\n\t\t\t\tserver.off('listening', onListening);\n\t\t\t};\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t};\n\t\t\tconst onListening = (): void => {\n\t\t\t\tcleanup();\n\t\t\t\tthis.log(\n\t\t\t\t\t'info',\n\t\t\t\t\t`Streamable HTTP transport listening on http://${this._host}:${this._port}`\n\t\t\t\t);\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tserver.once('error', onError);\n\t\t\tserver.once('listening', onListening);\n\t\t\ttry {\n\t\t\t\tserver.listen(this._port, this._host);\n\t\t\t} catch (error) {\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate _recordRequestMetrics(res: ServerResponse): void {\n\t\tconst startTime = Date.now();\n\t\tthis._metrics?.counter(\n\t\t\t'streamable_http_requests_total',\n\t\t\t1,\n\t\t\t{},\n\t\t\t'Total Streamable HTTP transport requests'\n\t\t);\n\t\tres.once('finish', () => {\n\t\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\t\tthis._metrics?.histogram('streamable_http_request_duration_seconds', durationSeconds, {});\n\t\t});\n\t}\n\n\t/**\n\t * Route and handle incoming HTTP requests.\n\t */\n\tprivate async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {\n\t\tthis._recordRequestMetrics(res);\n\n\t\t// Host validation\n\t\tif (!this.validateHostHeader(req)) {\n\t\t\tthis._sendJsonRpcError(res, 403, -32000, 'Forbidden - invalid host header');\n\t\t\treturn;\n\t\t}\n\n\t\t// Shutdown check\n\t\tif (this.isShuttingDown) {\n\t\t\tthis._sendJsonRpcError(res, 503, -32603, 'Server is shutting down');\n\t\t\treturn;\n\t\t}\n\n\t\t// Rate limiting\n\t\tconst clientIp = this.getClientIp(req);\n\t\tif (this.checkRateLimit(clientIp)) {\n\t\t\tres.setHeader('Retry-After', '60');\n\t\t\tthis._sendJsonRpcError(res, 429, -32000, 'Too many requests');\n\t\t\treturn;\n\t\t}\n\n\t\t// CORS validation\n\t\tif (!this.validateCorsOrigin(req)) {\n\t\t\tthis._sendJsonRpcError(res, 403, -32000, 'Forbidden - invalid origin');\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setCorsHeaders(res);\n\n\t\t// CORS preflight\n\t\tif (req.method === 'OPTIONS') {\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'Content-Type, Mcp-Session-Id');\n\t\t\tres.writeHead(204);\n\t\t\tres.end();\n\t\t\treturn;\n\t\t}\n\n\t\t// Parse URL path\n\t\tconst urlPath = req.url?.split('?')[0] ?? '/';\n\n\t\t// Metrics endpoint\n\t\tif (req.method === 'GET' && urlPath === '/metrics') {\n\t\t\tthis._handleMetrics(res);\n\t\t\treturn;\n\t\t}\n\n\t\t// Health check (liveness)\n\t\tif (req.method === 'GET' && urlPath === '/health') {\n\t\t\tthis._handleHealthCheck(res);\n\t\t\treturn;\n\t\t}\n\n\t\t// Readiness check\n\t\tif (req.method === 'GET' && urlPath === '/ready') {\n\t\t\tawait this._handleReadinessCheck(res);\n\t\t\treturn;\n\t\t}\n\n\t\t// MCP endpoint routing\n\t\tif (urlPath === this._path) {\n\t\t\tif (req.method === 'POST') {\n\t\t\t\tconst lease = this._preDispatch.acquire();\n\t\t\t\tif (!lease) {\n\t\t\t\t\tconst responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);\n\t\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\t\tthis._sendJsonRpcError(response, 503, -32603, 'Server is shutting down');\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait this._handleMcpPost(req, res, lease);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.writeHead(405, { 'Content-Type': 'application/json', Allow: 'POST' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\tid: null,\n\t\t\t\t\terror: { code: -32601, message: 'Method not allowed' },\n\t\t\t\t})\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// 404 for unknown paths\n\t\tthis._sendJsonRpcError(res, 404, -32601, 'Not Found');\n\t}\n\n\t/**\n\t * Send a JSON-RPC error response.\n\t */\n\tprivate _sendJsonRpcError(\n\t\tres: ServerResponse,\n\t\tstatusCode: number,\n\t\tcode: number,\n\t\tmessage: string,\n\t\tid: unknown = null,\n\t\textra?: Record<string, unknown>\n\t): void {\n\t\tconst error: Record<string, unknown> = { code, message };\n\t\tif (extra) {\n\t\t\tObject.assign(error, extra);\n\t\t}\n\t\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\t\tres.end(JSON.stringify({ jsonrpc: '2.0', id, error }));\n\t}\n\n\tprivate _parseJsonRpcRequest(\n\t\tbody: string,\n\t\tresponseFinalizer: ResponseFinalizer\n\t): Parameters<McpServer['receive']>[0] | null {\n\t\tlet rawBody: unknown;\n\t\ttry {\n\t\t\trawBody = JSON.parse(body) as unknown;\n\t\t} catch {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, 200, -32700, 'Parse error');\n\t\t\t});\n\t\t\treturn null;\n\t\t}\n\n\t\tconst parseResult = safeParse(JsonRpcRequestSchema, rawBody);\n\t\tconst rawId =\n\t\t\trawBody && typeof rawBody === 'object' && 'id' in rawBody\n\t\t\t\t? ((rawBody as { id?: unknown }).id ?? null)\n\t\t\t\t: null;\n\t\tif (!parseResult.success) {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(\n\t\t\t\t\tresponse,\n\t\t\t\t\t200,\n\t\t\t\t\t-32600,\n\t\t\t\t\t'Invalid Request',\n\t\t\t\t\trawId as string | number | null,\n\t\t\t\t\t{ data: parseResult.issues }\n\t\t\t\t);\n\t\t\t});\n\t\t\treturn null;\n\t\t}\n\t\treturn parseResult.output as Parameters<McpServer['receive']>[0];\n\t}\n\n\t/**\n\t * Handle POST /mcp — JSON-RPC method calls.\n\t *\n\t * Per the MCP Streamable HTTP spec:\n\t * - Accepts JSON-RPC request bodies\n\t * - Returns Mcp-Session-Id header for new sessions (stateful mode)\n\t * - Validates Mcp-Session-Id for existing sessions (stateful mode)\n\t * - Content-Type: application/json for responses\n\t */\n\tprivate async _handleMcpPost(\n\t\treq: IncomingMessage,\n\t\tres: ServerResponse,\n\t\tlease: PreDispatchLease\n\t): Promise<void> {\n\t\tthis._requestCount++;\n\t\tthis._activeRequests++;\n\t\tconst responseFinalizer = new ResponseFinalizer(res, this._lifecycleFailureReporter);\n\t\tlet acceptedSession: SessionState | null = null;\n\t\tconst onAborted = (): void => lease.cancel('peer');\n\t\treq.once('aborted', onAborted);\n\n\t\tconst timeout = setTimeout(() => {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, 500, -32603, 'Request timeout');\n\t\t\t});\n\t\t\tlease.cancel('timeout');\n\t\t}, this._requestTimeout);\n\t\ttry {\n\t\t\t// Read request body with size limit\n\t\t\tconst body = await readRequestBody(\n\t\t\t\treq,\n\t\t\t\tthis._bodySizeLimitEnabled ? this._maxBodySize : 0,\n\t\t\t\tlease.signal\n\t\t\t);\n\t\t\tif (body === null) {\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(response, 413, -32000, 'Request body too large');\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst jsonRpcRequest = this._parseJsonRpcRequest(body, responseFinalizer);\n\t\t\tif (jsonRpcRequest === null) return;\n\n\t\t\tconst session = this._acceptPostSession(req, responseFinalizer);\n\t\t\tif (!session) return;\n\t\t\tacceptedSession = session.state;\n\n\t\t\t// Check if MCP server is ready\n\t\t\tif (!this._mcpServer) {\n\t\t\t\tconst requestId = 'id' in jsonRpcRequest ? (jsonRpcRequest.id ?? null) : null;\n\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\tthis._sendJsonRpcError(response, 503, -32603, 'Server not ready', requestId);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treq.off('aborted', onAborted);\n\t\t\tconst acceptedWork = this._acceptedWork.transfer(lease, () =>\n\t\t\t\tthis._receiveAndFinalize(jsonRpcRequest, session.id, responseFinalizer).catch(\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\t\t\tthis._sendJsonRpcError(response, 200, -32603, 'Internal error', null, {\n\t\t\t\t\t\t\t\tdata: getErrorMessage(error),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t);\n\t\t\tawait acceptedWork;\n\t\t} catch (error) {\n\t\t\tif (lease.signal.aborted) {\n\t\t\t\tif (lease.cancellationReason === 'shutdown') {\n\t\t\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\t\t\tthis._sendJsonRpcError(response, 503, -32603, 'Server is shutting down');\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, 200, -32603, 'Internal error', null, {\n\t\t\t\t\tdata: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t});\n\t\t} finally {\n\t\t\treq.off('aborted', onAborted);\n\t\t\tlease.release();\n\t\t\tif (acceptedSession) acceptedSession.acceptedPostCount--;\n\t\t\tclearTimeout(timeout);\n\t\t\tthis._activeRequests--;\n\t\t}\n\t}\n\n\tprivate _acceptPostSession(\n\t\treq: IncomingMessage,\n\t\tresponseFinalizer: ResponseFinalizer\n\t): AcceptedPostSession | null {\n\t\tif (!this._stateful) return { id: undefined, state: null };\n\t\tif (this.isShuttingDown) {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, 503, -32603, 'Server is shutting down');\n\t\t\t});\n\t\t\treturn null;\n\t\t}\n\t\tconst session = this._resolveSession(req);\n\t\tif (!('state' in session)) {\n\t\t\tresponseFinalizer.finalize((response) => {\n\t\t\t\tthis._sendJsonRpcError(response, session.statusCode, session.code, session.message);\n\t\t\t});\n\t\t\treturn null;\n\t\t}\n\t\tsession.state.acceptedPostCount++;\n\t\treturn { id: session.id, state: session.state };\n\t}\n\n\tprivate async _receiveAndFinalize(\n\t\tjsonRpcRequest: Parameters<McpServer['receive']>[0],\n\t\tsessionId: string | undefined,\n\t\tresponseFinalizer: ResponseFinalizer\n\t): Promise<void> {\n\t\tconst owner = this._stateful ? (sessionId ?? randomUUID()) : randomUUID();\n\t\tconst response = await runWithContext({ requestId: randomUUID(), owner }, () =>\n\t\t\tthis._requireMcpServer().receive(jsonRpcRequest, { sessionInfo: {} })\n\t\t);\n\t\tconst responseHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (sessionId) responseHeaders['Mcp-Session-Id'] = sessionId;\n\n\t\tresponseFinalizer.finalize((httpResponse) => {\n\t\t\tif (response) {\n\t\t\t\thttpResponse.writeHead(200, responseHeaders);\n\t\t\t\thttpResponse.end(JSON.stringify(response));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (sessionId) httpResponse.setHeader('Mcp-Session-Id', sessionId);\n\t\t\thttpResponse.writeHead(202);\n\t\t\thttpResponse.end();\n\t\t});\n\t}\n\n\t/**\n\t * Resolve or create a session for a stateful request.\n\t *\n\t * @returns Session ID string on success, or the response error to finalize.\n\t */\n\tprivate _resolveSession(\n\t\treq: IncomingMessage\n\t): { readonly id: SessionId; readonly state: SessionState } | SessionError {\n\t\tconst headerSessionId = this._getSessionIdFromHeader(req);\n\n\t\tif (headerSessionId) {\n\t\t\t// Validate format\n\t\t\tif (!this.validateSessionId(headerSessionId)) {\n\t\t\t\treturn {\n\t\t\t\t\tstatusCode: 400,\n\t\t\t\t\tcode: -32600,\n\t\t\t\t\tmessage: 'Invalid Mcp-Session-Id format',\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Check if session exists\n\t\t\tconst session = this._sessions.get(asSessionId(headerSessionId));\n\t\t\tif (session) {\n\t\t\t\tsession.lastActivityAt = Date.now();\n\t\t\t\treturn { id: session.id, state: session };\n\t\t\t}\n\n\t\t\t// Unknown session ID — per spec, return 404\n\t\t\treturn { statusCode: 404, code: -32001, message: 'Session not found' };\n\t\t}\n\n\t\t// No session header — create new session\n\t\tif (this._sessionRetention && this._sessions.size >= this._sessionRetention.maxSessions) {\n\t\t\treturn { statusCode: 503, code: -32000, message: 'Session capacity reached' };\n\t\t}\n\t\tconst newSessionId = asSessionId(this._sessionIdGenerator());\n\t\tconst now = Date.now();\n\t\tconst sessionState: SessionState = {\n\t\t\tid: newSessionId,\n\t\t\tcreatedAt: now,\n\t\t\tlastActivityAt: now,\n\t\t\tacceptedPostCount: 0,\n\t\t};\n\t\tthis._sessions.set(newSessionId, sessionState);\n\t\tthis.log('info', `New session created: ${newSessionId}`);\n\t\tthis._updateSessionMetrics();\n\n\t\treturn { id: newSessionId, state: sessionState };\n\t}\n\n\tprivate _sweepExpiredSessions(): void {\n\t\tif (!this._sessionRetention) return;\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, session] of this._sessions) {\n\t\t\tif (\n\t\t\t\tsession.acceptedPostCount === 0 &&\n\t\t\t\tnow - session.lastActivityAt >= this._sessionRetention.sessionIdleTimeoutMs\n\t\t\t) {\n\t\t\t\tthis._disposeSession(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _disposeSession(sessionId: SessionId): void {\n\t\tif (!this._sessions.delete(sessionId)) return;\n\t\tthis._updateSessionMetrics();\n\t}\n\n\tprivate _stopSessionSweep(): void {\n\t\tconst interval = this._sessionSweepIntervalId;\n\t\tif (!interval) return;\n\t\tinterval.unref();\n\t\tclearInterval(interval);\n\t\tthis._sessionSweepIntervalId = null;\n\t}\n\n\t/**\n\t * Extract Mcp-Session-Id from request headers.\n\t */\n\tprivate _getSessionIdFromHeader(req: IncomingMessage): string | undefined {\n\t\tconst value = req.headers['mcp-session-id'];\n\t\tif (typeof value === 'string' && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Handle GET /metrics endpoint.\n\t */\n\tprivate _handleMetrics(res: ServerResponse): void {\n\t\tif (!this._metricsProvider) {\n\t\t\tres.writeHead(404, { 'Content-Type': 'text/plain' });\n\t\t\tres.end('Not Found');\n\t\t\treturn;\n\t\t}\n\n\t\tres.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8' });\n\t\tres.end(this._metricsProvider());\n\t}\n\n\t/**\n\t * Handle GET /health — Liveness check.\n\t */\n\tprivate _handleHealthCheck(res: ServerResponse): void {\n\t\tconst healthData: Record<string, unknown> = {\n\t\t\tstatus: 'healthy',\n\t\t\trequests: this._requestCount,\n\t\t\tsessions: this._sessions.size,\n\t\t\ttransport: 'streamable-http',\n\t\t};\n\t\tif (this._healthChecker) {\n\t\t\tconst liveness = this._healthChecker.checkLiveness();\n\t\t\thealthData.liveness = liveness;\n\t\t}\n\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\tres.end(JSON.stringify(healthData));\n\t}\n\n\t/**\n\t * Handle GET /ready — Readiness check.\n\t */\n\tprivate async _handleReadinessCheck(res: ServerResponse): Promise<void> {\n\t\tif (this._healthChecker) {\n\t\t\tconst readiness = await this._healthChecker.checkReadiness();\n\t\t\tconst statusCode = readiness.status === 'ok' ? 200 : 503;\n\t\t\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\t\t\tres.end(JSON.stringify(readiness));\n\t\t} else {\n\t\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tstatus: 'ok',\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tcomponents: {},\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Update session-related metrics.\n\t */\n\tprivate _updateSessionMetrics(): void {\n\t\tthis._metrics?.gauge(\n\t\t\t'streamable_http_active_sessions',\n\t\t\tthis._sessions.size,\n\t\t\t{},\n\t\t\t'Active Streamable HTTP sessions'\n\t\t);\n\t}\n\n\t/**\n\t * Stop transport server with graceful shutdown.\n\t *\n\t * @param timeout - Maximum time before force-closing HTTP connections (default: 30s)\n\t */\n\tstop(timeout?: number): Promise<void> {\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tthis._isShuttingDown = true;\n\t\tthis._preDispatch.closeAdmission('shutdown');\n\t\tthis._stopRateLimitCleanup();\n\t\tthis._stopSessionSweep();\n\n\t\tconst shutdownTimeout = timeout ?? 30000;\n\n\t\tfor (const sessionId of this._sessions.keys()) {\n\t\t\tthis._disposeSession(sessionId);\n\t\t}\n\n\t\tconst server = this._server;\n\t\tconst serverClosed = new Promise<void>((resolve, reject) => {\n\t\t\tif (!server?.listening) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet settled = false;\n\t\t\tlet forceClose: NodeJS.Timeout | null = null;\n\t\t\tserver.close((error) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (forceClose) clearTimeout(forceClose);\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tif (settled) return;\n\t\t\tforceClose = setTimeout(() => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tthis.log('warn', 'Streamable HTTP transport force-closing after timeout');\n\t\t\t\tserver.closeAllConnections();\n\t\t\t\tresolve();\n\t\t\t}, shutdownTimeout);\n\t\t});\n\t\tconst stopPromise = Promise.all([\n\t\t\tserverClosed,\n\t\t\tthis._preDispatch.join().then(() => this._acceptedWork.join()),\n\t\t]).then(() => {\n\t\t\tthis.log('info', 'Streamable HTTP transport stopped');\n\t\t});\n\t\tthis._stopPromise = stopPromise;\n\t\tvoid stopPromise.catch(() => {\n\t\t\tif (this._stopPromise === stopPromise) this._stopPromise = null;\n\t\t});\n\t\treturn stopPromise;\n\t}\n}\n\n/**\n * Create a Streamable HTTP transport with given options.\n *\n * @param options - Transport configuration\n * @returns A configured Streamable HTTP transport\n *\n * @example\n * ```typescript\n * const transport = createStreamableHttpTransport({ port: 3000, stateful: true });\n * await transport.connect(server);\n * ```\n */\nexport function createStreamableHttpTransport(\n\toptions: StreamableHttpTransportOptions = {}\n): StreamableHttpTransport {\n\treturn new StreamableHttpTransport(options);\n}\n"],"names":["parseSessionRetentionOptions","options","maxSessions","sessionIdleTimeoutMs","sessionSweepIntervalMs","undefined","Number","TypeError","StreamableHttpTransport","BaseTransport","Map","PreDispatchTracker","sessionRetention","randomUUID","LifecycleFailureReporter","error","getErrorMessage","AcceptedWorkTracker","setInterval","Error","mcpServer","server","createServer","req","res","responseFinalizer","ResponseFinalizer","response","Promise","resolve","reject","cleanup","onError","onListening","startTime","Date","durationSeconds","clientIp","urlPath","lease","JSON","statusCode","code","message","id","extra","Object","body","rawBody","parseResult","safeParse","JsonRpcRequestSchema","rawId","acceptedSession","onAborted","timeout","setTimeout","readRequestBody","jsonRpcRequest","session","requestId","acceptedWork","clearTimeout","sessionId","owner","runWithContext","responseHeaders","httpResponse","headerSessionId","asSessionId","newSessionId","now","sessionState","interval","clearInterval","value","healthData","liveness","readiness","shutdownTimeout","serverClosed","settled","forceClose","stopPromise","createStreamableHttpTransport"],"mappings":";;;;;;;;;;AA4GA,SAASA,6BACRC,OAAuC;IAEvC,MAAM,EAAEC,WAAW,EAAEC,oBAAoB,EAAEC,sBAAsB,EAAE,GAAGH;IACtE,IACCC,AAAgBG,WAAhBH,eACAC,AAAyBE,WAAzBF,wBACAC,AAA2BC,WAA3BD,wBAEA,OAAO;IAER,IACCF,AAAgBG,WAAhBH,eACA,CAACI,OAAO,QAAQ,CAACJ,gBACjB,CAACI,OAAO,SAAS,CAACJ,gBAClBA,eAAe,KACfC,AAAyBE,WAAzBF,wBACA,CAACG,OAAO,QAAQ,CAACH,yBACjB,CAACG,OAAO,SAAS,CAACH,yBAClBA,wBAAwB,KACxBC,AAA2BC,WAA3BD,0BACA,CAACE,OAAO,QAAQ,CAACF,2BACjB,CAACE,OAAO,SAAS,CAACF,2BAClBA,0BAA0B,GAE1B,MAAM,IAAIG,UACT;IAGF,OAAO;QACNL;QACAC;QACAC;IACD;AACD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YAID,IAAIoD,UAAU;YACd,IAAIC,aAAoC;YACxC7D,OAAO,KAAK,CAAC,CAACN;gBACb,IAAIkE,SAAS;gBACbA,UAAU;gBACV,IAAIC,YAAYpB,aAAaoB;gBAC7B,IAAInE,OAAO,YACVe,OAAOf;gBAGRc;YACD;YACA,IAAIoD,SAAS;YACbC,aAAa1B,WAAW;gBACvB,IAAIyB,SAAS;gBACbA,UAAU;gBACV,IAAI,CAAC,GAAG,CAAC,QAAQ;gBACjB5D,OAAO,mBAAmB;gBAC1BQ;YACD,GAAGkD;QACJ;QACA,MAAMI,cAAcvD,QAAQ,GAAG,CAAC;YAC/BoD;YACA,IAAI,CAAC,YAAY,CAAC,IAAI,GAAG,IAAI,CAAC,IAAM,IAAI,CAAC,aAAa,CAAC,IAAI;SAC3D,EAAE,IAAI,CAAC;YACP,IAAI,CAAC,GAAG,CAAC,QAAQ;QAClB;QACA,IAAI,CAAC,YAAY,GAAGG;QACfA,YAAY,KAAK,CAAC;YACtB,IAAI,IAAI,CAAC,YAAY,KAAKA,aAAa,IAAI,CAAC,YAAY,GAAG;QAC5D;QACA,OAAOA;IACR;AACD;AAcO,SAASC,8BACfnF,UAA0C,CAAC,CAAC;IAE5C,OAAO,IAAIO,wBAAwBP;AACpC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iworkforces/tracelattice",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.8",
|
|
4
4
|
"description": "Semantic Sequential Thinking Layer For AI Agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/lib.js",
|
|
@@ -85,14 +85,14 @@
|
|
|
85
85
|
"devDependencies": {
|
|
86
86
|
"@changesets/cli": "^3.0.3",
|
|
87
87
|
"@eslint/js": "^10.0.1",
|
|
88
|
-
"@rsbuild/core": "^2.2.
|
|
88
|
+
"@rsbuild/core": "^2.2.8",
|
|
89
89
|
"@rslib/core": "^1.0.1",
|
|
90
|
-
"@types/node": "^26.6.
|
|
90
|
+
"@types/node": "^26.6.2",
|
|
91
91
|
"@typescript-eslint/eslint-plugin": "^8.70.0",
|
|
92
92
|
"@typescript-eslint/parser": "^8.70.0",
|
|
93
93
|
"@vitest/coverage-v8": "^5.0.1",
|
|
94
94
|
"better-sqlite3": "13.0.3",
|
|
95
|
-
"eslint": "^10.
|
|
95
|
+
"eslint": "^10.11.0",
|
|
96
96
|
"globals": "^17.12.0",
|
|
97
97
|
"prettier": "^3.9.8",
|
|
98
98
|
"typescript": "^6.0.3",
|