mcp-use 1.5.0 → 1.5.1-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-WERYJ6PF.js → chunk-2AOGMX4T.js} +1 -1
  3. package/dist/{chunk-DSBKVAWD.js → chunk-2JBWOW4S.js} +152 -0
  4. package/dist/{chunk-UT7O4SIJ.js → chunk-BWOTID2D.js} +209 -75
  5. package/dist/{chunk-GPAOZN2F.js → chunk-QRABML5H.js} +15 -3
  6. package/dist/index.cjs +395 -84
  7. package/dist/index.d.ts +4 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +30 -10
  10. package/dist/src/agents/index.cjs +1 -0
  11. package/dist/src/agents/index.js +2 -2
  12. package/dist/src/browser.cjs +351 -72
  13. package/dist/src/browser.d.ts +2 -0
  14. package/dist/src/browser.d.ts.map +1 -1
  15. package/dist/src/browser.js +2 -2
  16. package/dist/src/client/browser.d.ts.map +1 -1
  17. package/dist/src/client/prompts.cjs +3 -0
  18. package/dist/src/client/prompts.js +2 -2
  19. package/dist/src/client.d.ts +8 -0
  20. package/dist/src/client.d.ts.map +1 -1
  21. package/dist/src/config.d.ts +2 -1
  22. package/dist/src/config.d.ts.map +1 -1
  23. package/dist/src/connectors/base.d.ts +79 -1
  24. package/dist/src/connectors/base.d.ts.map +1 -1
  25. package/dist/src/connectors/http.d.ts +1 -0
  26. package/dist/src/connectors/http.d.ts.map +1 -1
  27. package/dist/src/connectors/stdio.d.ts.map +1 -1
  28. package/dist/src/connectors/websocket.d.ts +6 -0
  29. package/dist/src/connectors/websocket.d.ts.map +1 -1
  30. package/dist/src/react/index.cjs +365 -73
  31. package/dist/src/react/index.d.ts +1 -0
  32. package/dist/src/react/index.d.ts.map +1 -1
  33. package/dist/src/react/index.js +3 -3
  34. package/dist/src/react/types.d.ts +9 -1
  35. package/dist/src/react/types.d.ts.map +1 -1
  36. package/dist/src/react/useMcp.d.ts.map +1 -1
  37. package/dist/src/server/adapters/mcp-ui-adapter.d.ts +1 -0
  38. package/dist/src/server/adapters/mcp-ui-adapter.d.ts.map +1 -1
  39. package/dist/src/server/index.cjs +605 -168
  40. package/dist/src/server/index.js +605 -168
  41. package/dist/src/server/mcp-server.d.ts +201 -10
  42. package/dist/src/server/mcp-server.d.ts.map +1 -1
  43. package/dist/src/server/types/common.d.ts +28 -0
  44. package/dist/src/server/types/common.d.ts.map +1 -1
  45. package/dist/src/session.d.ts +40 -1
  46. package/dist/src/session.d.ts.map +1 -1
  47. package/package.json +10 -4
@@ -70,7 +70,8 @@ function createAppsSdkResource(uri, htmlTemplate, metadata) {
70
70
  }
71
71
  __name(createAppsSdkResource, "createAppsSdkResource");
72
72
  function createUIResourceFromDefinition(definition, params, config) {
73
- const uri = definition.type === "appsSdk" ? `ui://widget/${definition.name}.html` : `ui://widget/${definition.name}`;
73
+ const buildIdPart = config.buildId ? `-${config.buildId}` : "";
74
+ const uri = definition.type === "appsSdk" ? `ui://widget/${definition.name}${buildIdPart}.html` : `ui://widget/${definition.name}${buildIdPart}`;
74
75
  const encoding = definition.encoding || "text";
75
76
  switch (definition.type) {
76
77
  case "externalUrl": {
@@ -296,6 +297,10 @@ async function requestLogger(c, next) {
296
297
  __name(requestLogger, "requestLogger");
297
298
 
298
299
  // src/server/mcp-server.ts
300
+ function generateUUID() {
301
+ return globalThis.crypto.randomUUID();
302
+ }
303
+ __name(generateUUID, "generateUUID");
299
304
  var TMP_MCP_USE_DIR = ".mcp-use";
300
305
  var isDeno = typeof globalThis.Deno !== "undefined";
301
306
  function getEnv(key) {
@@ -391,6 +396,9 @@ var McpServer = class {
391
396
  registeredTools = [];
392
397
  registeredPrompts = [];
393
398
  registeredResources = [];
399
+ buildId;
400
+ sessions = /* @__PURE__ */ new Map();
401
+ idleCleanupInterval;
394
402
  /**
395
403
  * Creates a new MCP server instance with Hono integration
396
404
  *
@@ -423,7 +431,9 @@ var McpServer = class {
423
431
  "mcp-session-id",
424
432
  "X-Proxy-Token",
425
433
  "X-Target-URL"
426
- ]
434
+ ],
435
+ // Expose mcp-session-id so browser clients can read it from responses
436
+ exposeHeaders: ["mcp-session-id"]
427
437
  })
428
438
  );
429
439
  this.app.use("*", requestLogger);
@@ -663,6 +673,11 @@ var McpServer = class {
663
673
  */
664
674
  tool(toolDefinition) {
665
675
  const inputSchema = this.createParamsSchema(toolDefinition.inputs || []);
676
+ const context = {
677
+ sample: /* @__PURE__ */ __name(async (params, options) => {
678
+ return await this.createMessage(params, options);
679
+ }, "sample")
680
+ };
666
681
  this.server.registerTool(
667
682
  toolDefinition.name,
668
683
  {
@@ -673,6 +688,9 @@ var McpServer = class {
673
688
  _meta: toolDefinition._meta
674
689
  },
675
690
  async (params) => {
691
+ if (toolDefinition.cb.length >= 2) {
692
+ return await toolDefinition.cb(params, context);
693
+ }
676
694
  return await toolDefinition.cb(params);
677
695
  }
678
696
  );
@@ -729,6 +747,46 @@ var McpServer = class {
729
747
  this.registeredPrompts.push(promptDefinition.name);
730
748
  return this;
731
749
  }
750
+ /**
751
+ * Request LLM sampling from connected clients.
752
+ *
753
+ * This method allows server tools to request LLM completions from clients
754
+ * that support the sampling capability. The client will handle model selection,
755
+ * user approval (human-in-the-loop), and return the generated response.
756
+ *
757
+ * @param params - Sampling request parameters including messages, model preferences, etc.
758
+ * @param options - Optional request options (timeouts, cancellation, etc.)
759
+ * @returns Promise resolving to the generated message from the client's LLM
760
+ *
761
+ * @example
762
+ * ```typescript
763
+ * // In a tool callback
764
+ * server.tool({
765
+ * name: 'analyze-sentiment',
766
+ * description: 'Analyze sentiment using LLM',
767
+ * inputs: [{ name: 'text', type: 'string', required: true }],
768
+ * cb: async (params, ctx) => {
769
+ * const result = await ctx.sample({
770
+ * messages: [{
771
+ * role: 'user',
772
+ * content: { type: 'text', text: `Analyze sentiment: ${params.text}` }
773
+ * }],
774
+ * modelPreferences: {
775
+ * intelligencePriority: 0.8,
776
+ * speedPriority: 0.5
777
+ * }
778
+ * });
779
+ * return {
780
+ * content: [{ type: 'text', text: result.content.text }]
781
+ * };
782
+ * }
783
+ * })
784
+ * ```
785
+ */
786
+ async createMessage(params, options) {
787
+ console.log("createMessage", params, options);
788
+ return await this.server.server.createMessage(params, options);
789
+ }
732
790
  /**
733
791
  * Register a UI widget as both a tool and a resource
734
792
  *
@@ -802,19 +860,19 @@ var McpServer = class {
802
860
  let mimeType;
803
861
  switch (definition.type) {
804
862
  case "externalUrl":
805
- resourceUri = `ui://widget/${definition.widget}`;
863
+ resourceUri = this.generateWidgetUri(definition.widget);
806
864
  mimeType = "text/uri-list";
807
865
  break;
808
866
  case "rawHtml":
809
- resourceUri = `ui://widget/${definition.name}`;
867
+ resourceUri = this.generateWidgetUri(definition.name);
810
868
  mimeType = "text/html";
811
869
  break;
812
870
  case "remoteDom":
813
- resourceUri = `ui://widget/${definition.name}`;
871
+ resourceUri = this.generateWidgetUri(definition.name);
814
872
  mimeType = "application/vnd.mcp-ui.remote-dom+javascript";
815
873
  break;
816
874
  case "appsSdk":
817
- resourceUri = `ui://widget/${definition.name}.html`;
875
+ resourceUri = this.generateWidgetUri(definition.name, ".html");
818
876
  mimeType = "text/html+skybridge";
819
877
  break;
820
878
  default:
@@ -833,16 +891,19 @@ var McpServer = class {
833
891
  readCallback: /* @__PURE__ */ __name(async () => {
834
892
  const params = definition.type === "externalUrl" ? this.applyDefaultProps(definition.props) : {};
835
893
  const uiResource = this.createWidgetUIResource(definition, params);
894
+ uiResource.resource.uri = resourceUri;
836
895
  return {
837
896
  contents: [uiResource.resource]
838
897
  };
839
898
  }, "readCallback")
840
899
  });
841
900
  if (definition.type === "appsSdk") {
901
+ const buildIdPart = this.buildId ? `-${this.buildId}` : "";
902
+ const uriTemplate = `ui://widget/${definition.name}${buildIdPart}-{id}.html`;
842
903
  this.resourceTemplate({
843
904
  name: `${definition.name}-dynamic`,
844
905
  resourceTemplate: {
845
- uriTemplate: `ui://widget/${definition.name}-{id}.html`,
906
+ uriTemplate,
846
907
  name: definition.title || definition.name,
847
908
  description: definition.description,
848
909
  mimeType
@@ -853,6 +914,7 @@ var McpServer = class {
853
914
  annotations: definition.annotations,
854
915
  readCallback: /* @__PURE__ */ __name(async (uri, params) => {
855
916
  const uiResource = this.createWidgetUIResource(definition, {});
917
+ uiResource.resource.uri = uri.toString();
856
918
  return {
857
919
  contents: [uiResource.resource]
858
920
  };
@@ -884,7 +946,11 @@ var McpServer = class {
884
946
  const uiResource = this.createWidgetUIResource(definition, params);
885
947
  if (definition.type === "appsSdk") {
886
948
  const randomId = Math.random().toString(36).substring(2, 15);
887
- const uniqueUri = `ui://widget/${definition.name}-${randomId}.html`;
949
+ const uniqueUri = this.generateWidgetUri(
950
+ definition.name,
951
+ ".html",
952
+ randomId
953
+ );
888
954
  const uniqueToolMetadata = {
889
955
  ...toolMetadata,
890
956
  "openai/outputTemplate": uniqueUri
@@ -941,7 +1007,8 @@ var McpServer = class {
941
1007
  }
942
1008
  const urlConfig = {
943
1009
  baseUrl: configBaseUrl,
944
- port: configPort
1010
+ port: configPort,
1011
+ buildId: this.buildId
945
1012
  };
946
1013
  const uiResource = createUIResourceFromDefinition(
947
1014
  definition,
@@ -956,6 +1023,25 @@ var McpServer = class {
956
1023
  }
957
1024
  return uiResource;
958
1025
  }
1026
+ /**
1027
+ * Generate a widget URI with optional build ID for cache busting
1028
+ *
1029
+ * @private
1030
+ * @param widgetName - Widget name/identifier
1031
+ * @param extension - Optional file extension (e.g., '.html')
1032
+ * @param suffix - Optional suffix (e.g., random ID for dynamic URIs)
1033
+ * @returns Widget URI with build ID if available
1034
+ */
1035
+ generateWidgetUri(widgetName, extension = "", suffix = "") {
1036
+ const parts = [widgetName];
1037
+ if (this.buildId) {
1038
+ parts.push(this.buildId);
1039
+ }
1040
+ if (suffix) {
1041
+ parts.push(suffix);
1042
+ }
1043
+ return `ui://widget/${parts.join("-")}${extension}`;
1044
+ }
959
1045
  /**
960
1046
  * Build a complete URL for a widget including query parameters
961
1047
  *
@@ -1501,6 +1587,10 @@ if (container && Component) {
1501
1587
  "utf8"
1502
1588
  );
1503
1589
  const manifest = JSON.parse(manifestContent);
1590
+ if (manifest.buildId && typeof manifest.buildId === "string") {
1591
+ this.buildId = manifest.buildId;
1592
+ console.log(`[WIDGETS] Build ID: ${this.buildId}`);
1593
+ }
1504
1594
  if (manifest.widgets && typeof manifest.widgets === "object" && !Array.isArray(manifest.widgets)) {
1505
1595
  widgets = Object.keys(manifest.widgets);
1506
1596
  widgetsMetadata = manifest.widgets;
@@ -1633,6 +1723,7 @@ if (container && Component) {
1633
1723
  resource_domains: [
1634
1724
  "https://*.oaistatic.com",
1635
1725
  "https://*.oaiusercontent.com",
1726
+ "https://*.openai.com",
1636
1727
  // always also add the base url of the server
1637
1728
  ...this.getServerBaseUrl() ? [this.getServerBaseUrl()] : [],
1638
1729
  ...metadata.appsSdkMetadata?.["openai/widgetCSP"]?.resource_domains || []
@@ -1665,12 +1756,11 @@ if (container && Component) {
1665
1756
  });
1666
1757
  }
1667
1758
  /**
1668
- * Mount MCP server endpoints at /mcp
1759
+ * Mount MCP server endpoints at /mcp and /sse
1669
1760
  *
1670
1761
  * Sets up the HTTP transport layer for the MCP server, creating endpoints for
1671
1762
  * Server-Sent Events (SSE) streaming, POST message handling, and DELETE session cleanup.
1672
- * Each request gets its own transport instance to prevent state conflicts between
1673
- * concurrent client connections.
1763
+ * Transports are reused per session ID to maintain state across requests.
1674
1764
  *
1675
1765
  * This method is called automatically when the server starts listening and ensures
1676
1766
  * that MCP clients can communicate with the server over HTTP.
@@ -1680,14 +1770,80 @@ if (container && Component) {
1680
1770
  *
1681
1771
  * @example
1682
1772
  * Endpoints created:
1683
- * - GET /mcp - SSE streaming endpoint for real-time communication
1684
- * - POST /mcp - Message handling endpoint for MCP protocol messages
1685
- * - DELETE /mcp - Session cleanup endpoint
1773
+ * - GET /mcp, GET /sse - SSE streaming endpoint for real-time communication
1774
+ * - POST /mcp, POST /sse - Message handling endpoint for MCP protocol messages
1775
+ * - DELETE /mcp, DELETE /sse - Session cleanup endpoint
1686
1776
  */
1687
1777
  async mountMcp() {
1688
1778
  if (this.mcpMounted) return;
1689
1779
  const { StreamableHTTPServerTransport } = await import("@modelcontextprotocol/sdk/server/streamableHttp.js");
1690
- const endpoint = "/mcp";
1780
+ const idleTimeoutMs = this.config.sessionIdleTimeoutMs ?? 3e5;
1781
+ const getOrCreateTransport = /* @__PURE__ */ __name(async (sessionId, isInit = false) => {
1782
+ if (isInit) {
1783
+ if (sessionId && this.sessions.has(sessionId)) {
1784
+ try {
1785
+ this.sessions.get(sessionId).transport.close();
1786
+ } catch (error) {
1787
+ }
1788
+ this.sessions.delete(sessionId);
1789
+ }
1790
+ const isProduction = this.isProductionMode();
1791
+ let allowedOrigins = this.config.allowedOrigins;
1792
+ let enableDnsRebindingProtection = false;
1793
+ if (isProduction) {
1794
+ if (allowedOrigins !== void 0) {
1795
+ enableDnsRebindingProtection = allowedOrigins.length > 0;
1796
+ }
1797
+ } else {
1798
+ allowedOrigins = void 0;
1799
+ enableDnsRebindingProtection = false;
1800
+ }
1801
+ const transport = new StreamableHTTPServerTransport({
1802
+ sessionIdGenerator: /* @__PURE__ */ __name(() => generateUUID(), "sessionIdGenerator"),
1803
+ enableJsonResponse: true,
1804
+ allowedOrigins,
1805
+ enableDnsRebindingProtection,
1806
+ onsessioninitialized: /* @__PURE__ */ __name((id) => {
1807
+ if (id) {
1808
+ this.sessions.set(id, {
1809
+ transport,
1810
+ lastAccessedAt: Date.now()
1811
+ });
1812
+ }
1813
+ }, "onsessioninitialized"),
1814
+ onsessionclosed: /* @__PURE__ */ __name((id) => {
1815
+ if (id) {
1816
+ this.sessions.delete(id);
1817
+ }
1818
+ }, "onsessionclosed")
1819
+ });
1820
+ await this.server.connect(transport);
1821
+ return transport;
1822
+ }
1823
+ if (sessionId && this.sessions.has(sessionId)) {
1824
+ const session = this.sessions.get(sessionId);
1825
+ session.lastAccessedAt = Date.now();
1826
+ return session.transport;
1827
+ }
1828
+ if (sessionId) {
1829
+ return null;
1830
+ }
1831
+ return null;
1832
+ }, "getOrCreateTransport");
1833
+ if (idleTimeoutMs > 0 && !this.idleCleanupInterval) {
1834
+ this.idleCleanupInterval = setInterval(() => {
1835
+ const now = Date.now();
1836
+ for (const [sessionId, session] of this.sessions.entries()) {
1837
+ if (now - session.lastAccessedAt > idleTimeoutMs) {
1838
+ try {
1839
+ session.transport.close();
1840
+ } catch (error) {
1841
+ }
1842
+ this.sessions.delete(sessionId);
1843
+ }
1844
+ }
1845
+ }, 6e4);
1846
+ }
1691
1847
  const createExpressLikeObjects = /* @__PURE__ */ __name((c) => {
1692
1848
  const req = c.req.raw;
1693
1849
  const responseBody = [];
@@ -1795,164 +1951,250 @@ if (container && Component) {
1795
1951
  }, "getResponse")
1796
1952
  };
1797
1953
  }, "createExpressLikeObjects");
1798
- this.app.post(endpoint, async (c) => {
1799
- const { expressReq, expressRes, getResponse } = createExpressLikeObjects(c);
1800
- try {
1801
- expressReq.body = await c.req.json();
1802
- } catch {
1803
- expressReq.body = {};
1804
- }
1805
- const transport = new StreamableHTTPServerTransport({
1806
- sessionIdGenerator: void 0,
1807
- enableJsonResponse: true
1954
+ const mountEndpoint = /* @__PURE__ */ __name((endpoint) => {
1955
+ this.app.post(endpoint, async (c) => {
1956
+ const { expressReq, expressRes, getResponse } = createExpressLikeObjects(c);
1957
+ let body = {};
1958
+ try {
1959
+ body = await c.req.json();
1960
+ expressReq.body = body;
1961
+ } catch {
1962
+ expressReq.body = {};
1963
+ }
1964
+ const isInit = body?.method === "initialize";
1965
+ const sessionId = c.req.header("mcp-session-id");
1966
+ const transport = await getOrCreateTransport(sessionId, isInit);
1967
+ if (!transport) {
1968
+ if (sessionId) {
1969
+ return c.json(
1970
+ {
1971
+ jsonrpc: "2.0",
1972
+ error: {
1973
+ code: -32e3,
1974
+ message: "Session not found or expired"
1975
+ },
1976
+ // Notifications don't have an id, but we include null for consistency
1977
+ id: body?.id ?? null
1978
+ },
1979
+ 404
1980
+ );
1981
+ } else {
1982
+ return c.json(
1983
+ {
1984
+ jsonrpc: "2.0",
1985
+ error: {
1986
+ code: -32e3,
1987
+ message: "Bad Request: Mcp-Session-Id header is required"
1988
+ },
1989
+ id: body?.id ?? null
1990
+ },
1991
+ 400
1992
+ );
1993
+ }
1994
+ }
1995
+ if (sessionId && this.sessions.has(sessionId)) {
1996
+ this.sessions.get(sessionId).lastAccessedAt = Date.now();
1997
+ }
1998
+ if (expressRes._closeHandler) {
1999
+ c.req.raw.signal?.addEventListener("abort", () => {
2000
+ transport.close();
2001
+ });
2002
+ }
2003
+ await this.waitForRequestComplete(
2004
+ transport,
2005
+ expressReq,
2006
+ expressRes,
2007
+ expressReq.body
2008
+ );
2009
+ const response = getResponse();
2010
+ if (response) {
2011
+ return response;
2012
+ }
2013
+ return c.text("", 200);
1808
2014
  });
1809
- if (expressRes._closeHandler) {
2015
+ this.app.get(endpoint, async (c) => {
2016
+ const sessionId = c.req.header("mcp-session-id");
2017
+ const transport = await getOrCreateTransport(sessionId, false);
2018
+ if (!transport) {
2019
+ if (sessionId) {
2020
+ return c.json(
2021
+ {
2022
+ jsonrpc: "2.0",
2023
+ error: {
2024
+ code: -32e3,
2025
+ message: "Session not found or expired"
2026
+ },
2027
+ id: null
2028
+ },
2029
+ 404
2030
+ );
2031
+ } else {
2032
+ return c.json(
2033
+ {
2034
+ jsonrpc: "2.0",
2035
+ error: {
2036
+ code: -32e3,
2037
+ message: "Bad Request: Mcp-Session-Id header is required"
2038
+ },
2039
+ id: null
2040
+ },
2041
+ 400
2042
+ );
2043
+ }
2044
+ }
2045
+ if (sessionId && this.sessions.has(sessionId)) {
2046
+ this.sessions.get(sessionId).lastAccessedAt = Date.now();
2047
+ }
1810
2048
  c.req.raw.signal?.addEventListener("abort", () => {
1811
2049
  transport.close();
1812
2050
  });
1813
- }
1814
- await this.server.connect(transport);
1815
- await this.waitForRequestComplete(
1816
- transport,
1817
- expressReq,
1818
- expressRes,
1819
- expressReq.body
1820
- );
1821
- const response = getResponse();
1822
- if (response) {
1823
- return response;
1824
- }
1825
- return c.text("", 200);
1826
- });
1827
- this.app.get(endpoint, async (c) => {
1828
- const transport = new StreamableHTTPServerTransport({
1829
- sessionIdGenerator: void 0,
1830
- enableJsonResponse: true
1831
- });
1832
- c.req.raw.signal?.addEventListener("abort", () => {
1833
- transport.close();
1834
- });
1835
- const { readable, writable } = new globalThis.TransformStream();
1836
- const writer = writable.getWriter();
1837
- const encoder = new TextEncoder();
1838
- let resolveResponse;
1839
- const responsePromise = new Promise((resolve) => {
1840
- resolveResponse = resolve;
1841
- });
1842
- let headersSent = false;
1843
- const headers = {};
1844
- let statusCode = 200;
1845
- const expressRes = {
1846
- statusCode: 200,
1847
- headersSent: false,
1848
- status: /* @__PURE__ */ __name((code) => {
1849
- statusCode = code;
1850
- expressRes.statusCode = code;
1851
- return expressRes;
1852
- }, "status"),
1853
- setHeader: /* @__PURE__ */ __name((name, value) => {
1854
- if (!headersSent) {
1855
- headers[name] = Array.isArray(value) ? value.join(", ") : value;
1856
- }
1857
- }, "setHeader"),
1858
- getHeader: /* @__PURE__ */ __name((name) => headers[name], "getHeader"),
1859
- write: /* @__PURE__ */ __name((chunk) => {
1860
- if (!headersSent) {
1861
- headersSent = true;
1862
- resolveResponse(
1863
- new Response(readable, {
1864
- status: statusCode,
1865
- headers
1866
- })
1867
- );
1868
- }
1869
- const data = typeof chunk === "string" ? encoder.encode(chunk) : chunk instanceof Uint8Array ? chunk : Buffer.from(chunk);
1870
- writer.write(data);
1871
- return true;
1872
- }, "write"),
1873
- end: /* @__PURE__ */ __name((chunk) => {
1874
- if (chunk) {
1875
- expressRes.write(chunk);
2051
+ const { readable, writable } = new globalThis.TransformStream();
2052
+ const writer = writable.getWriter();
2053
+ const encoder = new TextEncoder();
2054
+ let resolveResponse;
2055
+ const responsePromise = new Promise((resolve) => {
2056
+ resolveResponse = resolve;
2057
+ });
2058
+ let headersSent = false;
2059
+ const headers = {};
2060
+ let statusCode = 200;
2061
+ const expressRes = {
2062
+ statusCode: 200,
2063
+ headersSent: false,
2064
+ status: /* @__PURE__ */ __name((code) => {
2065
+ statusCode = code;
2066
+ expressRes.statusCode = code;
2067
+ return expressRes;
2068
+ }, "status"),
2069
+ setHeader: /* @__PURE__ */ __name((name, value) => {
2070
+ if (!headersSent) {
2071
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
2072
+ }
2073
+ }, "setHeader"),
2074
+ getHeader: /* @__PURE__ */ __name((name) => headers[name], "getHeader"),
2075
+ write: /* @__PURE__ */ __name((chunk) => {
2076
+ if (!headersSent) {
2077
+ headersSent = true;
2078
+ resolveResponse(
2079
+ new Response(readable, {
2080
+ status: statusCode,
2081
+ headers
2082
+ })
2083
+ );
2084
+ }
2085
+ const data = typeof chunk === "string" ? encoder.encode(chunk) : chunk instanceof Uint8Array ? chunk : Buffer.from(chunk);
2086
+ writer.write(data);
2087
+ return true;
2088
+ }, "write"),
2089
+ end: /* @__PURE__ */ __name((chunk) => {
2090
+ if (chunk) {
2091
+ expressRes.write(chunk);
2092
+ }
2093
+ if (!headersSent) {
2094
+ headersSent = true;
2095
+ resolveResponse(
2096
+ new Response(null, {
2097
+ status: statusCode,
2098
+ headers
2099
+ })
2100
+ );
2101
+ writer.close();
2102
+ } else {
2103
+ writer.close();
2104
+ }
2105
+ }, "end"),
2106
+ on: /* @__PURE__ */ __name((event, handler) => {
2107
+ if (event === "close") {
2108
+ expressRes._closeHandler = handler;
2109
+ }
2110
+ }, "on"),
2111
+ once: /* @__PURE__ */ __name(() => {
2112
+ }, "once"),
2113
+ removeListener: /* @__PURE__ */ __name(() => {
2114
+ }, "removeListener"),
2115
+ writeHead: /* @__PURE__ */ __name((code, _headers) => {
2116
+ statusCode = code;
2117
+ expressRes.statusCode = code;
2118
+ if (_headers) {
2119
+ Object.assign(headers, _headers);
2120
+ }
2121
+ if (!headersSent) {
2122
+ headersSent = true;
2123
+ resolveResponse(
2124
+ new Response(readable, {
2125
+ status: statusCode,
2126
+ headers
2127
+ })
2128
+ );
2129
+ }
2130
+ return expressRes;
2131
+ }, "writeHead"),
2132
+ flushHeaders: /* @__PURE__ */ __name(() => {
2133
+ }, "flushHeaders")
2134
+ };
2135
+ const expressReq = {
2136
+ ...c.req.raw,
2137
+ url: new URL(c.req.url).pathname + new URL(c.req.url).search,
2138
+ path: new URL(c.req.url).pathname,
2139
+ query: Object.fromEntries(new URL(c.req.url).searchParams),
2140
+ headers: c.req.header(),
2141
+ method: c.req.method
2142
+ };
2143
+ transport.handleRequest(expressReq, expressRes).catch((err) => {
2144
+ console.error("MCP Transport error:", err);
2145
+ try {
2146
+ writer.close();
2147
+ } catch {
1876
2148
  }
1877
- if (!headersSent) {
1878
- headersSent = true;
1879
- resolveResponse(
1880
- new Response(null, {
1881
- status: statusCode,
1882
- headers
1883
- })
2149
+ });
2150
+ return responsePromise;
2151
+ });
2152
+ this.app.delete(endpoint, async (c) => {
2153
+ const { expressReq, expressRes, getResponse } = createExpressLikeObjects(c);
2154
+ const sessionId = c.req.header("mcp-session-id");
2155
+ const transport = await getOrCreateTransport(sessionId, false);
2156
+ if (!transport) {
2157
+ if (sessionId) {
2158
+ return c.json(
2159
+ {
2160
+ jsonrpc: "2.0",
2161
+ error: {
2162
+ code: -32e3,
2163
+ message: "Session not found or expired"
2164
+ },
2165
+ id: null
2166
+ },
2167
+ 404
1884
2168
  );
1885
- writer.close();
1886
2169
  } else {
1887
- writer.close();
1888
- }
1889
- }, "end"),
1890
- on: /* @__PURE__ */ __name((event, handler) => {
1891
- if (event === "close") {
1892
- expressRes._closeHandler = handler;
1893
- }
1894
- }, "on"),
1895
- once: /* @__PURE__ */ __name(() => {
1896
- }, "once"),
1897
- removeListener: /* @__PURE__ */ __name(() => {
1898
- }, "removeListener"),
1899
- writeHead: /* @__PURE__ */ __name((code, _headers) => {
1900
- statusCode = code;
1901
- expressRes.statusCode = code;
1902
- if (_headers) {
1903
- Object.assign(headers, _headers);
1904
- }
1905
- if (!headersSent) {
1906
- headersSent = true;
1907
- resolveResponse(
1908
- new Response(readable, {
1909
- status: statusCode,
1910
- headers
1911
- })
2170
+ return c.json(
2171
+ {
2172
+ jsonrpc: "2.0",
2173
+ error: {
2174
+ code: -32e3,
2175
+ message: "Bad Request: Mcp-Session-Id header is required"
2176
+ },
2177
+ id: null
2178
+ },
2179
+ 400
1912
2180
  );
1913
2181
  }
1914
- return expressRes;
1915
- }, "writeHead"),
1916
- flushHeaders: /* @__PURE__ */ __name(() => {
1917
- }, "flushHeaders")
1918
- };
1919
- const expressReq = {
1920
- ...c.req.raw,
1921
- url: new URL(c.req.url).pathname + new URL(c.req.url).search,
1922
- path: new URL(c.req.url).pathname,
1923
- query: Object.fromEntries(new URL(c.req.url).searchParams),
1924
- headers: c.req.header(),
1925
- method: c.req.method
1926
- };
1927
- await this.server.connect(transport);
1928
- transport.handleRequest(expressReq, expressRes).catch((err) => {
1929
- console.error("MCP Transport error:", err);
1930
- try {
1931
- writer.close();
1932
- } catch {
1933
2182
  }
2183
+ c.req.raw.signal?.addEventListener("abort", () => {
2184
+ transport.close();
2185
+ });
2186
+ await this.waitForRequestComplete(transport, expressReq, expressRes);
2187
+ const response = getResponse();
2188
+ if (response) {
2189
+ return response;
2190
+ }
2191
+ return c.text("", 200);
1934
2192
  });
1935
- return responsePromise;
1936
- });
1937
- this.app.delete(endpoint, async (c) => {
1938
- const { expressReq, expressRes, getResponse } = createExpressLikeObjects(c);
1939
- const transport = new StreamableHTTPServerTransport({
1940
- sessionIdGenerator: void 0,
1941
- enableJsonResponse: true
1942
- });
1943
- c.req.raw.signal?.addEventListener("abort", () => {
1944
- transport.close();
1945
- });
1946
- await this.server.connect(transport);
1947
- await this.waitForRequestComplete(transport, expressReq, expressRes);
1948
- const response = getResponse();
1949
- if (response) {
1950
- return response;
1951
- }
1952
- return c.text("", 200);
1953
- });
2193
+ }, "mountEndpoint");
2194
+ mountEndpoint("/mcp");
2195
+ mountEndpoint("/sse");
1954
2196
  this.mcpMounted = true;
1955
- console.log(`[MCP] Server mounted at ${endpoint}`);
2197
+ console.log(`[MCP] Server mounted at /mcp and /sse`);
1956
2198
  }
1957
2199
  /**
1958
2200
  * Start the Hono server with MCP endpoints
@@ -1961,7 +2203,7 @@ if (container && Component) {
1961
2203
  * the inspector UI (if available), and starting the server to listen
1962
2204
  * for incoming connections. This is the main entry point for running the server.
1963
2205
  *
1964
- * The server will be accessible at the specified port with MCP endpoints at /mcp
2206
+ * The server will be accessible at the specified port with MCP endpoints at /mcp and /sse
1965
2207
  * and inspector UI at /inspector (if the inspector package is installed).
1966
2208
  *
1967
2209
  * @param port - Port number to listen on (defaults to 3001 if not specified)
@@ -1971,7 +2213,7 @@ if (container && Component) {
1971
2213
  * ```typescript
1972
2214
  * await server.listen(8080)
1973
2215
  * // Server now running at http://localhost:8080 (or configured host)
1974
- * // MCP endpoints: http://localhost:8080/mcp
2216
+ * // MCP endpoints: http://localhost:8080/mcp and http://localhost:8080/sse
1975
2217
  * // Inspector UI: http://localhost:8080/inspector
1976
2218
  * ```
1977
2219
  */
@@ -2075,7 +2317,7 @@ if (container && Component) {
2075
2317
  `[SERVER] Listening on http://${this.serverHost}:${this.serverPort}`
2076
2318
  );
2077
2319
  console.log(
2078
- `[MCP] Endpoints: http://${this.serverHost}:${this.serverPort}/mcp`
2320
+ `[MCP] Endpoints: http://${this.serverHost}:${this.serverPort}/mcp and http://${this.serverHost}:${this.serverPort}/sse`
2079
2321
  );
2080
2322
  }
2081
2323
  );
@@ -2159,6 +2401,192 @@ if (container && Component) {
2159
2401
  return result;
2160
2402
  };
2161
2403
  }
2404
+ /**
2405
+ * Get array of active session IDs
2406
+ *
2407
+ * Returns an array of all currently active session IDs. This is useful for
2408
+ * sending targeted notifications to specific clients or iterating over
2409
+ * connected clients.
2410
+ *
2411
+ * Note: This only works in stateful mode. In stateless mode (edge environments),
2412
+ * this will return an empty array.
2413
+ *
2414
+ * @returns Array of active session ID strings
2415
+ *
2416
+ * @example
2417
+ * ```typescript
2418
+ * const sessions = server.getActiveSessions();
2419
+ * console.log(`${sessions.length} clients connected`);
2420
+ *
2421
+ * // Send notification to first connected client
2422
+ * if (sessions.length > 0) {
2423
+ * server.sendNotificationToSession(sessions[0], "custom/hello", { message: "Hi!" });
2424
+ * }
2425
+ * ```
2426
+ */
2427
+ getActiveSessions() {
2428
+ return Array.from(this.sessions.keys());
2429
+ }
2430
+ /**
2431
+ * Send a notification to all connected clients
2432
+ *
2433
+ * Broadcasts a JSON-RPC notification to all active sessions. Notifications are
2434
+ * one-way messages that do not expect a response from the client.
2435
+ *
2436
+ * Note: This only works in stateful mode with active sessions. If no sessions
2437
+ * are connected, the notification is silently discarded (per MCP spec: "server MAY send").
2438
+ *
2439
+ * @param method - The notification method name (e.g., "custom/my-notification")
2440
+ * @param params - Optional parameters to include in the notification
2441
+ *
2442
+ * @example
2443
+ * ```typescript
2444
+ * // Send a simple notification to all clients
2445
+ * server.sendNotification("custom/server-status", {
2446
+ * status: "ready",
2447
+ * timestamp: new Date().toISOString()
2448
+ * });
2449
+ *
2450
+ * // Notify all clients that resources have changed
2451
+ * server.sendNotification("notifications/resources/list_changed");
2452
+ * ```
2453
+ */
2454
+ async sendNotification(method, params) {
2455
+ const notification = {
2456
+ jsonrpc: "2.0",
2457
+ method,
2458
+ ...params && { params }
2459
+ };
2460
+ for (const [sessionId, session] of this.sessions.entries()) {
2461
+ try {
2462
+ await session.transport.send(notification);
2463
+ } catch (error) {
2464
+ console.warn(
2465
+ `[MCP] Failed to send notification to session ${sessionId}:`,
2466
+ error
2467
+ );
2468
+ }
2469
+ }
2470
+ }
2471
+ /**
2472
+ * Send a notification to a specific client session
2473
+ *
2474
+ * Sends a JSON-RPC notification to a single client identified by their session ID.
2475
+ * This allows sending customized notifications to individual clients.
2476
+ *
2477
+ * Note: This only works in stateful mode. If the session ID doesn't exist,
2478
+ * the notification is silently discarded.
2479
+ *
2480
+ * @param sessionId - The target session ID (from getActiveSessions())
2481
+ * @param method - The notification method name (e.g., "custom/my-notification")
2482
+ * @param params - Optional parameters to include in the notification
2483
+ * @returns true if the notification was sent, false if session not found
2484
+ *
2485
+ * @example
2486
+ * ```typescript
2487
+ * const sessions = server.getActiveSessions();
2488
+ *
2489
+ * // Send different messages to different clients
2490
+ * sessions.forEach((sessionId, index) => {
2491
+ * server.sendNotificationToSession(sessionId, "custom/welcome", {
2492
+ * message: `Hello client #${index + 1}!`,
2493
+ * clientNumber: index + 1
2494
+ * });
2495
+ * });
2496
+ * ```
2497
+ */
2498
+ async sendNotificationToSession(sessionId, method, params) {
2499
+ const session = this.sessions.get(sessionId);
2500
+ if (!session) {
2501
+ return false;
2502
+ }
2503
+ const notification = {
2504
+ jsonrpc: "2.0",
2505
+ method,
2506
+ ...params && { params }
2507
+ };
2508
+ try {
2509
+ await session.transport.send(notification);
2510
+ return true;
2511
+ } catch (error) {
2512
+ console.warn(
2513
+ `[MCP] Failed to send notification to session ${sessionId}:`,
2514
+ error
2515
+ );
2516
+ return false;
2517
+ }
2518
+ }
2519
+ // Store the roots changed callback
2520
+ onRootsChangedCallback;
2521
+ /**
2522
+ * Register a callback for when a client's roots change
2523
+ *
2524
+ * When a client sends a `notifications/roots/list_changed` notification,
2525
+ * the server will automatically request the updated roots list and call
2526
+ * this callback with the new roots.
2527
+ *
2528
+ * @param callback - Function called with the updated roots array
2529
+ *
2530
+ * @example
2531
+ * ```typescript
2532
+ * server.onRootsChanged(async (roots) => {
2533
+ * console.log("Client roots updated:", roots);
2534
+ * roots.forEach(root => {
2535
+ * console.log(` - ${root.name || "unnamed"}: ${root.uri}`);
2536
+ * });
2537
+ * });
2538
+ * ```
2539
+ */
2540
+ onRootsChanged(callback) {
2541
+ this.onRootsChangedCallback = callback;
2542
+ return this;
2543
+ }
2544
+ /**
2545
+ * Request the current roots list from a specific client session
2546
+ *
2547
+ * This sends a `roots/list` request to the client and returns
2548
+ * the list of roots the client has configured.
2549
+ *
2550
+ * @param sessionId - The session ID of the client to query
2551
+ * @returns Array of roots, or null if the session doesn't exist or request fails
2552
+ *
2553
+ * @example
2554
+ * ```typescript
2555
+ * const sessions = server.getActiveSessions();
2556
+ * if (sessions.length > 0) {
2557
+ * const roots = await server.listRoots(sessions[0]);
2558
+ * if (roots) {
2559
+ * console.log(`Client has ${roots.length} roots:`);
2560
+ * roots.forEach(r => console.log(` - ${r.uri}`));
2561
+ * }
2562
+ * }
2563
+ * ```
2564
+ */
2565
+ async listRoots(sessionId) {
2566
+ const session = this.sessions.get(sessionId);
2567
+ if (!session) {
2568
+ return null;
2569
+ }
2570
+ try {
2571
+ const request = {
2572
+ jsonrpc: "2.0",
2573
+ id: generateUUID(),
2574
+ method: "roots/list",
2575
+ params: {}
2576
+ };
2577
+ const response = await session.transport.send(request);
2578
+ if (response && typeof response === "object" && "roots" in response) {
2579
+ return response.roots;
2580
+ }
2581
+ return [];
2582
+ } catch (error) {
2583
+ console.warn(
2584
+ `[MCP] Failed to list roots from session ${sessionId}:`,
2585
+ error
2586
+ );
2587
+ return null;
2588
+ }
2589
+ }
2162
2590
  /**
2163
2591
  * Mount MCP Inspector UI at /inspector
2164
2592
  *
@@ -2175,7 +2603,7 @@ if (container && Component) {
2175
2603
  * @example
2176
2604
  * If @mcp-use/inspector is installed:
2177
2605
  * - Inspector UI available at http://localhost:PORT/inspector
2178
- * - Automatically connects to http://localhost:PORT/mcp
2606
+ * - Automatically connects to http://localhost:PORT/mcp (or /sse)
2179
2607
  *
2180
2608
  * If not installed:
2181
2609
  * - Server continues to function normally
@@ -2194,7 +2622,14 @@ if (container && Component) {
2194
2622
  }
2195
2623
  try {
2196
2624
  const { mountInspector } = await import("@mcp-use/inspector");
2197
- mountInspector(this.app);
2625
+ const mcpUrl = `http://${this.serverHost}:${this.serverPort}/mcp`;
2626
+ const autoConnectConfig = JSON.stringify({
2627
+ url: mcpUrl,
2628
+ name: "Local MCP Server",
2629
+ transportType: "sse",
2630
+ connectionType: "Direct"
2631
+ });
2632
+ mountInspector(this.app, { autoConnectUrl: autoConnectConfig });
2198
2633
  this.inspectorMounted = true;
2199
2634
  console.log(
2200
2635
  `[INSPECTOR] UI available at http://${this.serverHost}:${this.serverPort}/inspector`
@@ -2518,7 +2953,9 @@ function createMCPServer(name, config = {}) {
2518
2953
  version: config.version || "1.0.0",
2519
2954
  description: config.description,
2520
2955
  host: config.host,
2521
- baseUrl: config.baseUrl
2956
+ baseUrl: config.baseUrl,
2957
+ allowedOrigins: config.allowedOrigins,
2958
+ sessionIdleTimeoutMs: config.sessionIdleTimeoutMs
2522
2959
  });
2523
2960
  return instance;
2524
2961
  }