@forklaunch/core 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,6 +30,7 @@ export * from './handlers/typedHandler';
30
30
  export * from './httpStatusCodes';
31
31
  export * from './interfaces/expressLikeRouter.interface';
32
32
  export * from './mcpGenerator/mcpGenerator';
33
+ export * from './mcpGenerator/mcpHttpHandler';
33
34
  export * from './middleware/request/createContext.middleware';
34
35
  export * from './middleware/response/enrichExpressLikeSend.middleware';
35
36
  export * from './openApiV3Generator/openApiV3Generator';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/http/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACnC,cAAc,sCAAsC,CAAC;AACrD,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,0BAA0B,CAAC;AACzC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,y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AAE3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC"}
package/lib/http/index.js CHANGED
@@ -38,6 +38,7 @@ __export(http_exports, {
38
38
  ATTR_HTTP_ROUTE: () => import_semantic_conventions.ATTR_HTTP_ROUTE,
39
39
  ATTR_SERVICE_NAME: () => import_semantic_conventions.ATTR_SERVICE_NAME,
40
40
  AuditLogger: () => AuditLogger,
41
+ DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS: () => DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
41
42
  EMAIL_LIMITS: () => EMAIL_LIMITS,
42
43
  EmailRequestError: () => EmailRequestError,
43
44
  ForklaunchExpressLikeApplication: () => ForklaunchExpressLikeApplication,
@@ -72,6 +73,7 @@ __export(http_exports, {
72
73
  createHmacToken: () => createHmacToken,
73
74
  createInstanceGatewayTransport: () => createInstanceGatewayTransport,
74
75
  createLocalModelGatewayClient: () => createLocalModelGatewayClient,
76
+ createMcpHttpHandler: () => createMcpHttpHandler,
75
77
  createModelGatewayClient: () => createModelGatewayClient,
76
78
  createPaymentsClient: () => createPaymentsClient,
77
79
  createPreviewModelGatewayClient: () => createPreviewModelGatewayClient,
@@ -92,6 +94,7 @@ __export(http_exports, {
92
94
  get: () => get,
93
95
  getCachedJwks: () => getCachedJwks,
94
96
  getCodeForStatus: () => getCodeForStatus,
97
+ getMcpTransportHeaders: () => getMcpTransportHeaders,
95
98
  head: () => head,
96
99
  httpErrorsTotalCounter: () => httpErrorsTotalCounter,
97
100
  httpRequestDurationMsHistogram: () => httpRequestDurationMsHistogram,
@@ -108,6 +111,7 @@ __export(http_exports, {
108
111
  isManagedInstance: () => isManagedInstance,
109
112
  isPortBound: () => isPortBound,
110
113
  isRedirection: () => isRedirection,
114
+ isSeparateMcpListener: () => isSeparateMcpListener,
111
115
  isServerError: () => isServerError,
112
116
  isSuccessful: () => isSuccessful,
113
117
  isValidStatusCode: () => isValidStatusCode,
@@ -570,13 +574,15 @@ new import_sdk_node.NodeSDK({
570
574
  url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/traces`,
571
575
  headers: otelHeaders
572
576
  }),
573
- metricReader: new import_sdk_metrics.PeriodicExportingMetricReader({
574
- exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter({
575
- url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/metrics`,
576
- headers: otelHeaders
577
- }),
578
- exportIntervalMillis: 5e3
579
- }),
577
+ metricReaders: [
578
+ new import_sdk_metrics.PeriodicExportingMetricReader({
579
+ exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter({
580
+ url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/metrics`,
581
+ headers: otelHeaders
582
+ }),
583
+ exportIntervalMillis: 5e3
584
+ })
585
+ ],
580
586
  logRecordProcessors: [
581
587
  new import_sdk_logs.BatchLogRecordProcessor({
582
588
  exporter: new import_exporter_logs_otlp_http.OTLPLogExporter({
@@ -4899,6 +4905,182 @@ function unpackRouters(routers, recursiveBasePath = []) {
4899
4905
  }, []);
4900
4906
  }
4901
4907
 
4908
+ // src/http/mcpGenerator/mcpHttpHandler.ts
4909
+ var import_webStandardStreamableHttp = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
4910
+ var import_async_hooks = require("async_hooks");
4911
+ var import_crypto6 = require("crypto");
4912
+ var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
4913
+ var mcpTransportHeaders = new import_async_hooks.AsyncLocalStorage();
4914
+ function getMcpTransportHeaders() {
4915
+ return mcpTransportHeaders.getStore();
4916
+ }
4917
+ function createMcpHttpHandler(mcpServer, options2) {
4918
+ const mode = options2?.sessions ?? "stateless";
4919
+ if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
4920
+ throw new Error(
4921
+ "Stateful MCP sessions live in one process's memory and cannot be shared across workers. Use mcp.sessions: 'stateless' or a single worker."
4922
+ );
4923
+ }
4924
+ const idleTimeoutMs = options2?.sessionIdleTimeoutMs ?? DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS;
4925
+ const sessions = /* @__PURE__ */ new Map();
4926
+ const jsonRpcError = (status, code, message, headers) => new Response(
4927
+ JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }),
4928
+ {
4929
+ status,
4930
+ headers: { "Content-Type": "application/json", ...headers }
4931
+ }
4932
+ );
4933
+ let sweepTimer;
4934
+ if (mode === "stateful") {
4935
+ sweepTimer = setInterval(
4936
+ () => {
4937
+ const cutoff = Date.now() - idleTimeoutMs;
4938
+ for (const [id, entry] of sessions) {
4939
+ if (entry.lastSeen < cutoff) {
4940
+ sessions.delete(id);
4941
+ entry.session.close().catch(() => void 0);
4942
+ }
4943
+ }
4944
+ },
4945
+ Math.min(idleTimeoutMs, 6e4)
4946
+ );
4947
+ sweepTimer.unref();
4948
+ }
4949
+ async function authenticateRequest(authRequest) {
4950
+ if (!options2?.authenticate) {
4951
+ return { ok: true, auth: void 0 };
4952
+ }
4953
+ try {
4954
+ const auth = await options2.authenticate(authRequest);
4955
+ return auth ? { ok: true, auth } : { ok: false };
4956
+ } catch {
4957
+ return { ok: false };
4958
+ }
4959
+ }
4960
+ async function handleStateless(request, auth) {
4961
+ if (request.method !== "POST") {
4962
+ return jsonRpcError(405, -32e3, "Method not allowed", {
4963
+ Allow: "POST"
4964
+ });
4965
+ }
4966
+ const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
4967
+ sessionIdGenerator: void 0
4968
+ });
4969
+ const session = await mcpServer.connect(transport, auth);
4970
+ let closed = false;
4971
+ const closeSession = () => {
4972
+ if (!closed) {
4973
+ closed = true;
4974
+ session.close().catch(() => void 0);
4975
+ }
4976
+ };
4977
+ try {
4978
+ const response = await mcpTransportHeaders.run(
4979
+ request.headers,
4980
+ () => transport.handleRequest(request)
4981
+ );
4982
+ return closeWhenBodyEnds(response, closeSession);
4983
+ } catch (error) {
4984
+ closeSession();
4985
+ throw error;
4986
+ }
4987
+ }
4988
+ async function handleStateful(request, auth) {
4989
+ const sessionId = request.headers.get("mcp-session-id");
4990
+ if (sessionId) {
4991
+ const entry = sessions.get(sessionId);
4992
+ if (!entry) {
4993
+ return jsonRpcError(404, -32001, "Session not found");
4994
+ }
4995
+ entry.lastSeen = Date.now();
4996
+ if (auth) {
4997
+ entry.session.updateAuth(auth);
4998
+ }
4999
+ return mcpTransportHeaders.run(
5000
+ request.headers,
5001
+ () => entry.transport.handleRequest(request)
5002
+ );
5003
+ }
5004
+ const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
5005
+ sessionIdGenerator: () => (0, import_crypto6.randomUUID)(),
5006
+ onsessioninitialized: (id) => {
5007
+ sessions.set(id, { transport, session, lastSeen: Date.now() });
5008
+ },
5009
+ onsessionclosed: (id) => {
5010
+ sessions.delete(id);
5011
+ }
5012
+ });
5013
+ const session = await mcpServer.connect(transport, auth);
5014
+ transport.onclose = /* @__PURE__ */ ((onclose) => () => {
5015
+ if (transport.sessionId) {
5016
+ sessions.delete(transport.sessionId);
5017
+ }
5018
+ onclose?.();
5019
+ })(transport.onclose);
5020
+ const response = await mcpTransportHeaders.run(
5021
+ request.headers,
5022
+ () => transport.handleRequest(request)
5023
+ );
5024
+ if (!transport.sessionId) {
5025
+ await session.close();
5026
+ }
5027
+ return response;
5028
+ }
5029
+ async function handle(request, authRequest) {
5030
+ const authResult = await authenticateRequest(authRequest);
5031
+ if (!authResult.ok) {
5032
+ return jsonRpcError(401, -32001, "Unauthorized", {
5033
+ "WWW-Authenticate": "Bearer"
5034
+ });
5035
+ }
5036
+ return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
5037
+ }
5038
+ async function close() {
5039
+ if (sweepTimer) {
5040
+ clearInterval(sweepTimer);
5041
+ }
5042
+ const entries = [...sessions.values()];
5043
+ sessions.clear();
5044
+ await Promise.all(entries.map(({ session }) => session.close()));
5045
+ }
5046
+ return { handle, close, sessions };
5047
+ }
5048
+ function closeWhenBodyEnds(response, done) {
5049
+ if (!response.body) {
5050
+ done();
5051
+ return response;
5052
+ }
5053
+ const reader = response.body.getReader();
5054
+ const body = new ReadableStream({
5055
+ async pull(controller) {
5056
+ try {
5057
+ const { done: finished, value } = await reader.read();
5058
+ if (finished) {
5059
+ controller.close();
5060
+ done();
5061
+ } else {
5062
+ controller.enqueue(value);
5063
+ }
5064
+ } catch (error) {
5065
+ controller.error(error);
5066
+ done();
5067
+ }
5068
+ },
5069
+ cancel(reason) {
5070
+ done();
5071
+ return reader.cancel(reason);
5072
+ }
5073
+ });
5074
+ return new Response(body, {
5075
+ status: response.status,
5076
+ statusText: response.statusText,
5077
+ headers: response.headers
5078
+ });
5079
+ }
5080
+ function isSeparateMcpListener(configuredPort) {
5081
+ return process.env.MCP_LISTENER === "separate" || configuredPort != null || Boolean(Number(process.env.MCP_PORT));
5082
+ }
5083
+
4902
5084
  // src/http/mcpGenerator/mcpGenerator.ts
4903
5085
  function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
4904
5086
  let discriminatedBody;
@@ -4928,6 +5110,36 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
4928
5110
  } : {}
4929
5111
  });
4930
5112
  }
5113
+ function buildRouteHeaders(toolHeaders, contentType) {
5114
+ const transportHeaders = getMcpTransportHeaders();
5115
+ const routeHeaders = new Headers();
5116
+ const authorization = transportHeaders?.get("authorization");
5117
+ if (authorization) {
5118
+ routeHeaders.set("authorization", authorization);
5119
+ }
5120
+ for (const [name, value] of Object.entries(toolHeaders ?? {})) {
5121
+ if (value != null) {
5122
+ routeHeaders.set(name, String(value));
5123
+ }
5124
+ }
5125
+ const correlationId = transportHeaders?.get("x-correlation-id");
5126
+ if (correlationId) {
5127
+ routeHeaders.set("x-correlation-id", correlationId);
5128
+ }
5129
+ const traceparent = transportHeaders?.get("traceparent");
5130
+ if (traceparent) {
5131
+ routeHeaders.set("traceparent", traceparent);
5132
+ routeHeaders.delete("tracestate");
5133
+ const tracestate = transportHeaders?.get("tracestate");
5134
+ if (tracestate) {
5135
+ routeHeaders.set("tracestate", tracestate);
5136
+ }
5137
+ }
5138
+ if (contentType !== void 0) {
5139
+ routeHeaders.set("content-type", contentType);
5140
+ }
5141
+ return routeHeaders;
5142
+ }
4931
5143
  function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate) {
4932
5144
  if (!(schemaValidator instanceof import_zod.ZodSchemaValidator)) {
4933
5145
  throw new Error(
@@ -5080,12 +5292,10 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5080
5292
  }
5081
5293
  const response = await fetch(url, {
5082
5294
  method: route.method.toUpperCase(),
5083
- headers: {
5084
- ...headers,
5085
- ...discriminatedBody?.contentType != "multipart/form-data" && (contentType ?? discriminatedBody?.contentType) !== void 0 ? {
5086
- "Content-Type": contentType ?? discriminatedBody?.contentType
5087
- } : {}
5088
- },
5295
+ headers: buildRouteHeaders(
5296
+ headers,
5297
+ discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
5298
+ ),
5089
5299
  body: parsedBody
5090
5300
  });
5091
5301
  if (response.status >= 300) {
@@ -6045,6 +6255,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6045
6255
  ATTR_HTTP_ROUTE,
6046
6256
  ATTR_SERVICE_NAME,
6047
6257
  AuditLogger,
6258
+ DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
6048
6259
  EMAIL_LIMITS,
6049
6260
  EmailRequestError,
6050
6261
  ForklaunchExpressLikeApplication,
@@ -6079,6 +6290,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6079
6290
  createHmacToken,
6080
6291
  createInstanceGatewayTransport,
6081
6292
  createLocalModelGatewayClient,
6293
+ createMcpHttpHandler,
6082
6294
  createModelGatewayClient,
6083
6295
  createPaymentsClient,
6084
6296
  createPreviewModelGatewayClient,
@@ -6099,6 +6311,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6099
6311
  get,
6100
6312
  getCachedJwks,
6101
6313
  getCodeForStatus,
6314
+ getMcpTransportHeaders,
6102
6315
  head,
6103
6316
  httpErrorsTotalCounter,
6104
6317
  httpRequestDurationMsHistogram,
@@ -6115,6 +6328,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6115
6328
  isManagedInstance,
6116
6329
  isPortBound,
6117
6330
  isRedirection,
6331
+ isSeparateMcpListener,
6118
6332
  isServerError,
6119
6333
  isSuccessful,
6120
6334
  isValidStatusCode,