mcp-use 1.5.1-canary.0 → 1.5.1-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -301,15 +301,46 @@ async function adaptConnectMiddleware(connectMiddleware, middlewarePath) {
301
301
  __name(adaptConnectMiddleware, "adaptConnectMiddleware");
302
302
 
303
303
  // src/server/logging.ts
304
+ var isDeno = typeof globalThis.Deno !== "undefined";
305
+ function getEnv(key) {
306
+ if (isDeno) {
307
+ return globalThis.Deno.env.get(key);
308
+ }
309
+ return typeof process !== "undefined" && process.env ? process.env[key] : void 0;
310
+ }
311
+ __name(getEnv, "getEnv");
312
+ function isDebugMode() {
313
+ const debugEnv = getEnv("DEBUG");
314
+ return debugEnv !== void 0 && debugEnv !== "" && debugEnv !== "0" && debugEnv.toLowerCase() !== "false";
315
+ }
316
+ __name(isDebugMode, "isDebugMode");
317
+ function formatForLogging(obj) {
318
+ try {
319
+ return JSON.stringify(obj, null, 2);
320
+ } catch {
321
+ return String(obj);
322
+ }
323
+ }
324
+ __name(formatForLogging, "formatForLogging");
304
325
  async function requestLogger(c, next) {
305
326
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
306
327
  const method = c.req.method;
307
328
  const url = c.req.url;
308
- let body = null;
309
- if (method === "POST" && url.includes("/mcp")) {
329
+ const debugMode = isDebugMode();
330
+ let requestBody = null;
331
+ let requestHeaders = {};
332
+ if (debugMode) {
333
+ const allHeaders = c.req.header();
334
+ if (allHeaders) {
335
+ requestHeaders = allHeaders;
336
+ }
337
+ }
338
+ if (method !== "GET" && method !== "HEAD") {
310
339
  try {
311
340
  const clonedRequest = c.req.raw.clone();
312
- body = await clonedRequest.json().catch(() => null);
341
+ requestBody = await clonedRequest.json().catch(() => {
342
+ return clonedRequest.text().catch(() => null);
343
+ });
313
344
  } catch {
314
345
  }
315
346
  }
@@ -326,11 +357,70 @@ async function requestLogger(c, next) {
326
357
  statusColor = "\x1B[35m";
327
358
  }
328
359
  let logMessage = `[${timestamp}] ${method} \x1B[1m${new URL(url).pathname}\x1B[0m`;
329
- if (method === "POST" && url.includes("/mcp") && body?.method) {
330
- logMessage += ` \x1B[1m[${body.method}]\x1B[0m`;
360
+ if (method === "POST" && url.includes("/mcp") && requestBody?.method) {
361
+ logMessage += ` \x1B[1m[${requestBody.method}]\x1B[0m`;
331
362
  }
332
363
  logMessage += ` ${statusColor}${statusCode}\x1B[0m`;
333
364
  console.log(logMessage);
365
+ if (debugMode) {
366
+ console.log("\n\x1B[36m" + "=".repeat(80) + "\x1B[0m");
367
+ console.log("\x1B[1m\x1B[36m[DEBUG] Request Details\x1B[0m");
368
+ console.log("\x1B[36m" + "-".repeat(80) + "\x1B[0m");
369
+ if (Object.keys(requestHeaders).length > 0) {
370
+ console.log("\x1B[33mRequest Headers:\x1B[0m");
371
+ console.log(formatForLogging(requestHeaders));
372
+ }
373
+ if (requestBody !== null) {
374
+ console.log("\x1B[33mRequest Body:\x1B[0m");
375
+ if (typeof requestBody === "string") {
376
+ console.log(requestBody);
377
+ } else {
378
+ console.log(formatForLogging(requestBody));
379
+ }
380
+ }
381
+ const responseHeaders = {};
382
+ c.res.headers.forEach((value, key) => {
383
+ responseHeaders[key] = value;
384
+ });
385
+ if (Object.keys(responseHeaders).length > 0) {
386
+ console.log("\x1B[33mResponse Headers:\x1B[0m");
387
+ console.log(formatForLogging(responseHeaders));
388
+ }
389
+ try {
390
+ if (c.res.body !== null && c.res.body !== void 0) {
391
+ try {
392
+ const clonedResponse = c.res.clone();
393
+ const responseBody = await clonedResponse.text().catch(() => null);
394
+ if (responseBody !== null && responseBody.length > 0) {
395
+ console.log("\x1B[33mResponse Body:\x1B[0m");
396
+ try {
397
+ const jsonBody = JSON.parse(responseBody);
398
+ console.log(formatForLogging(jsonBody));
399
+ } catch {
400
+ const maxLength = 1e4;
401
+ if (responseBody.length > maxLength) {
402
+ console.log(
403
+ responseBody.substring(0, maxLength) + `
404
+ ... (truncated, ${responseBody.length - maxLength} more characters)`
405
+ );
406
+ } else {
407
+ console.log(responseBody);
408
+ }
409
+ }
410
+ } else {
411
+ console.log("\x1B[33mResponse Body:\x1B[0m (empty)");
412
+ }
413
+ } catch (cloneError) {
414
+ console.log("\x1B[33mResponse Body:\x1B[0m (unable to clone/read)");
415
+ }
416
+ } else {
417
+ console.log("\x1B[33mResponse Body:\x1B[0m (no body)");
418
+ }
419
+ } catch (error) {
420
+ console.log("\x1B[33mResponse Body:\x1B[0m (unable to read)");
421
+ }
422
+ console.log("\x1B[36m" + "=".repeat(80) + "\x1B[0m\n");
423
+ }
334
424
  }
335
425
  __name(requestLogger, "requestLogger");
336
426
 
@@ -340,16 +430,16 @@ function generateUUID() {
340
430
  }
341
431
  __name(generateUUID, "generateUUID");
342
432
  var TMP_MCP_USE_DIR = ".mcp-use";
343
- var isDeno = typeof globalThis.Deno !== "undefined";
344
- function getEnv(key) {
345
- if (isDeno) {
433
+ var isDeno2 = typeof globalThis.Deno !== "undefined";
434
+ function getEnv2(key) {
435
+ if (isDeno2) {
346
436
  return globalThis.Deno.env.get(key);
347
437
  }
348
438
  return process.env[key];
349
439
  }
350
- __name(getEnv, "getEnv");
440
+ __name(getEnv2, "getEnv");
351
441
  function getCwd() {
352
- if (isDeno) {
442
+ if (isDeno2) {
353
443
  return globalThis.Deno.cwd();
354
444
  }
355
445
  return process.cwd();
@@ -357,7 +447,7 @@ function getCwd() {
357
447
  __name(getCwd, "getCwd");
358
448
  var fsHelpers = {
359
449
  async readFileSync(path, encoding = "utf8") {
360
- if (isDeno) {
450
+ if (isDeno2) {
361
451
  return await globalThis.Deno.readTextFile(path);
362
452
  }
363
453
  const { readFileSync } = await import("fs");
@@ -365,7 +455,7 @@ var fsHelpers = {
365
455
  return typeof result === "string" ? result : result.toString(encoding);
366
456
  },
367
457
  async readFile(path) {
368
- if (isDeno) {
458
+ if (isDeno2) {
369
459
  const data = await globalThis.Deno.readFile(path);
370
460
  return data.buffer;
371
461
  }
@@ -377,7 +467,7 @@ var fsHelpers = {
377
467
  );
378
468
  },
379
469
  async existsSync(path) {
380
- if (isDeno) {
470
+ if (isDeno2) {
381
471
  try {
382
472
  await globalThis.Deno.stat(path);
383
473
  return true;
@@ -389,7 +479,7 @@ var fsHelpers = {
389
479
  return existsSync(path);
390
480
  },
391
481
  async readdirSync(path) {
392
- if (isDeno) {
482
+ if (isDeno2) {
393
483
  const entries = [];
394
484
  for await (const entry of globalThis.Deno.readDir(path)) {
395
485
  entries.push(entry.name);
@@ -402,7 +492,7 @@ var fsHelpers = {
402
492
  };
403
493
  var pathHelpers = {
404
494
  join(...paths) {
405
- if (isDeno) {
495
+ if (isDeno2) {
406
496
  return paths.join("/").replace(/\/+/g, "/");
407
497
  }
408
498
  return paths.join("/").replace(/\/+/g, "/");
@@ -534,7 +624,7 @@ var McpServer = class {
534
624
  if (this.serverBaseUrl) {
535
625
  return this.serverBaseUrl;
536
626
  }
537
- const mcpUrl = getEnv("MCP_URL");
627
+ const mcpUrl = getEnv2("MCP_URL");
538
628
  if (mcpUrl) {
539
629
  return mcpUrl;
540
630
  }
@@ -1156,7 +1246,7 @@ var McpServer = class {
1156
1246
  * @returns true if in production mode, false otherwise
1157
1247
  */
1158
1248
  isProductionMode() {
1159
- return getEnv("NODE_ENV") === "production";
1249
+ return getEnv2("NODE_ENV") === "production";
1160
1250
  }
1161
1251
  /**
1162
1252
  * Read build manifest file
@@ -1167,7 +1257,7 @@ var McpServer = class {
1167
1257
  async readBuildManifest() {
1168
1258
  try {
1169
1259
  const manifestPath = pathHelpers.join(
1170
- isDeno ? "." : getCwd(),
1260
+ isDeno2 ? "." : getCwd(),
1171
1261
  "dist",
1172
1262
  "mcp-use.json"
1173
1263
  );
@@ -1189,7 +1279,7 @@ var McpServer = class {
1189
1279
  * @returns Promise that resolves when all widgets are mounted
1190
1280
  */
1191
1281
  async mountWidgets(options) {
1192
- if (this.isProductionMode() || isDeno) {
1282
+ if (this.isProductionMode() || isDeno2) {
1193
1283
  console.log("[WIDGETS] Mounting widgets in production mode");
1194
1284
  await this.mountWidgetsProduction(options);
1195
1285
  } else {
@@ -1609,7 +1699,7 @@ if (container && Component) {
1609
1699
  async mountWidgetsProduction(options) {
1610
1700
  const baseRoute = options?.baseRoute || "/mcp-use/widgets";
1611
1701
  const widgetsDir = pathHelpers.join(
1612
- isDeno ? "." : getCwd(),
1702
+ isDeno2 ? "." : getCwd(),
1613
1703
  "dist",
1614
1704
  "resources",
1615
1705
  "widgets"
@@ -1816,47 +1906,50 @@ if (container && Component) {
1816
1906
  if (this.mcpMounted) return;
1817
1907
  const { StreamableHTTPServerTransport } = await import("@modelcontextprotocol/sdk/server/streamableHttp.js");
1818
1908
  const idleTimeoutMs = this.config.sessionIdleTimeoutMs ?? 3e5;
1819
- const getOrCreateTransport = /* @__PURE__ */ __name(async (sessionId, isInit = false) => {
1820
- if (isInit) {
1821
- if (sessionId && this.sessions.has(sessionId)) {
1822
- try {
1823
- this.sessions.get(sessionId).transport.close();
1824
- } catch (error) {
1825
- }
1826
- this.sessions.delete(sessionId);
1909
+ const createNewTransport = /* @__PURE__ */ __name(async (closeOldSessionId) => {
1910
+ if (closeOldSessionId && this.sessions.has(closeOldSessionId)) {
1911
+ try {
1912
+ this.sessions.get(closeOldSessionId).transport.close();
1913
+ } catch (error) {
1827
1914
  }
1828
- const isProduction = this.isProductionMode();
1829
- let allowedOrigins = this.config.allowedOrigins;
1830
- let enableDnsRebindingProtection = false;
1831
- if (isProduction) {
1832
- if (allowedOrigins !== void 0) {
1833
- enableDnsRebindingProtection = allowedOrigins.length > 0;
1834
- }
1835
- } else {
1836
- allowedOrigins = void 0;
1837
- enableDnsRebindingProtection = false;
1915
+ this.sessions.delete(closeOldSessionId);
1916
+ }
1917
+ const isProduction = this.isProductionMode();
1918
+ let allowedOrigins = this.config.allowedOrigins;
1919
+ let enableDnsRebindingProtection = false;
1920
+ if (isProduction) {
1921
+ if (allowedOrigins !== void 0) {
1922
+ enableDnsRebindingProtection = allowedOrigins.length > 0;
1838
1923
  }
1839
- const transport = new StreamableHTTPServerTransport({
1840
- sessionIdGenerator: /* @__PURE__ */ __name(() => generateUUID(), "sessionIdGenerator"),
1841
- enableJsonResponse: true,
1842
- allowedOrigins,
1843
- enableDnsRebindingProtection,
1844
- onsessioninitialized: /* @__PURE__ */ __name((id) => {
1845
- if (id) {
1846
- this.sessions.set(id, {
1847
- transport,
1848
- lastAccessedAt: Date.now()
1849
- });
1850
- }
1851
- }, "onsessioninitialized"),
1852
- onsessionclosed: /* @__PURE__ */ __name((id) => {
1853
- if (id) {
1854
- this.sessions.delete(id);
1855
- }
1856
- }, "onsessionclosed")
1857
- });
1858
- await this.server.connect(transport);
1859
- return transport;
1924
+ } else {
1925
+ allowedOrigins = void 0;
1926
+ enableDnsRebindingProtection = false;
1927
+ }
1928
+ const transport = new StreamableHTTPServerTransport({
1929
+ sessionIdGenerator: /* @__PURE__ */ __name(() => generateUUID(), "sessionIdGenerator"),
1930
+ enableJsonResponse: true,
1931
+ allowedOrigins,
1932
+ enableDnsRebindingProtection,
1933
+ onsessioninitialized: /* @__PURE__ */ __name((id) => {
1934
+ if (id) {
1935
+ this.sessions.set(id, {
1936
+ transport,
1937
+ lastAccessedAt: Date.now()
1938
+ });
1939
+ }
1940
+ }, "onsessioninitialized"),
1941
+ onsessionclosed: /* @__PURE__ */ __name((id) => {
1942
+ if (id) {
1943
+ this.sessions.delete(id);
1944
+ }
1945
+ }, "onsessionclosed")
1946
+ });
1947
+ await this.server.connect(transport);
1948
+ return transport;
1949
+ }, "createNewTransport");
1950
+ const getOrCreateTransport = /* @__PURE__ */ __name(async (sessionId, isInit = false) => {
1951
+ if (isInit) {
1952
+ return await createNewTransport(sessionId);
1860
1953
  }
1861
1954
  if (sessionId && this.sessions.has(sessionId)) {
1862
1955
  const session = this.sessions.get(sessionId);
@@ -1864,7 +1957,15 @@ if (container && Component) {
1864
1957
  return session.transport;
1865
1958
  }
1866
1959
  if (sessionId) {
1867
- return null;
1960
+ const autoCreate = this.config.autoCreateSessionOnInvalidId ?? true;
1961
+ if (autoCreate) {
1962
+ console.warn(
1963
+ `[MCP] Session ${sessionId} not found (expired or invalid), auto-creating new session for seamless reconnection`
1964
+ );
1965
+ return await createNewTransport(sessionId);
1966
+ } else {
1967
+ return null;
1968
+ }
1868
1969
  }
1869
1970
  return null;
1870
1971
  }, "getOrCreateTransport");
@@ -1973,7 +2074,7 @@ if (container && Component) {
1973
2074
  getResponse: /* @__PURE__ */ __name(() => {
1974
2075
  if (ended) {
1975
2076
  if (responseBody.length > 0) {
1976
- const body = isDeno ? Buffer.concat(responseBody) : Buffer.concat(responseBody);
2077
+ const body = isDeno2 ? Buffer.concat(responseBody) : Buffer.concat(responseBody);
1977
2078
  return new Response(body, {
1978
2079
  status: statusCode,
1979
2080
  headers
@@ -2281,9 +2382,9 @@ if (container && Component) {
2281
2382
  console.log("");
2282
2383
  }
2283
2384
  async listen(port) {
2284
- const portEnv = getEnv("PORT");
2385
+ const portEnv = getEnv2("PORT");
2285
2386
  this.serverPort = port || (portEnv ? parseInt(portEnv, 10) : 3001);
2286
- const hostEnv = getEnv("HOST");
2387
+ const hostEnv = getEnv2("HOST");
2287
2388
  if (hostEnv) {
2288
2389
  this.serverHost = hostEnv;
2289
2390
  }
@@ -2294,7 +2395,7 @@ if (container && Component) {
2294
2395
  await this.mountMcp();
2295
2396
  await this.mountInspector();
2296
2397
  this.logRegisteredItems();
2297
- if (isDeno) {
2398
+ if (isDeno2) {
2298
2399
  const corsHeaders = {
2299
2400
  "Access-Control-Allow-Origin": "*",
2300
2401
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type"